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.

1112 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. num_checks = Check.objects.filter(user=request.team.user).count()
  372. ctx = {
  373. "page": "channels",
  374. "profile": request.team,
  375. "channels": channels,
  376. "num_checks": num_checks,
  377. "enable_pushbullet": settings.PUSHBULLET_CLIENT_ID is not None,
  378. "enable_pushover": settings.PUSHOVER_API_TOKEN is not None,
  379. "enable_discord": settings.DISCORD_CLIENT_ID is not None,
  380. "enable_telegram": settings.TELEGRAM_TOKEN is not None,
  381. "enable_sms": settings.TWILIO_AUTH is not None,
  382. "enable_pd": settings.PD_VENDOR_KEY is not None,
  383. "enable_trello": settings.TRELLO_APP_KEY is not None,
  384. "use_payments": settings.USE_PAYMENTS
  385. }
  386. return render(request, "front/channels.html", ctx)
  387. @login_required
  388. def channel_checks(request, code):
  389. channel = get_object_or_404(Channel, code=code)
  390. if channel.user_id != request.team.user.id:
  391. return HttpResponseForbidden()
  392. assigned = set(channel.checks.values_list('code', flat=True).distinct())
  393. checks = Check.objects.filter(user=request.team.user).order_by("created")
  394. ctx = {
  395. "checks": checks,
  396. "assigned": assigned,
  397. "channel": channel
  398. }
  399. return render(request, "front/channel_checks.html", ctx)
  400. @require_POST
  401. @login_required
  402. def update_channel_name(request, code):
  403. channel = get_object_or_404(Channel, code=code)
  404. if channel.user_id != request.team.user.id:
  405. return HttpResponseForbidden()
  406. form = ChannelNameForm(request.POST)
  407. if form.is_valid():
  408. channel.name = form.cleaned_data["name"]
  409. channel.save()
  410. return redirect("hc-channels")
  411. def verify_email(request, code, token):
  412. channel = get_object_or_404(Channel, code=code)
  413. if channel.make_token() == token:
  414. channel.email_verified = True
  415. channel.save()
  416. return render(request, "front/verify_email_success.html")
  417. return render(request, "bad_link.html")
  418. def unsubscribe_email(request, code, token):
  419. channel = get_object_or_404(Channel, code=code)
  420. if channel.make_token() != token:
  421. return render(request, "bad_link.html")
  422. if channel.kind != "email":
  423. return HttpResponseBadRequest()
  424. # Some email servers open links in emails to check for malicious content.
  425. # To work around this, we serve a form that auto-submits with JS.
  426. if "ask" in request.GET and request.method != "POST":
  427. return render(request, "accounts/unsubscribe_submit.html")
  428. channel.delete()
  429. return render(request, "front/unsubscribe_success.html")
  430. @require_POST
  431. @login_required
  432. def remove_channel(request, code):
  433. # user may refresh the page during POST and cause two deletion attempts
  434. channel = Channel.objects.filter(code=code).first()
  435. if channel:
  436. if channel.user != request.team.user:
  437. return HttpResponseForbidden()
  438. channel.delete()
  439. return redirect("hc-channels")
  440. @login_required
  441. def add_email(request):
  442. if request.method == "POST":
  443. form = AddEmailForm(request.POST)
  444. if form.is_valid():
  445. channel = Channel(user=request.team.user, kind="email")
  446. channel.value = form.cleaned_data["value"]
  447. channel.save()
  448. channel.assign_all_checks()
  449. channel.send_verify_link()
  450. return redirect("hc-channels")
  451. else:
  452. form = AddEmailForm()
  453. ctx = {"page": "channels", "form": form}
  454. return render(request, "integrations/add_email.html", ctx)
  455. @login_required
  456. def add_webhook(request):
  457. if request.method == "POST":
  458. form = AddWebhookForm(request.POST)
  459. if form.is_valid():
  460. channel = Channel(user=request.team.user, kind="webhook")
  461. channel.value = form.get_value()
  462. channel.save()
  463. channel.assign_all_checks()
  464. return redirect("hc-channels")
  465. else:
  466. form = AddWebhookForm()
  467. ctx = {
  468. "page": "channels",
  469. "form": form,
  470. "now": timezone.now().replace(microsecond=0).isoformat()
  471. }
  472. return render(request, "integrations/add_webhook.html", ctx)
  473. def _prepare_state(request, session_key):
  474. state = get_random_string()
  475. request.session[session_key] = state
  476. return state
  477. def _get_validated_code(request, session_key, key="code"):
  478. if session_key not in request.session:
  479. return None
  480. session_state = request.session.pop(session_key)
  481. request_state = request.GET.get("state")
  482. if session_state is None or session_state != request_state:
  483. return None
  484. return request.GET.get(key)
  485. def add_pd(request, state=None):
  486. if settings.PD_VENDOR_KEY is None:
  487. raise Http404("pagerduty integration is not available")
  488. if state and request.user.is_authenticated:
  489. if "pd" not in request.session:
  490. return HttpResponseBadRequest()
  491. session_state = request.session.pop("pd")
  492. if session_state != state:
  493. return HttpResponseBadRequest()
  494. if request.GET.get("error") == "cancelled":
  495. messages.warning(request, "PagerDuty setup was cancelled")
  496. return redirect("hc-channels")
  497. channel = Channel()
  498. channel.user = request.team.user
  499. channel.kind = "pd"
  500. channel.value = json.dumps({
  501. "service_key": request.GET.get("service_key"),
  502. "account": request.GET.get("account")
  503. })
  504. channel.save()
  505. channel.assign_all_checks()
  506. messages.success(request, "The PagerDuty integration has been added!")
  507. return redirect("hc-channels")
  508. state = _prepare_state(request, "pd")
  509. callback = settings.SITE_ROOT + reverse("hc-add-pd-state", args=[state])
  510. connect_url = "https://connect.pagerduty.com/connect?" + urlencode({
  511. "vendor": settings.PD_VENDOR_KEY,
  512. "callback": callback
  513. })
  514. ctx = {"page": "channels", "connect_url": connect_url}
  515. return render(request, "integrations/add_pd.html", ctx)
  516. @login_required
  517. def add_pagertree(request):
  518. if request.method == "POST":
  519. form = AddUrlForm(request.POST)
  520. if form.is_valid():
  521. channel = Channel(user=request.team.user, kind="pagertree")
  522. channel.value = form.cleaned_data["value"]
  523. channel.save()
  524. channel.assign_all_checks()
  525. return redirect("hc-channels")
  526. else:
  527. form = AddUrlForm()
  528. ctx = {"page": "channels", "form": form}
  529. return render(request, "integrations/add_pagertree.html", ctx)
  530. def add_slack(request):
  531. if not settings.SLACK_CLIENT_ID and not request.user.is_authenticated:
  532. return redirect("hc-login")
  533. if request.method == "POST":
  534. form = AddUrlForm(request.POST)
  535. if form.is_valid():
  536. channel = Channel(user=request.team.user, kind="slack")
  537. channel.value = form.cleaned_data["value"]
  538. channel.save()
  539. channel.assign_all_checks()
  540. return redirect("hc-channels")
  541. else:
  542. form = AddUrlForm()
  543. ctx = {
  544. "page": "channels",
  545. "form": form,
  546. "slack_client_id": settings.SLACK_CLIENT_ID
  547. }
  548. if settings.SLACK_CLIENT_ID and request.user.is_authenticated:
  549. ctx["state"] = _prepare_state(request, "slack")
  550. return render(request, "integrations/add_slack.html", ctx)
  551. @login_required
  552. def add_slack_btn(request):
  553. code = _get_validated_code(request, "slack")
  554. if code is None:
  555. return HttpResponseBadRequest()
  556. result = requests.post("https://slack.com/api/oauth.access", {
  557. "client_id": settings.SLACK_CLIENT_ID,
  558. "client_secret": settings.SLACK_CLIENT_SECRET,
  559. "code": code
  560. })
  561. doc = result.json()
  562. if doc.get("ok"):
  563. channel = Channel()
  564. channel.user = request.team.user
  565. channel.kind = "slack"
  566. channel.value = result.text
  567. channel.save()
  568. channel.assign_all_checks()
  569. messages.success(request, "The Slack integration has been added!")
  570. else:
  571. s = doc.get("error")
  572. messages.warning(request, "Error message from slack: %s" % s)
  573. return redirect("hc-channels")
  574. @login_required
  575. def add_hipchat(request):
  576. if "installable_url" in request.GET:
  577. url = request.GET["installable_url"]
  578. assert url.startswith("https://api.hipchat.com")
  579. response = requests.get(url)
  580. if "oauthId" not in response.json():
  581. messages.warning(request, "Something went wrong!")
  582. return redirect("hc-channels")
  583. channel = Channel(kind="hipchat")
  584. channel.user = request.team.user
  585. channel.value = response.text
  586. channel.save()
  587. channel.refresh_hipchat_access_token()
  588. channel.assign_all_checks()
  589. messages.success(request, "The HipChat integration has been added!")
  590. return redirect("hc-channels")
  591. install_url = "https://www.hipchat.com/addons/install?" + urlencode({
  592. "url": settings.SITE_ROOT + reverse("hc-hipchat-capabilities")
  593. })
  594. ctx = {
  595. "page": "channels",
  596. "install_url": install_url
  597. }
  598. return render(request, "integrations/add_hipchat.html", ctx)
  599. def hipchat_capabilities(request):
  600. return render(request, "integrations/hipchat_capabilities.json", {},
  601. content_type="application/json")
  602. @login_required
  603. def add_pushbullet(request):
  604. if settings.PUSHBULLET_CLIENT_ID is None:
  605. raise Http404("pushbullet integration is not available")
  606. if "code" in request.GET:
  607. code = _get_validated_code(request, "pushbullet")
  608. if code is None:
  609. return HttpResponseBadRequest()
  610. result = requests.post("https://api.pushbullet.com/oauth2/token", {
  611. "client_id": settings.PUSHBULLET_CLIENT_ID,
  612. "client_secret": settings.PUSHBULLET_CLIENT_SECRET,
  613. "code": code,
  614. "grant_type": "authorization_code"
  615. })
  616. doc = result.json()
  617. if "access_token" in doc:
  618. channel = Channel(kind="pushbullet")
  619. channel.user = request.team.user
  620. channel.value = doc["access_token"]
  621. channel.save()
  622. channel.assign_all_checks()
  623. messages.success(request,
  624. "The Pushbullet integration has been added!")
  625. else:
  626. messages.warning(request, "Something went wrong")
  627. return redirect("hc-channels")
  628. redirect_uri = settings.SITE_ROOT + reverse("hc-add-pushbullet")
  629. authorize_url = "https://www.pushbullet.com/authorize?" + urlencode({
  630. "client_id": settings.PUSHBULLET_CLIENT_ID,
  631. "redirect_uri": redirect_uri,
  632. "response_type": "code",
  633. "state": _prepare_state(request, "pushbullet")
  634. })
  635. ctx = {
  636. "page": "channels",
  637. "authorize_url": authorize_url
  638. }
  639. return render(request, "integrations/add_pushbullet.html", ctx)
  640. @login_required
  641. def add_discord(request):
  642. if settings.DISCORD_CLIENT_ID is None:
  643. raise Http404("discord integration is not available")
  644. redirect_uri = settings.SITE_ROOT + reverse("hc-add-discord")
  645. if "code" in request.GET:
  646. code = _get_validated_code(request, "discord")
  647. if code is None:
  648. return HttpResponseBadRequest()
  649. result = requests.post("https://discordapp.com/api/oauth2/token", {
  650. "client_id": settings.DISCORD_CLIENT_ID,
  651. "client_secret": settings.DISCORD_CLIENT_SECRET,
  652. "code": code,
  653. "grant_type": "authorization_code",
  654. "redirect_uri": redirect_uri
  655. })
  656. doc = result.json()
  657. if "access_token" in doc:
  658. channel = Channel(kind="discord")
  659. channel.user = request.team.user
  660. channel.value = result.text
  661. channel.save()
  662. channel.assign_all_checks()
  663. messages.success(request,
  664. "The Discord integration has been added!")
  665. else:
  666. messages.warning(request, "Something went wrong")
  667. return redirect("hc-channels")
  668. auth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode({
  669. "client_id": settings.DISCORD_CLIENT_ID,
  670. "scope": "webhook.incoming",
  671. "redirect_uri": redirect_uri,
  672. "response_type": "code",
  673. "state": _prepare_state(request, "discord")
  674. })
  675. ctx = {
  676. "page": "channels",
  677. "authorize_url": auth_url
  678. }
  679. return render(request, "integrations/add_discord.html", ctx)
  680. def add_pushover(request):
  681. if settings.PUSHOVER_API_TOKEN is None or settings.PUSHOVER_SUBSCRIPTION_URL is None:
  682. raise Http404("pushover integration is not available")
  683. if not request.user.is_authenticated:
  684. ctx = {"page": "channels"}
  685. return render(request, "integrations/add_pushover.html", ctx)
  686. if request.method == "POST":
  687. # Initiate the subscription
  688. state = _prepare_state(request, "pushover")
  689. failure_url = settings.SITE_ROOT + reverse("hc-channels")
  690. success_url = settings.SITE_ROOT + reverse("hc-add-pushover") + "?" + urlencode({
  691. "state": state,
  692. "prio": request.POST.get("po_priority", "0"),
  693. "prio_up": request.POST.get("po_priority_up", "0")
  694. })
  695. subscription_url = settings.PUSHOVER_SUBSCRIPTION_URL + "?" + urlencode({
  696. "success": success_url,
  697. "failure": failure_url,
  698. })
  699. return redirect(subscription_url)
  700. # Handle successful subscriptions
  701. if "pushover_user_key" in request.GET:
  702. key = _get_validated_code(request, "pushover", "pushover_user_key")
  703. if key is None:
  704. return HttpResponseBadRequest()
  705. # Validate priority
  706. prio = request.GET.get("prio")
  707. if prio not in ("-2", "-1", "0", "1", "2"):
  708. return HttpResponseBadRequest()
  709. prio_up = request.GET.get("prio_up")
  710. if prio_up not in ("-2", "-1", "0", "1", "2"):
  711. return HttpResponseBadRequest()
  712. if request.GET.get("pushover_unsubscribed") == "1":
  713. # Unsubscription: delete all Pushover channels for this user
  714. Channel.objects.filter(user=request.user, kind="po").delete()
  715. return redirect("hc-channels")
  716. # Subscription
  717. channel = Channel(user=request.team.user, kind="po")
  718. channel.value = "%s|%s|%s" % (key, prio, prio_up)
  719. channel.save()
  720. channel.assign_all_checks()
  721. messages.success(request, "The Pushover integration has been added!")
  722. return redirect("hc-channels")
  723. # Show Integration Settings form
  724. ctx = {
  725. "page": "channels",
  726. "po_retry_delay": td(seconds=settings.PUSHOVER_EMERGENCY_RETRY_DELAY),
  727. "po_expiration": td(seconds=settings.PUSHOVER_EMERGENCY_EXPIRATION),
  728. }
  729. return render(request, "integrations/add_pushover.html", ctx)
  730. @login_required
  731. def add_opsgenie(request):
  732. if request.method == "POST":
  733. form = AddOpsGenieForm(request.POST)
  734. if form.is_valid():
  735. channel = Channel(user=request.team.user, kind="opsgenie")
  736. channel.value = form.cleaned_data["value"]
  737. channel.save()
  738. channel.assign_all_checks()
  739. return redirect("hc-channels")
  740. else:
  741. form = AddUrlForm()
  742. ctx = {"page": "channels", "form": form}
  743. return render(request, "integrations/add_opsgenie.html", ctx)
  744. @login_required
  745. def add_victorops(request):
  746. if request.method == "POST":
  747. form = AddUrlForm(request.POST)
  748. if form.is_valid():
  749. channel = Channel(user=request.team.user, kind="victorops")
  750. channel.value = form.cleaned_data["value"]
  751. channel.save()
  752. channel.assign_all_checks()
  753. return redirect("hc-channels")
  754. else:
  755. form = AddUrlForm()
  756. ctx = {"page": "channels", "form": form}
  757. return render(request, "integrations/add_victorops.html", ctx)
  758. @csrf_exempt
  759. @require_POST
  760. def telegram_bot(request):
  761. try:
  762. doc = json.loads(request.body.decode())
  763. jsonschema.validate(doc, telegram_callback)
  764. except ValueError:
  765. return HttpResponseBadRequest()
  766. except jsonschema.ValidationError:
  767. # We don't recognize the message format, but don't want Telegram
  768. # retrying this over and over again, so respond with 200 OK
  769. return HttpResponse()
  770. if "/start" not in doc["message"]["text"]:
  771. return HttpResponse()
  772. chat = doc["message"]["chat"]
  773. name = max(chat.get("title", ""), chat.get("username", ""))
  774. invite = render_to_string("integrations/telegram_invite.html", {
  775. "qs": signing.dumps((chat["id"], chat["type"], name))
  776. })
  777. Telegram.send(chat["id"], invite)
  778. return HttpResponse()
  779. @login_required
  780. def add_telegram(request):
  781. chat_id, chat_type, chat_name = None, None, None
  782. qs = request.META["QUERY_STRING"]
  783. if qs:
  784. chat_id, chat_type, chat_name = signing.loads(qs, max_age=600)
  785. if request.method == "POST":
  786. channel = Channel(user=request.team.user, kind="telegram")
  787. channel.value = json.dumps({
  788. "id": chat_id,
  789. "type": chat_type,
  790. "name": chat_name
  791. })
  792. channel.save()
  793. channel.assign_all_checks()
  794. messages.success(request, "The Telegram integration has been added!")
  795. return redirect("hc-channels")
  796. ctx = {
  797. "chat_id": chat_id,
  798. "chat_type": chat_type,
  799. "chat_name": chat_name,
  800. "bot_name": settings.TELEGRAM_BOT_NAME
  801. }
  802. return render(request, "integrations/add_telegram.html", ctx)
  803. @login_required
  804. def add_sms(request):
  805. if settings.TWILIO_AUTH is None:
  806. raise Http404("sms integration is not available")
  807. if request.method == "POST":
  808. form = AddSmsForm(request.POST)
  809. if form.is_valid():
  810. channel = Channel(user=request.team.user, kind="sms")
  811. channel.name = form.cleaned_data["label"]
  812. channel.value = json.dumps({
  813. "value": form.cleaned_data["value"]
  814. })
  815. channel.save()
  816. channel.assign_all_checks()
  817. return redirect("hc-channels")
  818. else:
  819. form = AddSmsForm()
  820. ctx = {
  821. "page": "channels",
  822. "form": form,
  823. "profile": request.team
  824. }
  825. return render(request, "integrations/add_sms.html", ctx)
  826. @login_required
  827. def add_trello(request):
  828. if settings.TRELLO_APP_KEY is None:
  829. raise Http404("trello integration is not available")
  830. if request.method == "POST":
  831. channel = Channel(user=request.team.user, kind="trello")
  832. channel.value = request.POST["settings"]
  833. channel.save()
  834. channel.assign_all_checks()
  835. return redirect("hc-channels")
  836. authorize_url = "https://trello.com/1/authorize?" + urlencode({
  837. "expiration": "never",
  838. "name": settings.SITE_NAME,
  839. "scope": "read,write",
  840. "response_type": "token",
  841. "key": settings.TRELLO_APP_KEY,
  842. "return_url": settings.SITE_ROOT + reverse("hc-add-trello")
  843. })
  844. ctx = {
  845. "page": "channels",
  846. "authorize_url": authorize_url
  847. }
  848. return render(request, "integrations/add_trello.html", ctx)
  849. @login_required
  850. @require_POST
  851. def trello_settings(request):
  852. token = request.POST.get("token")
  853. url = "https://api.trello.com/1/members/me/boards?" + urlencode({
  854. "key": settings.TRELLO_APP_KEY,
  855. "token": token,
  856. "fields": "id,name",
  857. "lists": "open",
  858. "list_fields": "id,name"
  859. })
  860. r = requests.get(url)
  861. ctx = {
  862. "token": token,
  863. "data": r.json()
  864. }
  865. return render(request, "integrations/trello_settings.html", ctx)