PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/addons/mass_mailing/models/mail_mail.py

https://gitlab.com/thanhchatvn/cloud-odoo
Python | 114 lines | 83 code | 19 blank | 12 comment | 26 complexity | 8152ebb9f415028d9b8433848bbe6955 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 urlparse
  5. import werkzeug.urls
  6. from openerp import tools
  7. from openerp import SUPERUSER_ID
  8. from openerp.osv import osv, fields
  9. URL_REGEX = r'(\bhref=[\'"]([^\'"]+)[\'"])'
  10. class MailMail(osv.Model):
  11. """Add the mass mailing campaign data to mail"""
  12. _name = 'mail.mail'
  13. _inherit = ['mail.mail']
  14. _columns = {
  15. 'mailing_id': fields.many2one('mail.mass_mailing', 'Mass Mailing'),
  16. 'statistics_ids': fields.one2many(
  17. 'mail.mail.statistics', 'mail_mail_id',
  18. string='Statistics',
  19. ),
  20. }
  21. def create(self, cr, uid, values, context=None):
  22. """ Override mail_mail creation to create an entry in mail.mail.statistics """
  23. # TDE note: should be after 'all values computed', to have values (FIXME after merging other branch holding create refactoring)
  24. mail_id = super(MailMail, self).create(cr, uid, values, context=context)
  25. if values.get('statistics_ids'):
  26. mail = self.browse(cr, SUPERUSER_ID, mail_id, context=context)
  27. for stat in mail.statistics_ids:
  28. self.pool['mail.mail.statistics'].write(cr, uid, [stat.id], {'message_id': mail.message_id, 'state': 'outgoing'}, context=context)
  29. return mail_id
  30. def _get_tracking_url(self, cr, uid, mail, partner=None, context=None):
  31. base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
  32. track_url = urlparse.urljoin(
  33. base_url, 'mail/track/%(mail_id)s/blank.gif?%(params)s' % {
  34. 'mail_id': mail.id,
  35. 'params': werkzeug.url_encode({'db': cr.dbname})
  36. }
  37. )
  38. return '<img src="%s" alt=""/>' % track_url
  39. def _get_unsubscribe_url(self, cr, uid, mail, email_to, context=None):
  40. base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
  41. url = urlparse.urljoin(
  42. base_url, 'mail/mailing/%(mailing_id)s/unsubscribe?%(params)s' % {
  43. 'mailing_id': mail.mailing_id.id,
  44. 'params': werkzeug.url_encode({'db': cr.dbname, 'res_id': mail.res_id, 'email': email_to})
  45. }
  46. )
  47. return url
  48. def send_get_mail_body(self, cr, uid, ids, partner=None, context=None):
  49. """ Override to add the tracking URL to the body and to add
  50. Statistic_id in shorted urls """
  51. # TDE: temporary addition (mail was parameter) due to semi-new-API
  52. body = super(MailMail, self).send_get_mail_body(cr, uid, ids, partner=partner, context=context)
  53. mail = self.browse(cr, uid, ids[0], context=context)
  54. links_blacklist = ['/unsubscribe_from_list']
  55. if mail.mailing_id and body and mail.statistics_ids:
  56. for match in re.findall(URL_REGEX, mail.body_html):
  57. href = match[0]
  58. url = match[1]
  59. if not [s for s in links_blacklist if s in href]:
  60. new_href = href.replace(url, url + '/m/' + str(mail.statistics_ids[0].id))
  61. body = body.replace(href, new_href)
  62. # prepend <base> tag for images using absolute urls
  63. domain = self.pool.get("ir.config_parameter").get_param(cr, uid, "web.base.url", context=context)
  64. base = "<base href='%s'>" % domain
  65. body = tools.append_content_to_html(base, body, plaintext=False, container_tag='div')
  66. # resolve relative image url to absolute for outlook.com
  67. def _sub_relative2absolute(match):
  68. return match.group(1) + urlparse.urljoin(domain, match.group(2))
  69. body = re.sub('(<img(?=\s)[^>]*\ssrc=")(/[^/][^"]+)', _sub_relative2absolute, body)
  70. body = re.sub(r'(<[^>]+\bstyle="[^"]+\burl\(\'?)(/[^/\'][^\'")]+)', _sub_relative2absolute, body)
  71. # generate tracking URL
  72. if mail.statistics_ids:
  73. tracking_url = self._get_tracking_url(cr, uid, mail, partner, context=context)
  74. if tracking_url:
  75. body = tools.append_content_to_html(body, tracking_url, plaintext=False, container_tag='div')
  76. return body
  77. def send_get_email_dict(self, cr, uid, ids, partner=None, context=None):
  78. # TDE: temporary addition (mail was parameter) due to semi-new-API
  79. res = super(MailMail, self).send_get_email_dict(cr, uid, ids, partner, context=context)
  80. mail = self.browse(cr, uid, ids[0], context=context)
  81. base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
  82. if mail.mailing_id and res.get('body') and res.get('email_to'):
  83. emails = tools.email_split(res.get('email_to')[0])
  84. email_to = emails and emails[0] or False
  85. unsubscribe_url= self._get_unsubscribe_url(cr, uid, mail, email_to, context=context)
  86. link_to_replace = base_url+'/unsubscribe_from_list'
  87. if link_to_replace in res['body']:
  88. res['body'] = res['body'].replace(link_to_replace, unsubscribe_url if unsubscribe_url else '#')
  89. return res
  90. def _postprocess_sent_message(self, cr, uid, mail, context=None, mail_sent=True):
  91. if mail_sent is True and mail.statistics_ids:
  92. self.pool['mail.mail.statistics'].write(cr, uid, [s.id for s in mail.statistics_ids], {'sent': fields.datetime.now(), 'exception': False}, context=context)
  93. elif mail_sent is False and mail.statistics_ids:
  94. self.pool['mail.mail.statistics'].write(cr, uid, [s.id for s in mail.statistics_ids], {'exception': fields.datetime.now()}, context=context)
  95. return super(MailMail, self)._postprocess_sent_message(cr, uid, mail, context=context, mail_sent=mail_sent)