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.

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