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.

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