models.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from django.db import models
  2. from django.utils.translation import gettext_lazy as _
  3. from glitchtip.base_models import CreatedModel
  4. from .email import send_email_notification
  5. from .webhooks import send_webhook_notification
  6. class ProjectAlert(CreatedModel):
  7. """
  8. Example: Send notification when project has 15 events in 5 minutes.
  9. """
  10. name = models.CharField(max_length=255, blank=True)
  11. project = models.ForeignKey("projects.Project", on_delete=models.CASCADE)
  12. timespan_minutes = models.PositiveSmallIntegerField(blank=True, null=True)
  13. quantity = models.PositiveSmallIntegerField(blank=True, null=True)
  14. uptime = models.BooleanField(
  15. default=False, help_text="Send alert on any uptime monitor check failure"
  16. )
  17. class AlertRecipient(models.Model):
  18. """ An asset that accepts an alert such as email, SMS, webhooks """
  19. class RecipientType(models.TextChoices):
  20. EMAIL = "email", _("Email")
  21. WEBHOOK = "webhook", _("Webhook")
  22. alert = models.ForeignKey(ProjectAlert, on_delete=models.CASCADE)
  23. recipient_type = models.CharField(max_length=16, choices=RecipientType.choices)
  24. url = models.URLField(max_length=2000, blank=True)
  25. class Meta:
  26. unique_together = ("alert", "recipient_type", "url")
  27. def send(self, notification):
  28. if self.recipient_type == self.RecipientType.EMAIL:
  29. send_email_notification(notification)
  30. elif self.recipient_type == self.RecipientType.WEBHOOK:
  31. send_webhook_notification(notification, self.url)
  32. class Notification(CreatedModel):
  33. project_alert = models.ForeignKey(ProjectAlert, on_delete=models.CASCADE)
  34. is_sent = models.BooleanField(default=False)
  35. issues = models.ManyToManyField("issues.Issue")
  36. def send_notifications(self):
  37. for recipient in self.project_alert.alertrecipient_set.all():
  38. recipient.send(self)
  39. # Temp backwards compat hack - no recipients means not set up yet
  40. if self.project_alert.alertrecipient_set.all().exists() is False:
  41. send_email_notification(self)
  42. self.is_sent = True
  43. self.save()