2017-10-17 20:38:11 +02:00
|
|
|
# Copyright 2016 Tecnativa - Antonio Espinosa
|
|
|
|
# Copyright 2017 Tecnativa - David Vidal
|
2016-07-15 13:41:49 +02:00
|
|
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
|
|
|
|
|
|
|
|
import hashlib
|
|
|
|
import hmac
|
2020-04-02 11:15:00 +02:00
|
|
|
import logging
|
2016-07-15 13:41:49 +02:00
|
|
|
from datetime import datetime
|
2020-04-02 11:15:00 +02:00
|
|
|
|
|
|
|
import requests
|
|
|
|
|
2017-10-17 20:38:11 +02:00
|
|
|
from odoo import _, api, fields, models
|
2017-12-22 19:23:40 +01:00
|
|
|
from odoo.exceptions import UserError, ValidationError
|
2018-02-15 19:46:21 +01:00
|
|
|
from odoo.tools import email_split
|
2016-07-15 13:41:49 +02:00
|
|
|
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class MailTrackingEmail(models.Model):
|
|
|
|
_inherit = "mail.tracking.email"
|
|
|
|
|
|
|
|
def _country_search(self, country_code):
|
|
|
|
country = False
|
|
|
|
if country_code:
|
2020-04-02 11:15:00 +02:00
|
|
|
country = self.env["res.country"].search(
|
|
|
|
[("code", "=", country_code.upper())]
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
if country:
|
|
|
|
return country.id
|
|
|
|
return False
|
|
|
|
|
|
|
|
@property
|
|
|
|
def _mailgun_mandatory_fields(self):
|
2020-04-02 11:15:00 +02:00
|
|
|
return (
|
|
|
|
"event",
|
|
|
|
"timestamp",
|
|
|
|
"token",
|
|
|
|
"signature",
|
|
|
|
"tracking_email_id",
|
|
|
|
"odoo_db",
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def _mailgun_event_type_mapping(self):
|
|
|
|
return {
|
|
|
|
# Mailgun event type: tracking event type
|
2020-04-02 11:15:00 +02:00
|
|
|
"delivered": "delivered",
|
|
|
|
"opened": "open",
|
|
|
|
"clicked": "click",
|
|
|
|
"unsubscribed": "unsub",
|
|
|
|
"complained": "spam",
|
|
|
|
"bounced": "hard_bounce",
|
|
|
|
"dropped": "reject",
|
|
|
|
"accepted": "sent",
|
|
|
|
"failed": "error",
|
|
|
|
"rejected": "error",
|
2016-07-15 13:41:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
def _mailgun_event_type_verify(self, event):
|
|
|
|
event = event or {}
|
2020-04-02 11:15:00 +02:00
|
|
|
mailgun_event_type = event.get("event")
|
2016-09-09 13:29:58 +02:00
|
|
|
if mailgun_event_type not in self._mailgun_event_type_mapping:
|
2020-04-02 11:15:00 +02:00
|
|
|
_logger.error("Mailgun: event type '%s' not supported", mailgun_event_type)
|
2016-07-15 13:41:49 +02:00
|
|
|
return False
|
|
|
|
# OK, event type is valid
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _mailgun_signature(self, api_key, timestamp, token):
|
|
|
|
return hmac.new(
|
2020-04-02 11:15:00 +02:00
|
|
|
key=bytes(api_key, "utf-8"),
|
|
|
|
msg=bytes("{}{}".format(str(timestamp), str(token)), "utf-8"),
|
|
|
|
digestmod=hashlib.sha256,
|
|
|
|
).hexdigest()
|
2016-07-15 13:41:49 +02:00
|
|
|
|
2017-10-17 20:38:11 +02:00
|
|
|
def _mailgun_values(self):
|
2020-04-02 11:15:00 +02:00
|
|
|
icp = self.env["ir.config_parameter"].sudo()
|
|
|
|
api_key = icp.get_param("mailgun.apikey")
|
2017-10-17 20:38:11 +02:00
|
|
|
if not api_key:
|
2020-04-02 11:15:00 +02:00
|
|
|
raise ValidationError(_("There is no Mailgun API key!"))
|
|
|
|
api_url = icp.get_param("mailgun.api_url", "https://api.mailgun.net/v3")
|
|
|
|
catchall_domain = icp.get_param("mail.catchall.domain")
|
|
|
|
domain = icp.get_param("mailgun.domain", catchall_domain)
|
2017-10-17 20:38:11 +02:00
|
|
|
if not domain:
|
2020-04-02 11:15:00 +02:00
|
|
|
raise ValidationError(_("A Mailgun domain value is needed!"))
|
|
|
|
validation_key = icp.get_param("mailgun.validation_key")
|
2017-10-17 20:38:11 +02:00
|
|
|
return api_key, api_url, domain, validation_key
|
|
|
|
|
2016-07-15 13:41:49 +02:00
|
|
|
def _mailgun_signature_verify(self, event):
|
|
|
|
event = event or {}
|
2020-04-02 11:15:00 +02:00
|
|
|
icp = self.env["ir.config_parameter"].sudo()
|
|
|
|
api_key = icp.get_param("mailgun.apikey")
|
2016-07-15 13:41:49 +02:00
|
|
|
if not api_key:
|
2020-04-02 11:15:00 +02:00
|
|
|
_logger.warning(
|
|
|
|
"No Mailgun api key configured. "
|
|
|
|
"Please add 'mailgun.apikey' to System parameters "
|
|
|
|
"to enable Mailgun authentication webhoook "
|
|
|
|
"requests. More info at: "
|
|
|
|
"https://documentation.mailgun.com/"
|
|
|
|
"user_manual.html#webhooks"
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
else:
|
2020-04-02 11:15:00 +02:00
|
|
|
timestamp = event.get("timestamp")
|
|
|
|
token = event.get("token")
|
|
|
|
signature = event.get("signature")
|
2016-07-15 13:41:49 +02:00
|
|
|
event_digest = self._mailgun_signature(api_key, timestamp, token)
|
|
|
|
if signature != event_digest:
|
2020-04-02 11:15:00 +02:00
|
|
|
_logger.error(
|
|
|
|
"Mailgun: Invalid signature '%s' != '%s'", signature, event_digest
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
return False
|
|
|
|
# OK, signature is valid
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _db_verify(self, event):
|
|
|
|
event = event or {}
|
2020-04-02 11:15:00 +02:00
|
|
|
odoo_db = event.get("odoo_db")
|
2016-07-15 13:41:49 +02:00
|
|
|
current_db = self.env.cr.dbname
|
|
|
|
if odoo_db != current_db:
|
2020-04-02 11:15:00 +02:00
|
|
|
_logger.error("Mailgun: Database '%s' is not the current database", odoo_db)
|
2016-07-15 13:41:49 +02:00
|
|
|
return False
|
|
|
|
# OK, DB is current
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _mailgun_metadata(self, mailgun_event_type, event, metadata):
|
|
|
|
# Get Mailgun timestamp when found
|
2020-04-02 11:15:00 +02:00
|
|
|
ts = event.get("timestamp", False)
|
2016-07-15 13:41:49 +02:00
|
|
|
try:
|
|
|
|
ts = float(ts)
|
2018-05-08 18:24:36 +02:00
|
|
|
except Exception:
|
2016-07-15 13:41:49 +02:00
|
|
|
ts = False
|
|
|
|
if ts:
|
|
|
|
dt = datetime.utcfromtimestamp(ts)
|
2020-04-02 11:15:00 +02:00
|
|
|
metadata.update(
|
|
|
|
{
|
|
|
|
"timestamp": ts,
|
|
|
|
"time": fields.Datetime.to_string(dt),
|
|
|
|
"date": fields.Date.to_string(dt),
|
|
|
|
"mailgun_id": event.get("id", False),
|
|
|
|
}
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
# Common field mapping
|
|
|
|
mapping = {
|
2020-04-02 11:15:00 +02:00
|
|
|
"recipient": "recipient",
|
|
|
|
"ip": "ip",
|
|
|
|
"user_agent": "user-agent",
|
|
|
|
"os_family": "client-os",
|
|
|
|
"ua_family": "client-name",
|
|
|
|
"ua_type": "client-type",
|
|
|
|
"url": "url",
|
2016-07-15 13:41:49 +02:00
|
|
|
}
|
2018-05-08 18:24:36 +02:00
|
|
|
for k, v in mapping.items():
|
2016-07-15 13:41:49 +02:00
|
|
|
if event.get(v, False):
|
|
|
|
metadata[k] = event[v]
|
|
|
|
# Special field mapping
|
2020-04-02 11:15:00 +02:00
|
|
|
metadata.update(
|
|
|
|
{
|
|
|
|
"mobile": event.get("device-type") in {"mobile", "tablet"},
|
|
|
|
"user_country_id": self._country_search(event.get("country", False)),
|
|
|
|
}
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
# Mapping for special events
|
2020-04-02 11:15:00 +02:00
|
|
|
if mailgun_event_type == "bounced":
|
|
|
|
metadata.update(
|
|
|
|
{
|
|
|
|
"error_type": event.get("code", False),
|
|
|
|
"error_description": event.get("error", False),
|
|
|
|
"error_details": event.get("notification", False),
|
|
|
|
}
|
|
|
|
)
|
|
|
|
elif mailgun_event_type == "dropped":
|
|
|
|
metadata.update(
|
|
|
|
{
|
|
|
|
"error_type": event.get("reason", False),
|
|
|
|
"error_description": event.get("code", False),
|
|
|
|
"error_details": event.get("description", False),
|
|
|
|
}
|
|
|
|
)
|
|
|
|
elif mailgun_event_type == "complained":
|
|
|
|
metadata.update(
|
|
|
|
{
|
|
|
|
"error_type": "spam",
|
|
|
|
"error_description": "Recipient '%s' mark this email as spam"
|
|
|
|
% event.get("recipient", False),
|
|
|
|
}
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
return metadata
|
|
|
|
|
|
|
|
def _mailgun_tracking_get(self, event):
|
|
|
|
tracking = False
|
2020-04-02 11:15:00 +02:00
|
|
|
tracking_email_id = event.get("tracking_email_id", False)
|
2016-07-15 13:41:49 +02:00
|
|
|
if tracking_email_id and tracking_email_id.isdigit():
|
2020-04-02 11:15:00 +02:00
|
|
|
tracking = self.search([("id", "=", tracking_email_id)], limit=1)
|
2016-07-15 13:41:49 +02:00
|
|
|
return tracking
|
|
|
|
|
|
|
|
def _event_is_from_mailgun(self, event):
|
|
|
|
event = event or {}
|
|
|
|
return all([k in event for k in self._mailgun_mandatory_fields])
|
|
|
|
|
|
|
|
@api.model
|
|
|
|
def event_process(self, request, post, metadata, event_type=None):
|
|
|
|
res = super(MailTrackingEmail, self).event_process(
|
2020-04-02 11:15:00 +02:00
|
|
|
request, post, metadata, event_type=event_type
|
|
|
|
)
|
|
|
|
if res == "NONE" and self._event_is_from_mailgun(post):
|
2016-07-15 13:41:49 +02:00
|
|
|
if not self._mailgun_signature_verify(post):
|
2020-04-02 11:15:00 +02:00
|
|
|
res = "ERROR: Signature"
|
2016-07-15 13:41:49 +02:00
|
|
|
elif not self._mailgun_event_type_verify(post):
|
2020-04-02 11:15:00 +02:00
|
|
|
res = "ERROR: Event type not supported"
|
2016-07-15 13:41:49 +02:00
|
|
|
elif not self._db_verify(post):
|
2020-04-02 11:15:00 +02:00
|
|
|
res = "ERROR: Invalid DB"
|
2016-07-15 13:41:49 +02:00
|
|
|
else:
|
2020-04-02 11:15:00 +02:00
|
|
|
res = "OK"
|
|
|
|
if res == "OK":
|
|
|
|
mailgun_event_type = post.get("event")
|
|
|
|
mapped_event_type = (
|
|
|
|
self._mailgun_event_type_mapping.get(mailgun_event_type) or event_type
|
|
|
|
)
|
2016-07-15 13:41:49 +02:00
|
|
|
if not mapped_event_type: # pragma: no cover
|
2020-04-02 11:15:00 +02:00
|
|
|
res = "ERROR: Bad event"
|
2016-07-15 13:41:49 +02:00
|
|
|
tracking = self._mailgun_tracking_get(post)
|
|
|
|
if not tracking:
|
2020-04-02 11:15:00 +02:00
|
|
|
res = "ERROR: Tracking not found"
|
|
|
|
if res == "OK":
|
2016-07-15 13:41:49 +02:00
|
|
|
# Complete metadata with mailgun event info
|
2020-04-02 11:15:00 +02:00
|
|
|
metadata = self._mailgun_metadata(mailgun_event_type, post, metadata)
|
2016-07-15 13:41:49 +02:00
|
|
|
# Create event
|
|
|
|
tracking.event_create(mapped_event_type, metadata)
|
2020-04-02 11:15:00 +02:00
|
|
|
if res != "NONE":
|
2016-07-15 13:41:49 +02:00
|
|
|
if event_type:
|
2020-04-02 11:15:00 +02:00
|
|
|
_logger.info("Mailgun: event '%s' process '%s'", event_type, res)
|
2016-07-15 13:41:49 +02:00
|
|
|
else:
|
|
|
|
_logger.info("Mailgun: event process '%s'", res)
|
|
|
|
return res
|
2017-10-17 20:38:11 +02:00
|
|
|
|
|
|
|
@api.multi
|
|
|
|
def action_manual_check_mailgun(self):
|
|
|
|
"""
|
|
|
|
Manual check against Mailgun API
|
|
|
|
API Documentation:
|
|
|
|
https://documentation.mailgun.com/en/latest/api-events.html
|
|
|
|
"""
|
|
|
|
api_key, api_url, domain, validation_key = self._mailgun_values()
|
|
|
|
for tracking in self:
|
2017-12-22 19:23:40 +01:00
|
|
|
if not tracking.mail_message_id:
|
2020-04-02 11:15:00 +02:00
|
|
|
raise UserError(_("There is no tracked message!"))
|
|
|
|
message_id = tracking.mail_message_id.message_id.replace("<", "").replace(
|
|
|
|
">", ""
|
|
|
|
)
|
2017-10-17 20:38:11 +02:00
|
|
|
res = requests.get(
|
2020-04-02 11:15:00 +02:00
|
|
|
"{}/{}/events".format(api_url, domain),
|
2017-10-17 20:38:11 +02:00
|
|
|
auth=("api", api_key),
|
|
|
|
params={
|
|
|
|
"begin": tracking.timestamp,
|
|
|
|
"ascending": "yes",
|
|
|
|
"message-id": message_id,
|
2020-04-02 11:15:00 +02:00
|
|
|
},
|
2017-10-17 20:38:11 +02:00
|
|
|
)
|
|
|
|
if not res or res.status_code != 200:
|
2020-04-02 11:15:00 +02:00
|
|
|
raise ValidationError(_("Couldn't retrieve Mailgun information"))
|
2018-05-08 18:24:36 +02:00
|
|
|
content = res.json()
|
2017-10-17 20:38:11 +02:00
|
|
|
if "items" not in content:
|
|
|
|
raise ValidationError(_("Event information not longer stored"))
|
|
|
|
for item in content["items"]:
|
2018-02-15 19:46:21 +01:00
|
|
|
# mailgun event hasn't been synced and recipient is the same as
|
|
|
|
# in the evaluated tracking. We use email_split since tracking
|
|
|
|
# recipient could come in format: "example" <to@dest.com>
|
2020-04-02 11:15:00 +02:00
|
|
|
if not self.env["mail.tracking.event"].search(
|
|
|
|
[("mailgun_id", "=", item["id"])]
|
|
|
|
) and (item.get("recipient", "") == email_split(tracking.recipient)[0]):
|
2017-10-17 20:38:11 +02:00
|
|
|
mapped_event_type = self._mailgun_event_type_mapping.get(
|
2020-04-02 11:15:00 +02:00
|
|
|
item["event"], item["event"]
|
|
|
|
)
|
|
|
|
metadata = self._mailgun_metadata(mapped_event_type, item, {})
|
2017-10-17 20:38:11 +02:00
|
|
|
tracking.event_create(mapped_event_type, metadata)
|