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.

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