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.

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