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.

2047 lines
63 KiB

6 years ago
9 years ago
9 years ago
8 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
10 years ago
10 years ago
10 years ago
6 years ago
10 years ago
10 years ago
6 years ago
9 years ago
6 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
  1. from datetime import timedelta as td
  2. import email
  3. import json
  4. import os
  5. import re
  6. from secrets import token_urlsafe
  7. from urllib.parse import urlencode
  8. from cron_descriptor import ExpressionDescriptor
  9. from cronsim.cronsim import CronSim, CronSimError
  10. from django.conf import settings
  11. from django.contrib import messages
  12. from django.contrib.auth.decorators import login_required
  13. from django.core import signing
  14. from django.core.exceptions import PermissionDenied
  15. from django.db.models import Count, F
  16. from django.http import (
  17. Http404,
  18. HttpResponse,
  19. HttpResponseBadRequest,
  20. HttpResponseForbidden,
  21. JsonResponse,
  22. )
  23. from django.shortcuts import get_object_or_404, redirect, render
  24. from django.template.loader import get_template, render_to_string
  25. from django.urls import reverse
  26. from django.utils import timezone
  27. from django.views.decorators.csrf import csrf_exempt
  28. from django.views.decorators.http import require_POST
  29. from hc.accounts.models import Project, Member
  30. from hc.api.models import (
  31. DEFAULT_GRACE,
  32. DEFAULT_TIMEOUT,
  33. MAX_DELTA,
  34. Channel,
  35. Check,
  36. Ping,
  37. Notification,
  38. )
  39. from hc.api.transports import Telegram
  40. from hc.front.decorators import require_setting
  41. from hc.front import forms
  42. from hc.front.schemas import telegram_callback
  43. from hc.front.templatetags.hc_extras import (
  44. num_down_title,
  45. down_title,
  46. sortchecks,
  47. site_hostname,
  48. site_scheme,
  49. )
  50. from hc.lib import jsonschema
  51. from hc.lib.badges import get_badge_url
  52. import pytz
  53. from pytz.exceptions import UnknownTimeZoneError
  54. import requests
  55. VALID_SORT_VALUES = ("name", "-name", "last_ping", "-last_ping", "created")
  56. STATUS_TEXT_TMPL = get_template("front/log_status_text.html")
  57. LAST_PING_TMPL = get_template("front/last_ping_cell.html")
  58. EVENTS_TMPL = get_template("front/details_events.html")
  59. DOWNTIMES_TMPL = get_template("front/details_downtimes.html")
  60. def _tags_statuses(checks):
  61. tags, down, grace, num_down = {}, {}, {}, 0
  62. for check in checks:
  63. status = check.get_status()
  64. if status == "down":
  65. num_down += 1
  66. for tag in check.tags_list():
  67. down[tag] = "down"
  68. elif status == "grace":
  69. for tag in check.tags_list():
  70. grace[tag] = "grace"
  71. else:
  72. for tag in check.tags_list():
  73. tags[tag] = "up"
  74. tags.update(grace)
  75. tags.update(down)
  76. return tags, num_down
  77. def _get_check_for_user(request, code):
  78. """ Return specified check if current user has access to it. """
  79. assert request.user.is_authenticated
  80. check = get_object_or_404(Check.objects.select_related("project"), code=code)
  81. if request.user.is_superuser:
  82. return check, True
  83. if request.user.id == check.project.owner_id:
  84. return check, True
  85. membership = get_object_or_404(Member, project=check.project, user=request.user)
  86. return check, membership.is_rw
  87. def _get_rw_check_for_user(request, code):
  88. check, rw = _get_check_for_user(request, code)
  89. if not rw:
  90. raise PermissionDenied
  91. return check
  92. def _get_channel_for_user(request, code):
  93. """ Return specified channel if current user has access to it. """
  94. assert request.user.is_authenticated
  95. channel = get_object_or_404(Channel.objects.select_related("project"), code=code)
  96. if request.user.is_superuser:
  97. return channel, True
  98. if request.user.id == channel.project.owner_id:
  99. return channel, True
  100. membership = get_object_or_404(Member, project=channel.project, user=request.user)
  101. return channel, membership.is_rw
  102. def _get_rw_channel_for_user(request, code):
  103. channel, rw = _get_channel_for_user(request, code)
  104. if not rw:
  105. raise PermissionDenied
  106. return channel
  107. def _get_project_for_user(request, project_code):
  108. """ Check access, return (project, rw) tuple. """
  109. project = get_object_or_404(Project, code=project_code)
  110. if request.user.is_superuser:
  111. return project, True
  112. if request.user.id == project.owner_id:
  113. return project, True
  114. membership = get_object_or_404(Member, project=project, user=request.user)
  115. return project, membership.is_rw
  116. def _get_rw_project_for_user(request, project_code):
  117. """ Check access, return (project, rw) tuple. """
  118. project, rw = _get_project_for_user(request, project_code)
  119. if not rw:
  120. raise PermissionDenied
  121. return project
  122. def _refresh_last_active_date(profile):
  123. """ Update last_active_date if it is more than a day old. """
  124. now = timezone.now()
  125. if profile.last_active_date is None or (now - profile.last_active_date).days > 0:
  126. profile.last_active_date = now
  127. profile.save()
  128. @login_required
  129. def my_checks(request, code):
  130. _refresh_last_active_date(request.profile)
  131. project, rw = _get_project_for_user(request, code)
  132. if request.GET.get("sort") in VALID_SORT_VALUES:
  133. request.profile.sort = request.GET["sort"]
  134. request.profile.save()
  135. if request.GET.get("urls") in ("uuid", "slug") and rw:
  136. project.show_slugs = request.GET["urls"] == "slug"
  137. project.save()
  138. if request.session.get("last_project_id") != project.id:
  139. request.session["last_project_id"] = project.id
  140. q = Check.objects.filter(project=project)
  141. q = q.select_related("project")
  142. checks = list(q.prefetch_related("channel_set"))
  143. sortchecks(checks, request.profile.sort)
  144. tags_statuses, num_down = _tags_statuses(checks)
  145. pairs = list(tags_statuses.items())
  146. pairs.sort(key=lambda pair: pair[0].lower())
  147. channels = Channel.objects.filter(project=project)
  148. channels = list(channels.order_by("created"))
  149. hidden_checks = set()
  150. # Hide checks that don't match selected tags:
  151. selected_tags = set(request.GET.getlist("tag", []))
  152. if selected_tags:
  153. for check in checks:
  154. if not selected_tags.issubset(check.tags_list()):
  155. hidden_checks.add(check)
  156. # Hide checks that don't match the search string:
  157. search = request.GET.get("search", "")
  158. if search:
  159. for check in checks:
  160. search_key = "%s\n%s" % (check.name.lower(), check.code)
  161. if search not in search_key:
  162. hidden_checks.add(check)
  163. # Figure out which checks have ambiguous ping URLs
  164. seen, ambiguous = set(), set()
  165. if project.show_slugs:
  166. for check in checks:
  167. if check.slug and check.slug in seen:
  168. ambiguous.add(check.slug)
  169. else:
  170. seen.add(check.slug)
  171. # Do we need to show the "Last Duration" header?
  172. show_last_duration = False
  173. for check in checks:
  174. if check.clamped_last_duration():
  175. show_last_duration = True
  176. break
  177. ctx = {
  178. "page": "checks",
  179. "rw": rw,
  180. "checks": checks,
  181. "channels": channels,
  182. "num_down": num_down,
  183. "tags": pairs,
  184. "ping_endpoint": settings.PING_ENDPOINT,
  185. "timezones": pytz.all_timezones,
  186. "project": project,
  187. "num_available": project.num_checks_available(),
  188. "sort": request.profile.sort,
  189. "selected_tags": selected_tags,
  190. "search": search,
  191. "hidden_checks": hidden_checks,
  192. "ambiguous": ambiguous,
  193. "show_last_duration": show_last_duration,
  194. }
  195. return render(request, "front/my_checks.html", ctx)
  196. @login_required
  197. def status(request, code):
  198. _get_project_for_user(request, code)
  199. checks = list(Check.objects.filter(project__code=code))
  200. details = []
  201. for check in checks:
  202. ctx = {"check": check}
  203. details.append(
  204. {
  205. "code": str(check.code),
  206. "status": check.get_status(),
  207. "last_ping": LAST_PING_TMPL.render(ctx).strip(),
  208. "started": check.last_start is not None,
  209. }
  210. )
  211. tags_statuses, num_down = _tags_statuses(checks)
  212. return JsonResponse(
  213. {"details": details, "tags": tags_statuses, "title": num_down_title(num_down)}
  214. )
  215. @login_required
  216. @require_POST
  217. def switch_channel(request, code, channel_code):
  218. check = _get_rw_check_for_user(request, code)
  219. channel = get_object_or_404(Channel, code=channel_code)
  220. if channel.project_id != check.project_id:
  221. return HttpResponseBadRequest()
  222. if request.POST.get("state") == "on":
  223. channel.checks.add(check)
  224. else:
  225. channel.checks.remove(check)
  226. return HttpResponse()
  227. def index(request):
  228. if request.user.is_authenticated:
  229. project_ids = request.profile.projects().values("id")
  230. q = Project.objects.filter(id__in=project_ids)
  231. q = q.annotate(n_checks=Count("check", distinct=True))
  232. q = q.annotate(n_channels=Count("channel", distinct=True))
  233. q = q.annotate(owner_email=F("owner__email"))
  234. projects = list(q)
  235. # Primary sort key: projects with overall_status=down go first
  236. # Secondary sort key: project's name
  237. projects.sort(key=lambda p: (p.overall_status() != "down", p.name))
  238. ctx = {
  239. "page": "projects",
  240. "projects": projects,
  241. "last_project_id": request.session.get("last_project_id"),
  242. }
  243. return render(request, "front/projects.html", ctx)
  244. return redirect("hc-login")
  245. def dashboard(request):
  246. return render(request, "front/dashboard.html", {})
  247. def serve_doc(request, doc="introduction"):
  248. # Filenames in /templates/docs/ consist of lowercase letters and underscores,
  249. # -- make sure we don't accept anything else
  250. if not re.match(r"^[a-z_]+$", doc):
  251. raise Http404("not found")
  252. path = os.path.join(settings.BASE_DIR, "templates/docs", doc + ".html")
  253. if not os.path.exists(path):
  254. raise Http404("not found")
  255. content = open(path, "r", encoding="utf-8").read()
  256. if not doc.startswith("self_hosted"):
  257. replaces = {
  258. "{{ default_timeout }}": str(int(DEFAULT_TIMEOUT.total_seconds())),
  259. "{{ default_grace }}": str(int(DEFAULT_GRACE.total_seconds())),
  260. "SITE_NAME": settings.SITE_NAME,
  261. "SITE_ROOT": settings.SITE_ROOT,
  262. "SITE_HOSTNAME": site_hostname(),
  263. "SITE_SCHEME": site_scheme(),
  264. "PING_ENDPOINT": settings.PING_ENDPOINT,
  265. "PING_URL": settings.PING_ENDPOINT + "your-uuid-here",
  266. "IMG_URL": os.path.join(settings.STATIC_URL, "img/docs"),
  267. }
  268. for placeholder, value in replaces.items():
  269. content = content.replace(placeholder, value)
  270. ctx = {
  271. "page": "docs",
  272. "section": doc,
  273. "content": content,
  274. "first_line": content.split("\n")[0],
  275. }
  276. return render(request, "front/docs_single.html", ctx)
  277. def docs_cron(request):
  278. return render(request, "front/docs_cron.html", {})
  279. @require_POST
  280. @login_required
  281. def add_check(request, code):
  282. project = _get_rw_project_for_user(request, code)
  283. if project.num_checks_available() <= 0:
  284. return HttpResponseBadRequest()
  285. check = Check(project=project)
  286. check.save()
  287. check.assign_all_channels()
  288. url = reverse("hc-details", args=[check.code])
  289. return redirect(url + "?new")
  290. @require_POST
  291. @login_required
  292. def update_name(request, code):
  293. check = _get_rw_check_for_user(request, code)
  294. form = forms.NameTagsForm(request.POST)
  295. if form.is_valid():
  296. check.set_name_slug(form.cleaned_data["name"])
  297. check.tags = form.cleaned_data["tags"]
  298. check.desc = form.cleaned_data["desc"]
  299. check.save()
  300. if "/details/" in request.META.get("HTTP_REFERER", ""):
  301. return redirect("hc-details", code)
  302. return redirect("hc-checks", check.project.code)
  303. @require_POST
  304. @login_required
  305. def filtering_rules(request, code):
  306. check = _get_rw_check_for_user(request, code)
  307. form = forms.FilteringRulesForm(request.POST)
  308. if form.is_valid():
  309. check.subject = form.cleaned_data["subject"]
  310. check.subject_fail = form.cleaned_data["subject_fail"]
  311. check.methods = form.cleaned_data["methods"]
  312. check.manual_resume = form.cleaned_data["manual_resume"]
  313. check.save()
  314. return redirect("hc-details", code)
  315. @require_POST
  316. @login_required
  317. def update_timeout(request, code):
  318. check = _get_rw_check_for_user(request, code)
  319. kind = request.POST.get("kind")
  320. if kind == "simple":
  321. form = forms.TimeoutForm(request.POST)
  322. if not form.is_valid():
  323. return HttpResponseBadRequest()
  324. check.kind = "simple"
  325. check.timeout = form.cleaned_data["timeout"]
  326. check.grace = form.cleaned_data["grace"]
  327. elif kind == "cron":
  328. form = forms.CronForm(request.POST)
  329. if not form.is_valid():
  330. return HttpResponseBadRequest()
  331. check.kind = "cron"
  332. check.schedule = form.cleaned_data["schedule"]
  333. check.tz = form.cleaned_data["tz"]
  334. check.grace = td(minutes=form.cleaned_data["grace"])
  335. check.alert_after = check.going_down_after()
  336. if check.status == "up" and check.alert_after < timezone.now():
  337. # Checks can flip from "up" to "down" state as a result of changing check's
  338. # schedule. We don't want to send notifications when changing schedule
  339. # interactively in the web UI. So we update the `alert_after` and `status`
  340. # fields here the same way as `sendalerts` would do, but without sending
  341. # an actual alert:
  342. check.alert_after = None
  343. check.status = "down"
  344. check.save()
  345. if "/details/" in request.META.get("HTTP_REFERER", ""):
  346. return redirect("hc-details", code)
  347. return redirect("hc-checks", check.project.code)
  348. @require_POST
  349. def cron_preview(request):
  350. schedule = request.POST.get("schedule", "")
  351. tz = request.POST.get("tz")
  352. ctx = {"tz": tz, "dates": []}
  353. try:
  354. zone = pytz.timezone(tz)
  355. now_local = timezone.localtime(timezone.now(), zone)
  356. it = CronSim(schedule, now_local)
  357. for i in range(0, 6):
  358. ctx["dates"].append(next(it))
  359. except UnknownTimeZoneError:
  360. ctx["bad_tz"] = True
  361. except CronSimError:
  362. ctx["bad_schedule"] = True
  363. if ctx["dates"]:
  364. try:
  365. descriptor = ExpressionDescriptor(schedule, use_24hour_time_format=True)
  366. ctx["desc"] = descriptor.get_description()
  367. except:
  368. # We assume the schedule is valid if cronsim accepts it.
  369. # If cron-descriptor throws an exception, don't show the description
  370. # to the user.
  371. pass
  372. return render(request, "front/cron_preview.html", ctx)
  373. @login_required
  374. def ping_details(request, code, n=None):
  375. check, rw = _get_check_for_user(request, code)
  376. q = Ping.objects.filter(owner=check)
  377. if n:
  378. q = q.filter(n=n)
  379. try:
  380. ping = q.latest("created")
  381. except Ping.DoesNotExist:
  382. return render(request, "front/ping_details_not_found.html")
  383. ctx = {"check": check, "ping": ping, "plain": None, "html": None}
  384. if ping.scheme == "email":
  385. parsed = email.message_from_string(ping.body, policy=email.policy.SMTP)
  386. ctx["subject"] = parsed.get("subject", "")
  387. plain_mime_part = parsed.get_body(("plain",))
  388. if plain_mime_part:
  389. ctx["plain"] = plain_mime_part.get_content()
  390. html_mime_part = parsed.get_body(("html",))
  391. if html_mime_part:
  392. ctx["html"] = html_mime_part.get_content()
  393. return render(request, "front/ping_details.html", ctx)
  394. @require_POST
  395. @login_required
  396. def pause(request, code):
  397. check = _get_rw_check_for_user(request, code)
  398. check.status = "paused"
  399. check.last_start = None
  400. check.alert_after = None
  401. check.save()
  402. # After pausing a check we must check if all checks are up,
  403. # and Profile.next_nag_date needs to be cleared out:
  404. check.project.update_next_nag_dates()
  405. # Don't redirect after an AJAX request:
  406. if request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest":
  407. return HttpResponse()
  408. return redirect("hc-details", code)
  409. @require_POST
  410. @login_required
  411. def resume(request, code):
  412. check = _get_rw_check_for_user(request, code)
  413. check.status = "new"
  414. check.last_start = None
  415. check.last_ping = None
  416. check.alert_after = None
  417. check.save()
  418. return redirect("hc-details", code)
  419. @require_POST
  420. @login_required
  421. def remove_check(request, code):
  422. check = _get_rw_check_for_user(request, code)
  423. project = check.project
  424. check.delete()
  425. return redirect("hc-checks", project.code)
  426. def _get_events(check, limit):
  427. pings = Ping.objects.filter(owner=check).order_by("-id")[:limit]
  428. pings = list(pings)
  429. prev = None
  430. for ping in reversed(pings):
  431. if ping.kind != "start" and prev and prev.kind == "start":
  432. delta = ping.created - prev.created
  433. if delta < MAX_DELTA:
  434. setattr(ping, "delta", delta)
  435. prev = ping
  436. alerts = []
  437. if len(pings):
  438. cutoff = pings[-1].created
  439. alerts = Notification.objects.select_related("channel").filter(
  440. owner=check, check_status="down", created__gt=cutoff
  441. )
  442. events = pings + list(alerts)
  443. events.sort(key=lambda el: el.created, reverse=True)
  444. return events
  445. @login_required
  446. def log(request, code):
  447. check, rw = _get_check_for_user(request, code)
  448. limit = check.project.owner_profile.ping_log_limit
  449. ctx = {
  450. "project": check.project,
  451. "check": check,
  452. "events": _get_events(check, limit),
  453. "limit": limit,
  454. "show_limit_notice": check.n_pings > limit and settings.USE_PAYMENTS,
  455. }
  456. return render(request, "front/log.html", ctx)
  457. @login_required
  458. def details(request, code):
  459. _refresh_last_active_date(request.profile)
  460. check, rw = _get_check_for_user(request, code)
  461. if request.GET.get("urls") in ("uuid", "slug") and rw:
  462. check.project.show_slugs = request.GET["urls"] == "slug"
  463. check.project.save()
  464. channels = Channel.objects.filter(project=check.project)
  465. channels = list(channels.order_by("created"))
  466. all_tags = set()
  467. q = Check.objects.filter(project=check.project).exclude(tags="")
  468. for tags in q.values_list("tags", flat=True):
  469. all_tags.update(tags.split(" "))
  470. ctx = {
  471. "page": "details",
  472. "project": check.project,
  473. "check": check,
  474. "rw": rw,
  475. "channels": channels,
  476. "enabled_channels": list(check.channel_set.all()),
  477. "timezones": pytz.all_timezones,
  478. "downtimes": check.downtimes(months=3),
  479. "is_new": "new" in request.GET,
  480. "is_copied": "copied" in request.GET,
  481. "all_tags": " ".join(sorted(all_tags)),
  482. }
  483. return render(request, "front/details.html", ctx)
  484. @login_required
  485. def uncloak(request, unique_key):
  486. for check in request.profile.checks_from_all_projects().only("code"):
  487. if check.unique_key == unique_key:
  488. return redirect("hc-details", check.code)
  489. raise Http404("not found")
  490. @login_required
  491. def transfer(request, code):
  492. check = _get_rw_check_for_user(request, code)
  493. if request.method == "POST":
  494. target_project = _get_rw_project_for_user(request, request.POST["project"])
  495. if target_project.num_checks_available() <= 0:
  496. return HttpResponseBadRequest()
  497. check.project = target_project
  498. check.save()
  499. check.assign_all_channels()
  500. messages.success(request, "Check transferred successfully!")
  501. return redirect("hc-details", code)
  502. ctx = {"check": check}
  503. return render(request, "front/transfer_modal.html", ctx)
  504. @require_POST
  505. @login_required
  506. def copy(request, code):
  507. check = _get_rw_check_for_user(request, code)
  508. if check.project.num_checks_available() <= 0:
  509. return HttpResponseBadRequest()
  510. new_name = check.name + " (copy)"
  511. # Make sure we don't exceed the 100 character db field limit:
  512. if len(new_name) > 100:
  513. new_name = check.name[:90] + "... (copy)"
  514. copied = Check(project=check.project)
  515. copied.set_name_slug(new_name)
  516. copied.desc, copied.tags = check.desc, check.tags
  517. copied.subject, copied.subject_fail = check.subject, check.subject_fail
  518. copied.methods = check.methods
  519. copied.manual_resume = check.manual_resume
  520. copied.kind = check.kind
  521. copied.timeout, copied.grace = check.timeout, check.grace
  522. copied.schedule, copied.tz = check.schedule, check.tz
  523. copied.save()
  524. copied.channel_set.add(*check.channel_set.all())
  525. url = reverse("hc-details", args=[copied.code])
  526. return redirect(url + "?copied")
  527. @login_required
  528. def status_single(request, code):
  529. check, rw = _get_check_for_user(request, code)
  530. status = check.get_status()
  531. events = _get_events(check, 20)
  532. updated = "1"
  533. if len(events):
  534. updated = str(events[0].created.timestamp())
  535. doc = {
  536. "status": status,
  537. "status_text": STATUS_TEXT_TMPL.render({"check": check, "rw": rw}),
  538. "title": down_title(check),
  539. "updated": updated,
  540. }
  541. if updated != request.GET.get("u"):
  542. doc["events"] = EVENTS_TMPL.render({"check": check, "events": events})
  543. doc["downtimes"] = DOWNTIMES_TMPL.render({"downtimes": check.downtimes(3)})
  544. return JsonResponse(doc)
  545. @login_required
  546. def badges(request, code):
  547. project, rw = _get_project_for_user(request, code)
  548. tags = set()
  549. for check in Check.objects.filter(project=project):
  550. tags.update(check.tags_list())
  551. sorted_tags = sorted(tags, key=lambda s: s.lower())
  552. sorted_tags.append("*") # For the "overall status" badge
  553. key = project.badge_key
  554. urls = []
  555. for tag in sorted_tags:
  556. urls.append(
  557. {
  558. "tag": tag,
  559. "svg": get_badge_url(key, tag),
  560. "svg3": get_badge_url(key, tag, with_late=True),
  561. "json": get_badge_url(key, tag, fmt="json"),
  562. "json3": get_badge_url(key, tag, fmt="json", with_late=True),
  563. "shields": get_badge_url(key, tag, fmt="shields"),
  564. "shields3": get_badge_url(key, tag, fmt="shields", with_late=True),
  565. }
  566. )
  567. ctx = {
  568. "have_tags": len(urls) > 1,
  569. "page": "badges",
  570. "project": project,
  571. "badges": urls,
  572. }
  573. return render(request, "front/badges.html", ctx)
  574. @login_required
  575. def channels(request, code):
  576. project, rw = _get_project_for_user(request, code)
  577. if request.method == "POST":
  578. if not rw:
  579. return HttpResponseForbidden()
  580. code = request.POST["channel"]
  581. try:
  582. channel = Channel.objects.get(code=code)
  583. except Channel.DoesNotExist:
  584. return HttpResponseBadRequest()
  585. if channel.project_id != project.id:
  586. return HttpResponseForbidden()
  587. new_checks = []
  588. for key in request.POST:
  589. if key.startswith("check-"):
  590. code = key[6:]
  591. try:
  592. check = Check.objects.get(code=code)
  593. except Check.DoesNotExist:
  594. return HttpResponseBadRequest()
  595. if check.project_id != project.id:
  596. return HttpResponseForbidden()
  597. new_checks.append(check)
  598. channel.checks.set(new_checks)
  599. return redirect("hc-channels", project.code)
  600. channels = Channel.objects.filter(project=project)
  601. channels = channels.order_by("created")
  602. channels = channels.annotate(n_checks=Count("checks"))
  603. ctx = {
  604. "page": "channels",
  605. "rw": rw,
  606. "project": project,
  607. "profile": project.owner_profile,
  608. "channels": channels,
  609. "enable_apprise": settings.APPRISE_ENABLED is True,
  610. "enable_call": settings.TWILIO_AUTH is not None,
  611. "enable_discord": settings.DISCORD_CLIENT_ID is not None,
  612. "enable_linenotify": settings.LINENOTIFY_CLIENT_ID is not None,
  613. "enable_matrix": settings.MATRIX_ACCESS_TOKEN is not None,
  614. "enable_mattermost": settings.MATTERMOST_ENABLED is True,
  615. "enable_msteams": settings.MSTEAMS_ENABLED is True,
  616. "enable_opsgenie": settings.OPSGENIE_ENABLED is True,
  617. "enable_pagertree": settings.PAGERTREE_ENABLED is True,
  618. "enable_pd": settings.PD_ENABLED is True,
  619. "enable_prometheus": settings.PROMETHEUS_ENABLED is True,
  620. "enable_pushbullet": settings.PUSHBULLET_CLIENT_ID is not None,
  621. "enable_pushover": settings.PUSHOVER_API_TOKEN is not None,
  622. "enable_shell": settings.SHELL_ENABLED is True,
  623. "enable_signal": settings.SIGNAL_CLI_ENABLED is True,
  624. "enable_slack": settings.SLACK_ENABLED is True,
  625. "enable_slack_btn": settings.SLACK_CLIENT_ID is not None,
  626. "enable_sms": settings.TWILIO_AUTH is not None,
  627. "enable_spike": settings.SPIKE_ENABLED is True,
  628. "enable_telegram": settings.TELEGRAM_TOKEN is not None,
  629. "enable_trello": settings.TRELLO_APP_KEY is not None,
  630. "enable_victorops": settings.VICTOROPS_ENABLED is True,
  631. "enable_webhooks": settings.WEBHOOKS_ENABLED is True,
  632. "enable_whatsapp": settings.TWILIO_USE_WHATSAPP,
  633. "enable_zulip": settings.ZULIP_ENABLED is True,
  634. "use_payments": settings.USE_PAYMENTS,
  635. }
  636. return render(request, "front/channels.html", ctx)
  637. @login_required
  638. def channel_checks(request, code):
  639. channel = _get_rw_channel_for_user(request, code)
  640. assigned = set(channel.checks.values_list("code", flat=True).distinct())
  641. checks = Check.objects.filter(project=channel.project).order_by("created")
  642. ctx = {"checks": checks, "assigned": assigned, "channel": channel}
  643. return render(request, "front/channel_checks.html", ctx)
  644. @require_POST
  645. @login_required
  646. def update_channel_name(request, code):
  647. channel = _get_rw_channel_for_user(request, code)
  648. form = forms.ChannelNameForm(request.POST)
  649. if form.is_valid():
  650. channel.name = form.cleaned_data["name"]
  651. channel.save()
  652. return redirect("hc-channels", channel.project.code)
  653. def verify_email(request, code, token):
  654. channel = get_object_or_404(Channel, code=code)
  655. if channel.make_token() == token:
  656. channel.email_verified = True
  657. channel.save()
  658. return render(request, "front/verify_email_success.html")
  659. return render(request, "bad_link.html")
  660. @csrf_exempt
  661. def unsubscribe_email(request, code, signed_token):
  662. ctx = {}
  663. # Some email servers open links in emails to check for malicious content.
  664. # To work around this, on GET requests we serve a confirmation form.
  665. # If the signature is at least 5 minutes old, we also include JS code to
  666. # auto-submit the form.
  667. signer = signing.TimestampSigner(salt="alerts")
  668. # First, check the signature without looking at the timestamp:
  669. try:
  670. token = signer.unsign(signed_token)
  671. except signing.BadSignature:
  672. return render(request, "bad_link.html")
  673. # Then, check if timestamp is older than 5 minutes:
  674. try:
  675. signer.unsign(signed_token, max_age=300)
  676. except signing.SignatureExpired:
  677. ctx["autosubmit"] = True
  678. channel = get_object_or_404(Channel, code=code, kind="email")
  679. if channel.make_token() != token:
  680. return render(request, "bad_link.html")
  681. if request.method != "POST":
  682. return render(request, "accounts/unsubscribe_submit.html", ctx)
  683. channel.delete()
  684. return render(request, "front/unsubscribe_success.html")
  685. @require_POST
  686. @login_required
  687. def send_test_notification(request, code):
  688. channel, rw = _get_channel_for_user(request, code)
  689. dummy = Check(name="TEST", status="down", project=channel.project)
  690. dummy.last_ping = timezone.now() - td(days=1)
  691. dummy.n_pings = 42
  692. if channel.kind == "webhook" and not channel.url_down:
  693. if channel.url_up:
  694. # If we don't have url_down, but do have have url_up then
  695. # send "TEST is UP" notification instead:
  696. dummy.status = "up"
  697. # Delete all older test notifications for this channel
  698. Notification.objects.filter(channel=channel, owner=None).delete()
  699. # Send the test notification
  700. error = channel.notify(dummy, is_test=True)
  701. if error:
  702. messages.warning(request, "Could not send a test notification. %s" % error)
  703. else:
  704. messages.success(request, "Test notification sent!")
  705. return redirect("hc-channels", channel.project.code)
  706. @require_POST
  707. @login_required
  708. def remove_channel(request, code):
  709. channel = _get_rw_channel_for_user(request, code)
  710. project = channel.project
  711. channel.delete()
  712. return redirect("hc-channels", project.code)
  713. @login_required
  714. def email_form(request, channel=None, code=None):
  715. """ Add email integration or edit an existing email integration. """
  716. is_new = channel is None
  717. if is_new:
  718. project = _get_rw_project_for_user(request, code)
  719. channel = Channel(project=project, kind="email")
  720. if request.method == "POST":
  721. form = forms.EmailForm(request.POST)
  722. if form.is_valid():
  723. if form.cleaned_data["value"] != channel.email_value:
  724. if not settings.EMAIL_USE_VERIFICATION:
  725. # In self-hosted setting, administator can set
  726. # EMAIL_USE_VERIFICATION=False to disable email verification
  727. channel.email_verified = True
  728. elif form.cleaned_data["value"] == request.user.email:
  729. # If the user is adding *their own* address
  730. # we skip the verification step
  731. channel.email_verified = True
  732. else:
  733. channel.email_verified = False
  734. channel.value = form.get_value()
  735. channel.save()
  736. if is_new:
  737. channel.assign_all_checks()
  738. if not channel.email_verified:
  739. channel.send_verify_link()
  740. return redirect("hc-channels", channel.project.code)
  741. elif is_new:
  742. form = forms.EmailForm()
  743. else:
  744. form = forms.EmailForm(
  745. {
  746. "value": channel.email_value,
  747. "up": channel.email_notify_up,
  748. "down": channel.email_notify_down,
  749. }
  750. )
  751. ctx = {
  752. "page": "channels",
  753. "project": channel.project,
  754. "use_verification": settings.EMAIL_USE_VERIFICATION,
  755. "form": form,
  756. "is_new": is_new,
  757. }
  758. return render(request, "integrations/email_form.html", ctx)
  759. @login_required
  760. def edit_channel(request, code):
  761. channel = _get_rw_channel_for_user(request, code)
  762. if channel.kind == "email":
  763. return email_form(request, channel=channel)
  764. if channel.kind == "webhook":
  765. return webhook_form(request, channel=channel)
  766. if channel.kind == "sms":
  767. return sms_form(request, channel=channel)
  768. if channel.kind == "signal":
  769. return signal_form(request, channel=channel)
  770. if channel.kind == "whatsapp":
  771. return whatsapp_form(request, channel=channel)
  772. return HttpResponseBadRequest()
  773. @require_setting("WEBHOOKS_ENABLED")
  774. @login_required
  775. def webhook_form(request, channel=None, code=None):
  776. is_new = channel is None
  777. if is_new:
  778. project = _get_rw_project_for_user(request, code)
  779. channel = Channel(project=project, kind="webhook")
  780. if request.method == "POST":
  781. form = forms.WebhookForm(request.POST)
  782. if form.is_valid():
  783. channel.name = form.cleaned_data["name"]
  784. channel.value = form.get_value()
  785. channel.save()
  786. if is_new:
  787. channel.assign_all_checks()
  788. return redirect("hc-channels", channel.project.code)
  789. elif is_new:
  790. form = forms.WebhookForm()
  791. else:
  792. def flatten(d):
  793. return "\n".join("%s: %s" % pair for pair in d.items())
  794. doc = json.loads(channel.value)
  795. doc["headers_down"] = flatten(doc["headers_down"])
  796. doc["headers_up"] = flatten(doc["headers_up"])
  797. doc["name"] = channel.name
  798. form = forms.WebhookForm(doc)
  799. ctx = {
  800. "page": "channels",
  801. "project": channel.project,
  802. "form": form,
  803. "is_new": is_new,
  804. }
  805. return render(request, "integrations/webhook_form.html", ctx)
  806. @require_setting("SHELL_ENABLED")
  807. @login_required
  808. def add_shell(request, code):
  809. project = _get_rw_project_for_user(request, code)
  810. if request.method == "POST":
  811. form = forms.AddShellForm(request.POST)
  812. if form.is_valid():
  813. channel = Channel(project=project, kind="shell")
  814. channel.value = form.get_value()
  815. channel.save()
  816. channel.assign_all_checks()
  817. return redirect("hc-channels", project.code)
  818. else:
  819. form = forms.AddShellForm()
  820. ctx = {
  821. "page": "channels",
  822. "project": project,
  823. "form": form,
  824. }
  825. return render(request, "integrations/add_shell.html", ctx)
  826. @require_setting("PD_ENABLED")
  827. @login_required
  828. def add_pd(request, code):
  829. project = _get_rw_project_for_user(request, code)
  830. # Simple Install Flow
  831. if settings.PD_APP_ID:
  832. state = token_urlsafe()
  833. redirect_url = settings.SITE_ROOT + reverse("hc-add-pd-complete")
  834. redirect_url += "?" + urlencode({"state": state})
  835. install_url = "https://app.pagerduty.com/install/integration?" + urlencode(
  836. {"app_id": settings.PD_APP_ID, "redirect_url": redirect_url, "version": "2"}
  837. )
  838. ctx = {"page": "channels", "project": project, "install_url": install_url}
  839. request.session["pagerduty"] = (state, str(project.code))
  840. return render(request, "integrations/add_pd_simple.html", ctx)
  841. if request.method == "POST":
  842. form = forms.AddPdForm(request.POST)
  843. if form.is_valid():
  844. channel = Channel(project=project, kind="pd")
  845. channel.value = form.cleaned_data["value"]
  846. channel.save()
  847. channel.assign_all_checks()
  848. return redirect("hc-channels", project.code)
  849. else:
  850. form = forms.AddPdForm()
  851. ctx = {"page": "channels", "project": project, "form": form}
  852. return render(request, "integrations/add_pd.html", ctx)
  853. @require_setting("PD_ENABLED")
  854. @require_setting("PD_APP_ID")
  855. @login_required
  856. def add_pd_complete(request):
  857. if "pagerduty" not in request.session:
  858. return HttpResponseBadRequest()
  859. state, code = request.session.pop("pagerduty")
  860. if request.GET.get("state") != state:
  861. return HttpResponseForbidden()
  862. project = _get_rw_project_for_user(request, code)
  863. doc = json.loads(request.GET["config"])
  864. for item in doc["integration_keys"]:
  865. channel = Channel(kind="pd", project=project)
  866. channel.name = item["name"]
  867. channel.value = json.dumps(
  868. {"service_key": item["integration_key"], "account": doc["account"]["name"]}
  869. )
  870. channel.save()
  871. channel.assign_all_checks()
  872. messages.success(request, "The PagerDuty integration has been added!")
  873. return redirect("hc-channels", project.code)
  874. @require_setting("PD_ENABLED")
  875. @require_setting("PD_APP_ID")
  876. def pd_help(request):
  877. ctx = {"page": "channels"}
  878. return render(request, "integrations/add_pd_simple.html", ctx)
  879. @require_setting("PAGERTREE_ENABLED")
  880. @login_required
  881. def add_pagertree(request, code):
  882. project = _get_rw_project_for_user(request, code)
  883. if request.method == "POST":
  884. form = forms.AddUrlForm(request.POST)
  885. if form.is_valid():
  886. channel = Channel(project=project, kind="pagertree")
  887. channel.value = form.cleaned_data["value"]
  888. channel.save()
  889. channel.assign_all_checks()
  890. return redirect("hc-channels", project.code)
  891. else:
  892. form = forms.AddUrlForm()
  893. ctx = {"page": "channels", "project": project, "form": form}
  894. return render(request, "integrations/add_pagertree.html", ctx)
  895. @require_setting("SLACK_ENABLED")
  896. @login_required
  897. def add_slack(request, code):
  898. project = _get_rw_project_for_user(request, code)
  899. if request.method == "POST":
  900. form = forms.AddUrlForm(request.POST)
  901. if form.is_valid():
  902. channel = Channel(project=project, kind="slack")
  903. channel.value = form.cleaned_data["value"]
  904. channel.save()
  905. channel.assign_all_checks()
  906. return redirect("hc-channels", project.code)
  907. else:
  908. form = forms.AddUrlForm()
  909. ctx = {
  910. "page": "channels",
  911. "form": form,
  912. }
  913. return render(request, "integrations/add_slack.html", ctx)
  914. @require_setting("SLACK_ENABLED")
  915. @require_setting("SLACK_CLIENT_ID")
  916. def slack_help(request):
  917. ctx = {"page": "channels"}
  918. return render(request, "integrations/add_slack_btn.html", ctx)
  919. @require_setting("SLACK_ENABLED")
  920. @require_setting("SLACK_CLIENT_ID")
  921. @login_required
  922. def add_slack_btn(request, code):
  923. project = _get_rw_project_for_user(request, code)
  924. state = token_urlsafe()
  925. authorize_url = "https://slack.com/oauth/v2/authorize?" + urlencode(
  926. {
  927. "scope": "incoming-webhook",
  928. "client_id": settings.SLACK_CLIENT_ID,
  929. "state": state,
  930. }
  931. )
  932. ctx = {
  933. "project": project,
  934. "page": "channels",
  935. "authorize_url": authorize_url,
  936. }
  937. request.session["add_slack"] = (state, str(project.code))
  938. return render(request, "integrations/add_slack_btn.html", ctx)
  939. @require_setting("SLACK_ENABLED")
  940. @require_setting("SLACK_CLIENT_ID")
  941. @login_required
  942. def add_slack_complete(request):
  943. if "add_slack" not in request.session:
  944. return HttpResponseForbidden()
  945. state, code = request.session.pop("add_slack")
  946. project = _get_rw_project_for_user(request, code)
  947. if request.GET.get("error") == "access_denied":
  948. messages.warning(request, "Slack setup was cancelled.")
  949. return redirect("hc-channels", project.code)
  950. if request.GET.get("state") != state:
  951. return HttpResponseForbidden()
  952. result = requests.post(
  953. "https://slack.com/api/oauth.v2.access",
  954. {
  955. "client_id": settings.SLACK_CLIENT_ID,
  956. "client_secret": settings.SLACK_CLIENT_SECRET,
  957. "code": request.GET.get("code"),
  958. },
  959. )
  960. doc = result.json()
  961. if doc.get("ok"):
  962. channel = Channel(kind="slack", project=project)
  963. channel.value = result.text
  964. channel.save()
  965. channel.assign_all_checks()
  966. messages.success(request, "The Slack integration has been added!")
  967. else:
  968. s = doc.get("error")
  969. messages.warning(request, "Error message from slack: %s" % s)
  970. return redirect("hc-channels", project.code)
  971. @require_setting("MATTERMOST_ENABLED")
  972. @login_required
  973. def add_mattermost(request, code):
  974. project = _get_rw_project_for_user(request, code)
  975. if request.method == "POST":
  976. form = forms.AddUrlForm(request.POST)
  977. if form.is_valid():
  978. channel = Channel(project=project, kind="mattermost")
  979. channel.value = form.cleaned_data["value"]
  980. channel.save()
  981. channel.assign_all_checks()
  982. return redirect("hc-channels", project.code)
  983. else:
  984. form = forms.AddUrlForm()
  985. ctx = {"page": "channels", "form": form, "project": project}
  986. return render(request, "integrations/add_mattermost.html", ctx)
  987. @require_setting("PUSHBULLET_CLIENT_ID")
  988. @login_required
  989. def add_pushbullet(request, code):
  990. project = _get_rw_project_for_user(request, code)
  991. state = token_urlsafe()
  992. authorize_url = "https://www.pushbullet.com/authorize?" + urlencode(
  993. {
  994. "client_id": settings.PUSHBULLET_CLIENT_ID,
  995. "redirect_uri": settings.SITE_ROOT + reverse(add_pushbullet_complete),
  996. "response_type": "code",
  997. "state": state,
  998. }
  999. )
  1000. ctx = {
  1001. "page": "channels",
  1002. "project": project,
  1003. "authorize_url": authorize_url,
  1004. }
  1005. request.session["add_pushbullet"] = (state, str(project.code))
  1006. return render(request, "integrations/add_pushbullet.html", ctx)
  1007. @require_setting("PUSHBULLET_CLIENT_ID")
  1008. @login_required
  1009. def add_pushbullet_complete(request):
  1010. if "add_pushbullet" not in request.session:
  1011. return HttpResponseForbidden()
  1012. state, code = request.session.pop("add_pushbullet")
  1013. project = _get_rw_project_for_user(request, code)
  1014. if request.GET.get("error") == "access_denied":
  1015. messages.warning(request, "Pushbullet setup was cancelled.")
  1016. return redirect("hc-channels", project.code)
  1017. if request.GET.get("state") != state:
  1018. return HttpResponseForbidden()
  1019. result = requests.post(
  1020. "https://api.pushbullet.com/oauth2/token",
  1021. {
  1022. "client_id": settings.PUSHBULLET_CLIENT_ID,
  1023. "client_secret": settings.PUSHBULLET_CLIENT_SECRET,
  1024. "code": request.GET.get("code"),
  1025. "grant_type": "authorization_code",
  1026. },
  1027. )
  1028. doc = result.json()
  1029. if "access_token" in doc:
  1030. channel = Channel(kind="pushbullet", project=project)
  1031. channel.value = doc["access_token"]
  1032. channel.save()
  1033. channel.assign_all_checks()
  1034. messages.success(request, "The Pushbullet integration has been added!")
  1035. else:
  1036. messages.warning(request, "Something went wrong")
  1037. return redirect("hc-channels", project.code)
  1038. @require_setting("DISCORD_CLIENT_ID")
  1039. @login_required
  1040. def add_discord(request, code):
  1041. project = _get_rw_project_for_user(request, code)
  1042. state = token_urlsafe()
  1043. auth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode(
  1044. {
  1045. "client_id": settings.DISCORD_CLIENT_ID,
  1046. "scope": "webhook.incoming",
  1047. "redirect_uri": settings.SITE_ROOT + reverse(add_discord_complete),
  1048. "response_type": "code",
  1049. "state": state,
  1050. }
  1051. )
  1052. ctx = {"page": "channels", "project": project, "authorize_url": auth_url}
  1053. request.session["add_discord"] = (state, str(project.code))
  1054. return render(request, "integrations/add_discord.html", ctx)
  1055. @require_setting("DISCORD_CLIENT_ID")
  1056. @login_required
  1057. def add_discord_complete(request):
  1058. if "add_discord" not in request.session:
  1059. return HttpResponseForbidden()
  1060. state, code = request.session.pop("add_discord")
  1061. project = _get_rw_project_for_user(request, code)
  1062. if request.GET.get("error") == "access_denied":
  1063. messages.warning(request, "Discord setup was cancelled.")
  1064. return redirect("hc-channels", project.code)
  1065. if request.GET.get("state") != state:
  1066. return HttpResponseForbidden()
  1067. result = requests.post(
  1068. "https://discordapp.com/api/oauth2/token",
  1069. {
  1070. "client_id": settings.DISCORD_CLIENT_ID,
  1071. "client_secret": settings.DISCORD_CLIENT_SECRET,
  1072. "code": request.GET.get("code"),
  1073. "grant_type": "authorization_code",
  1074. "redirect_uri": settings.SITE_ROOT + reverse(add_discord_complete),
  1075. },
  1076. )
  1077. doc = result.json()
  1078. if "access_token" in doc:
  1079. channel = Channel(kind="discord", project=project)
  1080. channel.value = result.text
  1081. channel.save()
  1082. channel.assign_all_checks()
  1083. messages.success(request, "The Discord integration has been added!")
  1084. else:
  1085. messages.warning(request, "Something went wrong.")
  1086. return redirect("hc-channels", project.code)
  1087. @require_setting("PUSHOVER_API_TOKEN")
  1088. def pushover_help(request):
  1089. ctx = {"page": "channels"}
  1090. return render(request, "integrations/add_pushover_help.html", ctx)
  1091. @require_setting("PUSHOVER_API_TOKEN")
  1092. @login_required
  1093. def add_pushover(request, code):
  1094. project = _get_rw_project_for_user(request, code)
  1095. if request.method == "POST":
  1096. state = token_urlsafe()
  1097. failure_url = settings.SITE_ROOT + reverse("hc-channels", args=[project.code])
  1098. success_url = (
  1099. settings.SITE_ROOT
  1100. + reverse("hc-add-pushover", args=[project.code])
  1101. + "?"
  1102. + urlencode(
  1103. {
  1104. "state": state,
  1105. "prio": request.POST.get("po_priority", "0"),
  1106. "prio_up": request.POST.get("po_priority_up", "0"),
  1107. }
  1108. )
  1109. )
  1110. subscription_url = (
  1111. settings.PUSHOVER_SUBSCRIPTION_URL
  1112. + "?"
  1113. + urlencode({"success": success_url, "failure": failure_url})
  1114. )
  1115. request.session["pushover"] = state
  1116. return redirect(subscription_url)
  1117. # Handle successful subscriptions
  1118. if "pushover_user_key" in request.GET:
  1119. if "pushover" not in request.session:
  1120. return HttpResponseForbidden()
  1121. state = request.session.pop("pushover")
  1122. if request.GET.get("state") != state:
  1123. return HttpResponseForbidden()
  1124. if request.GET.get("pushover_unsubscribed") == "1":
  1125. # Unsubscription: delete all Pushover channels for this project
  1126. Channel.objects.filter(project=project, kind="po").delete()
  1127. return redirect("hc-channels", project.code)
  1128. form = forms.AddPushoverForm(request.GET)
  1129. if not form.is_valid():
  1130. return HttpResponseBadRequest()
  1131. channel = Channel(project=project, kind="po")
  1132. channel.value = form.get_value()
  1133. channel.save()
  1134. channel.assign_all_checks()
  1135. messages.success(request, "The Pushover integration has been added!")
  1136. return redirect("hc-channels", project.code)
  1137. # Show Integration Settings form
  1138. ctx = {
  1139. "page": "channels",
  1140. "project": project,
  1141. "po_retry_delay": td(seconds=settings.PUSHOVER_EMERGENCY_RETRY_DELAY),
  1142. "po_expiration": td(seconds=settings.PUSHOVER_EMERGENCY_EXPIRATION),
  1143. }
  1144. return render(request, "integrations/add_pushover.html", ctx)
  1145. @require_setting("OPSGENIE_ENABLED")
  1146. @login_required
  1147. def add_opsgenie(request, code):
  1148. project = _get_rw_project_for_user(request, code)
  1149. if request.method == "POST":
  1150. form = forms.AddOpsgenieForm(request.POST)
  1151. if form.is_valid():
  1152. channel = Channel(project=project, kind="opsgenie")
  1153. v = {"region": form.cleaned_data["region"], "key": form.cleaned_data["key"]}
  1154. channel.value = json.dumps(v)
  1155. channel.save()
  1156. channel.assign_all_checks()
  1157. return redirect("hc-channels", project.code)
  1158. else:
  1159. form = forms.AddOpsgenieForm()
  1160. ctx = {"page": "channels", "project": project, "form": form}
  1161. return render(request, "integrations/add_opsgenie.html", ctx)
  1162. @require_setting("VICTOROPS_ENABLED")
  1163. @login_required
  1164. def add_victorops(request, code):
  1165. project = _get_rw_project_for_user(request, code)
  1166. if request.method == "POST":
  1167. form = forms.AddUrlForm(request.POST)
  1168. if form.is_valid():
  1169. channel = Channel(project=project, kind="victorops")
  1170. channel.value = form.cleaned_data["value"]
  1171. channel.save()
  1172. channel.assign_all_checks()
  1173. return redirect("hc-channels", project.code)
  1174. else:
  1175. form = forms.AddUrlForm()
  1176. ctx = {"page": "channels", "project": project, "form": form}
  1177. return render(request, "integrations/add_victorops.html", ctx)
  1178. @require_setting("ZULIP_ENABLED")
  1179. @login_required
  1180. def add_zulip(request, code):
  1181. project = _get_rw_project_for_user(request, code)
  1182. if request.method == "POST":
  1183. form = forms.AddZulipForm(request.POST)
  1184. if form.is_valid():
  1185. channel = Channel(project=project, kind="zulip")
  1186. channel.value = form.get_value()
  1187. channel.save()
  1188. channel.assign_all_checks()
  1189. return redirect("hc-channels", project.code)
  1190. else:
  1191. form = forms.AddZulipForm()
  1192. ctx = {"page": "channels", "project": project, "form": form}
  1193. return render(request, "integrations/add_zulip.html", ctx)
  1194. @csrf_exempt
  1195. @require_POST
  1196. def telegram_bot(request):
  1197. try:
  1198. doc = json.loads(request.body.decode())
  1199. jsonschema.validate(doc, telegram_callback)
  1200. except ValueError:
  1201. return HttpResponseBadRequest()
  1202. except jsonschema.ValidationError:
  1203. # We don't recognize the message format, but don't want Telegram
  1204. # retrying this over and over again, so respond with 200 OK
  1205. return HttpResponse()
  1206. if "/start" not in doc["message"]["text"]:
  1207. return HttpResponse()
  1208. chat = doc["message"]["chat"]
  1209. name = max(chat.get("title", ""), chat.get("username", ""))
  1210. invite = render_to_string(
  1211. "integrations/telegram_invite.html",
  1212. {"qs": signing.dumps((chat["id"], chat["type"], name))},
  1213. )
  1214. Telegram.send(chat["id"], invite)
  1215. return HttpResponse()
  1216. @require_setting("TELEGRAM_TOKEN")
  1217. def telegram_help(request):
  1218. ctx = {
  1219. "page": "channels",
  1220. "bot_name": settings.TELEGRAM_BOT_NAME,
  1221. }
  1222. return render(request, "integrations/add_telegram.html", ctx)
  1223. @require_setting("TELEGRAM_TOKEN")
  1224. @login_required
  1225. def add_telegram(request):
  1226. chat_id, chat_type, chat_name = None, None, None
  1227. qs = request.META["QUERY_STRING"]
  1228. if qs:
  1229. try:
  1230. chat_id, chat_type, chat_name = signing.loads(qs, max_age=600)
  1231. except signing.BadSignature:
  1232. return render(request, "bad_link.html")
  1233. if request.method == "POST":
  1234. project = _get_rw_project_for_user(request, request.POST.get("project"))
  1235. channel = Channel(project=project, kind="telegram")
  1236. channel.value = json.dumps(
  1237. {"id": chat_id, "type": chat_type, "name": chat_name}
  1238. )
  1239. channel.save()
  1240. channel.assign_all_checks()
  1241. messages.success(request, "The Telegram integration has been added!")
  1242. return redirect("hc-channels", project.code)
  1243. ctx = {
  1244. "page": "channels",
  1245. "projects": request.profile.projects(),
  1246. "chat_id": chat_id,
  1247. "chat_type": chat_type,
  1248. "chat_name": chat_name,
  1249. "bot_name": settings.TELEGRAM_BOT_NAME,
  1250. }
  1251. return render(request, "integrations/add_telegram.html", ctx)
  1252. @require_setting("TWILIO_AUTH")
  1253. @login_required
  1254. def sms_form(request, channel=None, code=None):
  1255. is_new = channel is None
  1256. if is_new:
  1257. project = _get_rw_project_for_user(request, code)
  1258. channel = Channel(project=project, kind="sms")
  1259. if request.method == "POST":
  1260. form = forms.PhoneUpDownForm(request.POST)
  1261. if form.is_valid():
  1262. channel.name = form.cleaned_data["label"]
  1263. channel.value = form.get_json()
  1264. channel.save()
  1265. if is_new:
  1266. channel.assign_all_checks()
  1267. return redirect("hc-channels", channel.project.code)
  1268. elif is_new:
  1269. form = forms.PhoneUpDownForm(initial={"up": False})
  1270. else:
  1271. form = forms.PhoneUpDownForm(
  1272. {
  1273. "label": channel.name,
  1274. "phone": channel.phone_number,
  1275. "up": channel.sms_notify_up,
  1276. "down": channel.sms_notify_down,
  1277. }
  1278. )
  1279. ctx = {
  1280. "page": "channels",
  1281. "project": channel.project,
  1282. "form": form,
  1283. "profile": channel.project.owner_profile,
  1284. "is_new": is_new,
  1285. }
  1286. return render(request, "integrations/sms_form.html", ctx)
  1287. @require_setting("TWILIO_AUTH")
  1288. @login_required
  1289. def add_call(request, code):
  1290. project = _get_rw_project_for_user(request, code)
  1291. if request.method == "POST":
  1292. form = forms.PhoneNumberForm(request.POST)
  1293. if form.is_valid():
  1294. channel = Channel(project=project, kind="call")
  1295. channel.name = form.cleaned_data["label"]
  1296. channel.value = form.get_json()
  1297. channel.save()
  1298. channel.assign_all_checks()
  1299. return redirect("hc-channels", project.code)
  1300. else:
  1301. form = forms.PhoneNumberForm()
  1302. ctx = {
  1303. "page": "channels",
  1304. "project": project,
  1305. "form": form,
  1306. "profile": project.owner_profile,
  1307. }
  1308. return render(request, "integrations/add_call.html", ctx)
  1309. @require_setting("TWILIO_USE_WHATSAPP")
  1310. @login_required
  1311. def whatsapp_form(request, channel=None, code=None):
  1312. is_new = channel is None
  1313. if is_new:
  1314. project = _get_rw_project_for_user(request, code)
  1315. channel = Channel(project=project, kind="whatsapp")
  1316. if request.method == "POST":
  1317. form = forms.PhoneUpDownForm(request.POST)
  1318. if form.is_valid():
  1319. channel.name = form.cleaned_data["label"]
  1320. channel.value = form.get_json()
  1321. channel.save()
  1322. if is_new:
  1323. channel.assign_all_checks()
  1324. return redirect("hc-channels", channel.project.code)
  1325. elif is_new:
  1326. form = forms.PhoneUpDownForm()
  1327. else:
  1328. form = forms.PhoneUpDownForm(
  1329. {
  1330. "label": channel.name,
  1331. "phone": channel.phone_number,
  1332. "up": channel.whatsapp_notify_up,
  1333. "down": channel.whatsapp_notify_down,
  1334. }
  1335. )
  1336. ctx = {
  1337. "page": "channels",
  1338. "project": channel.project,
  1339. "form": form,
  1340. "profile": channel.project.owner_profile,
  1341. "is_new": is_new,
  1342. }
  1343. return render(request, "integrations/whatsapp_form.html", ctx)
  1344. @require_setting("SIGNAL_CLI_ENABLED")
  1345. @login_required
  1346. def signal_form(request, channel=None, code=None):
  1347. is_new = channel is None
  1348. if is_new:
  1349. project = _get_rw_project_for_user(request, code)
  1350. channel = Channel(project=project, kind="signal")
  1351. if request.method == "POST":
  1352. form = forms.PhoneUpDownForm(request.POST)
  1353. if form.is_valid():
  1354. channel.name = form.cleaned_data["label"]
  1355. channel.value = form.get_json()
  1356. channel.save()
  1357. if is_new:
  1358. channel.assign_all_checks()
  1359. return redirect("hc-channels", channel.project.code)
  1360. elif is_new:
  1361. form = forms.PhoneUpDownForm()
  1362. else:
  1363. form = forms.PhoneUpDownForm(
  1364. {
  1365. "label": channel.name,
  1366. "phone": channel.phone_number,
  1367. "up": channel.signal_notify_up,
  1368. "down": channel.signal_notify_down,
  1369. }
  1370. )
  1371. ctx = {
  1372. "page": "channels",
  1373. "project": channel.project,
  1374. "form": form,
  1375. "is_new": is_new,
  1376. }
  1377. return render(request, "integrations/signal_form.html", ctx)
  1378. @require_setting("TRELLO_APP_KEY")
  1379. @login_required
  1380. def add_trello(request, code):
  1381. project = _get_rw_project_for_user(request, code)
  1382. if request.method == "POST":
  1383. form = forms.AddTrelloForm(request.POST)
  1384. if not form.is_valid():
  1385. return HttpResponseBadRequest()
  1386. channel = Channel(project=project, kind="trello")
  1387. channel.value = form.get_value()
  1388. channel.save()
  1389. channel.assign_all_checks()
  1390. return redirect("hc-channels", project.code)
  1391. return_url = settings.SITE_ROOT + reverse("hc-add-trello", args=[project.code])
  1392. authorize_url = "https://trello.com/1/authorize?" + urlencode(
  1393. {
  1394. "expiration": "never",
  1395. "name": settings.SITE_NAME,
  1396. "scope": "read,write",
  1397. "response_type": "token",
  1398. "key": settings.TRELLO_APP_KEY,
  1399. "return_url": return_url,
  1400. }
  1401. )
  1402. ctx = {
  1403. "page": "channels",
  1404. "project": project,
  1405. "authorize_url": authorize_url,
  1406. }
  1407. return render(request, "integrations/add_trello.html", ctx)
  1408. @require_setting("MATRIX_ACCESS_TOKEN")
  1409. @login_required
  1410. def add_matrix(request, code):
  1411. project = _get_rw_project_for_user(request, code)
  1412. if request.method == "POST":
  1413. form = forms.AddMatrixForm(request.POST)
  1414. if form.is_valid():
  1415. channel = Channel(project=project, kind="matrix")
  1416. channel.value = form.cleaned_data["room_id"]
  1417. # If user supplied room alias instead of ID, use it as channel name
  1418. alias = form.cleaned_data["alias"]
  1419. if not alias.startswith("!"):
  1420. channel.name = alias
  1421. channel.save()
  1422. channel.assign_all_checks()
  1423. messages.success(request, "The Matrix integration has been added!")
  1424. return redirect("hc-channels", project.code)
  1425. else:
  1426. form = forms.AddMatrixForm()
  1427. ctx = {
  1428. "page": "channels",
  1429. "project": project,
  1430. "form": form,
  1431. "matrix_user_id": settings.MATRIX_USER_ID,
  1432. }
  1433. return render(request, "integrations/add_matrix.html", ctx)
  1434. @require_setting("APPRISE_ENABLED")
  1435. @login_required
  1436. def add_apprise(request, code):
  1437. project = _get_rw_project_for_user(request, code)
  1438. if request.method == "POST":
  1439. form = forms.AddAppriseForm(request.POST)
  1440. if form.is_valid():
  1441. channel = Channel(project=project, kind="apprise")
  1442. channel.value = form.cleaned_data["url"]
  1443. channel.save()
  1444. channel.assign_all_checks()
  1445. messages.success(request, "The Apprise integration has been added!")
  1446. return redirect("hc-channels", project.code)
  1447. else:
  1448. form = forms.AddAppriseForm()
  1449. ctx = {"page": "channels", "project": project, "form": form}
  1450. return render(request, "integrations/add_apprise.html", ctx)
  1451. @require_setting("TRELLO_APP_KEY")
  1452. @login_required
  1453. @require_POST
  1454. def trello_settings(request):
  1455. token = request.POST.get("token")
  1456. url = "https://api.trello.com/1/members/me/boards?" + urlencode(
  1457. {
  1458. "key": settings.TRELLO_APP_KEY,
  1459. "token": token,
  1460. "filter": "open",
  1461. "fields": "id,name",
  1462. "lists": "open",
  1463. "list_fields": "id,name",
  1464. }
  1465. )
  1466. boards = requests.get(url).json()
  1467. num_lists = sum(len(board["lists"]) for board in boards)
  1468. ctx = {"token": token, "boards": boards, "num_lists": num_lists}
  1469. return render(request, "integrations/trello_settings.html", ctx)
  1470. @require_setting("MSTEAMS_ENABLED")
  1471. @login_required
  1472. def add_msteams(request, code):
  1473. project = _get_rw_project_for_user(request, code)
  1474. if request.method == "POST":
  1475. form = forms.AddUrlForm(request.POST)
  1476. if form.is_valid():
  1477. channel = Channel(project=project, kind="msteams")
  1478. channel.value = form.cleaned_data["value"]
  1479. channel.save()
  1480. channel.assign_all_checks()
  1481. return redirect("hc-channels", project.code)
  1482. else:
  1483. form = forms.AddUrlForm()
  1484. ctx = {"page": "channels", "project": project, "form": form}
  1485. return render(request, "integrations/add_msteams.html", ctx)
  1486. @require_setting("PROMETHEUS_ENABLED")
  1487. @login_required
  1488. def add_prometheus(request, code):
  1489. project, rw = _get_project_for_user(request, code)
  1490. ctx = {"page": "channels", "project": project}
  1491. return render(request, "integrations/add_prometheus.html", ctx)
  1492. @require_setting("PROMETHEUS_ENABLED")
  1493. def metrics(request, code, key):
  1494. if len(key) != 32:
  1495. return HttpResponseBadRequest()
  1496. q = Project.objects.filter(code=code, api_key_readonly=key)
  1497. try:
  1498. project = q.get()
  1499. except Project.DoesNotExist:
  1500. return HttpResponseForbidden()
  1501. checks = Check.objects.filter(project_id=project.id).order_by("id")
  1502. def esc(s):
  1503. return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
  1504. def output(checks):
  1505. yield "# HELP hc_check_up Whether the check is currently up (1 for yes, 0 for no).\n"
  1506. yield "# TYPE hc_check_up gauge\n"
  1507. TMPL = """hc_check_up{name="%s", tags="%s", unique_key="%s"} %d\n"""
  1508. for check in checks:
  1509. value = 0 if check.get_status() == "down" else 1
  1510. yield TMPL % (esc(check.name), esc(check.tags), check.unique_key, value)
  1511. tags_statuses, num_down = _tags_statuses(checks)
  1512. yield "\n"
  1513. yield "# HELP hc_tag_up Whether all checks with this tag are up (1 for yes, 0 for no).\n"
  1514. yield "# TYPE hc_tag_up gauge\n"
  1515. TMPL = """hc_tag_up{tag="%s"} %d\n"""
  1516. for tag in sorted(tags_statuses):
  1517. value = 0 if tags_statuses[tag] == "down" else 1
  1518. yield TMPL % (esc(tag), value)
  1519. yield "\n"
  1520. yield "# HELP hc_checks_total The total number of checks.\n"
  1521. yield "# TYPE hc_checks_total gauge\n"
  1522. yield "hc_checks_total %d\n" % len(checks)
  1523. yield "\n"
  1524. yield "# HELP hc_checks_down_total The number of checks currently down.\n"
  1525. yield "# TYPE hc_checks_down_total gauge\n"
  1526. yield "hc_checks_down_total %d\n" % num_down
  1527. return HttpResponse(output(checks), content_type="text/plain")
  1528. @require_setting("SPIKE_ENABLED")
  1529. @login_required
  1530. def add_spike(request, code):
  1531. project = _get_rw_project_for_user(request, code)
  1532. if request.method == "POST":
  1533. form = forms.AddUrlForm(request.POST)
  1534. if form.is_valid():
  1535. channel = Channel(project=project, kind="spike")
  1536. channel.value = form.cleaned_data["value"]
  1537. channel.save()
  1538. channel.assign_all_checks()
  1539. return redirect("hc-channels", project.code)
  1540. else:
  1541. form = forms.AddUrlForm()
  1542. ctx = {"page": "channels", "project": project, "form": form}
  1543. return render(request, "integrations/add_spike.html", ctx)
  1544. @require_setting("LINENOTIFY_CLIENT_ID")
  1545. @login_required
  1546. def add_linenotify(request, code):
  1547. project = _get_rw_project_for_user(request, code)
  1548. state = token_urlsafe()
  1549. authorize_url = " https://notify-bot.line.me/oauth/authorize?" + urlencode(
  1550. {
  1551. "client_id": settings.LINENOTIFY_CLIENT_ID,
  1552. "redirect_uri": settings.SITE_ROOT + reverse(add_linenotify_complete),
  1553. "response_type": "code",
  1554. "state": state,
  1555. "scope": "notify",
  1556. }
  1557. )
  1558. ctx = {
  1559. "page": "channels",
  1560. "project": project,
  1561. "authorize_url": authorize_url,
  1562. }
  1563. request.session["add_linenotify"] = (state, str(project.code))
  1564. return render(request, "integrations/add_linenotify.html", ctx)
  1565. @require_setting("LINENOTIFY_CLIENT_ID")
  1566. @login_required
  1567. def add_linenotify_complete(request):
  1568. if "add_linenotify" not in request.session:
  1569. return HttpResponseForbidden()
  1570. state, code = request.session.pop("add_linenotify")
  1571. if request.GET.get("state") != state:
  1572. return HttpResponseForbidden()
  1573. project = _get_rw_project_for_user(request, code)
  1574. if request.GET.get("error") == "access_denied":
  1575. messages.warning(request, "LINE Notify setup was cancelled.")
  1576. return redirect("hc-channels", project.code)
  1577. # Exchange code for access token
  1578. result = requests.post(
  1579. "https://notify-bot.line.me/oauth/token",
  1580. {
  1581. "grant_type": "authorization_code",
  1582. "code": request.GET.get("code"),
  1583. "redirect_uri": settings.SITE_ROOT + reverse(add_linenotify_complete),
  1584. "client_id": settings.LINENOTIFY_CLIENT_ID,
  1585. "client_secret": settings.LINENOTIFY_CLIENT_SECRET,
  1586. },
  1587. )
  1588. doc = result.json()
  1589. if doc.get("status") != 200:
  1590. messages.warning(request, "Something went wrong.")
  1591. return redirect("hc-channels", project.code)
  1592. # Fetch notification target's name, will use it as channel name:
  1593. token = doc["access_token"]
  1594. result = requests.get(
  1595. "https://notify-api.line.me/api/status",
  1596. headers={"Authorization": "Bearer %s" % token},
  1597. )
  1598. doc = result.json()
  1599. channel = Channel(kind="linenotify", project=project)
  1600. channel.name = doc.get("target")
  1601. channel.value = token
  1602. channel.save()
  1603. channel.assign_all_checks()
  1604. messages.success(request, "The LINE Notify integration has been added!")
  1605. return redirect("hc-channels", project.code)
  1606. # Forks: add custom views after this line