|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# DejaCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: AGPL-3.0-only |
| 5 | +# See https://github.com/aboutcode-org/dejacode for support or download. |
| 6 | +# See https://aboutcode.org for more information about AboutCode FOSS projects. |
| 7 | +# |
| 8 | + |
| 9 | +import json |
| 10 | +import logging |
| 11 | +from urllib.parse import urlparse |
| 12 | + |
| 13 | +from django.core.serializers.json import DjangoJSONEncoder |
| 14 | +from django.db import models |
| 15 | +from django.utils.translation import gettext_lazy as _ |
| 16 | + |
| 17 | +import requests |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +class WebhookSubscriptionQuerySetMixin: |
| 23 | + """Mixin for WebhookSubscription querysets. Combine with the project's base QuerySet.""" |
| 24 | + |
| 25 | + def active(self): |
| 26 | + return self.filter(is_active=True) |
| 27 | + |
| 28 | + |
| 29 | +class AbstractWebhookSubscription(models.Model): |
| 30 | + """ |
| 31 | + Abstract base for Webhook subscription models. |
| 32 | +
|
| 33 | + Subclasses must implement get_payload(context) and create_delivery(payload, context). |
| 34 | + Override get_slack_payload(context) to support Slack webhook URLs. |
| 35 | + """ |
| 36 | + |
| 37 | + target_url = models.URLField( |
| 38 | + _("Target URL"), |
| 39 | + max_length=1024, |
| 40 | + blank=False, |
| 41 | + help_text=_( |
| 42 | + "The URL to which the POST request will be sent when the Webhook is triggered." |
| 43 | + ), |
| 44 | + ) |
| 45 | + is_active = models.BooleanField( |
| 46 | + default=True, |
| 47 | + help_text=_("Indicates whether the Webhook is currently active and should be triggered."), |
| 48 | + ) |
| 49 | + event = models.CharField( |
| 50 | + _("Event"), |
| 51 | + max_length=64, |
| 52 | + null=True, |
| 53 | + blank=True, |
| 54 | + help_text=_("The event type that triggers this Webhook subscription."), |
| 55 | + ) |
| 56 | + created_date = models.DateTimeField( |
| 57 | + auto_now_add=True, |
| 58 | + editable=False, |
| 59 | + help_text=_("The date and time when the Webhook subscription was created."), |
| 60 | + ) |
| 61 | + |
| 62 | + class Meta: |
| 63 | + abstract = True |
| 64 | + |
| 65 | + def get_payload(self, context): |
| 66 | + raise NotImplementedError |
| 67 | + |
| 68 | + def get_slack_payload(self, context): |
| 69 | + """Return a Slack-specific payload, or None to fall back to get_payload.""" |
| 70 | + return None |
| 71 | + |
| 72 | + def create_delivery(self, payload, context): |
| 73 | + raise NotImplementedError |
| 74 | + |
| 75 | + def get_headers(self): |
| 76 | + """Return the HTTP headers to include in the Webhook request.""" |
| 77 | + return {"Content-Type": "application/json"} |
| 78 | + |
| 79 | + def deliver(self, context, timeout=10, payload_override=None): |
| 80 | + """Deliver this Webhook by sending a POST request to the target_url.""" |
| 81 | + logger.info(f"Delivering Webhook {self.uuid}") |
| 82 | + |
| 83 | + if not self.is_active: |
| 84 | + logger.info(f"Webhook {self.uuid} is not active.") |
| 85 | + return False |
| 86 | + |
| 87 | + if payload_override: |
| 88 | + payload = payload_override |
| 89 | + else: |
| 90 | + parsed = urlparse(self.target_url) |
| 91 | + if parsed.hostname == "hooks.slack.com" and ( |
| 92 | + slack_payload := self.get_slack_payload(context) |
| 93 | + ): |
| 94 | + payload = slack_payload |
| 95 | + else: |
| 96 | + payload = self.get_payload(context) |
| 97 | + |
| 98 | + delivery = self.create_delivery(payload, context) |
| 99 | + |
| 100 | + try: |
| 101 | + response = requests.post( |
| 102 | + url=self.target_url, |
| 103 | + data=json.dumps(payload, cls=DjangoJSONEncoder), |
| 104 | + headers=self.get_headers(), |
| 105 | + timeout=timeout, |
| 106 | + ) |
| 107 | + except requests.exceptions.RequestException as exception: |
| 108 | + logger.error(exception) |
| 109 | + delivery.delivery_error = str(exception) |
| 110 | + delivery.save() |
| 111 | + return delivery |
| 112 | + |
| 113 | + delivery.response_status_code = response.status_code |
| 114 | + delivery.response_text = response.text |
| 115 | + delivery.save() |
| 116 | + |
| 117 | + if delivery.success: |
| 118 | + logger.info(f"Webhook {self.uuid} delivered successfully.") |
| 119 | + else: |
| 120 | + logger.info(f"Webhook {self.uuid} returned a {response.status_code}.") |
| 121 | + |
| 122 | + return delivery |
| 123 | + |
| 124 | + |
| 125 | +class AbstractWebhookDelivery(models.Model): |
| 126 | + """Abstract base for Webhook delivery history models.""" |
| 127 | + |
| 128 | + target_url = models.URLField( |
| 129 | + _("Target URL"), |
| 130 | + max_length=1024, |
| 131 | + blank=False, |
| 132 | + help_text=_( |
| 133 | + "Stores a copy of the Webhook target URL in case the subscription object is deleted." |
| 134 | + ), |
| 135 | + ) |
| 136 | + sent_date = models.DateTimeField( |
| 137 | + auto_now_add=True, |
| 138 | + editable=False, |
| 139 | + help_text=_("The date and time when the Webhook was sent."), |
| 140 | + ) |
| 141 | + payload = models.JSONField( |
| 142 | + blank=True, |
| 143 | + default=dict, |
| 144 | + help_text=_("The JSON payload that was sent to the target URL."), |
| 145 | + ) |
| 146 | + response_status_code = models.PositiveIntegerField( |
| 147 | + null=True, |
| 148 | + blank=True, |
| 149 | + help_text=_("The HTTP status code received in response to the Webhook request."), |
| 150 | + ) |
| 151 | + response_text = models.TextField( |
| 152 | + blank=True, |
| 153 | + help_text=_("The text response received from the target URL."), |
| 154 | + ) |
| 155 | + delivery_error = models.TextField( |
| 156 | + blank=True, |
| 157 | + help_text=_("Any error messages encountered during the Webhook delivery."), |
| 158 | + ) |
| 159 | + |
| 160 | + class Meta: |
| 161 | + abstract = True |
| 162 | + verbose_name = _("webhook delivery") |
| 163 | + verbose_name_plural = _("webhook deliveries") |
| 164 | + |
| 165 | + def __str__(self): |
| 166 | + return f"Webhook uuid={self.uuid} posted at {self.sent_date}" |
| 167 | + |
| 168 | + @property |
| 169 | + def delivered(self): |
| 170 | + return bool(self.response_status_code) |
| 171 | + |
| 172 | + @property |
| 173 | + def success(self): |
| 174 | + return self.response_status_code in (200, 201, 202) |
0 commit comments