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.

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