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.

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