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.

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