models.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. RecipientType.GOOGLE_CHAT,
  30. )
  31. def send(self, notification):
  32. if self.recipient_type == RecipientType.EMAIL:
  33. send_email_notification(notification)
  34. elif self.is_webhook:
  35. send_webhook_notification(notification, self.url, self.recipient_type)
  36. class Notification(CreatedModel):
  37. project_alert = models.ForeignKey(ProjectAlert, on_delete=models.CASCADE)
  38. is_sent = models.BooleanField(default=False)
  39. issues = models.ManyToManyField("issues.Issue")
  40. def send_notifications(self):
  41. for recipient in self.project_alert.alertrecipient_set.all():
  42. recipient.send(self)
  43. # Temp backwards compat hack - no recipients means not set up yet
  44. if self.project_alert.alertrecipient_set.all().exists() is False:
  45. send_email_notification(self)
  46. self.is_sent = True
  47. self.save()