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. # 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 email:
  98. return self.search([
  99. ('recipient_address', '=', email.lower())]).email_score()
  100. return 0.
  101. @api.model
  102. def _email_score_weights(self):
  103. """Default email score weights. Ready to be inherited"""
  104. return {
  105. 'error': -50.0,
  106. 'rejected': -25.0,
  107. 'spam': -25.0,
  108. 'bounced': -25.0,
  109. 'soft-bounced': -10.0,
  110. 'unsub': -10.0,
  111. 'delivered': 1.0,
  112. 'opened': 5.0,
  113. }
  114. def email_score(self):
  115. """Default email score algorimth. Ready to be inherited
  116. Must return a value beetwen 0.0 and 100.0
  117. - Bad reputation: Value between 0 and 50.0
  118. - Unknown reputation: Value 50.0
  119. - Good reputation: Value between 50.0 and 100.0
  120. """
  121. weights = self._email_score_weights()
  122. score = 50.0
  123. for tracking in self:
  124. score += weights.get(tracking.state, 0.0)
  125. if score > 100.0:
  126. score = 100.0
  127. elif score < 0.0:
  128. score = 0.0
  129. return score
  130. @api.depends('recipient')
  131. def _compute_recipient_address(self):
  132. for email in self:
  133. if email.recipient:
  134. matches = re.search(r'<(.*@.*)>', email.recipient)
  135. if matches:
  136. email.recipient_address = matches.group(1).lower()
  137. else:
  138. email.recipient_address = email.recipient.lower()
  139. else:
  140. email.recipient_address = False
  141. @api.depends('name', 'recipient')
  142. def _compute_tracking_display_name(self):
  143. for email in self:
  144. parts = [email.name or '']
  145. if email.recipient:
  146. parts.append(email.recipient)
  147. email.display_name = ' - '.join(parts)
  148. @api.depends('time')
  149. def _compute_date(self):
  150. for email in self:
  151. email.date = fields.Date.to_string(
  152. fields.Date.from_string(email.time))
  153. def _get_mail_tracking_img(self):
  154. m_config = self.env['ir.config_parameter']
  155. base_url = (m_config.get_param('mail_tracking.base.url') or
  156. m_config.get_param('web.base.url'))
  157. path_url = (
  158. 'mail/tracking/open/%(db)s/%(tracking_email_id)s/blank.gif' % {
  159. 'db': self.env.cr.dbname,
  160. 'tracking_email_id': self.id,
  161. })
  162. track_url = urllib.parse.urljoin(base_url, path_url)
  163. return (
  164. '<img src="%(url)s" alt="" '
  165. 'data-odoo-tracking-email="%(tracking_email_id)s"/>' % {
  166. 'url': track_url,
  167. 'tracking_email_id': self.id,
  168. })
  169. @api.multi
  170. def _partners_email_bounced_set(self, reason, event=None):
  171. recipients = []
  172. if event and event.recipient_address:
  173. recipients.append(event.recipient_address)
  174. else:
  175. recipients = [x for x in self.mapped('recipient_address') if x]
  176. for recipient in recipients:
  177. self.env['res.partner'].search([
  178. ('email', '=ilike', recipient)
  179. ]).email_bounced_set(self, reason, event=event)
  180. @api.multi
  181. def smtp_error(self, mail_server, smtp_server, exception):
  182. self.sudo().write({
  183. 'error_smtp_server': tools.ustr(smtp_server),
  184. 'error_type': exception.__class__.__name__,
  185. 'error_description': tools.ustr(exception),
  186. 'state': 'error',
  187. })
  188. self.sudo()._partners_email_bounced_set('error')
  189. return True
  190. @api.multi
  191. def tracking_img_add(self, email):
  192. self.ensure_one()
  193. tracking_url = self._get_mail_tracking_img()
  194. if tracking_url:
  195. content = email.get('body', '')
  196. content = re.sub(
  197. r'<img[^>]*data-odoo-tracking-email=["\'][0-9]*["\'][^>]*>',
  198. '', content)
  199. body = tools.append_content_to_html(
  200. content, tracking_url, plaintext=False,
  201. container_tag='div')
  202. email['body'] = body
  203. return email
  204. def _message_partners_check(self, message, message_id):
  205. if not self.mail_message_id.exists(): # pragma: no cover
  206. return True
  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. events = event_ids.sudo().create(vals)
  274. if event_type in {'hard_bounce', 'spam', 'reject'}:
  275. for event in events:
  276. self.sudo()._partners_email_bounced_set(
  277. event_type, event=event)
  278. event_ids += events
  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