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.

1519 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 == "webhook" and not channel.url_down:
  581. if channel.url_up:
  582. # If we don't have url_down, but do have have url_up then
  583. # send "TEST is UP" notification instead:
  584. dummy.status = "up"
  585. if channel.kind == "email":
  586. error = channel.transport.notify(dummy, channel.get_unsub_link())
  587. else:
  588. error = channel.transport.notify(dummy)
  589. if error:
  590. messages.warning(request, "Could not send a test notification: %s" % error)
  591. else:
  592. messages.success(request, "Test notification sent!")
  593. return redirect("hc-channels")
  594. @require_POST
  595. @login_required
  596. def remove_channel(request, code):
  597. # user may refresh the page during POST and cause two deletion attempts
  598. channel = Channel.objects.filter(code=code).first()
  599. if channel:
  600. if channel.project_id != request.project.id:
  601. return HttpResponseForbidden()
  602. channel.delete()
  603. return redirect("hc-channels")
  604. @login_required
  605. def add_email(request):
  606. if request.method == "POST":
  607. form = AddEmailForm(request.POST)
  608. if form.is_valid():
  609. channel = Channel(project=request.project, kind="email")
  610. channel.value = json.dumps(
  611. {
  612. "value": form.cleaned_data["value"],
  613. "up": form.cleaned_data["up"],
  614. "down": form.cleaned_data["down"],
  615. }
  616. )
  617. channel.save()
  618. channel.assign_all_checks()
  619. is_own_email = form.cleaned_data["value"] == request.user.email
  620. if is_own_email or not settings.EMAIL_USE_VERIFICATION:
  621. # If user is subscribing *their own* address
  622. # we can skip the verification step.
  623. # Additionally, in self-hosted setting, administator has the
  624. # option to disable the email verification step altogether.
  625. channel.email_verified = True
  626. channel.save()
  627. else:
  628. channel.send_verify_link()
  629. return redirect("hc-channels")
  630. else:
  631. form = AddEmailForm()
  632. ctx = {
  633. "page": "channels",
  634. "project": request.project,
  635. "use_verification": settings.EMAIL_USE_VERIFICATION,
  636. "form": form,
  637. }
  638. return render(request, "integrations/add_email.html", ctx)
  639. @login_required
  640. def add_webhook(request):
  641. if request.method == "POST":
  642. form = AddWebhookForm(request.POST)
  643. if form.is_valid():
  644. channel = Channel(project=request.project, kind="webhook")
  645. channel.value = form.get_value()
  646. channel.save()
  647. channel.assign_all_checks()
  648. return redirect("hc-channels")
  649. else:
  650. form = AddWebhookForm()
  651. ctx = {
  652. "page": "channels",
  653. "project": request.project,
  654. "form": form,
  655. "now": timezone.now().replace(microsecond=0).isoformat(),
  656. }
  657. return render(request, "integrations/add_webhook.html", ctx)
  658. @login_required
  659. def add_shell(request):
  660. if not settings.SHELL_ENABLED:
  661. raise Http404("shell integration is not available")
  662. if request.method == "POST":
  663. form = AddShellForm(request.POST)
  664. if form.is_valid():
  665. channel = Channel(project=request.project, kind="shell")
  666. channel.value = form.get_value()
  667. channel.save()
  668. channel.assign_all_checks()
  669. return redirect("hc-channels")
  670. else:
  671. form = AddShellForm()
  672. ctx = {
  673. "page": "channels",
  674. "project": request.project,
  675. "form": form,
  676. "now": timezone.now().replace(microsecond=0).isoformat(),
  677. }
  678. return render(request, "integrations/add_shell.html", ctx)
  679. def _prepare_state(request, session_key):
  680. state = get_random_string()
  681. request.session[session_key] = state
  682. return state
  683. def _get_validated_code(request, session_key, key="code"):
  684. if session_key not in request.session:
  685. return None
  686. session_state = request.session.pop(session_key)
  687. request_state = request.GET.get("state")
  688. if session_state is None or session_state != request_state:
  689. return None
  690. return request.GET.get(key)
  691. @login_required
  692. def add_pd(request):
  693. if request.method == "POST":
  694. form = AddPdForm(request.POST)
  695. if form.is_valid():
  696. channel = Channel(project=request.project, kind="pd")
  697. channel.value = form.cleaned_data["value"]
  698. channel.save()
  699. channel.assign_all_checks()
  700. return redirect("hc-channels")
  701. else:
  702. form = AddPdForm()
  703. ctx = {"page": "channels", "form": form}
  704. return render(request, "integrations/add_pd.html", ctx)
  705. def add_pdc(request, state=None):
  706. if settings.PD_VENDOR_KEY is None:
  707. raise Http404("pagerduty integration is not available")
  708. if state and request.user.is_authenticated:
  709. if "pd" not in request.session:
  710. return HttpResponseBadRequest()
  711. session_state = request.session.pop("pd")
  712. if session_state != state:
  713. return HttpResponseBadRequest()
  714. if request.GET.get("error") == "cancelled":
  715. messages.warning(request, "PagerDuty setup was cancelled")
  716. return redirect("hc-channels")
  717. channel = Channel(kind="pd", project=request.project)
  718. channel.user = request.project.owner
  719. channel.value = json.dumps(
  720. {
  721. "service_key": request.GET.get("service_key"),
  722. "account": request.GET.get("account"),
  723. }
  724. )
  725. channel.save()
  726. channel.assign_all_checks()
  727. messages.success(request, "The PagerDuty integration has been added!")
  728. return redirect("hc-channels")
  729. state = _prepare_state(request, "pd")
  730. callback = settings.SITE_ROOT + reverse("hc-add-pdc-state", args=[state])
  731. connect_url = "https://connect.pagerduty.com/connect?" + urlencode(
  732. {"vendor": settings.PD_VENDOR_KEY, "callback": callback}
  733. )
  734. ctx = {"page": "channels", "project": request.project, "connect_url": connect_url}
  735. return render(request, "integrations/add_pdc.html", ctx)
  736. @login_required
  737. def add_pagertree(request):
  738. if request.method == "POST":
  739. form = AddUrlForm(request.POST)
  740. if form.is_valid():
  741. channel = Channel(project=request.project, kind="pagertree")
  742. channel.value = form.cleaned_data["value"]
  743. channel.save()
  744. channel.assign_all_checks()
  745. return redirect("hc-channels")
  746. else:
  747. form = AddUrlForm()
  748. ctx = {"page": "channels", "project": request.project, "form": form}
  749. return render(request, "integrations/add_pagertree.html", ctx)
  750. @login_required
  751. def add_pagerteam(request):
  752. if request.method == "POST":
  753. form = AddUrlForm(request.POST)
  754. if form.is_valid():
  755. channel = Channel(project=request.project, kind="pagerteam")
  756. channel.value = form.cleaned_data["value"]
  757. channel.save()
  758. channel.assign_all_checks()
  759. return redirect("hc-channels")
  760. else:
  761. form = AddUrlForm()
  762. ctx = {"page": "channels", "project": request.project, "form": form}
  763. return render(request, "integrations/add_pagerteam.html", ctx)
  764. def add_slack(request):
  765. if not settings.SLACK_CLIENT_ID and not request.user.is_authenticated:
  766. return redirect("hc-login")
  767. if request.method == "POST":
  768. form = AddUrlForm(request.POST)
  769. if form.is_valid():
  770. channel = Channel(project=request.project, kind="slack")
  771. channel.value = form.cleaned_data["value"]
  772. channel.save()
  773. channel.assign_all_checks()
  774. return redirect("hc-channels")
  775. else:
  776. form = AddUrlForm()
  777. ctx = {
  778. "page": "channels",
  779. "form": form,
  780. "slack_client_id": settings.SLACK_CLIENT_ID,
  781. }
  782. if request.user.is_authenticated:
  783. ctx["project"] = request.project
  784. if settings.SLACK_CLIENT_ID and request.user.is_authenticated:
  785. ctx["state"] = _prepare_state(request, "slack")
  786. return render(request, "integrations/add_slack.html", ctx)
  787. @login_required
  788. def add_mattermost(request):
  789. if request.method == "POST":
  790. form = AddUrlForm(request.POST)
  791. if form.is_valid():
  792. channel = Channel(project=request.project, kind="mattermost")
  793. channel.value = form.cleaned_data["value"]
  794. channel.save()
  795. channel.assign_all_checks()
  796. return redirect("hc-channels")
  797. else:
  798. form = AddUrlForm()
  799. ctx = {"page": "channels", "form": form, "project": request.project}
  800. return render(request, "integrations/add_mattermost.html", ctx)
  801. @login_required
  802. def add_slack_btn(request):
  803. code = _get_validated_code(request, "slack")
  804. if code is None:
  805. return HttpResponseBadRequest()
  806. result = requests.post(
  807. "https://slack.com/api/oauth.access",
  808. {
  809. "client_id": settings.SLACK_CLIENT_ID,
  810. "client_secret": settings.SLACK_CLIENT_SECRET,
  811. "code": code,
  812. },
  813. )
  814. doc = result.json()
  815. if doc.get("ok"):
  816. channel = Channel(kind="slack", project=request.project)
  817. channel.user = request.project.owner
  818. channel.value = result.text
  819. channel.save()
  820. channel.assign_all_checks()
  821. messages.success(request, "The Slack integration has been added!")
  822. else:
  823. s = doc.get("error")
  824. messages.warning(request, "Error message from slack: %s" % s)
  825. return redirect("hc-channels")
  826. @login_required
  827. def add_pushbullet(request):
  828. if settings.PUSHBULLET_CLIENT_ID is None:
  829. raise Http404("pushbullet integration is not available")
  830. if "code" in request.GET:
  831. code = _get_validated_code(request, "pushbullet")
  832. if code is None:
  833. return HttpResponseBadRequest()
  834. result = requests.post(
  835. "https://api.pushbullet.com/oauth2/token",
  836. {
  837. "client_id": settings.PUSHBULLET_CLIENT_ID,
  838. "client_secret": settings.PUSHBULLET_CLIENT_SECRET,
  839. "code": code,
  840. "grant_type": "authorization_code",
  841. },
  842. )
  843. doc = result.json()
  844. if "access_token" in doc:
  845. channel = Channel(kind="pushbullet", project=request.project)
  846. channel.user = request.project.owner
  847. channel.value = doc["access_token"]
  848. channel.save()
  849. channel.assign_all_checks()
  850. messages.success(request, "The Pushbullet integration has been added!")
  851. else:
  852. messages.warning(request, "Something went wrong")
  853. return redirect("hc-channels")
  854. redirect_uri = settings.SITE_ROOT + reverse("hc-add-pushbullet")
  855. authorize_url = "https://www.pushbullet.com/authorize?" + urlencode(
  856. {
  857. "client_id": settings.PUSHBULLET_CLIENT_ID,
  858. "redirect_uri": redirect_uri,
  859. "response_type": "code",
  860. "state": _prepare_state(request, "pushbullet"),
  861. }
  862. )
  863. ctx = {
  864. "page": "channels",
  865. "project": request.project,
  866. "authorize_url": authorize_url,
  867. }
  868. return render(request, "integrations/add_pushbullet.html", ctx)
  869. @login_required
  870. def add_discord(request):
  871. if settings.DISCORD_CLIENT_ID is None:
  872. raise Http404("discord integration is not available")
  873. redirect_uri = settings.SITE_ROOT + reverse("hc-add-discord")
  874. if "code" in request.GET:
  875. code = _get_validated_code(request, "discord")
  876. if code is None:
  877. return HttpResponseBadRequest()
  878. result = requests.post(
  879. "https://discordapp.com/api/oauth2/token",
  880. {
  881. "client_id": settings.DISCORD_CLIENT_ID,
  882. "client_secret": settings.DISCORD_CLIENT_SECRET,
  883. "code": code,
  884. "grant_type": "authorization_code",
  885. "redirect_uri": redirect_uri,
  886. },
  887. )
  888. doc = result.json()
  889. if "access_token" in doc:
  890. channel = Channel(kind="discord", project=request.project)
  891. channel.user = request.project.owner
  892. channel.value = result.text
  893. channel.save()
  894. channel.assign_all_checks()
  895. messages.success(request, "The Discord integration has been added!")
  896. else:
  897. messages.warning(request, "Something went wrong")
  898. return redirect("hc-channels")
  899. auth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode(
  900. {
  901. "client_id": settings.DISCORD_CLIENT_ID,
  902. "scope": "webhook.incoming",
  903. "redirect_uri": redirect_uri,
  904. "response_type": "code",
  905. "state": _prepare_state(request, "discord"),
  906. }
  907. )
  908. ctx = {"page": "channels", "project": request.project, "authorize_url": auth_url}
  909. return render(request, "integrations/add_discord.html", ctx)
  910. def add_pushover(request):
  911. if (
  912. settings.PUSHOVER_API_TOKEN is None
  913. or settings.PUSHOVER_SUBSCRIPTION_URL is None
  914. ):
  915. raise Http404("pushover integration is not available")
  916. if not request.user.is_authenticated:
  917. ctx = {"page": "channels"}
  918. return render(request, "integrations/add_pushover.html", ctx)
  919. if request.method == "POST":
  920. # Initiate the subscription
  921. state = _prepare_state(request, "pushover")
  922. failure_url = settings.SITE_ROOT + reverse("hc-channels")
  923. success_url = (
  924. settings.SITE_ROOT
  925. + reverse("hc-add-pushover")
  926. + "?"
  927. + urlencode(
  928. {
  929. "state": state,
  930. "prio": request.POST.get("po_priority", "0"),
  931. "prio_up": request.POST.get("po_priority_up", "0"),
  932. }
  933. )
  934. )
  935. subscription_url = (
  936. settings.PUSHOVER_SUBSCRIPTION_URL
  937. + "?"
  938. + urlencode({"success": success_url, "failure": failure_url})
  939. )
  940. return redirect(subscription_url)
  941. # Handle successful subscriptions
  942. if "pushover_user_key" in request.GET:
  943. key = _get_validated_code(request, "pushover", "pushover_user_key")
  944. if key is None:
  945. return HttpResponseBadRequest()
  946. # Validate priority
  947. prio = request.GET.get("prio")
  948. if prio not in ("-2", "-1", "0", "1", "2"):
  949. return HttpResponseBadRequest()
  950. prio_up = request.GET.get("prio_up")
  951. if prio_up not in ("-2", "-1", "0", "1", "2"):
  952. return HttpResponseBadRequest()
  953. if request.GET.get("pushover_unsubscribed") == "1":
  954. # Unsubscription: delete all Pushover channels for this project
  955. Channel.objects.filter(project=request.project, kind="po").delete()
  956. return redirect("hc-channels")
  957. # Subscription
  958. channel = Channel(project=request.project, kind="po")
  959. channel.value = "%s|%s|%s" % (key, prio, prio_up)
  960. channel.save()
  961. channel.assign_all_checks()
  962. messages.success(request, "The Pushover integration has been added!")
  963. return redirect("hc-channels")
  964. # Show Integration Settings form
  965. ctx = {
  966. "page": "channels",
  967. "project": request.project,
  968. "po_retry_delay": td(seconds=settings.PUSHOVER_EMERGENCY_RETRY_DELAY),
  969. "po_expiration": td(seconds=settings.PUSHOVER_EMERGENCY_EXPIRATION),
  970. }
  971. return render(request, "integrations/add_pushover.html", ctx)
  972. @login_required
  973. def add_opsgenie(request):
  974. if request.method == "POST":
  975. form = AddOpsGenieForm(request.POST)
  976. if form.is_valid():
  977. channel = Channel(project=request.project, kind="opsgenie")
  978. v = {"region": form.cleaned_data["region"], "key": form.cleaned_data["key"]}
  979. channel.value = json.dumps(v)
  980. channel.save()
  981. channel.assign_all_checks()
  982. return redirect("hc-channels")
  983. else:
  984. form = AddOpsGenieForm()
  985. ctx = {"page": "channels", "project": request.project, "form": form}
  986. return render(request, "integrations/add_opsgenie.html", ctx)
  987. @login_required
  988. def add_victorops(request):
  989. if request.method == "POST":
  990. form = AddUrlForm(request.POST)
  991. if form.is_valid():
  992. channel = Channel(project=request.project, kind="victorops")
  993. channel.value = form.cleaned_data["value"]
  994. channel.save()
  995. channel.assign_all_checks()
  996. return redirect("hc-channels")
  997. else:
  998. form = AddUrlForm()
  999. ctx = {"page": "channels", "project": request.project, "form": form}
  1000. return render(request, "integrations/add_victorops.html", ctx)
  1001. @csrf_exempt
  1002. @require_POST
  1003. def telegram_bot(request):
  1004. try:
  1005. doc = json.loads(request.body.decode())
  1006. jsonschema.validate(doc, telegram_callback)
  1007. except ValueError:
  1008. return HttpResponseBadRequest()
  1009. except jsonschema.ValidationError:
  1010. # We don't recognize the message format, but don't want Telegram
  1011. # retrying this over and over again, so respond with 200 OK
  1012. return HttpResponse()
  1013. if "/start" not in doc["message"]["text"]:
  1014. return HttpResponse()
  1015. chat = doc["message"]["chat"]
  1016. name = max(chat.get("title", ""), chat.get("username", ""))
  1017. invite = render_to_string(
  1018. "integrations/telegram_invite.html",
  1019. {"qs": signing.dumps((chat["id"], chat["type"], name))},
  1020. )
  1021. Telegram.send(chat["id"], invite)
  1022. return HttpResponse()
  1023. @login_required
  1024. def add_telegram(request):
  1025. chat_id, chat_type, chat_name = None, None, None
  1026. qs = request.META["QUERY_STRING"]
  1027. if qs:
  1028. chat_id, chat_type, chat_name = signing.loads(qs, max_age=600)
  1029. if request.method == "POST":
  1030. channel = Channel(project=request.project, kind="telegram")
  1031. channel.value = json.dumps(
  1032. {"id": chat_id, "type": chat_type, "name": chat_name}
  1033. )
  1034. channel.save()
  1035. channel.assign_all_checks()
  1036. messages.success(request, "The Telegram integration has been added!")
  1037. return redirect("hc-channels")
  1038. ctx = {
  1039. "page": "channels",
  1040. "project": request.project,
  1041. "chat_id": chat_id,
  1042. "chat_type": chat_type,
  1043. "chat_name": chat_name,
  1044. "bot_name": settings.TELEGRAM_BOT_NAME,
  1045. }
  1046. return render(request, "integrations/add_telegram.html", ctx)
  1047. @login_required
  1048. def add_sms(request):
  1049. if settings.TWILIO_AUTH is None:
  1050. raise Http404("sms integration is not available")
  1051. if request.method == "POST":
  1052. form = AddSmsForm(request.POST)
  1053. if form.is_valid():
  1054. channel = Channel(project=request.project, kind="sms")
  1055. channel.name = form.cleaned_data["label"]
  1056. channel.value = json.dumps({"value": form.cleaned_data["value"]})
  1057. channel.save()
  1058. channel.assign_all_checks()
  1059. return redirect("hc-channels")
  1060. else:
  1061. form = AddSmsForm()
  1062. ctx = {
  1063. "page": "channels",
  1064. "project": request.project,
  1065. "form": form,
  1066. "profile": request.project.owner_profile,
  1067. }
  1068. return render(request, "integrations/add_sms.html", ctx)
  1069. @login_required
  1070. def add_whatsapp(request):
  1071. if not settings.TWILIO_USE_WHATSAPP:
  1072. raise Http404("whatsapp integration is not available")
  1073. if request.method == "POST":
  1074. form = AddSmsForm(request.POST)
  1075. if form.is_valid():
  1076. channel = Channel(project=request.project, kind="whatsapp")
  1077. channel.name = form.cleaned_data["label"]
  1078. channel.value = json.dumps(
  1079. {
  1080. "value": form.cleaned_data["value"],
  1081. "up": form.cleaned_data["up"],
  1082. "down": form.cleaned_data["down"],
  1083. }
  1084. )
  1085. channel.save()
  1086. channel.assign_all_checks()
  1087. return redirect("hc-channels")
  1088. else:
  1089. form = AddSmsForm()
  1090. ctx = {
  1091. "page": "channels",
  1092. "project": request.project,
  1093. "form": form,
  1094. "profile": request.project.owner_profile,
  1095. }
  1096. return render(request, "integrations/add_whatsapp.html", ctx)
  1097. @login_required
  1098. def add_trello(request):
  1099. if settings.TRELLO_APP_KEY is None:
  1100. raise Http404("trello integration is not available")
  1101. if request.method == "POST":
  1102. channel = Channel(project=request.project, kind="trello")
  1103. channel.value = request.POST["settings"]
  1104. channel.save()
  1105. channel.assign_all_checks()
  1106. return redirect("hc-channels")
  1107. authorize_url = "https://trello.com/1/authorize?" + urlencode(
  1108. {
  1109. "expiration": "never",
  1110. "name": settings.SITE_NAME,
  1111. "scope": "read,write",
  1112. "response_type": "token",
  1113. "key": settings.TRELLO_APP_KEY,
  1114. "return_url": settings.SITE_ROOT + reverse("hc-add-trello"),
  1115. }
  1116. )
  1117. ctx = {
  1118. "page": "channels",
  1119. "project": request.project,
  1120. "authorize_url": authorize_url,
  1121. }
  1122. return render(request, "integrations/add_trello.html", ctx)
  1123. @login_required
  1124. def add_matrix(request):
  1125. if settings.MATRIX_ACCESS_TOKEN is None:
  1126. raise Http404("matrix integration is not available")
  1127. if request.method == "POST":
  1128. form = AddMatrixForm(request.POST)
  1129. if form.is_valid():
  1130. channel = Channel(project=request.project, kind="matrix")
  1131. channel.value = form.cleaned_data["room_id"]
  1132. # If user supplied room alias instead of ID, use it as channel name
  1133. alias = form.cleaned_data["alias"]
  1134. if not alias.startswith("!"):
  1135. channel.name = alias
  1136. channel.save()
  1137. channel.assign_all_checks()
  1138. messages.success(request, "The Matrix integration has been added!")
  1139. return redirect("hc-channels")
  1140. else:
  1141. form = AddMatrixForm()
  1142. ctx = {
  1143. "page": "channels",
  1144. "project": request.project,
  1145. "form": form,
  1146. "matrix_user_id": settings.MATRIX_USER_ID,
  1147. }
  1148. return render(request, "integrations/add_matrix.html", ctx)
  1149. @login_required
  1150. def add_apprise(request):
  1151. if not settings.APPRISE_ENABLED:
  1152. raise Http404("apprise integration is not available")
  1153. if request.method == "POST":
  1154. form = AddAppriseForm(request.POST)
  1155. if form.is_valid():
  1156. channel = Channel(project=request.project, kind="apprise")
  1157. channel.value = form.cleaned_data["url"]
  1158. channel.save()
  1159. channel.assign_all_checks()
  1160. messages.success(request, "The Apprise integration has been added!")
  1161. return redirect("hc-channels")
  1162. else:
  1163. form = AddAppriseForm()
  1164. ctx = {"page": "channels", "project": request.project, "form": form}
  1165. return render(request, "integrations/add_apprise.html", ctx)
  1166. @login_required
  1167. @require_POST
  1168. def trello_settings(request):
  1169. token = request.POST.get("token")
  1170. url = "https://api.trello.com/1/members/me/boards?" + urlencode(
  1171. {
  1172. "key": settings.TRELLO_APP_KEY,
  1173. "token": token,
  1174. "fields": "id,name",
  1175. "lists": "open",
  1176. "list_fields": "id,name",
  1177. }
  1178. )
  1179. r = requests.get(url)
  1180. ctx = {"token": token, "data": r.json()}
  1181. return render(request, "integrations/trello_settings.html", ctx)
  1182. @login_required
  1183. def add_msteams(request):
  1184. if request.method == "POST":
  1185. form = AddUrlForm(request.POST)
  1186. if form.is_valid():
  1187. channel = Channel(project=request.project, kind="msteams")
  1188. channel.value = form.cleaned_data["value"]
  1189. channel.save()
  1190. channel.assign_all_checks()
  1191. return redirect("hc-channels")
  1192. else:
  1193. form = AddUrlForm()
  1194. ctx = {"page": "channels", "project": request.project, "form": form}
  1195. return render(request, "integrations/add_msteams.html", ctx)