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.

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