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.

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