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.

248 lines
9.4 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Tecnativa - Antonio Espinosa
  3. # Copyright 2017 Tecnativa - David Vidal
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  5. import hashlib
  6. import hmac
  7. import json
  8. import requests
  9. from datetime import datetime
  10. from openerp import _, api, fields, models
  11. from openerp.exceptions import ValidationError
  12. import logging
  13. _logger = logging.getLogger(__name__)
  14. class MailTrackingEmail(models.Model):
  15. _inherit = "mail.tracking.email"
  16. def _country_search(self, country_code):
  17. country = False
  18. if country_code:
  19. country = self.env['res.country'].search([
  20. ('code', '=', country_code.upper()),
  21. ])
  22. if country:
  23. return country.id
  24. return False
  25. @property
  26. def _mailgun_mandatory_fields(self):
  27. return ('event', 'timestamp', 'token', 'signature',
  28. 'tracking_email_id', 'odoo_db')
  29. @property
  30. def _mailgun_event_type_mapping(self):
  31. return {
  32. # Mailgun event type: tracking event type
  33. 'delivered': 'delivered',
  34. 'opened': 'open',
  35. 'clicked': 'click',
  36. 'unsubscribed': 'unsub',
  37. 'complained': 'spam',
  38. 'bounced': 'hard_bounce',
  39. 'dropped': 'reject',
  40. 'accepted': 'sent',
  41. }
  42. def _mailgun_event_type_verify(self, event):
  43. event = event or {}
  44. mailgun_event_type = event.get('event')
  45. if mailgun_event_type not in self._mailgun_event_type_mapping:
  46. _logger.error("Mailgun: event type '%s' not supported",
  47. mailgun_event_type)
  48. return False
  49. # OK, event type is valid
  50. return True
  51. def _mailgun_signature(self, api_key, timestamp, token):
  52. return hmac.new(
  53. key=str(api_key),
  54. msg='{}{}'.format(str(timestamp), str(token)),
  55. digestmod=hashlib.sha256).hexdigest()
  56. def _mailgun_values(self):
  57. icp = self.env['ir.config_parameter']
  58. api_key = icp.get_param('mailgun.apikey')
  59. if not api_key:
  60. raise ValidationError(_('There is no Mailgun API key!'))
  61. api_url = icp.get_param(
  62. 'mailgun.api_url', 'https://api.mailgun.net/v3')
  63. domain = icp.get_param('mail.catchall.domain')
  64. if not domain:
  65. raise ValidationError(_('A Mailgun domain value is needed!'))
  66. validation_key = icp.get_param('mailgun.validation_key')
  67. return api_key, api_url, domain, validation_key
  68. def _mailgun_signature_verify(self, event):
  69. event = event or {}
  70. api_key = self.env['ir.config_parameter'].get_param('mailgun.apikey')
  71. if not api_key:
  72. _logger.warning("No Mailgun api key configured. "
  73. "Please add 'mailgun.apikey' to System parameters "
  74. "to enable Mailgun authentication webhoook "
  75. "requests. More info at: "
  76. "https://documentation.mailgun.com/"
  77. "user_manual.html#webhooks")
  78. else:
  79. timestamp = event.get('timestamp')
  80. token = event.get('token')
  81. signature = event.get('signature')
  82. event_digest = self._mailgun_signature(api_key, timestamp, token)
  83. if signature != event_digest:
  84. _logger.error("Mailgun: Invalid signature '%s' != '%s'",
  85. signature, event_digest)
  86. return False
  87. # OK, signature is valid
  88. return True
  89. def _db_verify(self, event):
  90. event = event or {}
  91. odoo_db = event.get('odoo_db')
  92. current_db = self.env.cr.dbname
  93. if odoo_db != current_db:
  94. _logger.error("Mailgun: Database '%s' is not the current database",
  95. odoo_db)
  96. return False
  97. # OK, DB is current
  98. return True
  99. def _mailgun_metadata(self, mailgun_event_type, event, metadata):
  100. # Get Mailgun timestamp when found
  101. ts = event.get('timestamp', False)
  102. try:
  103. ts = float(ts)
  104. except:
  105. ts = False
  106. if ts:
  107. dt = datetime.utcfromtimestamp(ts)
  108. metadata.update({
  109. 'timestamp': ts,
  110. 'time': fields.Datetime.to_string(dt),
  111. 'date': fields.Date.to_string(dt),
  112. 'mailgun_id': event.get('id', False)
  113. })
  114. # Common field mapping
  115. mapping = {
  116. 'recipient': 'recipient',
  117. 'ip': 'ip',
  118. 'user_agent': 'user-agent',
  119. 'os_family': 'client-os',
  120. 'ua_family': 'client-name',
  121. 'ua_type': 'client-type',
  122. 'url': 'url',
  123. }
  124. for k, v in mapping.iteritems():
  125. if event.get(v, False):
  126. metadata[k] = event[v]
  127. # Special field mapping
  128. metadata.update({
  129. 'mobile': event.get('device-type') in {'mobile', 'tablet'},
  130. 'user_country_id': self._country_search(
  131. event.get('country', False)),
  132. })
  133. # Mapping for special events
  134. if mailgun_event_type == 'bounced':
  135. metadata.update({
  136. 'error_type': event.get('code', False),
  137. 'error_description': event.get('error', False),
  138. 'error_details': event.get('notification', False),
  139. })
  140. elif mailgun_event_type == 'dropped':
  141. metadata.update({
  142. 'error_type': event.get('reason', False),
  143. 'error_description': event.get('code', False),
  144. 'error_details': event.get('description', False),
  145. })
  146. elif mailgun_event_type == 'complained':
  147. metadata.update({
  148. 'error_type': 'spam',
  149. 'error_description':
  150. "Recipient '%s' mark this email as spam" %
  151. event.get('recipient', False),
  152. })
  153. return metadata
  154. def _mailgun_tracking_get(self, event):
  155. tracking = False
  156. tracking_email_id = event.get('tracking_email_id', False)
  157. if tracking_email_id and tracking_email_id.isdigit():
  158. tracking = self.search([('id', '=', tracking_email_id)], limit=1)
  159. return tracking
  160. def _event_is_from_mailgun(self, event):
  161. event = event or {}
  162. return all([k in event for k in self._mailgun_mandatory_fields])
  163. @api.model
  164. def event_process(self, request, post, metadata, event_type=None):
  165. res = super(MailTrackingEmail, self).event_process(
  166. request, post, metadata, event_type=event_type)
  167. if res == 'NONE' and self._event_is_from_mailgun(post):
  168. if not self._mailgun_signature_verify(post):
  169. res = 'ERROR: Signature'
  170. elif not self._mailgun_event_type_verify(post):
  171. res = 'ERROR: Event type not supported'
  172. elif not self._db_verify(post):
  173. res = 'ERROR: Invalid DB'
  174. else:
  175. res = 'OK'
  176. if res == 'OK':
  177. mailgun_event_type = post.get('event')
  178. mapped_event_type = self._mailgun_event_type_mapping.get(
  179. mailgun_event_type) or event_type
  180. if not mapped_event_type: # pragma: no cover
  181. res = 'ERROR: Bad event'
  182. tracking = self._mailgun_tracking_get(post)
  183. if not tracking:
  184. res = 'ERROR: Tracking not found'
  185. if res == 'OK':
  186. # Complete metadata with mailgun event info
  187. metadata = self._mailgun_metadata(
  188. mailgun_event_type, post, metadata)
  189. # Create event
  190. tracking.event_create(mapped_event_type, metadata)
  191. if res != 'NONE':
  192. if event_type:
  193. _logger.info(
  194. "Mailgun: event '%s' process '%s'", event_type, res)
  195. else:
  196. _logger.info("Mailgun: event process '%s'", res)
  197. return res
  198. @api.multi
  199. def action_manual_check_mailgun(self):
  200. """
  201. Manual check against Mailgun API
  202. API Documentation:
  203. https://documentation.mailgun.com/en/latest/api-events.html
  204. """
  205. api_key, api_url, domain, validation_key = self._mailgun_values()
  206. for tracking in self:
  207. message_id = tracking.mail_message_id.message_id.replace(
  208. "<", "").replace(">", "")
  209. res = requests.get(
  210. '%s/%s/events' % (api_url, domain),
  211. auth=("api", api_key),
  212. params={
  213. "begin": tracking.timestamp,
  214. "ascending": "yes",
  215. "message-id": message_id,
  216. }
  217. )
  218. if not res or res.status_code != 200:
  219. raise ValidationError(_(
  220. "Couldn't retrieve Mailgun information"))
  221. content = json.loads(res.content, res.apparent_encoding)
  222. if "items" not in content:
  223. raise ValidationError(_("Event information not longer stored"))
  224. for item in content["items"]:
  225. if not self.env['mail.tracking.event'].search(
  226. [('mailgun_id', '=', item["id"])]):
  227. mapped_event_type = self._mailgun_event_type_mapping.get(
  228. item["event"]) or False
  229. metadata = self._mailgun_metadata(
  230. mapped_event_type, item, {})
  231. tracking.event_create(mapped_event_type, metadata)