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.

300 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 datetime import timedelta
  2. from secrets import token_urlsafe
  3. import uuid
  4. from django.conf import settings
  5. from django.contrib.auth.hashers import check_password, make_password
  6. from django.contrib.auth.models import User
  7. from django.core.signing import TimestampSigner
  8. from django.db import models
  9. from django.db.models import Count, Q
  10. from django.urls import reverse
  11. from django.utils import timezone
  12. from hc.lib import emails
  13. from hc.lib.date import month_boundaries
  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. last_sms_date = models.DateTimeField(null=True, blank=True)
  46. sms_limit = models.IntegerField(default=5)
  47. sms_sent = models.IntegerField(default=0)
  48. team_limit = models.IntegerField(default=2)
  49. sort = models.CharField(max_length=20, default="created")
  50. deletion_notice_date = models.DateTimeField(null=True, blank=True)
  51. last_active_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 = token_urlsafe(24)
  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 send_sms_limit_notice(self, transport):
  91. ctx = {"transport": transport, "limit": self.sms_limit}
  92. if self.sms_limit != 500 and settings.USE_PAYMENTS:
  93. ctx["url"] = settings.SITE_ROOT + reverse("hc-pricing")
  94. emails.sms_limit(self.user.email, ctx)
  95. def projects(self):
  96. """ Return a queryset of all projects we have access to. """
  97. is_owner = Q(owner=self.user)
  98. is_member = Q(member__user=self.user)
  99. q = Project.objects.filter(is_owner | is_member)
  100. return q.distinct().order_by("name")
  101. def annotated_projects(self):
  102. """ Return all projects, annotated with 'n_down'. """
  103. # Subquery for getting project ids
  104. project_ids = self.projects().values("id")
  105. # Main query with the n_down annotation.
  106. # Must use the subquery, otherwise ORM gets confused by
  107. # joins and group by's
  108. q = Project.objects.filter(id__in=project_ids)
  109. n_down = Count("check", filter=Q(check__status="down"))
  110. q = q.annotate(n_down=n_down)
  111. return q.order_by("name")
  112. def checks_from_all_projects(self):
  113. """ Return a queryset of checks from projects we have access to. """
  114. project_ids = self.projects().values("id")
  115. from hc.api.models import Check
  116. return Check.objects.filter(project_id__in=project_ids)
  117. def send_report(self, nag=False):
  118. checks = self.checks_from_all_projects()
  119. # Has there been a ping in last 6 months?
  120. result = checks.aggregate(models.Max("last_ping"))
  121. last_ping = result["last_ping__max"]
  122. six_months_ago = timezone.now() - timedelta(days=180)
  123. if last_ping is None or last_ping < six_months_ago:
  124. return False
  125. # Is there at least one check that is down?
  126. num_down = checks.filter(status="down").count()
  127. if nag and num_down == 0:
  128. return False
  129. # Sort checks by project. Need this because will group by project in
  130. # template.
  131. checks = checks.select_related("project")
  132. checks = checks.order_by("project_id")
  133. # list() executes the query, to avoid DB access while
  134. # rendering the template
  135. checks = list(checks)
  136. unsub_url = self.reports_unsub_url()
  137. headers = {
  138. "List-Unsubscribe": "<%s>" % unsub_url,
  139. "X-Bounce-Url": unsub_url,
  140. "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
  141. }
  142. ctx = {
  143. "checks": checks,
  144. "sort": self.sort,
  145. "now": timezone.now(),
  146. "unsub_link": unsub_url,
  147. "notifications_url": self.notifications_url(),
  148. "nag": nag,
  149. "nag_period": self.nag_period.total_seconds(),
  150. "num_down": num_down,
  151. "month_boundaries": month_boundaries(),
  152. }
  153. emails.report(self.user.email, ctx, headers)
  154. return True
  155. def sms_sent_this_month(self):
  156. # IF last_sms_date was never set, we have not sent any messages yet.
  157. if not self.last_sms_date:
  158. return 0
  159. # If last sent date is not from this month, we've sent 0 this month.
  160. if month(timezone.now()) > month(self.last_sms_date):
  161. return 0
  162. return self.sms_sent
  163. def authorize_sms(self):
  164. """ If monthly limit not exceeded, increase counter and return True """
  165. sent_this_month = self.sms_sent_this_month()
  166. if sent_this_month >= self.sms_limit:
  167. return False
  168. self.sms_sent = sent_this_month + 1
  169. self.last_sms_date = timezone.now()
  170. self.save()
  171. return True
  172. class Project(models.Model):
  173. code = models.UUIDField(default=uuid.uuid4, unique=True)
  174. name = models.CharField(max_length=200, blank=True)
  175. owner = models.ForeignKey(User, models.CASCADE)
  176. api_key = models.CharField(max_length=128, blank=True, db_index=True)
  177. api_key_readonly = models.CharField(max_length=128, blank=True, db_index=True)
  178. badge_key = models.CharField(max_length=150, unique=True)
  179. def __str__(self):
  180. return self.name or self.owner.email
  181. @property
  182. def owner_profile(self):
  183. return Profile.objects.for_user(self.owner)
  184. def num_checks_available(self):
  185. from hc.api.models import Check
  186. num_used = Check.objects.filter(project__owner=self.owner).count()
  187. return self.owner_profile.check_limit - num_used
  188. def set_api_keys(self):
  189. self.api_key = token_urlsafe(nbytes=24)
  190. self.api_key_readonly = token_urlsafe(nbytes=24)
  191. self.save()
  192. def team(self):
  193. return User.objects.filter(memberships__project=self).order_by("email")
  194. def invite_suggestions(self):
  195. q = User.objects.filter(memberships__project__owner_id=self.owner_id)
  196. q = q.exclude(memberships__project=self)
  197. return q.distinct().order_by("email")
  198. def can_invite_new_users(self):
  199. q = User.objects.filter(memberships__project__owner_id=self.owner_id)
  200. used = q.distinct().count()
  201. return used < self.owner_profile.team_limit
  202. def invite(self, user):
  203. Member.objects.create(user=user, project=self)
  204. user.profile.send_instant_login_link(self)
  205. def set_next_nag_date(self):
  206. """ Set next_nag_date on profiles of all members of this project. """
  207. is_owner = Q(user=self.owner)
  208. is_member = Q(user__memberships__project=self)
  209. q = Profile.objects.filter(is_owner | is_member)
  210. q = q.exclude(nag_period=NO_NAG)
  211. # Exclude profiles with next_nag_date already set
  212. q = q.filter(next_nag_date__isnull=True)
  213. q.update(next_nag_date=timezone.now() + models.F("nag_period"))
  214. def overall_status(self):
  215. status = "up"
  216. for check in self.check_set.all():
  217. check_status = check.get_status(with_started=False)
  218. if status == "up" and check_status == "grace":
  219. status = "grace"
  220. if check_status == "down":
  221. status = "down"
  222. break
  223. return status
  224. def have_channel_issues(self):
  225. errors = list(self.channel_set.values_list("last_error", flat=True))
  226. # It's a problem if a project has no integrations at all
  227. if len(errors) == 0:
  228. return True
  229. # It's a problem if any integration has a logged error
  230. return True if max(errors) else False
  231. class Member(models.Model):
  232. user = models.ForeignKey(User, models.CASCADE, related_name="memberships")
  233. project = models.ForeignKey(Project, models.CASCADE)