expalert/apps/views/monitor.py
2023-12-04 16:09:40 +01:00

79 lines
2.4 KiB
Python

from django.views.generic import View
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from ..models import App
import json
@method_decorator(csrf_exempt, name='dispatch')
class MonitorView(View):
"""A view that returns information about a given app installation
"""
def post(self, request, *args, **kwargs):
"""Return information about a given app installation
Args:
request (HttpRequest): The request
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
JsonResponse: The response
"""
try:
data = json.loads(request.body)
app_id = data["id"]
app = App.objects.get(id=app_id)
return JsonResponse({
"success": True,
"name": app.name,
"owner": app.owner.username,
"last_heartbeat": app.last_heartbeat,
"heartbeat_too_old": app.heartbeat_too_old(),
})
except json.JSONDecodeError:
return JsonResponse({"success": False, "error": "Invalid JSON"})
except KeyError:
return JsonResponse({"success": False, "error": "Missing app installation key"})
except App.DoesNotExist:
return JsonResponse({"success": False, "error": "Invalid app installation key"})
def get(self, request, *args, **kwargs):
"""Return information about a given app installation
Args:
request (HttpRequest): The request
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
JsonResponse: The response
"""
try:
app_id = request.GET["id"]
app = App.objects.get(id=app_id)
return JsonResponse({
"success": True,
"name": app.name,
"owner": app.owner.username,
"last_heartbeat": app.last_heartbeat,
"heartbeat_too_old": app.heartbeat_too_old(),
})
except KeyError:
return JsonResponse({"success": False, "error": "Missing app installation key"})
except App.DoesNotExist:
return JsonResponse({"success": False, "error": "Invalid app installation key"})