PageRenderTime 30ms CodeModel.GetById 23ms app.highlight 5ms RepoModel.GetById 0ms app.codeStats 0ms

/addons/mass_mailing/models/mail_mail.py

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