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.

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