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.

1099 lines
33 KiB

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
9 years ago
6 years ago
9 years ago
10 years ago
10 years ago
10 years ago
6 years ago
9 years ago
9 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
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 (Http404, HttpResponse, HttpResponseBadRequest,
  11. HttpResponseForbidden, JsonResponse)
  12. from django.shortcuts import get_object_or_404, redirect, render
  13. from django.template.loader import get_template, render_to_string
  14. from django.urls import reverse
  15. from django.utils import timezone
  16. from django.utils.crypto import get_random_string
  17. from django.views.decorators.csrf import csrf_exempt
  18. from django.views.decorators.http import require_POST
  19. from hc.api.models import (DEFAULT_GRACE, DEFAULT_TIMEOUT, Channel, Check,
  20. Ping, Notification)
  21. from hc.api.transports import Telegram
  22. from hc.front.forms import (AddWebhookForm, NameTagsForm,
  23. TimeoutForm, AddUrlForm, AddEmailForm,
  24. AddOpsGenieForm, CronForm, AddSmsForm,
  25. ChannelNameForm)
  26. from hc.front.schemas import telegram_callback
  27. from hc.front.templatetags.hc_extras import (num_down_title, down_title,
  28. sortchecks)
  29. from hc.lib import jsonschema
  30. from pytz import all_timezones
  31. from pytz.exceptions import UnknownTimeZoneError
  32. import requests
  33. VALID_SORT_VALUES = ("name", "-name", "last_ping", "-last_ping", "created")
  34. STATUS_TEXT_TMPL = get_template("front/log_status_text.html")
  35. LAST_PING_TMPL = get_template("front/last_ping_cell.html")
  36. EVENTS_TMPL = get_template("front/details_events.html")
  37. def _tags_statuses(checks):
  38. tags, down, grace, num_down = {}, {}, {}, 0
  39. for check in checks:
  40. status = check.get_status()
  41. if status == "down":
  42. num_down += 1
  43. for tag in check.tags_list():
  44. down[tag] = "down"
  45. elif status == "grace":
  46. for tag in check.tags_list():
  47. grace[tag] = "grace"
  48. else:
  49. for tag in check.tags_list():
  50. tags[tag] = "up"
  51. tags.update(grace)
  52. tags.update(down)
  53. return tags, num_down
  54. def _get_check_for_user(request, code):
  55. """ Return specified check if current user has access to it. """
  56. if not request.user.is_authenticated:
  57. raise Http404("not found")
  58. if request.user.is_superuser:
  59. q = Check.objects
  60. else:
  61. q = request.profile.checks_from_all_teams()
  62. try:
  63. return q.get(code=code)
  64. except Check.DoesNotExist:
  65. raise Http404("not found")
  66. def _has_access(request, username):
  67. """ Return true if current user has access to the specified account. """
  68. if request.user.username == username:
  69. return True
  70. if request.user.is_superuser:
  71. return True
  72. mq = request.user.memberships
  73. return mq.filter(team__user__username=username).exists()
  74. @login_required
  75. def my_checks(request):
  76. if request.GET.get("sort") in VALID_SORT_VALUES:
  77. request.profile.sort = request.GET["sort"]
  78. request.profile.save()
  79. checks = list(Check.objects.filter(user=request.team.user).prefetch_related("channel_set"))
  80. sortchecks(checks, request.profile.sort)
  81. tags_statuses, num_down = _tags_statuses(checks)
  82. pairs = list(tags_statuses.items())
  83. pairs.sort(key=lambda pair: pair[0].lower())
  84. channels = Channel.objects.filter(user=request.team.user)
  85. channels = list(channels.order_by("created"))
  86. hidden_checks = set()
  87. # Hide checks that don't match selected tags:
  88. selected_tags = set(request.GET.getlist("tag", []))
  89. if selected_tags:
  90. for check in checks:
  91. if not selected_tags.issubset(check.tags_list()):
  92. hidden_checks.add(check)
  93. # Hide checks that don't match the search string:
  94. search = request.GET.get("search", "")
  95. if search:
  96. for check in checks:
  97. search_key = "%s\n%s" % (check.name.lower(), check.code)
  98. if search not in search_key:
  99. hidden_checks.add(check)
  100. ctx = {
  101. "page": "checks",
  102. "checks": checks,
  103. "channels": channels,
  104. "num_down": num_down,
  105. "now": timezone.now(),
  106. "tags": pairs,
  107. "ping_endpoint": settings.PING_ENDPOINT,
  108. "timezones": all_timezones,
  109. "num_available": request.team.check_limit - len(checks),
  110. "sort": request.profile.sort,
  111. "selected_tags": selected_tags,
  112. "show_search": True,
  113. "search": search,
  114. "hidden_checks": hidden_checks
  115. }
  116. return render(request, "front/my_checks.html", ctx)
  117. @login_required
  118. def status(request, username):
  119. if not _has_access(request, username):
  120. raise Http404("not found")
  121. checks = list(Check.objects.filter(user__username=username))
  122. details = []
  123. for check in checks:
  124. ctx = {"check": check}
  125. details.append({
  126. "code": str(check.code),
  127. "status": check.get_status(),
  128. "last_ping": LAST_PING_TMPL.render(ctx)
  129. })
  130. tags_statuses, num_down = _tags_statuses(checks)
  131. return JsonResponse({
  132. "details": details,
  133. "tags": tags_statuses,
  134. "title": num_down_title(num_down)
  135. })
  136. @login_required
  137. @require_POST
  138. def switch_channel(request, code, channel_code):
  139. check = _get_check_for_user(request, code)
  140. channel = get_object_or_404(Channel, code=channel_code)
  141. if channel.user_id != check.user_id:
  142. return HttpResponseBadRequest()
  143. if request.POST.get("state") == "on":
  144. channel.checks.add(check)
  145. else:
  146. channel.checks.remove(check)
  147. return HttpResponse()
  148. def index(request):
  149. if request.user.is_authenticated:
  150. return redirect("hc-checks")
  151. check = Check()
  152. ctx = {
  153. "page": "welcome",
  154. "check": check,
  155. "ping_url": check.url(),
  156. "enable_pushbullet": settings.PUSHBULLET_CLIENT_ID is not None,
  157. "enable_pushover": settings.PUSHOVER_API_TOKEN is not None,
  158. "enable_discord": settings.DISCORD_CLIENT_ID is not None,
  159. "enable_telegram": settings.TELEGRAM_TOKEN is not None,
  160. "enable_sms": settings.TWILIO_AUTH is not None,
  161. "enable_pd": settings.PD_VENDOR_KEY is not None,
  162. "enable_trello": settings.TRELLO_APP_KEY is not None,
  163. "registration_open": settings.REGISTRATION_OPEN
  164. }
  165. return render(request, "front/welcome.html", ctx)
  166. def docs(request):
  167. ctx = {
  168. "page": "docs",
  169. "section": "home",
  170. "ping_endpoint": settings.PING_ENDPOINT,
  171. "ping_email": "your-uuid-here@%s" % settings.PING_EMAIL_DOMAIN,
  172. "ping_url": settings.PING_ENDPOINT + "your-uuid-here"
  173. }
  174. return render(request, "front/docs.html", ctx)
  175. def docs_api(request):
  176. ctx = {
  177. "page": "docs",
  178. "section": "api",
  179. "SITE_ROOT": settings.SITE_ROOT,
  180. "PING_ENDPOINT": settings.PING_ENDPOINT,
  181. "default_timeout": int(DEFAULT_TIMEOUT.total_seconds()),
  182. "default_grace": int(DEFAULT_GRACE.total_seconds())
  183. }
  184. return render(request, "front/docs_api.html", ctx)
  185. def docs_cron(request):
  186. ctx = {"page": "docs", "section": "cron"}
  187. return render(request, "front/docs_cron.html", ctx)
  188. def docs_resources(request):
  189. ctx = {"page": "docs", "section": "resources"}
  190. return render(request, "front/docs_resources.html", ctx)
  191. @require_POST
  192. @login_required
  193. def add_check(request):
  194. num_checks = Check.objects.filter(user=request.team.user).count()
  195. if num_checks >= request.team.check_limit:
  196. return HttpResponseBadRequest()
  197. check = Check(user=request.team.user)
  198. check.save()
  199. check.assign_all_channels()
  200. return redirect("hc-checks")
  201. @require_POST
  202. @login_required
  203. def update_name(request, code):
  204. check = _get_check_for_user(request, code)
  205. form = NameTagsForm(request.POST)
  206. if form.is_valid():
  207. check.name = form.cleaned_data["name"]
  208. check.tags = form.cleaned_data["tags"]
  209. check.desc = form.cleaned_data["desc"]
  210. check.save()
  211. if "/details/" in request.META.get("HTTP_REFERER", ""):
  212. return redirect("hc-details", code)
  213. return redirect("hc-checks")
  214. @require_POST
  215. @login_required
  216. def update_timeout(request, code):
  217. check = _get_check_for_user(request, code)
  218. kind = request.POST.get("kind")
  219. if kind == "simple":
  220. form = TimeoutForm(request.POST)
  221. if not form.is_valid():
  222. return HttpResponseBadRequest()
  223. check.kind = "simple"
  224. check.timeout = form.cleaned_data["timeout"]
  225. check.grace = form.cleaned_data["grace"]
  226. elif kind == "cron":
  227. form = CronForm(request.POST)
  228. if not form.is_valid():
  229. return HttpResponseBadRequest()
  230. check.kind = "cron"
  231. check.schedule = form.cleaned_data["schedule"]
  232. check.tz = form.cleaned_data["tz"]
  233. check.grace = td(minutes=form.cleaned_data["grace"])
  234. if check.last_ping:
  235. check.alert_after = check.get_alert_after()
  236. check.save()
  237. if "/details/" in request.META.get("HTTP_REFERER", ""):
  238. return redirect("hc-details", code)
  239. return redirect("hc-checks")
  240. @require_POST
  241. def cron_preview(request):
  242. schedule = request.POST.get("schedule")
  243. tz = request.POST.get("tz")
  244. ctx = {"tz": tz, "dates": []}
  245. try:
  246. with timezone.override(tz):
  247. now_naive = timezone.make_naive(timezone.now())
  248. it = croniter(schedule, now_naive)
  249. for i in range(0, 6):
  250. naive = it.get_next(datetime)
  251. aware = timezone.make_aware(naive, is_dst=True)
  252. ctx["dates"].append((naive, aware))
  253. except UnknownTimeZoneError:
  254. ctx["bad_tz"] = True
  255. except:
  256. ctx["bad_schedule"] = True
  257. return render(request, "front/cron_preview.html", ctx)
  258. def ping_details(request, code, n=None):
  259. check = _get_check_for_user(request, code)
  260. q = Ping.objects.filter(owner=check)
  261. if n:
  262. q = q.filter(n=n)
  263. ping = q.latest("created")
  264. ctx = {
  265. "check": check,
  266. "ping": ping
  267. }
  268. return render(request, "front/ping_details.html", ctx)
  269. @require_POST
  270. @login_required
  271. def pause(request, code):
  272. check = _get_check_for_user(request, code)
  273. check.status = "paused"
  274. check.save()
  275. if "/details/" in request.META.get("HTTP_REFERER", ""):
  276. return redirect("hc-details", code)
  277. return redirect("hc-checks")
  278. @require_POST
  279. @login_required
  280. def remove_check(request, code):
  281. check = _get_check_for_user(request, code)
  282. check.delete()
  283. return redirect("hc-checks")
  284. def _get_events(check, limit):
  285. pings = Ping.objects.filter(owner=check).order_by("-id")[:limit]
  286. pings = list(pings)
  287. alerts = []
  288. if len(pings):
  289. cutoff = pings[-1].created
  290. alerts = Notification.objects \
  291. .select_related("channel") \
  292. .filter(owner=check, check_status="down", created__gt=cutoff)
  293. events = pings + list(alerts)
  294. events.sort(key=lambda el: el.created, reverse=True)
  295. return events
  296. @login_required
  297. def log(request, code):
  298. check = _get_check_for_user(request, code)
  299. limit = check.user.profile.ping_log_limit
  300. ctx = {
  301. "check": check,
  302. "events": _get_events(check, limit),
  303. "limit": limit,
  304. "show_limit_notice": check.n_pings > limit and settings.USE_PAYMENTS
  305. }
  306. return render(request, "front/log.html", ctx)
  307. @login_required
  308. def details(request, code):
  309. check = _get_check_for_user(request, code)
  310. channels = Channel.objects.filter(user=check.user)
  311. channels = list(channels.order_by("created"))
  312. ctx = {
  313. "page": "details",
  314. "check": check,
  315. "channels": channels,
  316. "timezones": all_timezones
  317. }
  318. return render(request, "front/details.html", ctx)
  319. @login_required
  320. def status_single(request, code):
  321. check = _get_check_for_user(request, code)
  322. status = check.get_status()
  323. events = _get_events(check, 20)
  324. updated = "1"
  325. if len(events):
  326. updated = events[0].created.strftime("%s.%f")
  327. doc = {
  328. "status": status,
  329. "status_text": STATUS_TEXT_TMPL.render({"check": check}),
  330. "title": down_title(check),
  331. "updated": updated
  332. }
  333. if updated != request.GET.get("u"):
  334. doc["events"] = EVENTS_TMPL.render({"check": check, "events": events})
  335. return JsonResponse(doc)
  336. @login_required
  337. def channels(request):
  338. if request.method == "POST":
  339. code = request.POST["channel"]
  340. try:
  341. channel = Channel.objects.get(code=code)
  342. except Channel.DoesNotExist:
  343. return HttpResponseBadRequest()
  344. if channel.user_id != request.team.user.id:
  345. return HttpResponseForbidden()
  346. new_checks = []
  347. for key in request.POST:
  348. if key.startswith("check-"):
  349. code = key[6:]
  350. try:
  351. check = Check.objects.get(code=code)
  352. except Check.DoesNotExist:
  353. return HttpResponseBadRequest()
  354. if check.user_id != request.team.user.id:
  355. return HttpResponseForbidden()
  356. new_checks.append(check)
  357. channel.checks.set(new_checks)
  358. return redirect("hc-channels")
  359. channels = Channel.objects.filter(user=request.team.user)
  360. channels = channels.order_by("created")
  361. channels = channels.annotate(n_checks=Count("checks"))
  362. num_checks = Check.objects.filter(user=request.team.user).count()
  363. ctx = {
  364. "page": "channels",
  365. "profile": request.team,
  366. "channels": channels,
  367. "num_checks": num_checks,
  368. "enable_pushbullet": settings.PUSHBULLET_CLIENT_ID is not None,
  369. "enable_pushover": settings.PUSHOVER_API_TOKEN is not None,
  370. "enable_discord": settings.DISCORD_CLIENT_ID is not None,
  371. "enable_telegram": settings.TELEGRAM_TOKEN is not None,
  372. "enable_sms": settings.TWILIO_AUTH is not None,
  373. "enable_pd": settings.PD_VENDOR_KEY is not None,
  374. "enable_trello": settings.TRELLO_APP_KEY is not None,
  375. "use_payments": settings.USE_PAYMENTS
  376. }
  377. return render(request, "front/channels.html", ctx)
  378. @login_required
  379. def channel_checks(request, code):
  380. channel = get_object_or_404(Channel, code=code)
  381. if channel.user_id != request.team.user.id:
  382. return HttpResponseForbidden()
  383. assigned = set(channel.checks.values_list('code', flat=True).distinct())
  384. checks = Check.objects.filter(user=request.team.user).order_by("created")
  385. ctx = {
  386. "checks": checks,
  387. "assigned": assigned,
  388. "channel": channel
  389. }
  390. return render(request, "front/channel_checks.html", ctx)
  391. @require_POST
  392. @login_required
  393. def update_channel_name(request, code):
  394. channel = get_object_or_404(Channel, code=code)
  395. if channel.user_id != request.team.user.id:
  396. return HttpResponseForbidden()
  397. form = ChannelNameForm(request.POST)
  398. if form.is_valid():
  399. channel.name = form.cleaned_data["name"]
  400. channel.save()
  401. return redirect("hc-channels")
  402. def verify_email(request, code, token):
  403. channel = get_object_or_404(Channel, code=code)
  404. if channel.make_token() == token:
  405. channel.email_verified = True
  406. channel.save()
  407. return render(request, "front/verify_email_success.html")
  408. return render(request, "bad_link.html")
  409. def unsubscribe_email(request, code, token):
  410. channel = get_object_or_404(Channel, code=code)
  411. if channel.make_token() != token:
  412. return render(request, "bad_link.html")
  413. if channel.kind != "email":
  414. return HttpResponseBadRequest()
  415. # Some email servers open links in emails to check for malicious content.
  416. # To work around this, we serve a form that auto-submits with JS.
  417. if "ask" in request.GET and request.method != "POST":
  418. return render(request, "accounts/unsubscribe_submit.html")
  419. channel.delete()
  420. return render(request, "front/unsubscribe_success.html")
  421. @require_POST
  422. @login_required
  423. def remove_channel(request, code):
  424. # user may refresh the page during POST and cause two deletion attempts
  425. channel = Channel.objects.filter(code=code).first()
  426. if channel:
  427. if channel.user != request.team.user:
  428. return HttpResponseForbidden()
  429. channel.delete()
  430. return redirect("hc-channels")
  431. @login_required
  432. def add_email(request):
  433. if request.method == "POST":
  434. form = AddEmailForm(request.POST)
  435. if form.is_valid():
  436. channel = Channel(user=request.team.user, kind="email")
  437. channel.value = form.cleaned_data["value"]
  438. channel.save()
  439. channel.assign_all_checks()
  440. channel.send_verify_link()
  441. return redirect("hc-channels")
  442. else:
  443. form = AddEmailForm()
  444. ctx = {"page": "channels", "form": form}
  445. return render(request, "integrations/add_email.html", ctx)
  446. @login_required
  447. def add_webhook(request):
  448. if request.method == "POST":
  449. form = AddWebhookForm(request.POST)
  450. if form.is_valid():
  451. channel = Channel(user=request.team.user, kind="webhook")
  452. channel.value = form.get_value()
  453. channel.save()
  454. channel.assign_all_checks()
  455. return redirect("hc-channels")
  456. else:
  457. form = AddWebhookForm()
  458. ctx = {
  459. "page": "channels",
  460. "form": form,
  461. "now": timezone.now().replace(microsecond=0).isoformat()
  462. }
  463. return render(request, "integrations/add_webhook.html", ctx)
  464. def _prepare_state(request, session_key):
  465. state = get_random_string()
  466. request.session[session_key] = state
  467. return state
  468. def _get_validated_code(request, session_key, key="code"):
  469. if session_key not in request.session:
  470. return None
  471. session_state = request.session.pop(session_key)
  472. request_state = request.GET.get("state")
  473. if session_state is None or session_state != request_state:
  474. return None
  475. return request.GET.get(key)
  476. def add_pd(request, state=None):
  477. if settings.PD_VENDOR_KEY is None:
  478. raise Http404("pagerduty integration is not available")
  479. if state and request.user.is_authenticated:
  480. if "pd" not in request.session:
  481. return HttpResponseBadRequest()
  482. session_state = request.session.pop("pd")
  483. if session_state != state:
  484. return HttpResponseBadRequest()
  485. if request.GET.get("error") == "cancelled":
  486. messages.warning(request, "PagerDuty setup was cancelled")
  487. return redirect("hc-channels")
  488. channel = Channel()
  489. channel.user = request.team.user
  490. channel.kind = "pd"
  491. channel.value = json.dumps({
  492. "service_key": request.GET.get("service_key"),
  493. "account": request.GET.get("account")
  494. })
  495. channel.save()
  496. channel.assign_all_checks()
  497. messages.success(request, "The PagerDuty integration has been added!")
  498. return redirect("hc-channels")
  499. state = _prepare_state(request, "pd")
  500. callback = settings.SITE_ROOT + reverse("hc-add-pd-state", args=[state])
  501. connect_url = "https://connect.pagerduty.com/connect?" + urlencode({
  502. "vendor": settings.PD_VENDOR_KEY,
  503. "callback": callback
  504. })
  505. ctx = {"page": "channels", "connect_url": connect_url}
  506. return render(request, "integrations/add_pd.html", ctx)
  507. @login_required
  508. def add_pagertree(request):
  509. if request.method == "POST":
  510. form = AddUrlForm(request.POST)
  511. if form.is_valid():
  512. channel = Channel(user=request.team.user, kind="pagertree")
  513. channel.value = form.cleaned_data["value"]
  514. channel.save()
  515. channel.assign_all_checks()
  516. return redirect("hc-channels")
  517. else:
  518. form = AddUrlForm()
  519. ctx = {"page": "channels", "form": form}
  520. return render(request, "integrations/add_pagertree.html", ctx)
  521. def add_slack(request):
  522. if not settings.SLACK_CLIENT_ID and not request.user.is_authenticated:
  523. return redirect("hc-login")
  524. if request.method == "POST":
  525. form = AddUrlForm(request.POST)
  526. if form.is_valid():
  527. channel = Channel(user=request.team.user, kind="slack")
  528. channel.value = form.cleaned_data["value"]
  529. channel.save()
  530. channel.assign_all_checks()
  531. return redirect("hc-channels")
  532. else:
  533. form = AddUrlForm()
  534. ctx = {
  535. "page": "channels",
  536. "form": form,
  537. "slack_client_id": settings.SLACK_CLIENT_ID
  538. }
  539. if settings.SLACK_CLIENT_ID and request.user.is_authenticated:
  540. ctx["state"] = _prepare_state(request, "slack")
  541. return render(request, "integrations/add_slack.html", ctx)
  542. @login_required
  543. def add_slack_btn(request):
  544. code = _get_validated_code(request, "slack")
  545. if code is None:
  546. return HttpResponseBadRequest()
  547. result = requests.post("https://slack.com/api/oauth.access", {
  548. "client_id": settings.SLACK_CLIENT_ID,
  549. "client_secret": settings.SLACK_CLIENT_SECRET,
  550. "code": code
  551. })
  552. doc = result.json()
  553. if doc.get("ok"):
  554. channel = Channel()
  555. channel.user = request.team.user
  556. channel.kind = "slack"
  557. channel.value = result.text
  558. channel.save()
  559. channel.assign_all_checks()
  560. messages.success(request, "The Slack integration has been added!")
  561. else:
  562. s = doc.get("error")
  563. messages.warning(request, "Error message from slack: %s" % s)
  564. return redirect("hc-channels")
  565. @login_required
  566. def add_hipchat(request):
  567. if "installable_url" in request.GET:
  568. url = request.GET["installable_url"]
  569. assert url.startswith("https://api.hipchat.com")
  570. response = requests.get(url)
  571. if "oauthId" not in response.json():
  572. messages.warning(request, "Something went wrong!")
  573. return redirect("hc-channels")
  574. channel = Channel(kind="hipchat")
  575. channel.user = request.team.user
  576. channel.value = response.text
  577. channel.save()
  578. channel.refresh_hipchat_access_token()
  579. channel.assign_all_checks()
  580. messages.success(request, "The HipChat integration has been added!")
  581. return redirect("hc-channels")
  582. install_url = "https://www.hipchat.com/addons/install?" + urlencode({
  583. "url": settings.SITE_ROOT + reverse("hc-hipchat-capabilities")
  584. })
  585. ctx = {
  586. "page": "channels",
  587. "install_url": install_url
  588. }
  589. return render(request, "integrations/add_hipchat.html", ctx)
  590. def hipchat_capabilities(request):
  591. return render(request, "integrations/hipchat_capabilities.json", {},
  592. content_type="application/json")
  593. @login_required
  594. def add_pushbullet(request):
  595. if settings.PUSHBULLET_CLIENT_ID is None:
  596. raise Http404("pushbullet integration is not available")
  597. if "code" in request.GET:
  598. code = _get_validated_code(request, "pushbullet")
  599. if code is None:
  600. return HttpResponseBadRequest()
  601. result = requests.post("https://api.pushbullet.com/oauth2/token", {
  602. "client_id": settings.PUSHBULLET_CLIENT_ID,
  603. "client_secret": settings.PUSHBULLET_CLIENT_SECRET,
  604. "code": code,
  605. "grant_type": "authorization_code"
  606. })
  607. doc = result.json()
  608. if "access_token" in doc:
  609. channel = Channel(kind="pushbullet")
  610. channel.user = request.team.user
  611. channel.value = doc["access_token"]
  612. channel.save()
  613. channel.assign_all_checks()
  614. messages.success(request,
  615. "The Pushbullet integration has been added!")
  616. else:
  617. messages.warning(request, "Something went wrong")
  618. return redirect("hc-channels")
  619. redirect_uri = settings.SITE_ROOT + reverse("hc-add-pushbullet")
  620. authorize_url = "https://www.pushbullet.com/authorize?" + urlencode({
  621. "client_id": settings.PUSHBULLET_CLIENT_ID,
  622. "redirect_uri": redirect_uri,
  623. "response_type": "code",
  624. "state": _prepare_state(request, "pushbullet")
  625. })
  626. ctx = {
  627. "page": "channels",
  628. "authorize_url": authorize_url
  629. }
  630. return render(request, "integrations/add_pushbullet.html", ctx)
  631. @login_required
  632. def add_discord(request):
  633. if settings.DISCORD_CLIENT_ID is None:
  634. raise Http404("discord integration is not available")
  635. redirect_uri = settings.SITE_ROOT + reverse("hc-add-discord")
  636. if "code" in request.GET:
  637. code = _get_validated_code(request, "discord")
  638. if code is None:
  639. return HttpResponseBadRequest()
  640. result = requests.post("https://discordapp.com/api/oauth2/token", {
  641. "client_id": settings.DISCORD_CLIENT_ID,
  642. "client_secret": settings.DISCORD_CLIENT_SECRET,
  643. "code": code,
  644. "grant_type": "authorization_code",
  645. "redirect_uri": redirect_uri
  646. })
  647. doc = result.json()
  648. if "access_token" in doc:
  649. channel = Channel(kind="discord")
  650. channel.user = request.team.user
  651. channel.value = result.text
  652. channel.save()
  653. channel.assign_all_checks()
  654. messages.success(request,
  655. "The Discord integration has been added!")
  656. else:
  657. messages.warning(request, "Something went wrong")
  658. return redirect("hc-channels")
  659. auth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode({
  660. "client_id": settings.DISCORD_CLIENT_ID,
  661. "scope": "webhook.incoming",
  662. "redirect_uri": redirect_uri,
  663. "response_type": "code",
  664. "state": _prepare_state(request, "discord")
  665. })
  666. ctx = {
  667. "page": "channels",
  668. "authorize_url": auth_url
  669. }
  670. return render(request, "integrations/add_discord.html", ctx)
  671. def add_pushover(request):
  672. if settings.PUSHOVER_API_TOKEN is None or settings.PUSHOVER_SUBSCRIPTION_URL is None:
  673. raise Http404("pushover integration is not available")
  674. if not request.user.is_authenticated:
  675. ctx = {"page": "channels"}
  676. return render(request, "integrations/add_pushover.html", ctx)
  677. if request.method == "POST":
  678. # Initiate the subscription
  679. state = _prepare_state(request, "pushover")
  680. failure_url = settings.SITE_ROOT + reverse("hc-channels")
  681. success_url = settings.SITE_ROOT + reverse("hc-add-pushover") + "?" + urlencode({
  682. "state": state,
  683. "prio": request.POST.get("po_priority", "0"),
  684. "prio_up": request.POST.get("po_priority_up", "0")
  685. })
  686. subscription_url = settings.PUSHOVER_SUBSCRIPTION_URL + "?" + urlencode({
  687. "success": success_url,
  688. "failure": failure_url,
  689. })
  690. return redirect(subscription_url)
  691. # Handle successful subscriptions
  692. if "pushover_user_key" in request.GET:
  693. key = _get_validated_code(request, "pushover", "pushover_user_key")
  694. if key is None:
  695. return HttpResponseBadRequest()
  696. # Validate priority
  697. prio = request.GET.get("prio")
  698. if prio not in ("-2", "-1", "0", "1", "2"):
  699. return HttpResponseBadRequest()
  700. prio_up = request.GET.get("prio_up")
  701. if prio_up not in ("-2", "-1", "0", "1", "2"):
  702. return HttpResponseBadRequest()
  703. if request.GET.get("pushover_unsubscribed") == "1":
  704. # Unsubscription: delete all Pushover channels for this user
  705. Channel.objects.filter(user=request.user, kind="po").delete()
  706. return redirect("hc-channels")
  707. # Subscription
  708. channel = Channel(user=request.team.user, kind="po")
  709. channel.value = "%s|%s|%s" % (key, prio, prio_up)
  710. channel.save()
  711. channel.assign_all_checks()
  712. messages.success(request, "The Pushover integration has been added!")
  713. return redirect("hc-channels")
  714. # Show Integration Settings form
  715. ctx = {
  716. "page": "channels",
  717. "po_retry_delay": td(seconds=settings.PUSHOVER_EMERGENCY_RETRY_DELAY),
  718. "po_expiration": td(seconds=settings.PUSHOVER_EMERGENCY_EXPIRATION),
  719. }
  720. return render(request, "integrations/add_pushover.html", ctx)
  721. @login_required
  722. def add_opsgenie(request):
  723. if request.method == "POST":
  724. form = AddOpsGenieForm(request.POST)
  725. if form.is_valid():
  726. channel = Channel(user=request.team.user, kind="opsgenie")
  727. channel.value = form.cleaned_data["value"]
  728. channel.save()
  729. channel.assign_all_checks()
  730. return redirect("hc-channels")
  731. else:
  732. form = AddUrlForm()
  733. ctx = {"page": "channels", "form": form}
  734. return render(request, "integrations/add_opsgenie.html", ctx)
  735. @login_required
  736. def add_victorops(request):
  737. if request.method == "POST":
  738. form = AddUrlForm(request.POST)
  739. if form.is_valid():
  740. channel = Channel(user=request.team.user, kind="victorops")
  741. channel.value = form.cleaned_data["value"]
  742. channel.save()
  743. channel.assign_all_checks()
  744. return redirect("hc-channels")
  745. else:
  746. form = AddUrlForm()
  747. ctx = {"page": "channels", "form": form}
  748. return render(request, "integrations/add_victorops.html", ctx)
  749. @csrf_exempt
  750. @require_POST
  751. def telegram_bot(request):
  752. try:
  753. doc = json.loads(request.body.decode())
  754. jsonschema.validate(doc, telegram_callback)
  755. except ValueError:
  756. return HttpResponseBadRequest()
  757. except jsonschema.ValidationError:
  758. # We don't recognize the message format, but don't want Telegram
  759. # retrying this over and over again, so respond with 200 OK
  760. return HttpResponse()
  761. if "/start" not in doc["message"]["text"]:
  762. return HttpResponse()
  763. chat = doc["message"]["chat"]
  764. name = max(chat.get("title", ""), chat.get("username", ""))
  765. invite = render_to_string("integrations/telegram_invite.html", {
  766. "qs": signing.dumps((chat["id"], chat["type"], name))
  767. })
  768. Telegram.send(chat["id"], invite)
  769. return HttpResponse()
  770. @login_required
  771. def add_telegram(request):
  772. chat_id, chat_type, chat_name = None, None, None
  773. qs = request.META["QUERY_STRING"]
  774. if qs:
  775. chat_id, chat_type, chat_name = signing.loads(qs, max_age=600)
  776. if request.method == "POST":
  777. channel = Channel(user=request.team.user, kind="telegram")
  778. channel.value = json.dumps({
  779. "id": chat_id,
  780. "type": chat_type,
  781. "name": chat_name
  782. })
  783. channel.save()
  784. channel.assign_all_checks()
  785. messages.success(request, "The Telegram integration has been added!")
  786. return redirect("hc-channels")
  787. ctx = {
  788. "chat_id": chat_id,
  789. "chat_type": chat_type,
  790. "chat_name": chat_name,
  791. "bot_name": settings.TELEGRAM_BOT_NAME
  792. }
  793. return render(request, "integrations/add_telegram.html", ctx)
  794. @login_required
  795. def add_sms(request):
  796. if settings.TWILIO_AUTH is None:
  797. raise Http404("sms integration is not available")
  798. if request.method == "POST":
  799. form = AddSmsForm(request.POST)
  800. if form.is_valid():
  801. channel = Channel(user=request.team.user, kind="sms")
  802. channel.name = form.cleaned_data["label"]
  803. channel.value = json.dumps({
  804. "value": form.cleaned_data["value"]
  805. })
  806. channel.save()
  807. channel.assign_all_checks()
  808. return redirect("hc-channels")
  809. else:
  810. form = AddSmsForm()
  811. ctx = {
  812. "page": "channels",
  813. "form": form,
  814. "profile": request.team
  815. }
  816. return render(request, "integrations/add_sms.html", ctx)
  817. @login_required
  818. def add_trello(request):
  819. if settings.TRELLO_APP_KEY is None:
  820. raise Http404("trello integration is not available")
  821. if request.method == "POST":
  822. channel = Channel(user=request.team.user, kind="trello")
  823. channel.value = request.POST["settings"]
  824. channel.save()
  825. channel.assign_all_checks()
  826. return redirect("hc-channels")
  827. authorize_url = "https://trello.com/1/authorize?" + urlencode({
  828. "expiration": "never",
  829. "name": settings.SITE_NAME,
  830. "scope": "read,write",
  831. "response_type": "token",
  832. "key": settings.TRELLO_APP_KEY,
  833. "return_url": settings.SITE_ROOT + reverse("hc-add-trello")
  834. })
  835. ctx = {
  836. "page": "channels",
  837. "authorize_url": authorize_url
  838. }
  839. return render(request, "integrations/add_trello.html", ctx)
  840. @login_required
  841. @require_POST
  842. def trello_settings(request):
  843. token = request.POST.get("token")
  844. url = "https://api.trello.com/1/members/me/boards?" + urlencode({
  845. "key": settings.TRELLO_APP_KEY,
  846. "token": token,
  847. "fields": "id,name",
  848. "lists": "open",
  849. "list_fields": "id,name"
  850. })
  851. r = requests.get(url)
  852. ctx = {
  853. "token": token,
  854. "data": r.json()
  855. }
  856. return render(request, "integrations/trello_settings.html", ctx)