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.

321 lines
13 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 odoo import models, api, fields, tools
  10. import odoo.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. # This table is going to grow fast and to infinite, so we index:
  20. # - name: Search in tree view
  21. # - time: default order fields
  22. # - recipient_address: Used for email_store calculation (non-store)
  23. # - state: Search and group_by in tree view
  24. name = fields.Char(string="Subject", readonly=True, index=True)
  25. display_name = fields.Char(
  26. string="Display name", readonly=True, store=True,
  27. compute="_compute_tracking_display_name")
  28. timestamp = fields.Float(
  29. string='UTC timestamp', readonly=True,
  30. digits=dp.get_precision('MailTracking Timestamp'))
  31. time = fields.Datetime(string="Time", readonly=True, index=True)
  32. date = fields.Date(
  33. string="Date", readonly=True, compute="_compute_date", store=True)
  34. mail_message_id = fields.Many2one(
  35. string="Message", comodel_name='mail.message', readonly=True,
  36. index=True)
  37. mail_id = fields.Many2one(
  38. string="Email", comodel_name='mail.mail', readonly=True)
  39. partner_id = fields.Many2one(
  40. string="Partner", comodel_name='res.partner', readonly=True)
  41. recipient = fields.Char(string='Recipient email', readonly=True)
  42. recipient_address = fields.Char(
  43. string='Recipient email address', readonly=True, store=True,
  44. compute='_compute_recipient_address', index=True)
  45. sender = fields.Char(string='Sender email', readonly=True)
  46. state = fields.Selection([
  47. ('error', 'Error'),
  48. ('deferred', 'Deferred'),
  49. ('sent', 'Sent'),
  50. ('delivered', 'Delivered'),
  51. ('opened', 'Opened'),
  52. ('rejected', 'Rejected'),
  53. ('spam', 'Spam'),
  54. ('unsub', 'Unsubscribed'),
  55. ('bounced', 'Bounced'),
  56. ('soft-bounced', 'Soft bounced'),
  57. ], string='State', index=True, readonly=True, default=False,
  58. help=" * The 'Error' status indicates that there was an error "
  59. "when trying to sent the email, for example, "
  60. "'No valid recipient'\n"
  61. " * The 'Sent' status indicates that message was succesfully "
  62. "sent via outgoing email server (SMTP).\n"
  63. " * The 'Delivered' status indicates that message was "
  64. "succesfully delivered to recipient Mail Exchange (MX) server.\n"
  65. " * The 'Opened' status indicates that message was opened or "
  66. "clicked by recipient.\n"
  67. " * The 'Rejected' status indicates that recipient email "
  68. "address is blacklisted by outgoing email server (SMTP). "
  69. "It is recomended to delete this email address.\n"
  70. " * The 'Spam' status indicates that outgoing email "
  71. "server (SMTP) consider this message as spam.\n"
  72. " * The 'Unsubscribed' status indicates that recipient has "
  73. "requested to be unsubscribed from this message.\n"
  74. " * The 'Bounced' status indicates that message was bounced "
  75. "by recipient Mail Exchange (MX) server.\n"
  76. " * The 'Soft bounced' status indicates that message was soft "
  77. "bounced by recipient Mail Exchange (MX) server.\n")
  78. error_smtp_server = fields.Char(string='Error SMTP server', readonly=True)
  79. error_type = fields.Char(string='Error type', readonly=True)
  80. error_description = fields.Char(
  81. string='Error description', readonly=True)
  82. bounce_type = fields.Char(string='Bounce type', readonly=True)
  83. bounce_description = fields.Char(
  84. string='Bounce description', readonly=True)
  85. tracking_event_ids = fields.One2many(
  86. string="Tracking events", comodel_name='mail.tracking.event',
  87. inverse_name='tracking_email_id', readonly=True)
  88. @api.model
  89. def _email_score_tracking_filter(self, domain, order='time desc',
  90. limit=10):
  91. """Default tracking search. Ready to be inherited."""
  92. return self.search(domain, limit=limit, order=order)
  93. @api.model
  94. def email_is_bounced(self, email):
  95. if email:
  96. return len(self._email_score_tracking_filter([
  97. ('recipient_address', '=', email.lower()),
  98. ('state', 'in', ('error', 'rejected', 'spam', 'bounced')),
  99. ])) > 0
  100. return False
  101. @api.model
  102. def email_score_from_email(self, email):
  103. if email:
  104. return self._email_score_tracking_filter([
  105. ('recipient_address', '=', email.lower())
  106. ]).email_score()
  107. return 0.
  108. @api.model
  109. def _email_score_weights(self):
  110. """Default email score weights. Ready to be inherited"""
  111. return {
  112. 'error': -50.0,
  113. 'rejected': -25.0,
  114. 'spam': -25.0,
  115. 'bounced': -25.0,
  116. 'soft-bounced': -10.0,
  117. 'unsub': -10.0,
  118. 'delivered': 1.0,
  119. 'opened': 5.0,
  120. }
  121. def email_score(self):
  122. """Default email score algorimth. Ready to be inherited
  123. Must return a value beetwen 0.0 and 100.0
  124. - Bad reputation: Value between 0 and 50.0
  125. - Unknown reputation: Value 50.0
  126. - Good reputation: Value between 50.0 and 100.0
  127. """
  128. weights = self._email_score_weights()
  129. score = 50.0
  130. for tracking in self:
  131. score += weights.get(tracking.state, 0.0)
  132. if score > 100.0:
  133. score = 100.0
  134. elif score < 0.0:
  135. score = 0.0
  136. return score
  137. @api.depends('recipient')
  138. def _compute_recipient_address(self):
  139. for email in self:
  140. if email.recipient:
  141. matches = re.search(r'<(.*@.*)>', email.recipient)
  142. if matches:
  143. email.recipient_address = matches.group(1).lower()
  144. else:
  145. email.recipient_address = email.recipient.lower()
  146. else:
  147. email.recipient_address = False
  148. @api.depends('name', 'recipient')
  149. def _compute_tracking_display_name(self):
  150. for email in self:
  151. parts = [email.name or '']
  152. if email.recipient:
  153. parts.append(email.recipient)
  154. email.display_name = ' - '.join(parts)
  155. @api.depends('time')
  156. def _compute_date(self):
  157. for email in self:
  158. email.date = fields.Date.to_string(
  159. fields.Date.from_string(email.time))
  160. def _get_mail_tracking_img(self):
  161. m_config = self.env['ir.config_parameter']
  162. base_url = (m_config.get_param('mail_tracking.base.url') or
  163. m_config.get_param('web.base.url'))
  164. path_url = (
  165. 'mail/tracking/open/%(db)s/%(tracking_email_id)s/blank.gif' % {
  166. 'db': self.env.cr.dbname,
  167. 'tracking_email_id': self.id,
  168. })
  169. track_url = urlparse.urljoin(base_url, path_url)
  170. return (
  171. '<img src="%(url)s" alt="" '
  172. 'data-odoo-tracking-email="%(tracking_email_id)s"/>' % {
  173. 'url': track_url,
  174. 'tracking_email_id': self.id,
  175. })
  176. @api.multi
  177. def _partners_email_bounced_set(self, reason, event=None):
  178. recipients = []
  179. if event and event.recipient_address:
  180. recipients.append(event.recipient_address)
  181. else:
  182. recipients = list(filter(None, self.mapped('recipient_address')))
  183. for recipient in recipients:
  184. self.env['res.partner'].search([
  185. ('email', '=ilike', recipient)
  186. ]).email_bounced_set(self, reason, event=event)
  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. self.sudo()._partners_email_bounced_set('error')
  196. return True
  197. @api.multi
  198. def tracking_img_add(self, email):
  199. self.ensure_one()
  200. tracking_url = self._get_mail_tracking_img()
  201. if tracking_url:
  202. content = email.get('body', '')
  203. content = re.sub(
  204. r'<img[^>]*data-odoo-tracking-email=["\'][0-9]*["\'][^>]*>',
  205. '', content)
  206. body = tools.append_content_to_html(
  207. content, tracking_url, plaintext=False,
  208. container_tag='div')
  209. email['body'] = body
  210. return email
  211. def _message_partners_check(self, message, message_id):
  212. if not self.mail_message_id.exists(): # pragma: no cover
  213. return True
  214. mail_message = self.mail_message_id
  215. partners = (
  216. mail_message.needaction_partner_ids | mail_message.partner_ids)
  217. if (self.partner_id and self.partner_id not in partners):
  218. # If mail_message haven't tracking partner, then
  219. # add it in order to see his tracking status in chatter
  220. if mail_message.subtype_id:
  221. mail_message.sudo().write({
  222. 'needaction_partner_ids': [(4, self.partner_id.id)],
  223. })
  224. else:
  225. mail_message.sudo().write({
  226. 'partner_ids': [(4, self.partner_id.id)],
  227. })
  228. return True
  229. @api.multi
  230. def _tracking_sent_prepare(self, mail_server, smtp_server, message,
  231. message_id):
  232. self.ensure_one()
  233. ts = time.time()
  234. dt = datetime.utcfromtimestamp(ts)
  235. self._message_partners_check(message, message_id)
  236. self.sudo().write({'state': 'sent'})
  237. return {
  238. 'recipient': message['To'],
  239. 'timestamp': '%.6f' % ts,
  240. 'time': fields.Datetime.to_string(dt),
  241. 'tracking_email_id': self.id,
  242. 'event_type': 'sent',
  243. 'smtp_server': smtp_server,
  244. }
  245. def _event_prepare(self, event_type, metadata):
  246. self.ensure_one()
  247. m_event = self.env['mail.tracking.event']
  248. method = getattr(m_event, 'process_' + event_type, None)
  249. if method and hasattr(method, '__call__'):
  250. return method(self, metadata)
  251. else: # pragma: no cover
  252. _logger.info('Unknown event type: %s' % event_type)
  253. return False
  254. def _concurrent_events(self, event_type, metadata):
  255. m_event = self.env['mail.tracking.event']
  256. self.ensure_one()
  257. concurrent_event_ids = False
  258. if event_type in {'open', 'click'}:
  259. ts = metadata.get('timestamp', time.time())
  260. delta = EVENT_OPEN_DELTA if event_type == 'open' \
  261. else EVENT_CLICK_DELTA
  262. domain = [
  263. ('timestamp', '>=', ts - delta),
  264. ('timestamp', '<=', ts + delta),
  265. ('tracking_email_id', '=', self.id),
  266. ('event_type', '=', event_type),
  267. ]
  268. if event_type == 'click':
  269. domain.append(('url', '=', metadata.get('url', False)))
  270. concurrent_event_ids = m_event.search(domain)
  271. return concurrent_event_ids
  272. @api.multi
  273. def event_create(self, event_type, metadata):
  274. event_ids = self.env['mail.tracking.event']
  275. for tracking_email in self:
  276. other_ids = tracking_email._concurrent_events(event_type, metadata)
  277. if not other_ids:
  278. vals = tracking_email._event_prepare(event_type, metadata)
  279. if vals:
  280. events = event_ids.sudo().create(vals)
  281. if event_type in {'hard_bounce', 'spam', 'reject'}:
  282. for event in events:
  283. self.sudo()._partners_email_bounced_set(
  284. event_type, event=event)
  285. event_ids += events
  286. else:
  287. _logger.debug("Concurrent event '%s' discarded", event_type)
  288. return event_ids
  289. @api.model
  290. def event_process(self, request, post, metadata, event_type=None):
  291. # Generic event process hook, inherit it and
  292. # - return 'OK' if processed
  293. # - return 'NONE' if this request is not for you
  294. # - return 'ERROR' if any error
  295. return 'NONE' # pragma: no cover