models.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from django.db import models
  2. from glitchtip.base_models import CreatedModel
  3. from .constants import RecipientType
  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. alert = models.ForeignKey(ProjectAlert, on_delete=models.CASCADE)
  20. recipient_type = models.CharField(max_length=16, choices=RecipientType.choices)
  21. url = models.URLField(max_length=2000, blank=True)
  22. class Meta:
  23. unique_together = ("alert", "recipient_type", "url")
  24. @property
  25. def is_webhook(self):
  26. return self.recipient_type in (
  27. RecipientType.DISCORD,
  28. RecipientType.GENERAL_WEBHOOK,
  29. )
  30. def send(self, notification):
  31. if self.recipient_type == RecipientType.EMAIL:
  32. send_email_notification(notification)
  33. elif self.is_webhook:
  34. send_webhook_notification(notification, self.url, self.recipient_type)
  35. class Notification(CreatedModel):
  36. project_alert = models.ForeignKey(ProjectAlert, on_delete=models.CASCADE)
  37. is_sent = models.BooleanField(default=False)
  38. issues = models.ManyToManyField("issues.Issue")
  39. def send_notifications(self):
  40. for recipient in self.project_alert.alertrecipient_set.all():
  41. recipient.send(self)
  42. # Temp backwards compat hack - no recipients means not set up yet
  43. if self.project_alert.alertrecipient_set.all().exists() is False:
  44. send_email_notification(self)
  45. self.is_sent = True
  46. self.save()