You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

313 lines
12 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import logging
  5. import urlparse
  6. import time
  7. import re
  8. from datetime import datetime
  9. from openerp import models, api, fields, tools
  10. import openerp.addons.decimal_precision as dp
  11. _logger = logging.getLogger(__name__)
  12. EVENT_OPEN_DELTA = 10 # seconds
  13. EVENT_CLICK_DELTA = 5 # seconds
  14. class MailTrackingEmail(models.Model):
  15. _name = "mail.tracking.email"
  16. _order = 'time desc'
  17. _rec_name = 'display_name'
  18. _description = 'MailTracking email'
  19. name = fields.Char(string="Subject", readonly=True, index=True)
  20. display_name = fields.Char(
  21. string="Display name", readonly=True, store=True,
  22. compute="_compute_display_name")
  23. timestamp = fields.Float(
  24. string='UTC timestamp', readonly=True,
  25. digits=dp.get_precision('MailTracking Timestamp'))
  26. time = fields.Datetime(string="Time", readonly=True)
  27. date = fields.Date(
  28. string="Date", readonly=True, compute="_compute_date", store=True)
  29. mail_message_id = fields.Many2one(
  30. string="Message", comodel_name='mail.message', readonly=True)
  31. mail_id = fields.Many2one(
  32. string="Email", comodel_name='mail.mail', readonly=True)
  33. partner_id = fields.Many2one(
  34. string="Partner", comodel_name='res.partner', readonly=True)
  35. recipient = fields.Char(string='Recipient email', readonly=True)
  36. recipient_address = fields.Char(
  37. string='Recipient email address', readonly=True, store=True,
  38. compute='_compute_recipient_address')
  39. sender = fields.Char(string='Sender email', readonly=True)
  40. state = fields.Selection([
  41. ('error', 'Error'),
  42. ('deferred', 'Deferred'),
  43. ('sent', 'Sent'),
  44. ('delivered', 'Delivered'),
  45. ('opened', 'Opened'),
  46. ('rejected', 'Rejected'),
  47. ('spam', 'Spam'),
  48. ('unsub', 'Unsubscribed'),
  49. ('bounced', 'Bounced'),
  50. ('soft-bounced', 'Soft bounced'),
  51. ], string='State', index=True, readonly=True, default=False,
  52. help=" * The 'Error' status indicates that there was an error "
  53. "when trying to sent the email, for example, "
  54. "'No valid recipient'\n"
  55. " * The 'Sent' status indicates that message was succesfully "
  56. "sent via outgoing email server (SMTP).\n"
  57. " * The 'Delivered' status indicates that message was "
  58. "succesfully delivered to recipient Mail Exchange (MX) server.\n"
  59. " * The 'Opened' status indicates that message was opened or "
  60. "clicked by recipient.\n"
  61. " * The 'Rejected' status indicates that recipient email "
  62. "address is blacklisted by outgoing email server (SMTP). "
  63. "It is recomended to delete this email address.\n"
  64. " * The 'Spam' status indicates that outgoing email "
  65. "server (SMTP) consider this message as spam.\n"
  66. " * The 'Unsubscribed' status indicates that recipient has "
  67. "requested to be unsubscribed from this message.\n"
  68. " * The 'Bounced' status indicates that message was bounced "
  69. "by recipient Mail Exchange (MX) server.\n"
  70. " * The 'Soft bounced' status indicates that message was soft "
  71. "bounced by recipient Mail Exchange (MX) server.\n")
  72. error_smtp_server = fields.Char(string='Error SMTP server', readonly=True)
  73. error_type = fields.Char(string='Error type', readonly=True)
  74. error_description = fields.Char(
  75. string='Error description', readonly=True)
  76. bounce_type = fields.Char(string='Bounce type', readonly=True)
  77. bounce_description = fields.Char(
  78. string='Bounce description', readonly=True)
  79. tracking_event_ids = fields.One2many(
  80. string="Tracking events", comodel_name='mail.tracking.event',
  81. inverse_name='tracking_email_id', readonly=True)
  82. @api.model
  83. def tracking_ids_recalculate(self, model, email_field, tracking_field,
  84. email, new_tracking=None):
  85. objects = self.env[model].search([
  86. (email_field, '=ilike', email),
  87. ])
  88. for obj in objects:
  89. trackings = obj[tracking_field]
  90. if new_tracking:
  91. trackings |= new_tracking
  92. trackings = trackings._email_score_tracking_filter()
  93. if set(obj[tracking_field].ids) != set(trackings.ids):
  94. if trackings:
  95. obj.write({
  96. tracking_field: [(6, False, trackings.ids)]
  97. })
  98. else:
  99. obj.write({
  100. tracking_field: [(5, False, False)]
  101. })
  102. return objects
  103. @api.model
  104. def _tracking_ids_to_write(self, email):
  105. trackings = self.env['mail.tracking.email'].search([
  106. ('recipient_address', '=ilike', email)
  107. ])
  108. trackings = trackings._email_score_tracking_filter()
  109. if trackings:
  110. return [(6, False, trackings.ids)]
  111. else:
  112. return [(5, False, False)]
  113. @api.multi
  114. def _email_score_tracking_filter(self):
  115. """Default email score filter for tracking emails"""
  116. # Consider only last 10 tracking emails
  117. return self.sorted(key=lambda r: r.time, reverse=True)[:10]
  118. @api.model
  119. def email_score_from_email(self, email):
  120. trackings = self.env['mail.tracking.email'].search([
  121. ('recipient_address', '=ilike', email)
  122. ])
  123. return trackings.email_score()
  124. @api.multi
  125. def email_score(self):
  126. """Default email score algorimth"""
  127. score = 50.0
  128. trackings = self._email_score_tracking_filter()
  129. for tracking in trackings:
  130. if tracking.state in ('error',):
  131. score -= 50.0
  132. elif tracking.state in ('rejected', 'spam', 'bounced'):
  133. score -= 25.0
  134. elif tracking.state in ('soft-bounced', 'unsub'):
  135. score -= 10.0
  136. elif tracking.state in ('delivered',):
  137. score += 5.0
  138. elif tracking.state in ('opened',):
  139. score += 10.0
  140. if score > 100.0:
  141. score = 100.0
  142. return score
  143. @api.multi
  144. @api.depends('recipient')
  145. def _compute_recipient_address(self):
  146. for email in self:
  147. matches = re.search(r'<(.*@.*)>', email.recipient)
  148. if matches:
  149. email.recipient_address = matches.group(1)
  150. else:
  151. email.recipient_address = email.recipient
  152. @api.multi
  153. @api.depends('name', 'recipient')
  154. def _compute_display_name(self):
  155. for email in self:
  156. parts = [email.name or '']
  157. if email.recipient:
  158. parts.append(email.recipient)
  159. email.display_name = ' - '.join(parts)
  160. @api.multi
  161. @api.depends('time')
  162. def _compute_date(self):
  163. for email in self:
  164. email.date = fields.Date.to_string(
  165. fields.Date.from_string(email.time))
  166. @api.model
  167. def create(self, vals):
  168. tracking = super(MailTrackingEmail, self).create(vals)
  169. self.tracking_ids_recalculate(
  170. 'res.partner', 'email', 'tracking_email_ids',
  171. tracking.recipient_address, new_tracking=tracking)
  172. return tracking
  173. def _get_mail_tracking_img(self):
  174. base_url = self.env['ir.config_parameter'].get_param('web.base.url')
  175. path_url = (
  176. 'mail/tracking/open/%(db)s/%(tracking_email_id)s/blank.gif' % {
  177. 'db': self.env.cr.dbname,
  178. 'tracking_email_id': self.id,
  179. })
  180. track_url = urlparse.urljoin(base_url, path_url)
  181. return (
  182. '<img src="%(url)s" alt="" '
  183. 'data-odoo-tracking-email="%(tracking_email_id)s"/>' % {
  184. 'url': track_url,
  185. 'tracking_email_id': self.id,
  186. })
  187. @api.multi
  188. def smtp_error(self, mail_server, smtp_server, exception):
  189. self.sudo().write({
  190. 'error_smtp_server': tools.ustr(smtp_server),
  191. 'error_type': exception.__class__.__name__,
  192. 'error_description': tools.ustr(exception),
  193. 'state': 'error',
  194. })
  195. return True
  196. @api.multi
  197. def tracking_img_add(self, email):
  198. self.ensure_one()
  199. tracking_url = self._get_mail_tracking_img()
  200. if tracking_url:
  201. body = tools.append_content_to_html(
  202. email.get('body', ''), tracking_url, plaintext=False,
  203. container_tag='div')
  204. email['body'] = body
  205. return email
  206. def _message_partners_check(self, message, message_id):
  207. mail_message = self.mail_message_id
  208. partners = (
  209. mail_message.needaction_partner_ids | mail_message.partner_ids)
  210. if (self.partner_id and self.partner_id not in partners):
  211. # If mail_message haven't tracking partner, then
  212. # add it in order to see his tracking status in chatter
  213. if mail_message.subtype_id:
  214. mail_message.sudo().write({
  215. 'needaction_partner_ids': [(4, self.partner_id.id)],
  216. })
  217. else:
  218. mail_message.sudo().write({
  219. 'partner_ids': [(4, self.partner_id.id)],
  220. })
  221. return True
  222. @api.multi
  223. def _tracking_sent_prepare(self, mail_server, smtp_server, message,
  224. message_id):
  225. self.ensure_one()
  226. ts = time.time()
  227. dt = datetime.utcfromtimestamp(ts)
  228. self._message_partners_check(message, message_id)
  229. self.sudo().write({'state': 'sent'})
  230. return {
  231. 'recipient': message['To'],
  232. 'timestamp': '%.6f' % ts,
  233. 'time': fields.Datetime.to_string(dt),
  234. 'tracking_email_id': self.id,
  235. 'event_type': 'sent',
  236. 'smtp_server': smtp_server,
  237. }
  238. def _event_prepare(self, event_type, metadata):
  239. self.ensure_one()
  240. m_event = self.env['mail.tracking.event']
  241. method = getattr(m_event, 'process_' + event_type, None)
  242. if method and hasattr(method, '__call__'):
  243. return method(self, metadata)
  244. else: # pragma: no cover
  245. _logger.info('Unknown event type: %s' % event_type)
  246. return False
  247. def _concurrent_events(self, event_type, metadata):
  248. m_event = self.env['mail.tracking.event']
  249. self.ensure_one()
  250. concurrent_event_ids = False
  251. if event_type in {'open', 'click'}:
  252. ts = metadata.get('timestamp', time.time())
  253. delta = EVENT_OPEN_DELTA if event_type == 'open' \
  254. else EVENT_CLICK_DELTA
  255. domain = [
  256. ('timestamp', '>=', ts - delta),
  257. ('timestamp', '<=', ts + delta),
  258. ('tracking_email_id', '=', self.id),
  259. ('event_type', '=', event_type),
  260. ]
  261. if event_type == 'click':
  262. domain.append(('url', '=', metadata.get('url', False)))
  263. concurrent_event_ids = m_event.search(domain)
  264. return concurrent_event_ids
  265. @api.multi
  266. def event_create(self, event_type, metadata):
  267. event_ids = self.env['mail.tracking.event']
  268. for tracking_email in self:
  269. other_ids = tracking_email._concurrent_events(event_type, metadata)
  270. if not other_ids:
  271. vals = tracking_email._event_prepare(event_type, metadata)
  272. if vals:
  273. event_ids += event_ids.sudo().create(vals)
  274. partners = self.tracking_ids_recalculate(
  275. 'res.partner', 'email', 'tracking_email_ids',
  276. tracking_email.recipient_address)
  277. if partners:
  278. partners.email_score_calculate()
  279. else:
  280. _logger.debug("Concurrent event '%s' discarded", event_type)
  281. return event_ids
  282. @api.model
  283. def event_process(self, request, post, metadata, event_type=None):
  284. # Generic event process hook, inherit it and
  285. # - return 'OK' if processed
  286. # - return 'NONE' if this request is not for you
  287. # - return 'ERROR' if any error
  288. return 'NONE' # pragma: no cover