You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

274 lines
9.4 KiB

10 years ago
8 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. from base64 import urlsafe_b64encode
  2. from datetime import timedelta
  3. import os
  4. import uuid
  5. from django.conf import settings
  6. from django.contrib.auth.hashers import check_password, make_password
  7. from django.contrib.auth.models import User
  8. from django.core.signing import TimestampSigner
  9. from django.db import models
  10. from django.db.models import Count, Q
  11. from django.urls import reverse
  12. from django.utils import timezone
  13. from hc.lib import emails
  14. NO_NAG = timedelta()
  15. NAG_PERIODS = (
  16. (NO_NAG, "Disabled"),
  17. (timedelta(hours=1), "Hourly"),
  18. (timedelta(days=1), "Daily"),
  19. )
  20. def month(dt):
  21. """ For a given datetime, return the matching first-day-of-month date. """
  22. return dt.date().replace(day=1)
  23. class ProfileManager(models.Manager):
  24. def for_user(self, user):
  25. try:
  26. return user.profile
  27. except Profile.DoesNotExist:
  28. profile = Profile(user=user)
  29. if not settings.USE_PAYMENTS:
  30. # If not using payments, set high limits
  31. profile.check_limit = 500
  32. profile.sms_limit = 500
  33. profile.team_limit = 500
  34. profile.save()
  35. return profile
  36. class Profile(models.Model):
  37. user = models.OneToOneField(User, models.CASCADE, blank=True, null=True)
  38. next_report_date = models.DateTimeField(null=True, blank=True)
  39. reports_allowed = models.BooleanField(default=True)
  40. nag_period = models.DurationField(default=NO_NAG, choices=NAG_PERIODS)
  41. next_nag_date = models.DateTimeField(null=True, blank=True)
  42. ping_log_limit = models.IntegerField(default=100)
  43. check_limit = models.IntegerField(default=20)
  44. token = models.CharField(max_length=128, blank=True)
  45. current_project = models.ForeignKey("Project", models.SET_NULL, null=True)
  46. last_sms_date = models.DateTimeField(null=True, blank=True)
  47. sms_limit = models.IntegerField(default=0)
  48. sms_sent = models.IntegerField(default=0)
  49. team_limit = models.IntegerField(default=2)
  50. sort = models.CharField(max_length=20, default="created")
  51. deletion_notice_date = models.DateTimeField(null=True, blank=True)
  52. objects = ProfileManager()
  53. def __str__(self):
  54. return "Profile for %s" % self.user.email
  55. def notifications_url(self):
  56. return settings.SITE_ROOT + reverse("hc-notifications")
  57. def reports_unsub_url(self):
  58. signer = TimestampSigner(salt="reports")
  59. signed_username = signer.sign(self.user.username)
  60. path = reverse("hc-unsubscribe-reports", args=[signed_username])
  61. return settings.SITE_ROOT + path
  62. def prepare_token(self, salt):
  63. token = urlsafe_b64encode(os.urandom(24)).decode()
  64. self.token = make_password(token, salt)
  65. self.save()
  66. return token
  67. def check_token(self, token, salt):
  68. return salt in self.token and check_password(token, self.token)
  69. def send_instant_login_link(self, inviting_project=None, redirect_url=None):
  70. token = self.prepare_token("login")
  71. path = reverse("hc-check-token", args=[self.user.username, token])
  72. if redirect_url:
  73. path += "?next=%s" % redirect_url
  74. ctx = {
  75. "button_text": "Sign In",
  76. "button_url": settings.SITE_ROOT + path,
  77. "inviting_project": inviting_project,
  78. }
  79. emails.login(self.user.email, ctx)
  80. def send_set_password_link(self):
  81. token = self.prepare_token("set-password")
  82. path = reverse("hc-set-password", args=[token])
  83. ctx = {"button_text": "Set Password", "button_url": settings.SITE_ROOT + path}
  84. emails.set_password(self.user.email, ctx)
  85. def send_change_email_link(self):
  86. token = self.prepare_token("change-email")
  87. path = reverse("hc-change-email", args=[token])
  88. ctx = {"button_text": "Change Email", "button_url": settings.SITE_ROOT + path}
  89. emails.change_email(self.user.email, ctx)
  90. def projects(self):
  91. """ Return a queryset of all projects we have access to. """
  92. is_owner = Q(owner=self.user)
  93. is_member = Q(member__user=self.user)
  94. q = Project.objects.filter(is_owner | is_member)
  95. return q.distinct().order_by("name")
  96. def annotated_projects(self):
  97. """ Return all projects, annotated with 'n_down'. """
  98. # Subquery for getting project ids
  99. project_ids = self.projects().values("id")
  100. # Main query with the n_down annotation.
  101. # Must use the subquery, otherwise ORM gets confused by
  102. # joins and group by's
  103. q = Project.objects.filter(id__in=project_ids)
  104. n_down = Count("check", filter=Q(check__status="down"))
  105. q = q.annotate(n_down=n_down)
  106. return q.order_by("name")
  107. def checks_from_all_projects(self):
  108. """ Return a queryset of checks from projects we have access to. """
  109. project_ids = self.projects().values("id")
  110. from hc.api.models import Check
  111. return Check.objects.filter(project_id__in=project_ids)
  112. def send_report(self, nag=False):
  113. checks = self.checks_from_all_projects()
  114. # Has there been a ping in last 6 months?
  115. result = checks.aggregate(models.Max("last_ping"))
  116. last_ping = result["last_ping__max"]
  117. six_months_ago = timezone.now() - timedelta(days=180)
  118. if last_ping is None or last_ping < six_months_ago:
  119. return False
  120. # Is there at least one check that is down?
  121. num_down = checks.filter(status="down").count()
  122. if nag and num_down == 0:
  123. return False
  124. # Sort checks by project. Need this because will group by project in
  125. # template.
  126. checks = checks.select_related("project")
  127. checks = checks.order_by("project_id")
  128. # list() executes the query, to avoid DB access while
  129. # rendering the template
  130. checks = list(checks)
  131. unsub_url = self.reports_unsub_url()
  132. headers = {"List-Unsubscribe": unsub_url, "X-Bounce-Url": unsub_url}
  133. ctx = {
  134. "checks": checks,
  135. "sort": self.sort,
  136. "now": timezone.now(),
  137. "unsub_link": unsub_url,
  138. "notifications_url": self.notifications_url(),
  139. "nag": nag,
  140. "nag_period": self.nag_period.total_seconds(),
  141. "num_down": num_down,
  142. }
  143. emails.report(self.user.email, ctx, headers)
  144. return True
  145. def sms_sent_this_month(self):
  146. # IF last_sms_date was never set, we have not sent any messages yet.
  147. if not self.last_sms_date:
  148. return 0
  149. # If last sent date is not from this month, we've sent 0 this month.
  150. if month(timezone.now()) > month(self.last_sms_date):
  151. return 0
  152. return self.sms_sent
  153. def authorize_sms(self):
  154. """ If monthly limit not exceeded, increase counter and return True """
  155. sent_this_month = self.sms_sent_this_month()
  156. if sent_this_month >= self.sms_limit:
  157. return False
  158. self.sms_sent = sent_this_month + 1
  159. self.last_sms_date = timezone.now()
  160. self.save()
  161. return True
  162. class Project(models.Model):
  163. code = models.UUIDField(default=uuid.uuid4, unique=True)
  164. name = models.CharField(max_length=200, blank=True)
  165. owner = models.ForeignKey(User, models.CASCADE)
  166. api_key = models.CharField(max_length=128, blank=True, db_index=True)
  167. api_key_readonly = models.CharField(max_length=128, blank=True, db_index=True)
  168. badge_key = models.CharField(max_length=150, unique=True)
  169. def __str__(self):
  170. return self.name or self.owner.email
  171. @property
  172. def owner_profile(self):
  173. return Profile.objects.for_user(self.owner)
  174. def num_checks_available(self):
  175. from hc.api.models import Check
  176. num_used = Check.objects.filter(project__owner=self.owner).count()
  177. return self.owner_profile.check_limit - num_used
  178. def set_api_keys(self):
  179. self.api_key = urlsafe_b64encode(os.urandom(24)).decode()
  180. self.api_key_readonly = urlsafe_b64encode(os.urandom(24)).decode()
  181. self.save()
  182. def can_invite(self):
  183. return self.member_set.count() < self.owner_profile.team_limit
  184. def invite(self, user):
  185. Member.objects.create(user=user, project=self)
  186. # Switch the invited user over to the new team so they
  187. # notice the new team on next visit:
  188. user.profile.current_project = self
  189. user.profile.save()
  190. user.profile.send_instant_login_link(self)
  191. def set_next_nag_date(self):
  192. """ Set next_nag_date on profiles of all members of this project. """
  193. is_owner = Q(user=self.owner)
  194. is_member = Q(user__memberships__project=self)
  195. q = Profile.objects.filter(is_owner | is_member)
  196. q = q.exclude(nag_period=NO_NAG)
  197. # Exclude profiles with next_nag_date already set
  198. q = q.filter(next_nag_date__isnull=True)
  199. q.update(next_nag_date=timezone.now() + models.F("nag_period"))
  200. def overall_status(self):
  201. status = "up"
  202. for check in self.check_set.all():
  203. check_status = check.get_status(with_started=False)
  204. if status == "up" and check_status == "grace":
  205. status = "grace"
  206. if check_status == "down":
  207. status = "down"
  208. break
  209. return status
  210. class Member(models.Model):
  211. user = models.ForeignKey(User, models.CASCADE, related_name="memberships")
  212. project = models.ForeignKey(Project, models.CASCADE)