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.

256 lines
10 KiB

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