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.

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