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.

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