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.

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