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.

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