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.

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