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.

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