PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/addons/mass_mailing/models/mail_mail.py

https://gitlab.com/padjis/mapan
Python | 106 lines | 78 code | 18 blank | 10 comment | 23 complexity | 8d1fe9d5a3db7aa52fcc19f05ab1fd11 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import re
  4. import werkzeug.urls
  5. from odoo import api, fields, models, tools
  6. from odoo.addons.link_tracker.models.link_tracker import URL_REGEX
  7. class MailMail(models.Model):
  8. """Add the mass mailing campaign data to mail"""
  9. _inherit = ['mail.mail']
  10. mailing_id = fields.Many2one('mail.mass_mailing', string='Mass Mailing')
  11. statistics_ids = fields.One2many('mail.mail.statistics', 'mail_mail_id', string='Statistics')
  12. @api.model
  13. def create(self, values):
  14. """ Override mail_mail creation to create an entry in mail.mail.statistics """
  15. # TDE note: should be after 'all values computed', to have values (FIXME after merging other branch holding create refactoring)
  16. mail = super(MailMail, self).create(values)
  17. if values.get('statistics_ids'):
  18. mail_sudo = mail.sudo()
  19. mail_sudo.statistics_ids.write({'message_id': mail_sudo.message_id, 'state': 'outgoing'})
  20. return mail
  21. def _get_tracking_url(self):
  22. base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
  23. track_url = werkzeug.urls.url_join(
  24. base_url, 'mail/track/%(mail_id)s/blank.gif?%(params)s' % {
  25. 'mail_id': self.id,
  26. 'params': werkzeug.urls.url_encode({'db': self.env.cr.dbname})
  27. }
  28. )
  29. return '<img src="%s" alt=""/>' % track_url
  30. def _get_unsubscribe_url(self, email_to):
  31. base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
  32. url = werkzeug.urls.url_join(
  33. base_url, 'mail/mailing/%(mailing_id)s/unsubscribe?%(params)s' % {
  34. 'mailing_id': self.mailing_id.id,
  35. 'params': werkzeug.urls.url_encode({
  36. 'db': self.env.cr.dbname,
  37. 'res_id': self.res_id,
  38. 'email': email_to,
  39. 'token': self.mailing_id._unsubscribe_token(
  40. self.res_id, email_to),
  41. }),
  42. }
  43. )
  44. return url
  45. @api.multi
  46. def _send_prepare_body(self):
  47. """ Override to add the tracking URL to the body and to add
  48. Statistic_id in shorted urls """
  49. # TDE: temporary addition (mail was parameter) due to semi-new-API
  50. self.ensure_one()
  51. body = super(MailMail, self)._send_prepare_body()
  52. if self.mailing_id and body and self.statistics_ids:
  53. for match in re.findall(URL_REGEX, self.body_html):
  54. href = match[0]
  55. url = match[1]
  56. parsed = werkzeug.urls.url_parse(url, scheme='http')
  57. if parsed.scheme.startswith('http') and parsed.path.startswith('/r/'):
  58. new_href = href.replace(url, url + '/m/' + str(self.statistics_ids[0].id))
  59. body = body.replace(href, new_href)
  60. # generate tracking URL
  61. tracking_url = self._get_tracking_url()
  62. if tracking_url:
  63. body = tools.append_content_to_html(body, tracking_url, plaintext=False, container_tag='div')
  64. body = self.env['mail.thread']._replace_local_links(body)
  65. return body
  66. @api.multi
  67. def _send_prepare_values(self, partner=None):
  68. # TDE: temporary addition (mail was parameter) due to semi-new-API
  69. res = super(MailMail, self)._send_prepare_values(partner)
  70. base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url').rstrip('/')
  71. if self.mailing_id and res.get('body') and res.get('email_to'):
  72. emails = tools.email_split(res.get('email_to')[0])
  73. email_to = emails and emails[0] or False
  74. unsubscribe_url = self._get_unsubscribe_url(email_to)
  75. link_to_replace = base_url + '/unsubscribe_from_list'
  76. if link_to_replace in res['body']:
  77. res['body'] = res['body'].replace(link_to_replace, unsubscribe_url if unsubscribe_url else '#')
  78. return res
  79. @api.multi
  80. def _postprocess_sent_message(self, success_pids, failure_reason=False, failure_type=None):
  81. mail_sent = not failure_type # we consider that a recipient error is a failure with mass mailling and show them as failed
  82. for mail in self:
  83. if mail.mailing_id:
  84. if mail_sent is True and mail.statistics_ids:
  85. mail.statistics_ids.write({'sent': fields.Datetime.now(), 'exception': False})
  86. elif mail_sent is False and mail.statistics_ids:
  87. mail.statistics_ids.write({'exception': fields.Datetime.now()})
  88. return super(MailMail, self)._postprocess_sent_message(success_pids, failure_reason=failure_reason, failure_type=failure_type)