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.

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