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.

196 lines
7.2 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. import hashlib
  5. import hmac
  6. import threading
  7. from datetime import datetime
  8. from openerp import models, api, fields
  9. import logging
  10. _logger = logging.getLogger(__name__)
  11. class MailTrackingEmail(models.Model):
  12. _inherit = "mail.tracking.email"
  13. def _country_search(self, country_code):
  14. country = False
  15. if country_code:
  16. country = self.env['res.country'].search([
  17. ('code', '=ilike', country_code),
  18. ])
  19. if country:
  20. return country.id
  21. return False
  22. def _mailgun_mandatory_fields(self):
  23. return ('event', 'timestamp', 'token', 'signature',
  24. 'tracking_email_id', 'odoo_db')
  25. def _mailgun_event_type_mapping(self):
  26. return {
  27. # Mailgun event type: tracking event type
  28. 'delivered': 'delivered',
  29. 'opened': 'open',
  30. 'clicked': 'click',
  31. 'unsubscribed': 'unsub',
  32. 'complained': 'spam',
  33. 'bounced': 'hard_bounce',
  34. 'dropped': 'reject',
  35. }
  36. def _mailgun_supported_event_types(self):
  37. return self._mailgun_event_type_mapping().keys()
  38. def _mailgun_event_type_verify(self, event):
  39. event = event or {}
  40. mailgun_event_type = event.get('event')
  41. if mailgun_event_type not in self._mailgun_supported_event_types():
  42. _logger.info("Mailgun: event type '%s' not supported",
  43. mailgun_event_type)
  44. return False
  45. # OK, event type is valid
  46. return True
  47. def _mailgun_signature(self, api_key, timestamp, token):
  48. return hmac.new(
  49. key=str(api_key),
  50. msg='{}{}'.format(str(timestamp), str(token)),
  51. digestmod=hashlib.sha256).hexdigest()
  52. def _mailgun_signature_verify(self, event):
  53. event = event or {}
  54. api_key = self.env['ir.config_parameter'].get_param('mailgun.apikey')
  55. if not api_key:
  56. _logger.info("No Mailgun api key configured. "
  57. "Please add 'mailgun.apikey' to System parameters "
  58. "to enable Mailgun authentication webhoook requests. "
  59. "More info at: "
  60. "https://documentation.mailgun.com/user_manual.html"
  61. "#webhooks")
  62. else:
  63. timestamp = event.get('timestamp')
  64. token = event.get('token')
  65. signature = event.get('signature')
  66. event_digest = self._mailgun_signature(api_key, timestamp, token)
  67. if signature != event_digest:
  68. _logger.info("Mailgun: Invalid signature '%s' != '%s'",
  69. signature, event_digest)
  70. return False
  71. # OK, signature is valid
  72. return True
  73. def _db_verify(self, event):
  74. event = event or {}
  75. odoo_db = event.get('odoo_db')
  76. current_db = getattr(threading.currentThread(), 'dbname', None)
  77. if odoo_db != current_db:
  78. _logger.info("Mailgun: Database '%s' is not the current database",
  79. odoo_db)
  80. return False
  81. # OK, DB is current
  82. return True
  83. def _mailgun_metadata(self, mailgun_event_type, event, metadata):
  84. # Get Mailgun timestamp when found
  85. ts = event.get('timestamp', False)
  86. try:
  87. ts = float(ts)
  88. except:
  89. ts = False
  90. if ts:
  91. dt = datetime.utcfromtimestamp(ts)
  92. metadata.update({
  93. 'timestamp': ts,
  94. 'time': fields.Datetime.to_string(dt),
  95. 'date': fields.Date.to_string(dt),
  96. })
  97. # Common field mapping
  98. mapping = {
  99. 'recipient': 'recipient',
  100. 'ip': 'ip',
  101. 'user_agent': 'user-agent',
  102. 'os_family': 'client-os',
  103. 'ua_family': 'client-name',
  104. 'ua_type': 'client-type',
  105. 'url': 'url',
  106. }
  107. for k, v in mapping.iteritems():
  108. if event.get(v, False):
  109. metadata[k] = event[v]
  110. # Special field mapping
  111. metadata.update({
  112. 'mobile': event.get('device-type') in ('mobile', 'tablet'),
  113. 'user_country_id': self._country_search(
  114. event.get('country', False)),
  115. })
  116. # Mapping for special events
  117. if mailgun_event_type == 'bounced':
  118. metadata.update({
  119. 'error_type': event.get('code', False),
  120. 'error_description': event.get('error', False),
  121. 'error_details': event.get('notification', False),
  122. })
  123. elif mailgun_event_type == 'dropped':
  124. metadata.update({
  125. 'error_type': event.get('reason', False),
  126. 'error_description': event.get('code', False),
  127. 'error_details': event.get('description', False),
  128. })
  129. elif mailgun_event_type == 'complained':
  130. metadata.update({
  131. 'error_type': 'spam',
  132. 'error_description':
  133. "Recipient '%s' mark this email as spam" %
  134. event.get('recipient', False),
  135. })
  136. return metadata
  137. def _mailgun_tracking_get(self, event):
  138. tracking = False
  139. tracking_email_id = event.get('tracking_email_id', False)
  140. if tracking_email_id and tracking_email_id.isdigit():
  141. tracking = self.search([('id', '=', tracking_email_id)])
  142. return tracking
  143. def _event_is_from_mailgun(self, event):
  144. event = event or {}
  145. return all([k in event for k in self._mailgun_mandatory_fields()])
  146. @api.model
  147. def event_process(self, request, post, metadata, event_type=None):
  148. res = super(MailTrackingEmail, self).event_process(
  149. request, post, metadata, event_type=event_type)
  150. if res == 'NONE' and self._event_is_from_mailgun(post):
  151. if not self._mailgun_signature_verify(post):
  152. res = 'ERROR: Signature'
  153. elif not self._mailgun_event_type_verify(post):
  154. res = 'ERROR: Event type not supported'
  155. elif not self._db_verify(post):
  156. res = 'ERROR: Invalid DB'
  157. else:
  158. res = 'OK'
  159. if res == 'OK':
  160. mailgun_event_type = post.get('event')
  161. mapped_event_type = self._mailgun_event_type_mapping().get(
  162. mailgun_event_type) or event_type
  163. if not mapped_event_type: # pragma: no cover
  164. res = 'ERROR: Bad event'
  165. tracking = self._mailgun_tracking_get(post)
  166. if not tracking:
  167. res = 'ERROR: Tracking not found'
  168. if res == 'OK':
  169. # Complete metadata with mailgun event info
  170. metadata = self._mailgun_metadata(
  171. mailgun_event_type, post, metadata)
  172. # Create event
  173. tracking.event_create(mapped_event_type, metadata)
  174. if res != 'NONE':
  175. if event_type:
  176. _logger.info(
  177. "Mailgun: event '%s' process '%s'", event_type, res)
  178. else:
  179. _logger.info("Mailgun: event process '%s'", res)
  180. return res