models.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. """ Email only for now, eventually needs to be an extendable system """
  38. for recipient in self.project_alert.alertrecipient_set.all():
  39. recipient.send(self)
  40. # Temp backwards compat hack - no recipients means not set up yet
  41. if self.project_alert.alertrecipient_set.all().exists() is False:
  42. send_email_notification(self)
  43. self.is_sent = True
  44. self.save()