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.

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