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.

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