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.

819 lines
24 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
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 collections import Counter
  2. from datetime import datetime, timedelta as td
  3. from itertools import tee
  4. import json
  5. from croniter import croniter
  6. from django.conf import settings
  7. from django.contrib import messages
  8. from django.contrib.auth.decorators import login_required
  9. from django.core import signing
  10. from django.db.models import Count
  11. from django.http import (Http404, HttpResponse, HttpResponseBadRequest,
  12. HttpResponseForbidden)
  13. from django.shortcuts import get_object_or_404, redirect, render
  14. from django.template.loader import render_to_string
  15. from django.urls import reverse
  16. from django.utils import timezone
  17. from django.utils.crypto import get_random_string
  18. from django.utils.six.moves.urllib.parse import urlencode
  19. from django.views.decorators.csrf import csrf_exempt
  20. from django.views.decorators.http import require_POST
  21. from hc.api.decorators import uuid_or_400
  22. from hc.api.models import (DEFAULT_GRACE, DEFAULT_TIMEOUT, Channel, Check,
  23. Ping, Notification)
  24. from hc.api.transports import Telegram
  25. from hc.front.forms import (AddWebhookForm, NameTagsForm,
  26. TimeoutForm, AddUrlForm, AddPdForm, AddEmailForm,
  27. AddOpsGenieForm, CronForm)
  28. from hc.front.schemas import telegram_callback
  29. from hc.lib import jsonschema
  30. from pytz import all_timezones
  31. from pytz.exceptions import UnknownTimeZoneError
  32. import requests
  33. # from itertools recipes:
  34. def pairwise(iterable):
  35. "s -> (s0,s1), (s1,s2), (s2, s3), ..."
  36. a, b = tee(iterable)
  37. next(b, None)
  38. return zip(a, b)
  39. @login_required
  40. def my_checks(request):
  41. q = Check.objects.filter(user=request.team.user).order_by("created")
  42. checks = list(q)
  43. counter = Counter()
  44. down_tags, grace_tags = set(), set()
  45. for check in checks:
  46. status = check.get_status()
  47. for tag in check.tags_list():
  48. if tag == "":
  49. continue
  50. counter[tag] += 1
  51. if status == "down":
  52. down_tags.add(tag)
  53. elif check.in_grace_period():
  54. grace_tags.add(tag)
  55. can_add_more = len(checks) < request.team.check_limit
  56. ctx = {
  57. "page": "checks",
  58. "checks": checks,
  59. "now": timezone.now(),
  60. "tags": counter.most_common(),
  61. "down_tags": down_tags,
  62. "grace_tags": grace_tags,
  63. "ping_endpoint": settings.PING_ENDPOINT,
  64. "timezones": all_timezones,
  65. "can_add_more": can_add_more
  66. }
  67. return render(request, "front/my_checks.html", ctx)
  68. def _welcome_check(request):
  69. check = None
  70. if "welcome_code" in request.session:
  71. code = request.session["welcome_code"]
  72. check = Check.objects.filter(code=code).first()
  73. if check is None:
  74. check = Check()
  75. check.save()
  76. request.session["welcome_code"] = str(check.code)
  77. return check
  78. def index(request):
  79. if request.user.is_authenticated:
  80. return redirect("hc-checks")
  81. check = _welcome_check(request)
  82. ctx = {
  83. "page": "welcome",
  84. "check": check,
  85. "ping_url": check.url(),
  86. "enable_pushbullet": settings.PUSHBULLET_CLIENT_ID is not None,
  87. "enable_pushover": settings.PUSHOVER_API_TOKEN is not None,
  88. "enable_discord": settings.DISCORD_CLIENT_ID is not None,
  89. "enable_telegram": settings.TELEGRAM_TOKEN is not None,
  90. "registration_open": settings.REGISTRATION_OPEN
  91. }
  92. return render(request, "front/welcome.html", ctx)
  93. def docs(request):
  94. check = _welcome_check(request)
  95. ctx = {
  96. "page": "docs",
  97. "section": "home",
  98. "ping_endpoint": settings.PING_ENDPOINT,
  99. "check": check,
  100. "ping_url": check.url()
  101. }
  102. return render(request, "front/docs.html", ctx)
  103. def docs_api(request):
  104. ctx = {
  105. "page": "docs",
  106. "section": "api",
  107. "SITE_ROOT": settings.SITE_ROOT,
  108. "PING_ENDPOINT": settings.PING_ENDPOINT,
  109. "default_timeout": int(DEFAULT_TIMEOUT.total_seconds()),
  110. "default_grace": int(DEFAULT_GRACE.total_seconds())
  111. }
  112. return render(request, "front/docs_api.html", ctx)
  113. def about(request):
  114. return render(request, "front/about.html", {"page": "about"})
  115. @require_POST
  116. @login_required
  117. def add_check(request):
  118. num_checks = Check.objects.filter(user=request.team.user).count()
  119. if num_checks >= request.team.check_limit:
  120. return HttpResponseBadRequest()
  121. check = Check(user=request.team.user)
  122. check.save()
  123. check.assign_all_channels()
  124. return redirect("hc-checks")
  125. @require_POST
  126. @login_required
  127. @uuid_or_400
  128. def update_name(request, code):
  129. check = get_object_or_404(Check, code=code)
  130. if check.user_id != request.team.user.id:
  131. return HttpResponseForbidden()
  132. form = NameTagsForm(request.POST)
  133. if form.is_valid():
  134. check.name = form.cleaned_data["name"]
  135. check.tags = form.cleaned_data["tags"]
  136. check.save()
  137. return redirect("hc-checks")
  138. @require_POST
  139. @login_required
  140. @uuid_or_400
  141. def update_timeout(request, code):
  142. check = get_object_or_404(Check, code=code)
  143. if check.user != request.team.user:
  144. return HttpResponseForbidden()
  145. kind = request.POST.get("kind")
  146. if kind == "simple":
  147. form = TimeoutForm(request.POST)
  148. if not form.is_valid():
  149. return HttpResponseBadRequest()
  150. check.kind = "simple"
  151. check.timeout = td(seconds=form.cleaned_data["timeout"])
  152. check.grace = td(seconds=form.cleaned_data["grace"])
  153. elif kind == "cron":
  154. form = CronForm(request.POST)
  155. if not form.is_valid():
  156. return HttpResponseBadRequest()
  157. check.kind = "cron"
  158. check.schedule = form.cleaned_data["schedule"]
  159. check.tz = form.cleaned_data["tz"]
  160. check.grace = td(minutes=form.cleaned_data["grace"])
  161. if check.last_ping:
  162. check.alert_after = check.get_alert_after()
  163. check.save()
  164. return redirect("hc-checks")
  165. @require_POST
  166. def cron_preview(request):
  167. schedule = request.POST.get("schedule")
  168. tz = request.POST.get("tz")
  169. ctx = {"tz": tz, "dates": []}
  170. try:
  171. with timezone.override(tz):
  172. now_naive = timezone.make_naive(timezone.now())
  173. it = croniter(schedule, now_naive)
  174. for i in range(0, 6):
  175. naive = it.get_next(datetime)
  176. aware = timezone.make_aware(naive)
  177. ctx["dates"].append((naive, aware))
  178. except UnknownTimeZoneError:
  179. ctx["bad_tz"] = True
  180. except:
  181. ctx["bad_schedule"] = True
  182. return render(request, "front/cron_preview.html", ctx)
  183. @require_POST
  184. def last_ping(request, code):
  185. if not request.user.is_authenticated:
  186. return HttpResponseForbidden()
  187. check = get_object_or_404(Check, code=code)
  188. if check.user_id != request.team.user.id:
  189. return HttpResponseForbidden()
  190. ping = Ping.objects.filter(owner=check).latest("created")
  191. ctx = {
  192. "check": check,
  193. "ping": ping
  194. }
  195. return render(request, "front/last_ping.html", ctx)
  196. @require_POST
  197. @login_required
  198. @uuid_or_400
  199. def pause(request, code):
  200. check = get_object_or_404(Check, code=code)
  201. if check.user_id != request.team.user.id:
  202. return HttpResponseForbidden()
  203. check.status = "paused"
  204. check.save()
  205. return redirect("hc-checks")
  206. @require_POST
  207. @login_required
  208. @uuid_or_400
  209. def remove_check(request, code):
  210. check = get_object_or_404(Check, code=code)
  211. if check.user != request.team.user:
  212. return HttpResponseForbidden()
  213. check.delete()
  214. return redirect("hc-checks")
  215. @login_required
  216. @uuid_or_400
  217. def log(request, code):
  218. check = get_object_or_404(Check, code=code)
  219. if check.user != request.team.user:
  220. return HttpResponseForbidden()
  221. limit = request.team.ping_log_limit
  222. pings = Ping.objects.filter(owner=check).order_by("-id")[:limit + 1]
  223. pings = list(pings)
  224. num_pings = len(pings)
  225. pings = pings[:limit]
  226. alerts = []
  227. if len(pings):
  228. cutoff = pings[-1].created
  229. alerts = Notification.objects \
  230. .select_related("channel") \
  231. .filter(owner=check, check_status="down", created__gt=cutoff)
  232. events = pings + list(alerts)
  233. events.sort(key=lambda el: el.created, reverse=True)
  234. ctx = {
  235. "check": check,
  236. "events": events,
  237. "num_pings": min(num_pings, limit),
  238. "limit": limit,
  239. "show_limit_notice": num_pings > limit and settings.USE_PAYMENTS
  240. }
  241. return render(request, "front/log.html", ctx)
  242. @login_required
  243. def channels(request):
  244. if request.method == "POST":
  245. code = request.POST["channel"]
  246. try:
  247. channel = Channel.objects.get(code=code)
  248. except Channel.DoesNotExist:
  249. return HttpResponseBadRequest()
  250. if channel.user_id != request.team.user.id:
  251. return HttpResponseForbidden()
  252. new_checks = []
  253. for key in request.POST:
  254. if key.startswith("check-"):
  255. code = key[6:]
  256. try:
  257. check = Check.objects.get(code=code)
  258. except Check.DoesNotExist:
  259. return HttpResponseBadRequest()
  260. if check.user_id != request.team.user.id:
  261. return HttpResponseForbidden()
  262. new_checks.append(check)
  263. channel.checks = new_checks
  264. return redirect("hc-channels")
  265. channels = Channel.objects.filter(user=request.team.user)
  266. channels = channels.order_by("created")
  267. channels = channels.annotate(n_checks=Count("checks"))
  268. num_checks = Check.objects.filter(user=request.team.user).count()
  269. ctx = {
  270. "page": "channels",
  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. }
  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. @login_required
  355. def add_pd(request):
  356. if request.method == "POST":
  357. form = AddPdForm(request.POST)
  358. if form.is_valid():
  359. channel = Channel(user=request.team.user, kind="pd")
  360. channel.value = form.cleaned_data["value"]
  361. channel.save()
  362. channel.assign_all_checks()
  363. return redirect("hc-channels")
  364. else:
  365. form = AddPdForm()
  366. ctx = {"page": "channels", "form": form}
  367. return render(request, "integrations/add_pd.html", ctx)
  368. def _prepare_state(request, session_key):
  369. state = get_random_string()
  370. request.session[session_key] = state
  371. return state
  372. def _get_validated_code(request, session_key):
  373. if session_key not in request.session:
  374. return None
  375. session_state = request.session.pop(session_key)
  376. request_state = request.GET.get("state")
  377. if session_state is None or session_state != request_state:
  378. return None
  379. return request.GET.get("code")
  380. def add_slack(request):
  381. if not settings.SLACK_CLIENT_ID and not request.user.is_authenticated:
  382. return redirect("hc-login")
  383. if request.method == "POST":
  384. form = AddUrlForm(request.POST)
  385. if form.is_valid():
  386. channel = Channel(user=request.team.user, kind="slack")
  387. channel.value = form.cleaned_data["value"]
  388. channel.save()
  389. channel.assign_all_checks()
  390. return redirect("hc-channels")
  391. else:
  392. form = AddUrlForm()
  393. ctx = {
  394. "page": "channels",
  395. "form": form,
  396. "slack_client_id": settings.SLACK_CLIENT_ID
  397. }
  398. if settings.SLACK_CLIENT_ID:
  399. ctx["state"] = _prepare_state(request, "slack")
  400. return render(request, "integrations/add_slack.html", ctx)
  401. @login_required
  402. def add_slack_btn(request):
  403. code = _get_validated_code(request, "slack")
  404. if code is None:
  405. return HttpResponseBadRequest()
  406. result = requests.post("https://slack.com/api/oauth.access", {
  407. "client_id": settings.SLACK_CLIENT_ID,
  408. "client_secret": settings.SLACK_CLIENT_SECRET,
  409. "code": code
  410. })
  411. doc = result.json()
  412. if doc.get("ok"):
  413. channel = Channel()
  414. channel.user = request.team.user
  415. channel.kind = "slack"
  416. channel.value = result.text
  417. channel.save()
  418. channel.assign_all_checks()
  419. messages.success(request, "The Slack integration has been added!")
  420. else:
  421. s = doc.get("error")
  422. messages.warning(request, "Error message from slack: %s" % s)
  423. return redirect("hc-channels")
  424. @login_required
  425. def add_hipchat(request):
  426. if request.method == "POST":
  427. form = AddUrlForm(request.POST)
  428. if form.is_valid():
  429. channel = Channel(user=request.team.user, kind="hipchat")
  430. channel.value = form.cleaned_data["value"]
  431. channel.save()
  432. channel.assign_all_checks()
  433. return redirect("hc-channels")
  434. else:
  435. form = AddUrlForm()
  436. ctx = {"page": "channels", "form": form}
  437. return render(request, "integrations/add_hipchat.html", ctx)
  438. @login_required
  439. def add_pushbullet(request):
  440. if settings.PUSHBULLET_CLIENT_ID is None:
  441. raise Http404("pushbullet integration is not available")
  442. if "code" in request.GET:
  443. code = _get_validated_code(request, "pushbullet")
  444. if code is None:
  445. return HttpResponseBadRequest()
  446. result = requests.post("https://api.pushbullet.com/oauth2/token", {
  447. "client_id": settings.PUSHBULLET_CLIENT_ID,
  448. "client_secret": settings.PUSHBULLET_CLIENT_SECRET,
  449. "code": code,
  450. "grant_type": "authorization_code"
  451. })
  452. doc = result.json()
  453. if "access_token" in doc:
  454. channel = Channel(kind="pushbullet")
  455. channel.user = request.team.user
  456. channel.value = doc["access_token"]
  457. channel.save()
  458. channel.assign_all_checks()
  459. messages.success(request,
  460. "The Pushbullet integration has been added!")
  461. else:
  462. messages.warning(request, "Something went wrong")
  463. return redirect("hc-channels")
  464. redirect_uri = settings.SITE_ROOT + reverse("hc-add-pushbullet")
  465. authorize_url = "https://www.pushbullet.com/authorize?" + urlencode({
  466. "client_id": settings.PUSHBULLET_CLIENT_ID,
  467. "redirect_uri": redirect_uri,
  468. "response_type": "code",
  469. "state": _prepare_state(request, "pushbullet")
  470. })
  471. ctx = {
  472. "page": "channels",
  473. "authorize_url": authorize_url
  474. }
  475. return render(request, "integrations/add_pushbullet.html", ctx)
  476. @login_required
  477. def add_discord(request):
  478. if settings.DISCORD_CLIENT_ID is None:
  479. raise Http404("discord integration is not available")
  480. redirect_uri = settings.SITE_ROOT + reverse("hc-add-discord")
  481. if "code" in request.GET:
  482. code = _get_validated_code(request, "discord")
  483. if code is None:
  484. return HttpResponseBadRequest()
  485. result = requests.post("https://discordapp.com/api/oauth2/token", {
  486. "client_id": settings.DISCORD_CLIENT_ID,
  487. "client_secret": settings.DISCORD_CLIENT_SECRET,
  488. "code": code,
  489. "grant_type": "authorization_code",
  490. "redirect_uri": redirect_uri
  491. })
  492. doc = result.json()
  493. if "access_token" in doc:
  494. channel = Channel(kind="discord")
  495. channel.user = request.team.user
  496. channel.value = result.text
  497. channel.save()
  498. channel.assign_all_checks()
  499. messages.success(request,
  500. "The Discord integration has been added!")
  501. else:
  502. messages.warning(request, "Something went wrong")
  503. return redirect("hc-channels")
  504. auth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode({
  505. "client_id": settings.DISCORD_CLIENT_ID,
  506. "scope": "webhook.incoming",
  507. "redirect_uri": redirect_uri,
  508. "response_type": "code",
  509. "state": _prepare_state(request, "discord")
  510. })
  511. ctx = {
  512. "page": "channels",
  513. "authorize_url": auth_url
  514. }
  515. return render(request, "integrations/add_discord.html", ctx)
  516. @login_required
  517. def add_pushover(request):
  518. if settings.PUSHOVER_API_TOKEN is None or settings.PUSHOVER_SUBSCRIPTION_URL is None:
  519. raise Http404("pushover integration is not available")
  520. if request.method == "POST":
  521. # Initiate the subscription
  522. nonce = get_random_string()
  523. request.session["po_nonce"] = nonce
  524. failure_url = settings.SITE_ROOT + reverse("hc-channels")
  525. success_url = settings.SITE_ROOT + reverse("hc-add-pushover") + "?" + urlencode({
  526. "nonce": nonce,
  527. "prio": request.POST.get("po_priority", "0"),
  528. })
  529. subscription_url = settings.PUSHOVER_SUBSCRIPTION_URL + "?" + urlencode({
  530. "success": success_url,
  531. "failure": failure_url,
  532. })
  533. return redirect(subscription_url)
  534. # Handle successful subscriptions
  535. if "pushover_user_key" in request.GET:
  536. if "nonce" not in request.GET or "prio" not in request.GET:
  537. return HttpResponseBadRequest()
  538. # Validate nonce
  539. if request.GET["nonce"] != request.session.get("po_nonce"):
  540. return HttpResponseForbidden()
  541. # Validate priority
  542. if request.GET["prio"] not in ("-2", "-1", "0", "1", "2"):
  543. return HttpResponseBadRequest()
  544. # All looks well--
  545. del request.session["po_nonce"]
  546. if request.GET.get("pushover_unsubscribed") == "1":
  547. # Unsubscription: delete all Pushover channels for this user
  548. Channel.objects.filter(user=request.user, kind="po").delete()
  549. return redirect("hc-channels")
  550. else:
  551. # Subscription
  552. user_key = request.GET["pushover_user_key"]
  553. priority = int(request.GET["prio"])
  554. channel = Channel(user=request.team.user, kind="po")
  555. channel.value = "%s|%d" % (user_key, priority)
  556. channel.save()
  557. channel.assign_all_checks()
  558. return redirect("hc-channels")
  559. # Show Integration Settings form
  560. ctx = {
  561. "page": "channels",
  562. "po_retry_delay": td(seconds=settings.PUSHOVER_EMERGENCY_RETRY_DELAY),
  563. "po_expiration": td(seconds=settings.PUSHOVER_EMERGENCY_EXPIRATION),
  564. }
  565. return render(request, "integrations/add_pushover.html", ctx)
  566. @login_required
  567. def add_opsgenie(request):
  568. if request.method == "POST":
  569. form = AddOpsGenieForm(request.POST)
  570. if form.is_valid():
  571. channel = Channel(user=request.team.user, kind="opsgenie")
  572. channel.value = form.cleaned_data["value"]
  573. channel.save()
  574. channel.assign_all_checks()
  575. return redirect("hc-channels")
  576. else:
  577. form = AddUrlForm()
  578. ctx = {"page": "channels", "form": form}
  579. return render(request, "integrations/add_opsgenie.html", ctx)
  580. @login_required
  581. def add_victorops(request):
  582. if request.method == "POST":
  583. form = AddUrlForm(request.POST)
  584. if form.is_valid():
  585. channel = Channel(user=request.team.user, kind="victorops")
  586. channel.value = form.cleaned_data["value"]
  587. channel.save()
  588. channel.assign_all_checks()
  589. return redirect("hc-channels")
  590. else:
  591. form = AddUrlForm()
  592. ctx = {"page": "channels", "form": form}
  593. return render(request, "integrations/add_victorops.html", ctx)
  594. @csrf_exempt
  595. @require_POST
  596. def telegram_bot(request):
  597. try:
  598. doc = json.loads(request.body.decode("utf-8"))
  599. jsonschema.validate(doc, telegram_callback)
  600. except ValueError:
  601. return HttpResponseBadRequest()
  602. except jsonschema.ValidationError:
  603. return HttpResponseBadRequest()
  604. if "/start" not in doc["message"]["text"]:
  605. return HttpResponse()
  606. chat = doc["message"]["chat"]
  607. name = max(chat.get("title", ""), chat.get("username", ""))
  608. invite = render_to_string("integrations/telegram_invite.html", {
  609. "qs": signing.dumps((chat["id"], chat["type"], name))
  610. })
  611. Telegram.send(chat["id"], invite)
  612. return HttpResponse()
  613. @login_required
  614. def add_telegram(request):
  615. chat_id, chat_type, chat_name = None, None, None
  616. qs = request.META["QUERY_STRING"]
  617. if qs:
  618. chat_id, chat_type, chat_name = signing.loads(qs, max_age=600)
  619. if request.method == "POST":
  620. channel = Channel(user=request.team.user, kind="telegram")
  621. channel.value = json.dumps({
  622. "id": chat_id,
  623. "type": chat_type,
  624. "name": chat_name
  625. })
  626. channel.save()
  627. channel.assign_all_checks()
  628. messages.success(request, "The Telegram integration has been added!")
  629. return redirect("hc-channels")
  630. ctx = {
  631. "chat_id": chat_id,
  632. "chat_type": chat_type,
  633. "chat_name": chat_name,
  634. "bot_name": settings.TELEGRAM_BOT_NAME
  635. }
  636. return render(request, "integrations/add_telegram.html", ctx)
  637. def privacy(request):
  638. return render(request, "front/privacy.html", {})
  639. def terms(request):
  640. return render(request, "front/terms.html", {})