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.

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