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.

320 lines
13 KiB

  1. # Copyright 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com>
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  3. import logging
  4. import urllib.parse
  5. import time
  6. import re
  7. from datetime import datetime
  8. from odoo import models, api, fields, tools
  9. import odoo.addons.decimal_precision as dp
  10. _logger = logging.getLogger(__name__)
  11. EVENT_OPEN_DELTA = 10 # seconds
  12. EVENT_CLICK_DELTA = 5 # seconds
  13. class MailTrackingEmail(models.Model):
  14. _name = "mail.tracking.email"
  15. _order = 'time desc'
  16. _rec_name = 'display_name'
  17. _description = 'MailTracking email'
  18. # This table is going to grow fast and to infinite, so we index:
  19. # - name: Search in tree view
  20. # - time: default order fields
  21. # - recipient_address: Used for email_store calculation (non-store)
  22. # - state: Search and group_by in tree view
  23. name = fields.Char(string="Subject", readonly=True, index=True)
  24. display_name = fields.Char(
  25. string="Display name", readonly=True, store=True,
  26. compute="_compute_tracking_display_name")
  27. timestamp = fields.Float(
  28. string='UTC timestamp', readonly=True,
  29. digits=dp.get_precision('MailTracking Timestamp'))
  30. time = fields.Datetime(string="Time", readonly=True, index=True)
  31. date = fields.Date(
  32. string="Date", readonly=True, compute="_compute_date", store=True)
  33. mail_message_id = fields.Many2one(
  34. string="Message", comodel_name='mail.message', readonly=True,
  35. index=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_is_bounced(self, email):
  89. if email:
  90. return self.search_count([
  91. ('recipient_address', '=', email.lower()),
  92. ('state', 'in', ('error', 'rejected', 'spam', 'bounced')),
  93. ]) > 0
  94. return False
  95. @api.model
  96. def email_score_from_email(self, email):
  97. if not email:
  98. return 0.
  99. data = self.read_group([('recipient_address', '=', email.lower())],
  100. ['recipient_address', 'state'], ['state'])
  101. mapped_data = {state['state']: state['state_count'] for state in data}
  102. return self.with_context(mt_states=mapped_data).email_score()
  103. @api.model
  104. def _email_score_weights(self):
  105. """Default email score weights. Ready to be inherited"""
  106. return {
  107. 'error': -50.0,
  108. 'rejected': -25.0,
  109. 'spam': -25.0,
  110. 'bounced': -25.0,
  111. 'soft-bounced': -10.0,
  112. 'unsub': -10.0,
  113. 'delivered': 1.0,
  114. 'opened': 5.0,
  115. }
  116. def email_score(self):
  117. """Default email score algorimth. Ready to be inherited
  118. It can receive a recordset or mapped states dictionary via context.
  119. Must return a value beetwen 0.0 and 100.0
  120. - Bad reputation: Value between 0 and 50.0
  121. - Unknown reputation: Value 50.0
  122. - Good reputation: Value between 50.0 and 100.0
  123. """
  124. weights = self._email_score_weights()
  125. score = 50.0
  126. states = self.env.context.get('mt_states', False)
  127. if states:
  128. for state in states.keys():
  129. score += weights.get(state, 0.0) * states[state]
  130. else:
  131. for tracking in self:
  132. score += weights.get(tracking.state, 0.0)
  133. if score > 100.0:
  134. score = 100.0
  135. elif score < 0.0:
  136. score = 0.0
  137. return score
  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.depends('name', 'recipient')
  150. def _compute_tracking_display_name(self):
  151. for email in self:
  152. parts = [email.name or '']
  153. if email.recipient:
  154. parts.append(email.recipient)
  155. email.display_name = ' - '.join(parts)
  156. @api.depends('time')
  157. def _compute_date(self):
  158. for email in self:
  159. email.date = fields.Date.to_string(
  160. fields.Date.from_string(email.time))
  161. def _get_mail_tracking_img(self):
  162. m_config = self.env['ir.config_parameter']
  163. base_url = (m_config.get_param('mail_tracking.base.url') or
  164. m_config.get_param('web.base.url'))
  165. path_url = (
  166. 'mail/tracking/open/%(db)s/%(tracking_email_id)s/blank.gif' % {
  167. 'db': self.env.cr.dbname,
  168. 'tracking_email_id': self.id,
  169. })
  170. track_url = urllib.parse.urljoin(base_url, path_url)
  171. return (
  172. '<img src="%(url)s" alt="" '
  173. 'data-odoo-tracking-email="%(tracking_email_id)s"/>' % {
  174. 'url': track_url,
  175. 'tracking_email_id': self.id,
  176. })
  177. @api.multi
  178. def _partners_email_bounced_set(self, reason, event=None):
  179. recipients = []
  180. if event and event.recipient_address:
  181. recipients.append(event.recipient_address)
  182. else:
  183. recipients = [x for x in self.mapped('recipient_address') if x]
  184. for recipient in recipients:
  185. self.env['res.partner'].search([
  186. ('email', '=ilike', recipient)
  187. ]).email_bounced_set(self, reason, event=event)
  188. @api.multi
  189. def smtp_error(self, mail_server, smtp_server, exception):
  190. self.sudo().write({
  191. 'error_smtp_server': tools.ustr(smtp_server),
  192. 'error_type': exception.__class__.__name__,
  193. 'error_description': tools.ustr(exception),
  194. 'state': 'error',
  195. })
  196. self.sudo()._partners_email_bounced_set('error')
  197. return True
  198. @api.multi
  199. def tracking_img_add(self, email):
  200. self.ensure_one()
  201. tracking_url = self._get_mail_tracking_img()
  202. if tracking_url:
  203. content = email.get('body', '')
  204. content = re.sub(
  205. r'<img[^>]*data-odoo-tracking-email=["\'][0-9]*["\'][^>]*>',
  206. '', content)
  207. body = tools.append_content_to_html(
  208. content, tracking_url, plaintext=False,
  209. container_tag='div')
  210. email['body'] = body
  211. return email
  212. def _message_partners_check(self, message, message_id):
  213. if not self.mail_message_id.exists(): # pragma: no cover
  214. return True
  215. mail_message = self.mail_message_id
  216. partners = (
  217. mail_message.needaction_partner_ids | mail_message.partner_ids)
  218. if (self.partner_id and self.partner_id not in partners):
  219. # If mail_message haven't tracking partner, then
  220. # add it in order to see his tracking status in chatter
  221. if mail_message.subtype_id:
  222. mail_message.sudo().write({
  223. 'needaction_partner_ids': [(4, self.partner_id.id)],
  224. })
  225. else:
  226. mail_message.sudo().write({
  227. 'partner_ids': [(4, self.partner_id.id)],
  228. })
  229. return True
  230. @api.multi
  231. def _tracking_sent_prepare(self, mail_server, smtp_server, message,
  232. message_id):
  233. self.ensure_one()
  234. ts = time.time()
  235. dt = datetime.utcfromtimestamp(ts)
  236. self._message_partners_check(message, message_id)
  237. self.sudo().write({'state': 'sent'})
  238. return {
  239. 'recipient': message['To'],
  240. 'timestamp': '%.6f' % ts,
  241. 'time': fields.Datetime.to_string(dt),
  242. 'tracking_email_id': self.id,
  243. 'event_type': 'sent',
  244. 'smtp_server': smtp_server,
  245. }
  246. def _event_prepare(self, event_type, metadata):
  247. self.ensure_one()
  248. m_event = self.env['mail.tracking.event']
  249. method = getattr(m_event, 'process_' + event_type, None)
  250. if method and hasattr(method, '__call__'):
  251. return method(self, metadata)
  252. else: # pragma: no cover
  253. _logger.info('Unknown event type: %s' % event_type)
  254. return False
  255. def _concurrent_events(self, event_type, metadata):
  256. m_event = self.env['mail.tracking.event']
  257. self.ensure_one()
  258. concurrent_event_ids = False
  259. if event_type in {'open', 'click'}:
  260. ts = metadata.get('timestamp', time.time())
  261. delta = EVENT_OPEN_DELTA if event_type == 'open' \
  262. else EVENT_CLICK_DELTA
  263. domain = [
  264. ('timestamp', '>=', ts - delta),
  265. ('timestamp', '<=', ts + delta),
  266. ('tracking_email_id', '=', self.id),
  267. ('event_type', '=', event_type),
  268. ]
  269. if event_type == 'click':
  270. domain.append(('url', '=', metadata.get('url', False)))
  271. concurrent_event_ids = m_event.search(domain)
  272. return concurrent_event_ids
  273. @api.multi
  274. def event_create(self, event_type, metadata):
  275. event_ids = self.env['mail.tracking.event']
  276. for tracking_email in self:
  277. other_ids = tracking_email._concurrent_events(event_type, metadata)
  278. if not other_ids:
  279. vals = tracking_email._event_prepare(event_type, metadata)
  280. if vals:
  281. events = event_ids.sudo().create(vals)
  282. if event_type in {'hard_bounce', 'spam', 'reject'}:
  283. for event in events:
  284. self.sudo()._partners_email_bounced_set(
  285. event_type, event=event)
  286. event_ids += events
  287. else:
  288. _logger.debug("Concurrent event '%s' discarded", event_type)
  289. return event_ids
  290. @api.model
  291. def event_process(self, request, post, metadata, event_type=None):
  292. # Generic event process hook, inherit it and
  293. # - return 'OK' if processed
  294. # - return 'NONE' if this request is not for you
  295. # - return 'ERROR' if any error
  296. return 'NONE' # pragma: no cover