notifications.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. from email.header import Header
  4. from email.mime.multipart import MIMEMultipart
  5. from email.mime.text import MIMEText
  6. import lxml
  7. from lxml.html.diff import htmldiff
  8. from mako.template import Template
  9. from tracim.lib.base import logger
  10. from tracim.lib.email import SmtpConfiguration
  11. from tracim.lib.email import send_email_through
  12. from tracim.lib.email import EmailSender
  13. from tracim.lib.user import UserApi
  14. from tracim.lib.workspace import WorkspaceApi
  15. from tracim.lib.utils import lazy_ugettext as l_
  16. from tracim.model.serializers import Context
  17. from tracim.model.serializers import CTX
  18. from tracim.model.serializers import DictLikeClass
  19. from tracim.model.data import Content, UserRoleInWorkspace, ContentType, \
  20. ActionDescription
  21. from tracim.model.auth import User
  22. class INotifier(object):
  23. """
  24. Interface for Notifier instances
  25. """
  26. def __init__(self, current_user: User=None):
  27. pass
  28. def notify_content_update(self, content: Content):
  29. raise NotImplementedError
  30. class NotifierFactory(object):
  31. @classmethod
  32. def create(cls, current_user: User=None) -> INotifier:
  33. # TODO: Find a way to import properly without cyclic import
  34. from tracim.config.app_cfg import CFG
  35. cfg = CFG.get_instance()
  36. if not cfg.EMAIL_NOTIFICATION_ACTIVATED:
  37. return DummyNotifier(current_user)
  38. return RealNotifier(current_user)
  39. class DummyNotifier(INotifier):
  40. send_count = 0
  41. def __init__(self, current_user: User=None):
  42. logger.info(self, 'Instantiating Dummy Notifier')
  43. def notify_content_update(self, content: Content):
  44. type(self).send_count += 1
  45. logger.info(self, 'Fake notifier, do not send email-notification for update of content {}'.format(content.content_id))
  46. class RealNotifier(object):
  47. def __init__(self, current_user: User=None):
  48. """
  49. :param current_user: the user that has triggered the notification
  50. :return:
  51. """
  52. logger.info(self, 'Instantiating Real Notifier')
  53. # TODO: Find a way to import properly without cyclic import
  54. from tracim.config.app_cfg import CFG
  55. cfg = CFG.get_instance()
  56. self._user = current_user
  57. self._smtp_config = SmtpConfiguration(cfg.EMAIL_NOTIFICATION_SMTP_SERVER,
  58. cfg.EMAIL_NOTIFICATION_SMTP_PORT,
  59. cfg.EMAIL_NOTIFICATION_SMTP_USER,
  60. cfg.EMAIL_NOTIFICATION_SMTP_PASSWORD)
  61. def notify_content_update(self, content: Content):
  62. # TODO: Find a way to import properly without cyclic import
  63. from tracim.config.app_cfg import CFG
  64. global_config = CFG.get_instance()
  65. if content.get_last_action().id not \
  66. in global_config.EMAIL_NOTIFICATION_NOTIFIED_EVENTS:
  67. logger.info(
  68. self,
  69. 'Skip email notification for update of content {}'
  70. 'by user {} (the action is {})'.format(
  71. content.content_id,
  72. # below: 0 means "no user"
  73. self._user.user_id if self._user else 0,
  74. content.get_last_action().id
  75. )
  76. )
  77. return
  78. logger.info(self,
  79. 'About to email-notify update'
  80. 'of content {} by user {}'.format(
  81. content.content_id,
  82. # Below: 0 means "no user"
  83. self._user.user_id if self._user else 0
  84. )
  85. )
  86. if content.type not \
  87. in global_config.EMAIL_NOTIFICATION_NOTIFIED_CONTENTS:
  88. logger.info(
  89. self,
  90. 'Skip email notification for update of content {}'
  91. 'by user {} (the content type is {})'.format(
  92. content.type,
  93. # below: 0 means "no user"
  94. self._user.user_id if self._user else 0,
  95. content.get_last_action().id
  96. )
  97. )
  98. return
  99. logger.info(self,
  100. 'About to email-notify update'
  101. 'of content {} by user {}'.format(
  102. content.content_id,
  103. # Below: 0 means "no user"
  104. self._user.user_id if self._user else 0
  105. )
  106. )
  107. ####
  108. #
  109. # INFO - D.A. - 2014-11-05 - Emails are sent through asynchronous jobs.
  110. # For that reason, we do not give SQLAlchemy objects but ids only
  111. # (SQLA objects are related to a given thread/session)
  112. #
  113. try:
  114. if global_config.EMAIL_NOTIFICATION_PROCESSING_MODE.lower()==global_config.CST.ASYNC.lower():
  115. logger.info(self, 'Sending email in ASYNC mode')
  116. # TODO - D.A - 2014-11-06
  117. # This feature must be implemented in order to be able to scale to large communities
  118. raise NotImplementedError('Sending emails through ASYNC mode is not working yet')
  119. else:
  120. logger.info(self, 'Sending email in SYNC mode')
  121. EmailNotifier(self._smtp_config, global_config).notify_content_update(self._user.user_id, content.content_id)
  122. except Exception as e:
  123. logger.error(self, 'Exception catched during email notification: {}'.format(e.__str__()))
  124. class EST(object):
  125. """
  126. EST = Email Subject Tags - this is a convenient class - no business logic here
  127. This class is intended to agregate all dynamic content that may be included in email subjects
  128. """
  129. WEBSITE_TITLE = '{website_title}'
  130. WORKSPACE_LABEL = '{workspace_label}'
  131. CONTENT_LABEL = '{content_label}'
  132. CONTENT_STATUS_LABEL = '{content_status_label}'
  133. @classmethod
  134. def all(cls):
  135. return [
  136. cls.CONTENT_LABEL,
  137. cls.CONTENT_STATUS_LABEL,
  138. cls.WEBSITE_TITLE,
  139. cls.WORKSPACE_LABEL
  140. ]
  141. class EmailNotifier(object):
  142. """
  143. Compared to Notifier, this class is independant from the HTTP request thread
  144. TODO: Do this class really independant (but it means to get as parameter the user language
  145. and other stuff related to the turbogears environment)
  146. """
  147. def __init__(self, smtp_config: SmtpConfiguration, global_config):
  148. self._smtp_config = smtp_config
  149. self._global_config = global_config
  150. def _get_sender(self, user: User=None) -> str:
  151. """
  152. Return sender string like "Bob Dylan
  153. (via Tracim) <notification@mail.com>"
  154. :param user: user to extract display name
  155. :return: sender string
  156. """
  157. email_template = self._global_config.EMAIL_NOTIFICATION_FROM_EMAIL
  158. mail_sender_name = self._global_config.EMAIL_NOTIFICATION_FROM_DEFAULT_LABEL # nopep8
  159. if user:
  160. mail_sender_name = '{name} via Tracim'.format(name=user.display_name)
  161. email_address = email_template.replace('{user_id}', str(user.user_id))
  162. # INFO - D.A. - 2017-08-04
  163. # We use email_template.replace() instead of .format() because this
  164. # method is more robust to errors in config file.
  165. #
  166. # For example, if the email is info+{userid}@tracim.fr
  167. # email.format(user_id='bob') will raise an exception
  168. # email.replace('{user_id}', 'bob') will just ignore {userid}
  169. else:
  170. email_address = email_template.replace('{user_id}', '0')
  171. return '{label} <{email_address}>'.format(
  172. label = Header(mail_sender_name).encode(),
  173. email_address = email_address
  174. )
  175. @staticmethod
  176. def _log_notification(
  177. recipient: str,
  178. subject: str
  179. ) -> None:
  180. """Log notification metadata."""
  181. from tracim.config.app_cfg import CFG
  182. log_path = CFG.get_instance().EMAIL_NOTIFICATION_LOG_FILE_PATH
  183. if log_path:
  184. with open(log_path, 'a') as log_file:
  185. print(
  186. datetime.datetime.now(),
  187. recipient,
  188. subject,
  189. sep='|',
  190. file=log_file,
  191. )
  192. def notify_content_update(self, event_actor_id: int, event_content_id: int):
  193. """
  194. Look for all users to be notified about the new content and send them an individual email
  195. :param event_actor_id: id of the user that has triggered the event
  196. :param event_content_id: related content_id
  197. :return:
  198. """
  199. # FIXME - D.A. - 2014-11-05
  200. # Dirty import. It's here in order to avoid circular import
  201. from tracim.lib.content import ContentApi
  202. user = UserApi(None).get_one(event_actor_id)
  203. logger.debug(self, 'Content: {}'.format(event_content_id))
  204. content = ContentApi(user, show_archived=True, show_deleted=True).get_one(event_content_id, ContentType.Any) # TODO - use a system user instead of the user that has triggered the event
  205. main_content = content.parent if content.type==ContentType.Comment else content
  206. notifiable_roles = WorkspaceApi(user).get_notifiable_roles(content.workspace)
  207. if len(notifiable_roles)<=0:
  208. logger.info(self, 'Skipping notification as nobody subscribed to in workspace {}'.format(content.workspace.label))
  209. return
  210. logger.info(self, 'Sending asynchronous emails to {} user(s)'.format(len(notifiable_roles)))
  211. # INFO - D.A. - 2014-11-06
  212. # The following email sender will send emails in the async task queue
  213. # This allow to build all mails through current thread but really send them (including SMTP connection)
  214. # In the other thread.
  215. #
  216. # This way, the webserver will return sooner (actually before notification emails are sent
  217. async_email_sender = EmailSender(self._smtp_config, self._global_config.EMAIL_NOTIFICATION_ACTIVATED)
  218. for role in notifiable_roles:
  219. logger.info(self, 'Sending email to {}'.format(role.user.email))
  220. to_addr = '{name} <{email}>'.format(name=role.user.display_name, email=role.user.email)
  221. #
  222. # INFO - D.A. - 2014-11-06
  223. # We do not use .format() here because the subject defined in the .ini file
  224. # may not include all required labels. In order to avoid partial format() (which result in an exception)
  225. # we do use replace and force the use of .__str__() in order to process LazyString objects
  226. #
  227. subject = self._global_config.EMAIL_NOTIFICATION_CONTENT_UPDATE_SUBJECT
  228. subject = subject.replace(EST.WEBSITE_TITLE, self._global_config.WEBSITE_TITLE.__str__())
  229. subject = subject.replace(EST.WORKSPACE_LABEL, main_content.workspace.label.__str__())
  230. subject = subject.replace(EST.CONTENT_LABEL, main_content.label.__str__())
  231. subject = subject.replace(EST.CONTENT_STATUS_LABEL, main_content.get_status().label.__str__())
  232. message = MIMEMultipart('alternative')
  233. message['Subject'] = subject
  234. message['From'] = self._get_sender(user)
  235. message['To'] = to_addr
  236. body_text = self._build_email_body(self._global_config.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_TEXT, role, content, user)
  237. body_html = self._build_email_body(self._global_config.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_HTML, role, content, user)
  238. part1 = MIMEText(body_text, 'plain', 'utf-8')
  239. part2 = MIMEText(body_html, 'html', 'utf-8')
  240. # Attach parts into message container.
  241. # According to RFC 2046, the last part of a multipart message, in this case
  242. # the HTML message, is best and preferred.
  243. message.attach(part1)
  244. message.attach(part2)
  245. self._log_notification(
  246. recipient=message['for'],
  247. subject=message['Subject'],
  248. )
  249. send_email_through(async_email_sender.send_mail, message)
  250. def _build_email_body(self, mako_template_filepath: str, role: UserRoleInWorkspace, content: Content, actor: User) -> str:
  251. """
  252. Build an email body and return it as a string
  253. :param mako_template_filepath: the absolute path to the mako template to be used for email body building
  254. :param role: the role related to user to whom the email must be sent. The role is required (and not the user only) in order to show in the mail why the user receive the notification
  255. :param content: the content item related to the notification
  256. :param actor: the user at the origin of the action / notification (for example the one who wrote a comment
  257. :param config: the global configuration
  258. :return: the built email body as string. In case of multipart email, this method must be called one time for text and one time for html
  259. """
  260. logger.debug(self, 'Building email content from MAKO template {}'.format(mako_template_filepath))
  261. template = Template(filename=mako_template_filepath)
  262. # TODO - D.A. - 2014-11-06 - move this
  263. # Import is here for circular import problem
  264. import tracim.lib.helpers as helpers
  265. dictified_item = Context(CTX.EMAIL_NOTIFICATION, self._global_config.WEBSITE_BASE_URL).toDict(content)
  266. dictified_actor = Context(CTX.DEFAULT).toDict(actor)
  267. main_title = dictified_item.label
  268. content_intro = ''
  269. content_text = ''
  270. call_to_action_text = ''
  271. action = content.get_last_action().id
  272. if ActionDescription.COMMENT == action:
  273. content_intro = l_('<span id="content-intro-username">{}</span> added a comment:').format(actor.display_name)
  274. content_text = content.description
  275. call_to_action_text = l_('Answer')
  276. elif ActionDescription.CREATION == action:
  277. # Default values (if not overriden)
  278. content_text = content.description
  279. call_to_action_text = l_('View online')
  280. if ContentType.Thread == content.type:
  281. call_to_action_text = l_('Answer')
  282. content_intro = l_('<span id="content-intro-username">{}</span> started a thread entitled:').format(actor.display_name)
  283. content_text = '<p id="content-body-intro">{}</p>'.format(content.label) + \
  284. content.get_last_comment_from(actor).description
  285. elif ContentType.File == content.type:
  286. content_intro = l_('<span id="content-intro-username">{}</span> added a file entitled:').format(actor.display_name)
  287. if content.description:
  288. content_text = content.description
  289. else:
  290. content_text = '<span id="content-body-only-title">{}</span>'.format(content.label)
  291. elif ContentType.Page == content.type:
  292. content_intro = l_('<span id="content-intro-username">{}</span> added a page entitled:').format(actor.display_name)
  293. content_text = '<span id="content-body-only-title">{}</span>'.format(content.label)
  294. elif ActionDescription.REVISION == action:
  295. content_text = content.description
  296. call_to_action_text = l_('View online')
  297. if ContentType.File == content.type:
  298. content_intro = l_('<span id="content-intro-username">{}</span> uploaded a new revision.').format(actor.display_name)
  299. content_text = ''
  300. elif ContentType.Page == content.type:
  301. content_intro = l_('<span id="content-intro-username">{}</span> updated this page.').format(actor.display_name)
  302. previous_revision = content.get_previous_revision()
  303. title_diff = ''
  304. if previous_revision.label != content.label:
  305. title_diff = htmldiff(previous_revision.label, content.label)
  306. content_text = str(l_('<p id="content-body-intro">Here is an overview of the changes:</p>'))+ \
  307. title_diff + \
  308. htmldiff(previous_revision.description, content.description)
  309. elif ContentType.Thread == content.type:
  310. content_intro = l_('<span id="content-intro-username">{}</span> updated the thread description.').format(actor.display_name)
  311. previous_revision = content.get_previous_revision()
  312. title_diff = ''
  313. if previous_revision.label != content.label:
  314. title_diff = htmldiff(previous_revision.label, content.label)
  315. content_text = str(l_('<p id="content-body-intro">Here is an overview of the changes:</p>'))+ \
  316. title_diff + \
  317. htmldiff(previous_revision.description, content.description)
  318. # elif ContentType.Thread == content.type:
  319. # content_intro = l_('<span id="content-intro-username">{}</span> updated this page.').format(actor.display_name)
  320. # previous_revision = content.get_previous_revision()
  321. # content_text = l_('<p id="content-body-intro">Here is an overview of the changes:</p>')+ \
  322. # htmldiff(previous_revision.description, content.description)
  323. elif ActionDescription.EDITION == action:
  324. call_to_action_text = l_('View online')
  325. if ContentType.File == content.type:
  326. content_intro = l_('<span id="content-intro-username">{}</span> updated the file description.').format(actor.display_name)
  327. content_text = '<p id="content-body-intro">{}</p>'.format(content.get_label()) + \
  328. content.description
  329. elif ActionDescription.STATUS_UPDATE == action:
  330. call_to_action_text = l_('View online')
  331. intro_user_msg = l_(
  332. '<span id="content-intro-username">{}</span> '
  333. 'updated the following status:'
  334. )
  335. content_intro = intro_user_msg.format(actor.display_name)
  336. intro_body_msg = '<p id="content-body-intro">{}: {}</p>'
  337. content_text = intro_body_msg.format(
  338. content.get_label(),
  339. content.get_status().label,
  340. )
  341. if '' == content_intro and content_text == '':
  342. # Skip notification, but it's not normal
  343. logger.error(
  344. self, 'A notification is being sent but no content. '
  345. 'Here are some debug informations: [content_id: {cid}]'
  346. '[action: {act}][author: {actor}]'.format(
  347. cid=content.content_id, act=action, actor=actor
  348. )
  349. )
  350. raise ValueError('Unexpected empty notification')
  351. # Import done here because cyclic import
  352. from tracim.config.app_cfg import CFG
  353. body_content = template.render(
  354. base_url=self._global_config.WEBSITE_BASE_URL,
  355. _=l_,
  356. h=helpers,
  357. user_display_name=role.user.display_name,
  358. user_role_label=role.role_as_label(),
  359. workspace_label=role.workspace.label,
  360. content_intro=content_intro,
  361. content_text=content_text,
  362. main_title=main_title,
  363. call_to_action_text=call_to_action_text,
  364. result = DictLikeClass(item=dictified_item, actor=dictified_actor),
  365. CFG=CFG.get_instance(),
  366. )
  367. return body_content