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.

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