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.

89 lines
2.5 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
  1. import json
  2. from django.contrib.humanize.templatetags.humanize import naturaltime
  3. from django.http import HttpResponse, HttpResponseBadRequest
  4. from django.utils import timezone
  5. from django.views.decorators.csrf import csrf_exempt
  6. from hc.api.decorators import uuid_or_400
  7. from hc.api.models import Check, Ping
  8. @csrf_exempt
  9. @uuid_or_400
  10. def ping(request, code):
  11. try:
  12. check = Check.objects.get(code=code)
  13. except Check.DoesNotExist:
  14. return HttpResponseBadRequest()
  15. check.last_ping = timezone.now()
  16. if check.status == "new":
  17. check.status = "up"
  18. check.save()
  19. ping = Ping(owner=check)
  20. headers = request.META
  21. ping.remote_addr = headers.get("HTTP_X_REAL_IP", headers["REMOTE_ADDR"])
  22. ping.scheme = headers.get("HTTP_X_SCHEME", "http")
  23. ping.method = headers["REQUEST_METHOD"]
  24. # If User-Agent is longer than 200 characters, truncate it:
  25. ping.ua = headers.get("HTTP_USER_AGENT", "")[:200]
  26. ping.body = request.body
  27. ping.save()
  28. response = HttpResponse("OK")
  29. response["Access-Control-Allow-Origin"] = "*"
  30. return response
  31. @csrf_exempt
  32. def handle_email(request):
  33. if request.method != "POST":
  34. return HttpResponseBadRequest()
  35. events = json.loads(request.POST["mandrill_events"])
  36. for event in events:
  37. for recipient_address, recipient_name in event["msg"]["to"]:
  38. code, domain = recipient_address.split("@")
  39. try:
  40. check = Check.objects.get(code=code)
  41. except ValueError:
  42. continue
  43. except Check.DoesNotExist:
  44. continue
  45. check.last_ping = timezone.now()
  46. if check.status == "new":
  47. check.status = "up"
  48. check.save()
  49. ping = Ping(owner=check)
  50. ping.scheme = "email"
  51. ping.body = event["msg"]["raw_msg"]
  52. ping.save()
  53. response = HttpResponse("OK")
  54. return response
  55. @uuid_or_400
  56. def status(request, code):
  57. response = {
  58. "last_ping": None,
  59. "last_ping_human": None,
  60. "secs_to_alert": None
  61. }
  62. check = Check.objects.get(code=code)
  63. if check.last_ping and check.alert_after:
  64. response["last_ping"] = check.last_ping.isoformat()
  65. response["last_ping_human"] = naturaltime(check.last_ping)
  66. duration = check.alert_after - timezone.now()
  67. response["secs_to_alert"] = int(duration.total_seconds())
  68. return HttpResponse(json.dumps(response),
  69. content_type="application/javascript")