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.

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