notifier.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import typing
  4. from email.mime.multipart import MIMEMultipart
  5. from email.mime.text import MIMEText
  6. from email.utils import formataddr
  7. from lxml.html.diff import htmldiff
  8. from mako.template import Template
  9. from sqlalchemy.orm import Session
  10. from tracim_backend import CFG
  11. from tracim_backend.lib.core.notifications import INotifier
  12. from tracim_backend.lib.mail_notifier.sender import EmailSender
  13. from tracim_backend.lib.mail_notifier.utils import SmtpConfiguration, EST
  14. from tracim_backend.lib.mail_notifier.sender import send_email_through
  15. from tracim_backend.lib.core.workspace import WorkspaceApi
  16. from tracim_backend.lib.utils.logger import logger
  17. from tracim_backend.models import User
  18. from tracim_backend.models.auth import User
  19. from tracim_backend.models.contents import CONTENT_TYPES
  20. from tracim_backend.models.data import ActionDescription
  21. from tracim_backend.models.data import Content
  22. from tracim_backend.models.data import UserRoleInWorkspace
  23. from tracim_backend.lib.utils.translation import fake_translator as l_, \
  24. fake_translator as _
  25. class EmailNotifier(INotifier):
  26. """
  27. EmailNotifier, this class will decide how to notify by mail
  28. in order to let a EmailManager create email
  29. """
  30. def __init__(
  31. self,
  32. config: CFG,
  33. session: Session,
  34. current_user: User=None
  35. ):
  36. """
  37. :param current_user: the user that has triggered the notification
  38. :return:
  39. """
  40. INotifier.__init__(self, config, session, current_user)
  41. logger.info(self, 'Instantiating Email Notifier')
  42. self._user = current_user
  43. self.session = session
  44. self.config = config
  45. self._smtp_config = SmtpConfiguration(
  46. self.config.EMAIL_NOTIFICATION_SMTP_SERVER,
  47. self.config.EMAIL_NOTIFICATION_SMTP_PORT,
  48. self.config.EMAIL_NOTIFICATION_SMTP_USER,
  49. self.config.EMAIL_NOTIFICATION_SMTP_PASSWORD
  50. )
  51. def notify_content_update(self, content: Content):
  52. if content.get_last_action().id not \
  53. in self.config.EMAIL_NOTIFICATION_NOTIFIED_EVENTS:
  54. logger.info(
  55. self,
  56. 'Skip email notification for update of content {}'
  57. 'by user {} (the action is {})'.format(
  58. content.content_id,
  59. # below: 0 means "no user"
  60. self._user.user_id if self._user else 0,
  61. content.get_last_action().id
  62. )
  63. )
  64. return
  65. logger.info(self,
  66. 'About to email-notify update'
  67. 'of content {} by user {}'.format(
  68. content.content_id,
  69. # Below: 0 means "no user"
  70. self._user.user_id if self._user else 0
  71. )
  72. )
  73. if content.type not \
  74. in self.config.EMAIL_NOTIFICATION_NOTIFIED_CONTENTS:
  75. logger.info(
  76. self,
  77. 'Skip email notification for update of content {}'
  78. 'by user {} (the content type is {})'.format(
  79. content.type,
  80. # below: 0 means "no user"
  81. self._user.user_id if self._user else 0,
  82. content.get_last_action().id
  83. )
  84. )
  85. return
  86. logger.info(self,
  87. 'About to email-notify update'
  88. 'of content {} by user {}'.format(
  89. content.content_id,
  90. # Below: 0 means "no user"
  91. self._user.user_id if self._user else 0
  92. )
  93. )
  94. ####
  95. #
  96. # INFO - D.A. - 2014-11-05 - Emails are sent through asynchronous jobs.
  97. # For that reason, we do not give SQLAlchemy objects but ids only
  98. # (SQLA objects are related to a given thread/session)
  99. #
  100. try:
  101. if self.config.EMAIL_NOTIFICATION_PROCESSING_MODE.lower() == self.config.CST.ASYNC.lower():
  102. logger.info(self, 'Sending email in ASYNC mode')
  103. # TODO - D.A - 2014-11-06
  104. # This feature must be implemented in order to be able to scale to large communities
  105. raise NotImplementedError('Sending emails through ASYNC mode is not working yet')
  106. else:
  107. logger.info(self, 'Sending email in SYNC mode')
  108. EmailManager(
  109. self._smtp_config,
  110. self.config,
  111. self.session,
  112. ).notify_content_update(self._user.user_id, content.content_id)
  113. except TypeError as e:
  114. logger.error(self, 'Exception catched during email notification: {}'.format(e.__str__()))
  115. class EmailManager(object):
  116. """
  117. Compared to Notifier, this class is independant from the HTTP request thread
  118. This class will build Email and send it for both created account and content
  119. update
  120. """
  121. def __init__(
  122. self,
  123. smtp_config: SmtpConfiguration,
  124. config: CFG,
  125. session: Session
  126. ) -> None:
  127. self._smtp_config = smtp_config
  128. self.config = config
  129. self.session = session
  130. # FIXME - G.M - We need to have a session for the emailNotifier
  131. # if not self.session:
  132. # engine = get_engine(settings)
  133. # session_factory = get_session_factory(engine)
  134. # app_config = CFG(settings)
  135. def _get_sender(self, user: User=None) -> str:
  136. """
  137. Return sender string like "Bob Dylan
  138. (via Tracim) <notification@mail.com>"
  139. :param user: user to extract display name
  140. :return: sender string
  141. """
  142. email_template = self.config.EMAIL_NOTIFICATION_FROM_EMAIL
  143. mail_sender_name = self.config.EMAIL_NOTIFICATION_FROM_DEFAULT_LABEL # nopep8
  144. if user:
  145. mail_sender_name = '{name} via Tracim'.format(name=user.display_name)
  146. email_address = email_template.replace('{user_id}', str(user.user_id))
  147. # INFO - D.A. - 2017-08-04
  148. # We use email_template.replace() instead of .format() because this
  149. # method is more robust to errors in config file.
  150. #
  151. # For example, if the email is info+{userid}@tracim.fr
  152. # email.format(user_id='bob') will raise an exception
  153. # email.replace('{user_id}', 'bob') will just ignore {userid}
  154. else:
  155. email_address = email_template.replace('{user_id}', '0')
  156. return formataddr((mail_sender_name, email_address))
  157. # Content Notification
  158. @staticmethod
  159. def log_notification(
  160. config: CFG,
  161. action: str,
  162. recipient: typing.Optional[str],
  163. subject: typing.Optional[str],
  164. ) -> None:
  165. """Log notification metadata."""
  166. log_path = config.EMAIL_NOTIFICATION_LOG_FILE_PATH
  167. if log_path:
  168. # TODO - A.P - 2017-09-06 - file logging inefficiency
  169. # Updating a document with 100 users to notify will leads to open
  170. # and close the file 100 times.
  171. with open(log_path, 'a') as log_file:
  172. print(
  173. datetime.datetime.now(),
  174. action,
  175. recipient,
  176. subject,
  177. sep='|',
  178. file=log_file,
  179. )
  180. def notify_content_update(
  181. self,
  182. event_actor_id: int,
  183. event_content_id: int
  184. ) -> None:
  185. """
  186. Look for all users to be notified about the new content and send them an
  187. individual email
  188. :param event_actor_id: id of the user that has triggered the event
  189. :param event_content_id: related content_id
  190. :return:
  191. """
  192. # FIXME - D.A. - 2014-11-05
  193. # Dirty import. It's here in order to avoid circular import
  194. from tracim_backend.lib.core.content import ContentApi
  195. from tracim_backend.lib.core.user import UserApi
  196. user = UserApi(
  197. None,
  198. config=self.config,
  199. session=self.session,
  200. ).get_one(event_actor_id)
  201. logger.debug(self, 'Content: {}'.format(event_content_id))
  202. content_api = ContentApi(
  203. current_user=user,
  204. session=self.session,
  205. config=self.config,
  206. )
  207. content = ContentApi(
  208. session=self.session,
  209. current_user=user, # TODO - use a system user instead of the user that has triggered the event
  210. config=self.config,
  211. show_archived=True,
  212. show_deleted=True,
  213. ).get_one(event_content_id, CONTENT_TYPES.Any_SLUG)
  214. main_content = content.parent if content.type == CONTENT_TYPES.Comment.slug else content
  215. notifiable_roles = WorkspaceApi(
  216. current_user=user,
  217. session=self.session,
  218. config=self.config,
  219. ).get_notifiable_roles(content.workspace)
  220. if len(notifiable_roles) <= 0:
  221. logger.info(self, 'Skipping notification as nobody subscribed to in workspace {}'.format(content.workspace.label))
  222. return
  223. logger.info(self, 'Sending asynchronous emails to {} user(s)'.format(len(notifiable_roles)))
  224. # INFO - D.A. - 2014-11-06
  225. # The following email sender will send emails in the async task queue
  226. # This allow to build all mails through current thread but really send them (including SMTP connection)
  227. # In the other thread.
  228. #
  229. # This way, the webserver will return sooner (actually before notification emails are sent
  230. async_email_sender = EmailSender(
  231. self.config,
  232. self._smtp_config,
  233. self.config.EMAIL_NOTIFICATION_ACTIVATED
  234. )
  235. for role in notifiable_roles:
  236. logger.info(self, 'Sending email to {}'.format(role.user.email))
  237. to_addr = formataddr((role.user.display_name, role.user.email))
  238. #
  239. # INFO - G.M - 2017-11-15 - set content_id in header to permit reply
  240. # references can have multiple values, but only one in this case.
  241. replyto_addr = self.config.EMAIL_NOTIFICATION_REPLY_TO_EMAIL.replace( # nopep8
  242. '{content_id}',str(content.content_id)
  243. )
  244. reference_addr = self.config.EMAIL_NOTIFICATION_REFERENCES_EMAIL.replace( #nopep8
  245. '{content_id}',str(content.content_id)
  246. )
  247. #
  248. # INFO - D.A. - 2014-11-06
  249. # We do not use .format() here because the subject defined in the .ini file
  250. # may not include all required labels. In order to avoid partial format() (which result in an exception)
  251. # we do use replace and force the use of .__str__() in order to process LazyString objects
  252. #
  253. subject = self.config.EMAIL_NOTIFICATION_CONTENT_UPDATE_SUBJECT
  254. subject = subject.replace(EST.WEBSITE_TITLE, self.config.WEBSITE_TITLE.__str__())
  255. subject = subject.replace(EST.WORKSPACE_LABEL, main_content.workspace.label.__str__())
  256. subject = subject.replace(EST.CONTENT_LABEL, main_content.label.__str__())
  257. subject = subject.replace(EST.CONTENT_STATUS_LABEL, main_content.get_status().label.__str__())
  258. reply_to_label = l_('{username} & all members of {workspace}').format(
  259. username=user.display_name,
  260. workspace=main_content.workspace.label)
  261. message = MIMEMultipart('alternative')
  262. message['Subject'] = subject
  263. message['From'] = self._get_sender(user)
  264. message['To'] = to_addr
  265. message['Reply-to'] = formataddr((reply_to_label, replyto_addr))
  266. # INFO - G.M - 2017-11-15
  267. # References can theorically have label, but in pratice, references
  268. # contains only message_id from parents post in thread.
  269. # To link this email to a content we create a virtual parent
  270. # in reference who contain the content_id.
  271. message['References'] = formataddr(('',reference_addr))
  272. body_text = self._build_email_body_for_content(self.config.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_TEXT, role, content, user)
  273. body_html = self._build_email_body_for_content(self.config.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_HTML, role, content, user)
  274. part1 = MIMEText(body_text, 'plain', 'utf-8')
  275. part2 = MIMEText(body_html, 'html', 'utf-8')
  276. # Attach parts into message container.
  277. # According to RFC 2046, the last part of a multipart message, in this case
  278. # the HTML message, is best and preferred.
  279. message.attach(part1)
  280. message.attach(part2)
  281. self.log_notification(
  282. action='CREATED',
  283. recipient=message['To'],
  284. subject=message['Subject'],
  285. config=self.config,
  286. )
  287. send_email_through(
  288. self.config,
  289. async_email_sender.send_mail,
  290. message
  291. )
  292. def notify_created_account(
  293. self,
  294. user: User,
  295. password: str,
  296. ) -> None:
  297. """
  298. Send created account email to given user.
  299. :param password: choosed password
  300. :param user: user to notify
  301. """
  302. # TODO BS 20160712: Cyclic import
  303. logger.debug(self, 'user: {}'.format(user.user_id))
  304. logger.info(self, 'Sending asynchronous email to 1 user ({0})'.format(
  305. user.email,
  306. ))
  307. async_email_sender = EmailSender(
  308. self.config,
  309. self._smtp_config,
  310. self.config.EMAIL_NOTIFICATION_ACTIVATED
  311. )
  312. subject = \
  313. self.config.EMAIL_NOTIFICATION_CREATED_ACCOUNT_SUBJECT \
  314. .replace(
  315. EST.WEBSITE_TITLE,
  316. self.config.WEBSITE_TITLE.__str__()
  317. )
  318. message = MIMEMultipart('alternative')
  319. message['Subject'] = subject
  320. message['From'] = self._get_sender()
  321. message['To'] = formataddr((user.get_display_name(), user.email))
  322. text_template_file_path = self.config.EMAIL_NOTIFICATION_CREATED_ACCOUNT_TEMPLATE_TEXT # nopep8
  323. html_template_file_path = self.config.EMAIL_NOTIFICATION_CREATED_ACCOUNT_TEMPLATE_HTML # nopep8
  324. context = {
  325. 'user': user,
  326. 'password': password,
  327. # TODO - G.M - 11-06-2018 - [emailTemplateURL] correct value for logo_url # nopep8
  328. 'logo_url': '',
  329. # TODO - G.M - 11-06-2018 - [emailTemplateURL] correct value for login_url # nopep8
  330. 'login_url': self.config.WEBSITE_BASE_URL,
  331. }
  332. body_text = self._render_template(
  333. mako_template_filepath=text_template_file_path,
  334. context=context
  335. )
  336. body_html = self._render_template(
  337. mako_template_filepath=html_template_file_path,
  338. context=context,
  339. )
  340. part1 = MIMEText(body_text, 'plain', 'utf-8')
  341. part2 = MIMEText(body_html, 'html', 'utf-8')
  342. # Attach parts into message container.
  343. # According to RFC 2046, the last part of a multipart message,
  344. # in this case the HTML message, is best and preferred.
  345. message.attach(part1)
  346. message.attach(part2)
  347. send_email_through(
  348. config=self.config,
  349. sendmail_callable=async_email_sender.send_mail,
  350. message=message
  351. )
  352. def _render_template(
  353. self,
  354. mako_template_filepath: str,
  355. context: dict
  356. ) -> str:
  357. """
  358. Render mako template with all needed current variables.
  359. :param mako_template_filepath: file path of mako template
  360. :param context: dict with template context
  361. :return: template rendered string
  362. """
  363. template = Template(filename=mako_template_filepath)
  364. return template.render(
  365. _=_,
  366. config=self.config,
  367. **context
  368. )
  369. def _build_email_body_for_content(
  370. self,
  371. mako_template_filepath: str,
  372. role: UserRoleInWorkspace,
  373. content: Content,
  374. actor: User
  375. ) -> str:
  376. """
  377. Build an email body and return it as a string
  378. :param mako_template_filepath: the absolute path to the mako template to be used for email body building
  379. :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
  380. :param content: the content item related to the notification
  381. :param actor: the user at the origin of the action / notification (for example the one who wrote a comment
  382. :param config: the global configuration
  383. :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
  384. """
  385. logger.debug(self, 'Building email content from MAKO template {}'.format(mako_template_filepath))
  386. main_title = content.label
  387. content_intro = ''
  388. content_text = ''
  389. call_to_action_text = ''
  390. # TODO - G.M - 11-06-2018 - [emailTemplateURL] correct value for call_to_action_url # nopep8
  391. call_to_action_url =''
  392. # TODO - G.M - 11-06-2018 - [emailTemplateURL] correct value for status_icon_url # nopep8
  393. status_icon_url = ''
  394. # TODO - G.M - 11-06-2018 - [emailTemplateURL] correct value for workspace_url # nopep8
  395. workspace_url = ''
  396. # TODO - G.M - 11-06-2018 - [emailTemplateURL] correct value for logo_url # nopep8
  397. logo_url = ''
  398. action = content.get_last_action().id
  399. if ActionDescription.COMMENT == action:
  400. content_intro = l_('<span id="content-intro-username">{}</span> added a comment:').format(actor.display_name)
  401. content_text = content.description
  402. call_to_action_text = l_('Answer')
  403. elif ActionDescription.CREATION == action:
  404. # Default values (if not overriden)
  405. content_text = content.description
  406. call_to_action_text = l_('View online')
  407. if CONTENT_TYPES.Thread.slug == content.type:
  408. call_to_action_text = l_('Answer')
  409. content_intro = l_('<span id="content-intro-username">{}</span> started a thread entitled:').format(actor.display_name)
  410. content_text = '<p id="content-body-intro">{}</p>'.format(content.label) + \
  411. content.get_last_comment_from(actor).description
  412. elif CONTENT_TYPES.File.slug == content.type:
  413. content_intro = l_('<span id="content-intro-username">{}</span> added a file entitled:').format(actor.display_name)
  414. if content.description:
  415. content_text = content.description
  416. else:
  417. content_text = '<span id="content-body-only-title">{}</span>'.format(content.label)
  418. elif CONTENT_TYPES.Page.slug == content.type:
  419. content_intro = l_('<span id="content-intro-username">{}</span> added a page entitled:').format(actor.display_name)
  420. content_text = '<span id="content-body-only-title">{}</span>'.format(content.label)
  421. elif ActionDescription.REVISION == action:
  422. content_text = content.description
  423. call_to_action_text = l_('View online')
  424. if CONTENT_TYPES.File.slug == content.type:
  425. content_intro = l_('<span id="content-intro-username">{}</span> uploaded a new revision.').format(actor.display_name)
  426. content_text = ''
  427. elif CONTENT_TYPES.Page.slug == content.type:
  428. content_intro = l_('<span id="content-intro-username">{}</span> updated this page.').format(actor.display_name)
  429. previous_revision = content.get_previous_revision()
  430. title_diff = ''
  431. if previous_revision.label != content.label:
  432. title_diff = htmldiff(previous_revision.label, content.label)
  433. content_text = str(l_('<p id="content-body-intro">Here is an overview of the changes:</p>'))+ \
  434. title_diff + \
  435. htmldiff(previous_revision.description, content.description)
  436. elif CONTENT_TYPES.Thread.slug == content.type:
  437. content_intro = l_('<span id="content-intro-username">{}</span> updated the thread description.').format(actor.display_name)
  438. previous_revision = content.get_previous_revision()
  439. title_diff = ''
  440. if previous_revision.label != content.label:
  441. title_diff = htmldiff(previous_revision.label, content.label)
  442. content_text = str(l_('<p id="content-body-intro">Here is an overview of the changes:</p>'))+ \
  443. title_diff + \
  444. htmldiff(previous_revision.description, content.description)
  445. elif ActionDescription.EDITION == action:
  446. call_to_action_text = l_('View online')
  447. if CONTENT_TYPES.File.slug == content.type:
  448. content_intro = l_('<span id="content-intro-username">{}</span> updated the file description.').format(actor.display_name)
  449. content_text = '<p id="content-body-intro">{}</p>'.format(content.get_label()) + \
  450. content.description
  451. elif ActionDescription.STATUS_UPDATE == action:
  452. call_to_action_text = l_('View online')
  453. intro_user_msg = l_(
  454. '<span id="content-intro-username">{}</span> '
  455. 'updated the following status:'
  456. )
  457. content_intro = intro_user_msg.format(actor.display_name)
  458. intro_body_msg = '<p id="content-body-intro">{}: {}</p>'
  459. content_text = intro_body_msg.format(
  460. content.get_label(),
  461. content.get_status().label,
  462. )
  463. if '' == content_intro and content_text == '':
  464. # Skip notification, but it's not normal
  465. logger.error(
  466. self, 'A notification is being sent but no content. '
  467. 'Here are some debug informations: [content_id: {cid}]'
  468. '[action: {act}][author: {actor}]'.format(
  469. cid=content.content_id, act=action, actor=actor
  470. )
  471. )
  472. raise ValueError('Unexpected empty notification')
  473. context = {
  474. 'user': role.user,
  475. 'workspace': role.workspace,
  476. 'workspace_url': workspace_url,
  477. 'main_title': main_title,
  478. 'status_label': content.get_status().label,
  479. 'status_icon_url': status_icon_url,
  480. 'role_label': role.role_as_label(),
  481. 'content_intro': content_intro,
  482. 'content_text': content_text,
  483. 'call_to_action_text': call_to_action_text,
  484. 'call_to_action_url': call_to_action_url,
  485. 'logo_url': logo_url,
  486. }
  487. user = role.user
  488. workspace = role.workspace
  489. body_content = self._render_template(
  490. mako_template_filepath=mako_template_filepath,
  491. context=context,
  492. )
  493. return body_content
  494. def get_email_manager(config: CFG, session: Session):
  495. """
  496. :return: EmailManager instance
  497. """
  498. #  TODO: Find a way to import properly without cyclic import
  499. smtp_config = SmtpConfiguration(
  500. config.EMAIL_NOTIFICATION_SMTP_SERVER,
  501. config.EMAIL_NOTIFICATION_SMTP_PORT,
  502. config.EMAIL_NOTIFICATION_SMTP_USER,
  503. config.EMAIL_NOTIFICATION_SMTP_PASSWORD
  504. )
  505. return EmailManager(config=config, smtp_config=smtp_config, session=session)