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.

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