|
| 1 | +# Copyright 2024 Hoang Tran <[email protected]>. |
| 2 | +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). |
| 3 | +import base64 |
| 4 | +import logging |
| 5 | +import traceback |
| 6 | +from uuid import uuid4 |
| 7 | + |
| 8 | +from pytz import timezone |
| 9 | + |
| 10 | +from odoo import Command, _, api, exceptions, fields, models, tools |
| 11 | +from odoo.tools import ustr |
| 12 | +from odoo.tools.float_utils import float_compare |
| 13 | +from odoo.tools.safe_eval import safe_eval |
| 14 | + |
| 15 | +_logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class InheritedBaseAutomation(models.Model): |
| 19 | + _inherit = "base.automation" |
| 20 | + |
| 21 | + trigger = fields.Selection( |
| 22 | + selection_add=[("on_webhook", "On webhook")], ondelete={"on_webhook": "cascade"} |
| 23 | + ) |
| 24 | + webhook_uuid = fields.Char( |
| 25 | + string="Webhook UUID", |
| 26 | + readonly=True, |
| 27 | + copy=False, |
| 28 | + default=lambda self: str(uuid4()), |
| 29 | + ) |
| 30 | + url = fields.Char(string="Webhook URL", compute="_compute_url") |
| 31 | + log_webhook_calls = fields.Boolean(string="Log Calls", default=False) |
| 32 | + allow_creation = fields.Boolean( |
| 33 | + string="Allow creation?", |
| 34 | + help="Allow executing webhook to maybe create record if a record is not " |
| 35 | + "found using record getter", |
| 36 | + ) |
| 37 | + record_getter = fields.Char( |
| 38 | + default="model.env[payload.get('_model')].browse(int(payload.get('_id')))", |
| 39 | + help="This code will be run to find on which record the automation rule should be run.", |
| 40 | + ) |
| 41 | + create_record_code = fields.Text( |
| 42 | + "Record Creation Code", |
| 43 | + default="""# Available variables: |
| 44 | +# - env: Odoo Environment on which the action is triggered |
| 45 | +# - model: Odoo Model of the record on which the action is triggered; |
| 46 | +# is a void recordset |
| 47 | +# - record: record on which the action is triggered; may be void |
| 48 | +# - records: recordset of all records on which the action is triggered |
| 49 | +# in multi-mode; may be void |
| 50 | +# - payload: input payload from webhook request |
| 51 | +# - time, datetime, dateutil, timezone: useful Python libraries |
| 52 | +# - float_compare: Odoo function to compare floats based on specific precisions |
| 53 | +# - log: log(message, level='info'): logging function to record debug information |
| 54 | +# in ir.logging table |
| 55 | +# - UserError: Warning Exception to use with raise |
| 56 | +# - Command: x2Many commands namespace |
| 57 | +# You must return the created record by assign it to `record` variable: |
| 58 | +# - record = res.partner(1,) |
| 59 | +""", |
| 60 | + help="This block of code is eval if Record Getter couldn't find a matching record.", |
| 61 | + ) |
| 62 | + create_record_action_id = fields.Many2one(comodel_name="ir.actions.server") |
| 63 | + delay_execution = fields.Boolean( |
| 64 | + help="Queue actions to perform to delay execution." |
| 65 | + ) |
| 66 | + |
| 67 | + @api.depends("webhook_uuid") |
| 68 | + def _compute_webhook_url(self): |
| 69 | + base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url") |
| 70 | + for webhook in self: |
| 71 | + webhook.webhook_url = "%s/web/hook/%s" % (base_url, webhook.webhook_uuid) |
| 72 | + |
| 73 | + @api.depends("trigger", "webhook_uuid") |
| 74 | + def _compute_url(self): |
| 75 | + for automation in self: |
| 76 | + if automation.trigger != "on_webhook": |
| 77 | + automation.url = "" |
| 78 | + else: |
| 79 | + automation.url = "%s/web/hook/%s" % ( |
| 80 | + automation.get_base_url(), |
| 81 | + automation.webhook_uuid, |
| 82 | + ) |
| 83 | + |
| 84 | + def _get_eval_context(self, payload=None): |
| 85 | + """ |
| 86 | + Override to add payload to context |
| 87 | + """ |
| 88 | + eval_context = super()._get_eval_context() |
| 89 | + eval_context["model"] = self.env[self.model_name] |
| 90 | + eval_context["payload"] = payload if payload is not None else {} |
| 91 | + return eval_context |
| 92 | + |
| 93 | + def _execute_webhook(self, payload): |
| 94 | + """Execute the webhook for the given payload. |
| 95 | + The payload is a dictionnary that can be used by the `record_getter` to |
| 96 | + identify the record on which the automation should be run. |
| 97 | + """ |
| 98 | + self.ensure_one() |
| 99 | + |
| 100 | + # info logging is done by the ir.http logger |
| 101 | + msg = "Webhook #%s triggered with payload %s" |
| 102 | + msg_args = (self.id, payload) |
| 103 | + _logger.debug(msg, *msg_args) |
| 104 | + |
| 105 | + record = self.env[self.model_name] |
| 106 | + eval_context = self._get_eval_context(payload=payload) |
| 107 | + |
| 108 | + if self.record_getter: |
| 109 | + try: |
| 110 | + record = safe_eval(self.record_getter, eval_context) |
| 111 | + except Exception as e: # noqa: BLE001 |
| 112 | + msg = "Webhook #%s could not be triggered because the record_getter failed:\n%s" |
| 113 | + msg_args = (self.id, traceback.format_exc()) |
| 114 | + _logger.warning(msg, *msg_args) |
| 115 | + self._webhook_logging(payload, self._add_postmortem(e)) |
| 116 | + raise e |
| 117 | + |
| 118 | + if not record.exists() and self.allow_creation: |
| 119 | + try: |
| 120 | + create_eval_context = self._get_create_eval_context(payload=payload) |
| 121 | + safe_eval( |
| 122 | + self.create_record_code, |
| 123 | + create_eval_context, |
| 124 | + mode="exec", |
| 125 | + nocopy=True, |
| 126 | + ) # nocopy allows to return 'action' |
| 127 | + record = create_eval_context.get("record", self.model_id.browse()) |
| 128 | + except Exception as e: # noqa: BLE001 |
| 129 | + msg = "Webhook #%s failed with error:\n%s" |
| 130 | + msg_args = (self.id, traceback.format_exc()) |
| 131 | + _logger.warning(msg, *msg_args) |
| 132 | + self._webhook_logging(payload, self._add_postmortem(e)) |
| 133 | + elif not record.exists(): |
| 134 | + msg = "Webhook #%s could not be triggered because no record to run it on was found." |
| 135 | + msg_args = (self.id,) |
| 136 | + _logger.warning(msg, *msg_args) |
| 137 | + self._webhook_logging(payload, msg) |
| 138 | + raise exceptions.ValidationError( |
| 139 | + _("No record to run the automation on was found.") |
| 140 | + ) |
| 141 | + |
| 142 | + try: |
| 143 | + # quirk: base.automation(,)._process has a ``context["__action_done"]`` |
| 144 | + # at the very beginning of the function while it wasn't set before-hand. |
| 145 | + # so setting this context now to avoid further issue advancing forward. |
| 146 | + if "__action_done" not in self._context: |
| 147 | + self = self.with_context(__action_done={}, payload=payload) |
| 148 | + return self._process(record) |
| 149 | + except Exception as e: # noqa: BLE001 |
| 150 | + msg = "Webhook #%s failed with error:\n%s" |
| 151 | + msg_args = (self.id, traceback.format_exc()) |
| 152 | + _logger.warning(msg, *msg_args) |
| 153 | + self._webhook_logging(payload, self._add_postmortem(e)) |
| 154 | + raise e |
| 155 | + finally: |
| 156 | + self._webhook_logging(payload, None) |
| 157 | + |
| 158 | + def _get_create_eval_context(self, payload=None): |
| 159 | + def log(message, level="info"): |
| 160 | + with self.pool.cursor() as cr: |
| 161 | + cr.execute( |
| 162 | + """ |
| 163 | + INSERT INTO ir_logging( |
| 164 | + create_date, create_uid, type, dbname, name, |
| 165 | + level, message, path, line, func |
| 166 | + ) |
| 167 | + VALUES (NOW() at time zone 'UTC', %s, %s, %s, %s, %s, %s, %s, %s, %s) |
| 168 | + """, |
| 169 | + ( |
| 170 | + self.env.uid, |
| 171 | + "server", |
| 172 | + self._cr.dbname, |
| 173 | + __name__, |
| 174 | + level, |
| 175 | + message, |
| 176 | + "action", |
| 177 | + self.id, |
| 178 | + self.name, |
| 179 | + ), |
| 180 | + ) |
| 181 | + |
| 182 | + eval_context = dict(self.env.context) |
| 183 | + model_name = self.model_id.sudo().model |
| 184 | + model = self.env[model_name] |
| 185 | + eval_context.update( |
| 186 | + { |
| 187 | + "uid": self._uid, |
| 188 | + "user": self.env.user, |
| 189 | + "time": tools.safe_eval.time, |
| 190 | + "datetime": tools.safe_eval.datetime, |
| 191 | + "dateutil": tools.safe_eval.dateutil, |
| 192 | + "timezone": timezone, |
| 193 | + "float_compare": float_compare, |
| 194 | + "b64encode": base64.b64encode, |
| 195 | + "b64decode": base64.b64decode, |
| 196 | + "Command": Command, |
| 197 | + "env": self.env, |
| 198 | + "model": model, |
| 199 | + "log": log, |
| 200 | + "payload": payload, |
| 201 | + } |
| 202 | + ) |
| 203 | + return eval_context |
| 204 | + |
| 205 | + def _webhook_logging(self, body, response): |
| 206 | + if self.log_webhook_calls: |
| 207 | + |
| 208 | + vals = { |
| 209 | + "webhook_type": "incoming", |
| 210 | + "webhook": "%s (%s)" % (self.name, self), |
| 211 | + "endpoint": self.url, |
| 212 | + "headers": "{}", |
| 213 | + "request": ustr(body), |
| 214 | + "body": "{}", |
| 215 | + "response": ustr(response), |
| 216 | + "status": getattr(response, "status_code", None), |
| 217 | + } |
| 218 | + self.env["webhook.logging"].create(vals) |
| 219 | + |
| 220 | + def _process(self, records, domain_post=None): |
| 221 | + """ |
| 222 | + Override to allow delay execution |
| 223 | + """ |
| 224 | + to_delay = self.filtered(lambda a: a.delay_execution) |
| 225 | + execute_now = self - to_delay |
| 226 | + |
| 227 | + super( |
| 228 | + InheritedBaseAutomation, |
| 229 | + to_delay.with_context(delay_execution=True), |
| 230 | + )._process(records, domain_post=domain_post) |
| 231 | + |
| 232 | + return super(InheritedBaseAutomation, execute_now)._process( |
| 233 | + records, domain_post=domain_post |
| 234 | + ) |
0 commit comments