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.

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