notify.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. # -*- coding: utf-8 -*-
  2. """
  3. (c) 2014-2018 - Copyright Red Hat Inc
  4. Authors:
  5. Pierre-Yves Chibon <pingou@pingoured.fr>
  6. pagure notifications.
  7. """
  8. from __future__ import print_function, unicode_literals, absolute_import
  9. # pylint: disable=too-many-branches
  10. # pylint: disable=too-many-arguments
  11. import datetime
  12. import hashlib
  13. import json
  14. import logging
  15. import os
  16. import re
  17. import smtplib
  18. import time
  19. import six
  20. import ssl
  21. from email.header import Header
  22. from email.mime.text import MIMEText
  23. from six.moves.urllib_parse import urljoin
  24. import blinker
  25. import flask
  26. import pagure.lib.query
  27. import pagure.lib.tasks_services
  28. from pagure.config import config as pagure_config
  29. _log = logging.getLogger(__name__)
  30. REPLY_MSG = "To reply, visit the link below"
  31. if pagure_config["EVENTSOURCE_SOURCE"]:
  32. REPLY_MSG += " or just reply to this email"
  33. def fedmsg_publish(*args, **kwargs): # pragma: no cover
  34. """ Try to publish a message on the fedmsg bus. """
  35. if not pagure_config.get("FEDMSG_NOTIFICATIONS", True):
  36. return
  37. _log.warning(
  38. "fedmsg support is being deprecated in favor of fedora-messaging "
  39. "you likely want to stop relying on it as it will disapear in the "
  40. "future, most likely in the 6.0 release"
  41. )
  42. # We catch Exception if we want :-p
  43. # pylint: disable=broad-except
  44. # Ignore message about fedmsg import
  45. # pylint: disable=import-error
  46. kwargs["modname"] = "pagure"
  47. kwargs["cert_prefix"] = "pagure"
  48. kwargs["active"] = True
  49. try:
  50. import fedmsg
  51. fedmsg.publish(*args, **kwargs)
  52. except Exception:
  53. _log.exception("Error sending fedmsg")
  54. def fedora_messaging_publish(topic, message): # pragma: no cover
  55. """ Try to publish a message on AMQP using fedora-messaging. """
  56. if not pagure_config.get("FEDORA_MESSAGING_NOTIFICATIONS", False):
  57. return
  58. try:
  59. import fedora_messaging.api
  60. import fedora_messaging.exceptions
  61. msg = fedora_messaging.api.Message(
  62. topic="pagure.{}".format(topic), body=message
  63. )
  64. fedora_messaging.api.publish(msg)
  65. except fedora_messaging.exceptions.PublishReturned as e:
  66. _log.warning(
  67. "Fedora Messaging broker rejected message %s: %s", msg.id, e
  68. )
  69. except fedora_messaging.exceptions.ConnectionException as e:
  70. _log.warning("Error sending message %s: %s", msg.id, e)
  71. except Exception:
  72. _log.exception("Error sending fedora-messaging message")
  73. stomp_conn = None
  74. def stomp_publish(topic, message):
  75. """ Try to publish a message on a Stomp-compliant message bus. """
  76. if not pagure_config.get("STOMP_NOTIFICATIONS", False):
  77. return
  78. # We catch Exception if we want :-p
  79. # pylint: disable=broad-except
  80. # Ignore message about stomp import
  81. # pylint: disable=import-error
  82. try:
  83. import stomp
  84. global stomp_conn
  85. if not stomp_conn or not stomp_conn.is_connected():
  86. stomp_conn = stomp.Connection12(pagure_config["STOMP_BROKERS"])
  87. if pagure_config.get("STOMP_SSL"):
  88. stomp_conn.set_ssl(
  89. pagure_config["STOMP_BROKERS"],
  90. key_file=pagure_config.get("STOMP_KEY_FILE"),
  91. cert_file=pagure_config.get("STOMP_CERT_FILE"),
  92. password=pagure_config.get("STOMP_CREDS_PASSWORD"),
  93. )
  94. from stomp import PrintingListener
  95. stomp_conn.set_listener("", PrintingListener())
  96. stomp_conn.start()
  97. stomp_conn.connect(wait=True)
  98. hierarchy = pagure_config["STOMP_HIERARCHY"]
  99. stomp_conn.send(
  100. destination=hierarchy + topic, body=json.dumps(message)
  101. )
  102. except Exception:
  103. _log.exception("Error sending stomp message")
  104. def blinker_publish(topic, message):
  105. _log.info("Sending blinker signal to: pagure - topic: %s", topic)
  106. ready = blinker.signal("pagure")
  107. ready.send("pagure", topic=topic, message=message)
  108. def mqtt_publish(topic, message):
  109. """ Try to publish a message on a MQTT message bus. """
  110. if not pagure_config.get("MQTT_NOTIFICATIONS", False):
  111. return
  112. mqtt_host = pagure_config.get("MQTT_HOST")
  113. mqtt_port = pagure_config.get("MQTT_PORT")
  114. mqtt_username = pagure_config.get("MQTT_USERNAME")
  115. mqtt_pass = pagure_config.get("MQTT_PASSWORD")
  116. mqtt_ca_certs = pagure_config.get("MQTT_CA_CERTS")
  117. mqtt_certfile = pagure_config.get("MQTT_CERTFILE")
  118. mqtt_keyfile = pagure_config.get("MQTT_KEYFILE")
  119. mqtt_cert_reqs = pagure_config.get("MQTT_CERT_REQS", ssl.CERT_REQUIRED)
  120. mqtt_tls_version = pagure_config.get(
  121. "MQTT_TLS_VERSION", ssl.PROTOCOL_TLSv1_2
  122. )
  123. mqtt_ciphers = pagure_config.get("MQTT_CIPHERS")
  124. mqtt_topic_prefix = pagure_config.get("MQTT_TOPIC_PREFIX") or None
  125. if mqtt_topic_prefix:
  126. topic = "/".join([mqtt_topic_prefix.rstrip("/"), topic])
  127. # We catch Exception if we want :-p
  128. # pylint: disable=broad-except
  129. # Ignore message about mqtt import
  130. # pylint: disable=import-error
  131. try:
  132. import paho.mqtt.client as mqtt
  133. client = mqtt.Client(os.uname()[1])
  134. client.tls_set(
  135. ca_certs=mqtt_ca_certs,
  136. certfile=mqtt_certfile,
  137. keyfile=mqtt_keyfile,
  138. cert_reqs=mqtt_cert_reqs,
  139. tls_version=mqtt_tls_version,
  140. ciphers=mqtt_ciphers,
  141. )
  142. if mqtt_username and mqtt_pass:
  143. client.username_pw_set(mqtt_username, mqtt_pass)
  144. client.connect(mqtt_host, mqtt_port)
  145. client.publish(topic, json.dumps(message))
  146. client.disconnect()
  147. except Exception:
  148. _log.exception("Error sending mqtt message")
  149. def log(project, topic, msg, webhook=True):
  150. """ This is the place where we send notifications to user about actions
  151. occuring in pagure.
  152. """
  153. # Send fedmsg notification (if fedmsg is there and set-up)
  154. if not project or (
  155. project.settings.get("fedmsg_notifications", True)
  156. and not project.private
  157. ):
  158. fedmsg_publish(topic, msg)
  159. fedora_messaging_publish(topic, msg)
  160. # Send stomp notification (if stomp is there and set-up)
  161. if not project or (
  162. project.settings.get("stomp_notifications", True)
  163. and not project.private
  164. ):
  165. stomp_publish(topic, msg)
  166. # Send mqtt notification (if mqtt is there and set-up)
  167. if not project or (
  168. project.settings.get("mqtt_notifications", True)
  169. and not project.private
  170. ):
  171. mqtt_publish(topic, msg)
  172. # Send blink notification to any 3rd party plugins, if there are any
  173. blinker_publish(topic, msg)
  174. if webhook and project and not project.private:
  175. pagure.lib.tasks_services.webhook_notification.delay(
  176. topic=topic,
  177. msg=msg,
  178. namespace=project.namespace,
  179. name=project.name,
  180. user=project.user.username if project.is_fork else None,
  181. )
  182. def _add_mentioned_users(emails, comment):
  183. """ Check the comment to see if an user is mentioned in it and if
  184. so add this user to the list of people to notify.
  185. """
  186. mentio_re = r"@(\w+)"
  187. for username in re.findall(mentio_re, comment):
  188. user = pagure.lib.query.search_user(flask.g.session, username=username)
  189. if user:
  190. emails.add(user.default_email)
  191. return emails
  192. def _clean_emails(emails, user):
  193. """ Remove the email of the user doing the action if it is in the list.
  194. This avoids receiving emails about action you do.
  195. """
  196. # Remove the user doing the action from the list of person to email
  197. # unless they actively asked for it
  198. if (
  199. user
  200. and user.emails
  201. and not user.settings.get("cc_me_to_my_actions", False)
  202. ):
  203. for email in user.emails:
  204. if email.email in emails:
  205. emails.remove(email.email)
  206. return emails
  207. def _get_emails_for_obj(obj):
  208. """ Return the list of emails to send notification to when notifying
  209. about the specified issue or pull-request.
  210. """
  211. emails = set()
  212. # Add project creator/owner
  213. if obj.project.user.default_email:
  214. emails.add(obj.project.user.default_email)
  215. # Add committers is object is private, otherwise all contributors
  216. if obj.isa in ["issue", "pull-request"] and obj.private:
  217. for user in obj.project.committers:
  218. if user.default_email:
  219. emails.add(user.default_email)
  220. else:
  221. for user in obj.project.users:
  222. if user.default_email:
  223. emails.add(user.default_email)
  224. # Add people in groups with any access to the project:
  225. for group in obj.project.groups:
  226. if group.creator.default_email:
  227. emails.add(group.creator.default_email)
  228. for user in group.users:
  229. if user.default_email:
  230. emails.add(user.default_email)
  231. # Add people that commented on the issue/PR
  232. if obj.isa in ["issue", "pull-request"]:
  233. for comment in obj.comments:
  234. if comment.user.default_email:
  235. emails.add(comment.user.default_email)
  236. # Add the person that opened the issue/PR
  237. if obj.user.default_email:
  238. emails.add(obj.user.default_email)
  239. # Add the person assigned to the issue/PR
  240. if obj.isa in ["issue", "pull-request"]:
  241. if obj.assignee and obj.assignee.default_email:
  242. emails.add(obj.assignee.default_email)
  243. # Add public notifications to lists/users set project-wide
  244. if obj.isa == "issue" and not obj.private:
  245. for notifs in obj.project.notifications.get("issues", []):
  246. emails.add(notifs)
  247. elif obj.isa == "pull-request":
  248. for notifs in obj.project.notifications.get("requests", []):
  249. emails.add(notifs)
  250. # Add the person watching this project, if it's a public issue or a
  251. # pull-request
  252. if (obj.isa == "issue" and not obj.private) or obj.isa == "pull-request":
  253. for watcher in obj.project.watchers:
  254. if watcher.watch_issues:
  255. emails.add(watcher.user.default_email)
  256. else:
  257. # If there is a watch entry and it is false, it means the user
  258. # explicitly requested to not watch the issue
  259. if watcher.user.default_email in emails:
  260. emails.remove(watcher.user.default_email)
  261. # Add/Remove people who explicitly asked to be added/removed
  262. if obj.isa in ["issue", "pull-request"]:
  263. for watcher in obj.watchers:
  264. if not watcher.watch and watcher.user.default_email in emails:
  265. emails.remove(watcher.user.default_email)
  266. elif watcher.watch:
  267. emails.add(watcher.user.default_email)
  268. # Drop the email used by pagure when sending
  269. emails = _clean_emails(
  270. emails,
  271. pagure_config.get(
  272. pagure_config.get("FROM_EMAIL", "pagure@fedoraproject.org")
  273. ),
  274. )
  275. return emails
  276. def _get_emails_for_commit_notification(project):
  277. emails = set()
  278. for watcher in project.watchers:
  279. if watcher.watch_commits:
  280. emails.add(watcher.user.default_email)
  281. # Drop the email used by pagure when sending
  282. emails = _clean_emails(
  283. emails,
  284. pagure_config.get(
  285. pagure_config.get("FROM_EMAIL", "pagure@fedoraproject.org")
  286. ),
  287. )
  288. return emails
  289. def _build_url(*args):
  290. """ Build a URL from a given list of arguments. """
  291. items = []
  292. for idx, arg in enumerate(args):
  293. arg = "%s" % arg
  294. if arg.startswith("/"):
  295. arg = arg[1:]
  296. if arg.endswith("/") and not idx + 1 == len(args):
  297. arg = arg[:-1]
  298. items.append(arg)
  299. return "/".join(items)
  300. def _fullname_to_url(fullname):
  301. """ For forked projects, fullname is 'forks/user/...' but URL is
  302. 'fork/user/...'. This is why we can't have nice things.
  303. """
  304. if fullname.startswith("forks/"):
  305. fullname = fullname.replace("forks", "fork", 1)
  306. return fullname
  307. def send_email(
  308. text,
  309. subject,
  310. to_mail,
  311. mail_id=None,
  312. in_reply_to=None,
  313. project_name=None,
  314. user_from=None,
  315. reporter=None,
  316. assignee=None,
  317. ): # pragma: no cover
  318. """ Send an email with the specified information.
  319. :arg text: the content of the email to send
  320. :type text: unicode
  321. :arg subject: the subject of the email
  322. :arg to_mail: a string representing a list of recipient separated by a
  323. comma
  324. :kwarg mail_id: if defined, the header `mail-id` is set with this value
  325. :kwarg in_reply_to: if defined, the header `In-Reply-To` is set with
  326. this value
  327. :kwarg project_name: if defined, the name of the project
  328. """
  329. if not to_mail:
  330. return
  331. from_email = pagure_config.get("FROM_EMAIL", "pagure@fedoraproject.org")
  332. if isinstance(from_email, bytes):
  333. from_email = from_email.decode("utf-8")
  334. if user_from:
  335. header = Header(user_from, "utf-8")
  336. from_email = "%s <%s>" % (header.encode(), from_email)
  337. if project_name is not None:
  338. subject_tag = project_name
  339. else:
  340. subject_tag = "Pagure"
  341. if mail_id:
  342. mail_id = mail_id + "@%s" % pagure_config["DOMAIN_EMAIL_NOTIFICATIONS"]
  343. if in_reply_to:
  344. in_reply_to = (
  345. in_reply_to + "@%s" % pagure_config["DOMAIN_EMAIL_NOTIFICATIONS"]
  346. )
  347. smtp = None
  348. for mailto in to_mail.split(","):
  349. try:
  350. pagure.lib.query.allowed_emailaddress(mailto)
  351. except pagure.exceptions.PagureException:
  352. continue
  353. msg = MIMEText(text.encode("utf-8"), "plain", "utf-8")
  354. msg["Subject"] = Header("[%s] %s" % (subject_tag, subject), "utf-8")
  355. msg["From"] = from_email
  356. if mail_id:
  357. msg["mail-id"] = mail_id
  358. msg["Message-Id"] = "<%s>" % mail_id
  359. if in_reply_to:
  360. msg["In-Reply-To"] = "<%s>" % in_reply_to
  361. msg["X-Auto-Response-Suppress"] = "All"
  362. msg["X-pagure"] = pagure_config["APP_URL"]
  363. if project_name is not None:
  364. msg["X-pagure-project"] = project_name
  365. msg["List-ID"] = project_name
  366. msg["List-Archive"] = _build_url(
  367. pagure_config["APP_URL"], _fullname_to_url(project_name)
  368. )
  369. if reporter is not None:
  370. msg["X-pagure-reporter"] = reporter
  371. if assignee is not None:
  372. msg["X-pagure-assignee"] = assignee
  373. # Send the message via our own SMTP server, but don't include the
  374. # envelope header.
  375. msg["To"] = mailto
  376. salt = pagure_config.get("SALT_EMAIL")
  377. if salt and not isinstance(salt, bytes):
  378. salt = salt.encode("utf-8")
  379. if mail_id and pagure_config["EVENTSOURCE_SOURCE"]:
  380. key = (
  381. b"<"
  382. + mail_id.encode("utf-8")
  383. + b">"
  384. + salt
  385. + mailto.encode("utf-8")
  386. )
  387. if isinstance(key, six.text_type):
  388. key = key.encode("utf-8")
  389. mhash = hashlib.sha512(key)
  390. msg["Reply-To"] = "reply+%s@%s" % (
  391. mhash.hexdigest(),
  392. pagure_config["DOMAIN_EMAIL_NOTIFICATIONS"],
  393. )
  394. msg["Mail-Followup-To"] = msg["Reply-To"]
  395. if not pagure_config.get("EMAIL_SEND", True):
  396. _log.debug("******EMAIL******")
  397. _log.debug("From: %s", from_email)
  398. _log.debug("To: %s", to_mail)
  399. _log.debug("Subject: %s", subject)
  400. _log.debug("in_reply_to: %s", in_reply_to)
  401. _log.debug("mail_id: %s", mail_id)
  402. _log.debug("Contents:")
  403. _log.debug("%s" % text)
  404. _log.debug("*****************")
  405. _log.debug(msg.as_string())
  406. _log.debug("*****/EMAIL******")
  407. continue
  408. try:
  409. if smtp is None:
  410. if pagure_config["SMTP_SSL"]:
  411. smtp = smtplib.SMTP_SSL(
  412. pagure_config["SMTP_SERVER"],
  413. pagure_config["SMTP_PORT"],
  414. )
  415. else:
  416. smtp = smtplib.SMTP(
  417. pagure_config["SMTP_SERVER"],
  418. pagure_config["SMTP_PORT"],
  419. )
  420. if (
  421. pagure_config["SMTP_USERNAME"]
  422. and pagure_config["SMTP_PASSWORD"]
  423. ):
  424. smtp.login(
  425. pagure_config["SMTP_USERNAME"],
  426. pagure_config["SMTP_PASSWORD"],
  427. )
  428. smtp.sendmail(from_email, [mailto], msg.as_string())
  429. except smtplib.SMTPException as err:
  430. _log.exception(err)
  431. if smtp:
  432. smtp.quit()
  433. return msg
  434. def notify_new_comment(comment, user=None):
  435. """ Notify the people following an issue that a new comment was added
  436. to the issue.
  437. """
  438. text = """
  439. %s added a new comment to an issue you are following:
  440. ``
  441. %s
  442. ``
  443. %s
  444. %s
  445. """ % (
  446. comment.user.user,
  447. comment.comment,
  448. REPLY_MSG,
  449. _build_url(
  450. pagure_config["APP_URL"],
  451. _fullname_to_url(comment.issue.project.fullname),
  452. "issue",
  453. comment.issue.id,
  454. ),
  455. )
  456. mail_to = _get_emails_for_obj(comment.issue)
  457. if comment.user and comment.user.default_email:
  458. mail_to.add(comment.user.default_email)
  459. mail_to = _add_mentioned_users(mail_to, comment.comment)
  460. mail_to = _clean_emails(mail_to, user)
  461. assignee = comment.issue.assignee.user if comment.issue.assignee else None
  462. send_email(
  463. text,
  464. "Issue #%s: %s" % (comment.issue.id, comment.issue.title),
  465. ",".join(mail_to),
  466. mail_id=comment.mail_id,
  467. in_reply_to=comment.issue.mail_id,
  468. project_name=comment.issue.project.fullname,
  469. user_from=comment.user.fullname or comment.user.user,
  470. reporter=comment.issue.user.user,
  471. assignee=assignee,
  472. )
  473. def notify_new_issue(issue, user=None):
  474. """ Notify the people following a project that a new issue was added
  475. to it.
  476. """
  477. text = """
  478. %s reported a new issue against the project: `%s` that you are following:
  479. ``
  480. %s
  481. ``
  482. %s
  483. %s
  484. """ % (
  485. issue.user.user,
  486. issue.project.name,
  487. issue.content,
  488. REPLY_MSG,
  489. _build_url(
  490. pagure_config["APP_URL"],
  491. _fullname_to_url(issue.project.fullname),
  492. "issue",
  493. issue.id,
  494. ),
  495. )
  496. mail_to = _get_emails_for_obj(issue)
  497. mail_to = _add_mentioned_users(mail_to, issue.content)
  498. mail_to = _clean_emails(mail_to, user)
  499. assignee = issue.assignee.user if issue.assignee else None
  500. send_email(
  501. text,
  502. "Issue #%s: %s" % (issue.id, issue.title),
  503. ",".join(mail_to),
  504. mail_id=issue.mail_id,
  505. project_name=issue.project.fullname,
  506. user_from=issue.user.fullname or issue.user.user,
  507. reporter=issue.user.user,
  508. assignee=assignee,
  509. )
  510. def notify_assigned_issue(issue, new_assignee, user):
  511. """ Notify the people following an issue that the assignee changed.
  512. """
  513. action = "reset"
  514. if new_assignee:
  515. action = "assigned to `%s`" % new_assignee.user
  516. text = """
  517. The issue: `%s` of project: `%s` has been %s by %s.
  518. %s
  519. """ % (
  520. issue.title,
  521. issue.project.name,
  522. action,
  523. user.username,
  524. _build_url(
  525. pagure_config["APP_URL"],
  526. _fullname_to_url(issue.project.fullname),
  527. "issue",
  528. issue.id,
  529. ),
  530. )
  531. mail_to = _get_emails_for_obj(issue)
  532. if new_assignee and new_assignee.default_email:
  533. mail_to.add(new_assignee.default_email)
  534. mail_to = _clean_emails(mail_to, user)
  535. uid = time.mktime(datetime.datetime.now().timetuple())
  536. assignee = issue.assignee.user if issue.assignee else None
  537. send_email(
  538. text,
  539. "Issue #%s: %s" % (issue.id, issue.title),
  540. ",".join(mail_to),
  541. mail_id="%s/assigned/%s" % (issue.mail_id, uid),
  542. in_reply_to=issue.mail_id,
  543. project_name=issue.project.fullname,
  544. user_from=user.fullname or user.user,
  545. reporter=issue.user.user,
  546. assignee=assignee,
  547. )
  548. def notify_status_change_issue(issue, user):
  549. """ Notify the people following a project that an issue changed status.
  550. """
  551. status = issue.status
  552. if status.lower() != "open" and issue.close_status:
  553. status = "%s as %s" % (status, issue.close_status)
  554. text = """
  555. The status of the issue: `%s` of project: `%s` has been updated to: %s by %s.
  556. %s
  557. """ % (
  558. issue.title,
  559. issue.project.fullname,
  560. status,
  561. user.username,
  562. _build_url(
  563. pagure_config["APP_URL"],
  564. _fullname_to_url(issue.project.fullname),
  565. "issue",
  566. issue.id,
  567. ),
  568. )
  569. mail_to = _get_emails_for_obj(issue)
  570. uid = time.mktime(datetime.datetime.now().timetuple())
  571. assignee = issue.assignee.user if issue.assignee else None
  572. send_email(
  573. text,
  574. "Issue #%s: %s" % (issue.id, issue.title),
  575. ",".join(mail_to),
  576. mail_id="%s/close/%s" % (issue.mail_id, uid),
  577. in_reply_to=issue.mail_id,
  578. project_name=issue.project.fullname,
  579. user_from=user.fullname or user.user,
  580. reporter=issue.user.user,
  581. assignee=assignee,
  582. )
  583. def notify_meta_change_issue(issue, user, msg):
  584. """ Notify that a custom field changed
  585. """
  586. text = """
  587. `%s` updated issue.
  588. %s
  589. %s
  590. """ % (
  591. user.username,
  592. msg,
  593. _build_url(
  594. pagure_config["APP_URL"],
  595. _fullname_to_url(issue.project.fullname),
  596. "issue",
  597. issue.id,
  598. ),
  599. )
  600. mail_to = _get_emails_for_obj(issue)
  601. uid = time.mktime(datetime.datetime.now().timetuple())
  602. assignee = issue.assignee.user if issue.assignee else None
  603. send_email(
  604. text,
  605. "Issue #%s: %s" % (issue.id, issue.title),
  606. ",".join(mail_to),
  607. mail_id="%s/close/%s" % (issue.mail_id, uid),
  608. in_reply_to=issue.mail_id,
  609. project_name=issue.project.fullname,
  610. user_from=user.fullname or user.user,
  611. reporter=issue.user.user,
  612. assignee=assignee,
  613. )
  614. def notify_assigned_request(request, new_assignee, user):
  615. """ Notify the people following a pull-request that the assignee changed.
  616. """
  617. action = "reset"
  618. if new_assignee:
  619. action = "assigned to `%s`" % new_assignee.user
  620. text = """
  621. The pull-request: `%s` of project: `%s` has been %s by %s.
  622. %s
  623. """ % (
  624. request.title,
  625. request.project.name,
  626. action,
  627. user.username,
  628. _build_url(
  629. pagure_config["APP_URL"],
  630. _fullname_to_url(request.project.fullname),
  631. "pull-request",
  632. request.id,
  633. ),
  634. )
  635. mail_to = _get_emails_for_obj(request)
  636. if new_assignee and new_assignee.default_email:
  637. mail_to.add(new_assignee.default_email)
  638. mail_to = _clean_emails(mail_to, user)
  639. uid = time.mktime(datetime.datetime.now().timetuple())
  640. assignee = request.assignee.user if request.assignee else None
  641. send_email(
  642. text,
  643. "PR #%s: %s" % (request.id, request.title),
  644. ",".join(mail_to),
  645. mail_id="%s/assigned/%s" % (request.mail_id, uid),
  646. in_reply_to=request.mail_id,
  647. project_name=request.project.fullname,
  648. user_from=user.fullname or user.user,
  649. reporter=request.user.user,
  650. assignee=assignee,
  651. )
  652. def notify_new_pull_request(request):
  653. """ Notify the people following a project that a new pull-request was
  654. added to it.
  655. """
  656. text = """
  657. %s opened a new pull-request against the project: `%s` that you are following:
  658. ``
  659. %s
  660. ``
  661. %s
  662. %s
  663. """ % (
  664. request.user.user,
  665. request.project.name,
  666. request.title,
  667. REPLY_MSG,
  668. _build_url(
  669. pagure_config["APP_URL"],
  670. _fullname_to_url(request.project.fullname),
  671. "pull-request",
  672. request.id,
  673. ),
  674. )
  675. mail_to = _get_emails_for_obj(request)
  676. assignee = request.assignee.user if request.assignee else None
  677. send_email(
  678. text,
  679. "PR #%s: %s" % (request.id, request.title),
  680. ",".join(mail_to),
  681. mail_id=request.mail_id,
  682. project_name=request.project.fullname,
  683. user_from=request.user.fullname or request.user.user,
  684. reporter=request.user.user,
  685. assignee=assignee,
  686. )
  687. def notify_merge_pull_request(request, user):
  688. """ Notify the people following a project that a pull-request was merged
  689. in it.
  690. """
  691. text = """
  692. %s merged a pull-request against the project: `%s` that you are following.
  693. Merged pull-request:
  694. ``
  695. %s
  696. ``
  697. %s
  698. """ % (
  699. user.username,
  700. request.project.name,
  701. request.title,
  702. _build_url(
  703. pagure_config["APP_URL"],
  704. _fullname_to_url(request.project.fullname),
  705. "pull-request",
  706. request.id,
  707. ),
  708. )
  709. mail_to = _get_emails_for_obj(request)
  710. uid = time.mktime(datetime.datetime.now().timetuple())
  711. assignee = request.assignee.user if request.assignee else None
  712. send_email(
  713. text,
  714. "PR #%s: %s" % (request.id, request.title),
  715. ",".join(mail_to),
  716. mail_id="%s/close/%s" % (request.mail_id, uid),
  717. in_reply_to=request.mail_id,
  718. project_name=request.project.fullname,
  719. user_from=user.fullname or user.user,
  720. reporter=request.user.user,
  721. assignee=assignee,
  722. )
  723. def notify_reopen_pull_request(request, user):
  724. """ Notify the people following a project that a closed pull-request
  725. has been reopened.
  726. """
  727. text = """
  728. %s reopened a pull-request against the project: `%s` that you are following.
  729. Reopened pull-request:
  730. ``
  731. %s
  732. ``
  733. %s
  734. """ % (
  735. user.username,
  736. request.project.name,
  737. request.title,
  738. _build_url(
  739. pagure_config["APP_URL"],
  740. _fullname_to_url(request.project.fullname),
  741. "pull-request",
  742. request.id,
  743. ),
  744. )
  745. mail_to = _get_emails_for_obj(request)
  746. uid = time.mktime(datetime.datetime.now().timetuple())
  747. assignee = request.assignee.user if request.assignee else None
  748. send_email(
  749. text,
  750. "PR #%s: %s" % (request.id, request.title),
  751. ",".join(mail_to),
  752. mail_id="%s/close/%s" % (request.mail_id, uid),
  753. in_reply_to=request.mail_id,
  754. project_name=request.project.fullname,
  755. user_from=user.fullname or user.user,
  756. reporter=request.user.user,
  757. assignee=assignee,
  758. )
  759. def notify_closed_pull_request(request, user):
  760. """ Notify the people following a project that a pull-request was
  761. closed in it.
  762. """
  763. text = """
  764. %s closed without merging a pull-request against the project: `%s` that you
  765. are following.
  766. Closed pull-request:
  767. ``
  768. %s
  769. ``
  770. %s
  771. """ % (
  772. user.username,
  773. request.project.name,
  774. request.title,
  775. _build_url(
  776. pagure_config["APP_URL"],
  777. _fullname_to_url(request.project.fullname),
  778. "pull-request",
  779. request.id,
  780. ),
  781. )
  782. mail_to = _get_emails_for_obj(request)
  783. uid = time.mktime(datetime.datetime.now().timetuple())
  784. assignee = request.assignee.user if request.assignee else None
  785. send_email(
  786. text,
  787. "PR #%s: %s" % (request.id, request.title),
  788. ",".join(mail_to),
  789. mail_id="%s/close/%s" % (request.mail_id, uid),
  790. in_reply_to=request.mail_id,
  791. project_name=request.project.fullname,
  792. user_from=user.fullname or user.user,
  793. reporter=request.user.user,
  794. assignee=assignee,
  795. )
  796. def notify_pull_request_comment(comment, user):
  797. """ Notify the people following a pull-request that a new comment was
  798. added to it.
  799. """
  800. text = """
  801. %s commented on the pull-request: `%s` that you are following:
  802. ``
  803. %s
  804. ``
  805. %s
  806. %s
  807. """ % (
  808. comment.user.user,
  809. comment.pull_request.title,
  810. comment.comment,
  811. REPLY_MSG,
  812. _build_url(
  813. pagure_config["APP_URL"],
  814. _fullname_to_url(comment.pull_request.project.fullname),
  815. "pull-request",
  816. comment.pull_request.id,
  817. ),
  818. )
  819. mail_to = _get_emails_for_obj(comment.pull_request)
  820. mail_to = _add_mentioned_users(mail_to, comment.comment)
  821. mail_to = _clean_emails(mail_to, user)
  822. assignee = (
  823. comment.pull_request.assignee.user
  824. if comment.pull_request.assignee
  825. else None
  826. )
  827. send_email(
  828. text,
  829. "PR #%s: %s" % (comment.pull_request.id, comment.pull_request.title),
  830. ",".join(mail_to),
  831. mail_id=comment.mail_id,
  832. in_reply_to=comment.pull_request.mail_id,
  833. project_name=comment.pull_request.project.fullname,
  834. user_from=comment.user.fullname or comment.user.user,
  835. reporter=comment.pull_request.user.user,
  836. assignee=assignee,
  837. )
  838. def notify_pull_request_flag(flag, user):
  839. """ Notify the people following a pull-request that a new flag was
  840. added to it.
  841. """
  842. text = """
  843. %s flagged the pull-request `%s` as %s: %s
  844. %s
  845. """ % (
  846. flag.username,
  847. flag.pull_request.title,
  848. flag.status,
  849. flag.comment,
  850. _build_url(
  851. pagure_config["APP_URL"],
  852. _fullname_to_url(flag.pull_request.project.fullname),
  853. "pull-request",
  854. flag.pull_request.id,
  855. ),
  856. )
  857. mail_to = _get_emails_for_obj(flag.pull_request)
  858. assignee = (
  859. flag.pull_request.assignee.user if flag.pull_request.assignee else None
  860. )
  861. send_email(
  862. text,
  863. "PR #%s - %s: %s" % (flag.pull_request.id, flag.username, flag.status),
  864. ",".join(mail_to),
  865. mail_id=flag.mail_id,
  866. in_reply_to=flag.pull_request.mail_id,
  867. project_name=flag.pull_request.project.fullname,
  868. user_from=flag.username,
  869. reporter=flag.pull_request.user.user,
  870. assignee=assignee,
  871. )
  872. def notify_new_email(email, user):
  873. """ Ask the user to confirm to the email belong to them.
  874. """
  875. root_url = pagure_config.get("APP_URL", flask.request.url_root)
  876. url = urljoin(
  877. root_url or flask.request.url_root,
  878. flask.url_for("ui_ns.confirm_email", token=email.token),
  879. )
  880. text = """Dear %(username)s,
  881. You have registered a new email on pagure at %(root_url)s.
  882. To finish your validate this registration, please click on the following
  883. link or copy/paste it in your browser, this link will remain valid only 2 days:
  884. %(url)s
  885. The email will not be activated until you finish this step.
  886. Sincerely,
  887. Your pagure admin.
  888. """ % (
  889. {"username": user.username, "url": url, "root_url": root_url}
  890. )
  891. send_email(
  892. text,
  893. "Confirm new email",
  894. email.email,
  895. user_from=user.fullname or user.user,
  896. )
  897. def notify_new_commits(abspath, project, branch, commits):
  898. """ Notify the people following a project's commits that new commits have
  899. been added.
  900. """
  901. # string note: abspath, project and branch can only contain ASCII
  902. # by policy (pagure and/or gitolite)
  903. commits_info = []
  904. for commit in commits:
  905. commits_info.append(
  906. {
  907. "commit": commit,
  908. "author": pagure.lib.git.get_author(commit, abspath),
  909. "subject": pagure.lib.git.get_commit_subject(commit, abspath),
  910. }
  911. )
  912. # make sure this is unicode
  913. commits_string = "\n".join(
  914. "{0} {1} {2}".format(
  915. commit_info["commit"],
  916. commit_info["author"],
  917. commit_info["subject"],
  918. )
  919. for commit_info in commits_info
  920. )
  921. commit_url = _build_url(
  922. pagure_config["APP_URL"],
  923. _fullname_to_url(project.fullname),
  924. "commits",
  925. branch,
  926. )
  927. email_body = """
  928. The following commits were pushed to the repo %s on branch
  929. %s, which you are following:
  930. %s
  931. To view more about the commits, visit:
  932. %s
  933. """ % (
  934. project.fullname,
  935. branch,
  936. commits_string,
  937. commit_url,
  938. )
  939. mail_to = _get_emails_for_commit_notification(project)
  940. send_email(
  941. email_body,
  942. 'New Commits To "{0}" ({1})'.format(project.fullname, branch),
  943. ",".join(mail_to),
  944. project_name=project.fullname,
  945. )
  946. def notify_commit_flag(flag, user):
  947. """ Notify the people following a project that a new flag was added
  948. to one of its commit.
  949. """
  950. text = """
  951. %s flagged the commit `%s` as %s: %s
  952. %s
  953. """ % (
  954. flag.username,
  955. flag.commit_hash,
  956. flag.status,
  957. flag.comment,
  958. _build_url(
  959. pagure_config["APP_URL"],
  960. _fullname_to_url(flag.project.fullname),
  961. "c",
  962. flag.commit_hash,
  963. ),
  964. )
  965. mail_to = _get_emails_for_obj(flag)
  966. send_email(
  967. text,
  968. "Commit #%s - %s: %s" % (flag.commit_hash, flag.username, flag.status),
  969. ",".join(mail_to),
  970. mail_id=flag.mail_id,
  971. in_reply_to=flag.project.mail_id,
  972. project_name=flag.project.fullname,
  973. user_from=flag.username,
  974. )