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.

1113 lines
33 KiB

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