notifier.py 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 import CFG
  11. from tracim.lib.core.notifications import INotifier
  12. from tracim.lib.mail_notifier.sender import EmailSender
  13. from tracim.lib.mail_notifier.utils import SmtpConfiguration, EST
  14. from tracim.lib.mail_notifier.sender import send_email_through
  15. from tracim.lib.core.workspace import WorkspaceApi
  16. from tracim.lib.utils.logger import logger
  17. from tracim.models import User
  18. from tracim.models.auth import User
  19. from tracim.models.data import ActionDescription
  20. from tracim.models.data import Content
  21. from tracim.models.data import ContentType
  22. from tracim.models.data import UserRoleInWorkspace
  23. from tracim.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.lib.core.content import ContentApi
  195. from tracim.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, ContentType.Any)
  214. main_content = content.parent if content.type == ContentType.Comment else content
  215. notifiable_roles = WorkspaceApi(
  216. current_user=user,
  217. session=self.session,
  218. ).get_notifiable_roles(content.workspace)
  219. if len(notifiable_roles) <= 0:
  220. logger.info(self, 'Skipping notification as nobody subscribed to in workspace {}'.format(content.workspace.label))
  221. return
  222. logger.info(self, 'Sending asynchronous emails to {} user(s)'.format(len(notifiable_roles)))
  223. # INFO - D.A. - 2014-11-06
  224. # The following email sender will send emails in the async task queue
  225. # This allow to build all mails through current thread but really send them (including SMTP connection)
  226. # In the other thread.
  227. #
  228. # This way, the webserver will return sooner (actually before notification emails are sent
  229. async_email_sender = EmailSender(
  230. self.config,
  231. self._smtp_config,
  232. self.config.EMAIL_NOTIFICATION_ACTIVATED
  233. )
  234. for role in notifiable_roles:
  235. logger.info(self, 'Sending email to {}'.format(role.user.email))
  236. to_addr = formataddr((role.user.display_name, role.user.email))
  237. #
  238. # INFO - G.M - 2017-11-15 - set content_id in header to permit reply
  239. # references can have multiple values, but only one in this case.
  240. replyto_addr = self.config.EMAIL_NOTIFICATION_REPLY_TO_EMAIL.replace( # nopep8
  241. '{content_id}',str(content.content_id)
  242. )
  243. reference_addr = self.config.EMAIL_NOTIFICATION_REFERENCES_EMAIL.replace( #nopep8
  244. '{content_id}',str(content.content_id)
  245. )
  246. #
  247. # INFO - D.A. - 2014-11-06
  248. # We do not use .format() here because the subject defined in the .ini file
  249. # may not include all required labels. In order to avoid partial format() (which result in an exception)
  250. # we do use replace and force the use of .__str__() in order to process LazyString objects
  251. #
  252. subject = self.config.EMAIL_NOTIFICATION_CONTENT_UPDATE_SUBJECT
  253. subject = subject.replace(EST.WEBSITE_TITLE, self.config.WEBSITE_TITLE.__str__())
  254. subject = subject.replace(EST.WORKSPACE_LABEL, main_content.workspace.label.__str__())
  255. subject = subject.replace(EST.CONTENT_LABEL, main_content.label.__str__())
  256. subject = subject.replace(EST.CONTENT_STATUS_LABEL, main_content.get_status().label.__str__())
  257. reply_to_label = l_('{username} & all members of {workspace}').format(
  258. username=user.display_name,
  259. workspace=main_content.workspace.label)
  260. message = MIMEMultipart('alternative')
  261. message['Subject'] = subject
  262. message['From'] = self._get_sender(user)
  263. message['To'] = to_addr
  264. message['Reply-to'] = formataddr((reply_to_label, replyto_addr))
  265. # INFO - G.M - 2017-11-15
  266. # References can theorically have label, but in pratice, references
  267. # contains only message_id from parents post in thread.
  268. # To link this email to a content we create a virtual parent
  269. # in reference who contain the content_id.
  270. message['References'] = formataddr(('',reference_addr))
  271. body_text = self._build_email_body_for_content(self.config.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_TEXT, role, content, user)
  272. body_html = self._build_email_body_for_content(self.config.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_HTML, role, content, user)
  273. part1 = MIMEText(body_text, 'plain', 'utf-8')
  274. part2 = MIMEText(body_html, 'html', 'utf-8')
  275. # Attach parts into message container.
  276. # According to RFC 2046, the last part of a multipart message, in this case
  277. # the HTML message, is best and preferred.
  278. message.attach(part1)
  279. message.attach(part2)
  280. self.log_notification(
  281. action='CREATED',
  282. recipient=message['To'],
  283. subject=message['Subject'],
  284. config=self.config,
  285. )
  286. send_email_through(
  287. self.config,
  288. async_email_sender.send_mail,
  289. message
  290. )
  291. def notify_created_account(
  292. self,
  293. user: User,
  294. password: str,
  295. ) -> None:
  296. """
  297. Send created account email to given user.
  298. :param password: choosed password
  299. :param user: user to notify
  300. """
  301. # TODO BS 20160712: Cyclic import
  302. logger.debug(self, 'user: {}'.format(user.user_id))
  303. logger.info(self, 'Sending asynchronous email to 1 user ({0})'.format(
  304. user.email,
  305. ))
  306. async_email_sender = EmailSender(
  307. self.config,
  308. self._smtp_config,
  309. self.config.EMAIL_NOTIFICATION_ACTIVATED
  310. )
  311. subject = \
  312. self.config.EMAIL_NOTIFICATION_CREATED_ACCOUNT_SUBJECT \
  313. .replace(
  314. EST.WEBSITE_TITLE,
  315. self.config.WEBSITE_TITLE.__str__()
  316. )
  317. message = MIMEMultipart('alternative')
  318. message['Subject'] = subject
  319. message['From'] = self._get_sender()
  320. message['To'] = formataddr((user.get_display_name(), user.email))
  321. text_template_file_path = self.config.EMAIL_NOTIFICATION_CREATED_ACCOUNT_TEMPLATE_TEXT # nopep8
  322. html_template_file_path = self.config.EMAIL_NOTIFICATION_CREATED_ACCOUNT_TEMPLATE_HTML # nopep8
  323. body_text = self._render_template(
  324. mako_template_filepath=text_template_file_path,
  325. context={
  326. 'user': user,
  327. 'password': password,
  328. 'login_url': self.config.WEBSITE_BASE_URL,
  329. }
  330. )
  331. body_html = self._render_template(
  332. mako_template_filepath=html_template_file_path,
  333. context={
  334. 'user': user,
  335. 'password': password,
  336. 'login_url': self.config.WEBSITE_BASE_URL,
  337. }
  338. )
  339. part1 = MIMEText(body_text, 'plain', 'utf-8')
  340. part2 = MIMEText(body_html, 'html', 'utf-8')
  341. # Attach parts into message container.
  342. # According to RFC 2046, the last part of a multipart message,
  343. # in this case the HTML message, is best and preferred.
  344. message.attach(part1)
  345. message.attach(part2)
  346. send_email_through(
  347. config=self.config,
  348. sendmail_callable=async_email_sender.send_mail,
  349. message=message
  350. )
  351. def _render_template(
  352. self,
  353. mako_template_filepath: str,
  354. context: dict
  355. ) -> str:
  356. """
  357. Render mako template with all needed current variables.
  358. :param mako_template_filepath: file path of mako template
  359. :param context: dict with template context
  360. :return: template rendered string
  361. """
  362. template = Template(filename=mako_template_filepath)
  363. return template.render(
  364. _=_,
  365. config=self.config,
  366. **context
  367. )
  368. def _build_email_body_for_content(
  369. self,
  370. mako_template_filepath: str,
  371. role: UserRoleInWorkspace,
  372. content: Content,
  373. actor: User
  374. ) -> str:
  375. """
  376. Build an email body and return it as a string
  377. :param mako_template_filepath: the absolute path to the mako template to be used for email body building
  378. :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
  379. :param content: the content item related to the notification
  380. :param actor: the user at the origin of the action / notification (for example the one who wrote a comment
  381. :param config: the global configuration
  382. :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
  383. """
  384. logger.debug(self, 'Building email content from MAKO template {}'.format(mako_template_filepath))
  385. main_title = content.label
  386. content_intro = ''
  387. content_text = ''
  388. call_to_action_text = ''
  389. action = content.get_last_action().id
  390. if ActionDescription.COMMENT == action:
  391. content_intro = l_('<span id="content-intro-username">{}</span> added a comment:').format(actor.display_name)
  392. content_text = content.description
  393. call_to_action_text = l_('Answer')
  394. elif ActionDescription.CREATION == action:
  395. # Default values (if not overriden)
  396. content_text = content.description
  397. call_to_action_text = l_('View online')
  398. if ContentType.Thread == content.type:
  399. call_to_action_text = l_('Answer')
  400. content_intro = l_('<span id="content-intro-username">{}</span> started a thread entitled:').format(actor.display_name)
  401. content_text = '<p id="content-body-intro">{}</p>'.format(content.label) + \
  402. content.get_last_comment_from(actor).description
  403. elif ContentType.File == content.type:
  404. content_intro = l_('<span id="content-intro-username">{}</span> added a file entitled:').format(actor.display_name)
  405. if content.description:
  406. content_text = content.description
  407. else:
  408. content_text = '<span id="content-body-only-title">{}</span>'.format(content.label)
  409. elif ContentType.Page == content.type:
  410. content_intro = l_('<span id="content-intro-username">{}</span> added a page entitled:').format(actor.display_name)
  411. content_text = '<span id="content-body-only-title">{}</span>'.format(content.label)
  412. elif ActionDescription.REVISION == action:
  413. content_text = content.description
  414. call_to_action_text = l_('View online')
  415. if ContentType.File == content.type:
  416. content_intro = l_('<span id="content-intro-username">{}</span> uploaded a new revision.').format(actor.display_name)
  417. content_text = ''
  418. elif ContentType.Page == content.type:
  419. content_intro = l_('<span id="content-intro-username">{}</span> updated this page.').format(actor.display_name)
  420. previous_revision = content.get_previous_revision()
  421. title_diff = ''
  422. if previous_revision.label != content.label:
  423. title_diff = htmldiff(previous_revision.label, content.label)
  424. content_text = str(l_('<p id="content-body-intro">Here is an overview of the changes:</p>'))+ \
  425. title_diff + \
  426. htmldiff(previous_revision.description, content.description)
  427. elif ContentType.Thread == content.type:
  428. content_intro = l_('<span id="content-intro-username">{}</span> updated the thread description.').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 ActionDescription.EDITION == action:
  437. call_to_action_text = l_('View online')
  438. if ContentType.File == content.type:
  439. content_intro = l_('<span id="content-intro-username">{}</span> updated the file description.').format(actor.display_name)
  440. content_text = '<p id="content-body-intro">{}</p>'.format(content.get_label()) + \
  441. content.description
  442. elif ActionDescription.STATUS_UPDATE == action:
  443. call_to_action_text = l_('View online')
  444. intro_user_msg = l_(
  445. '<span id="content-intro-username">{}</span> '
  446. 'updated the following status:'
  447. )
  448. content_intro = intro_user_msg.format(actor.display_name)
  449. intro_body_msg = '<p id="content-body-intro">{}: {}</p>'
  450. content_text = intro_body_msg.format(
  451. content.get_label(),
  452. content.get_status().label,
  453. )
  454. if '' == content_intro and content_text == '':
  455. # Skip notification, but it's not normal
  456. logger.error(
  457. self, 'A notification is being sent but no content. '
  458. 'Here are some debug informations: [content_id: {cid}]'
  459. '[action: {act}][author: {actor}]'.format(
  460. cid=content.content_id, act=action, actor=actor
  461. )
  462. )
  463. raise ValueError('Unexpected empty notification')
  464. user = role.user
  465. workspace = role.workspace
  466. body_content = self._render_template(
  467. mako_template_filepath=mako_template_filepath,
  468. context={
  469. 'user': role.user,
  470. 'workspace': role.workspace,
  471. 'main_title': main_title,
  472. 'status': content.get_status().label,
  473. 'role': role.role_as_label(),
  474. 'content_intro': content_intro,
  475. 'content_text': content_text,
  476. 'call_to_action_text': call_to_action_text,
  477. }
  478. )
  479. return body_content
  480. def get_email_manager(config: CFG, session: Session):
  481. """
  482. :return: EmailManager instance
  483. """
  484. #  TODO: Find a way to import properly without cyclic import
  485. smtp_config = SmtpConfiguration(
  486. config.EMAIL_NOTIFICATION_SMTP_SERVER,
  487. config.EMAIL_NOTIFICATION_SMTP_PORT,
  488. config.EMAIL_NOTIFICATION_SMTP_USER,
  489. config.EMAIL_NOTIFICATION_SMTP_PASSWORD
  490. )
  491. return EmailManager(config=config, smtp_config=smtp_config, session=session)