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.

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