diff --git a/core/lib/serde/__init__.py b/core/lib/serde/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/lib/serde/drakdoo.py b/core/lib/serde/drakdoo.py new file mode 100644 index 0000000..8a1bb1c --- /dev/null +++ b/core/lib/serde/drakdoo.py @@ -0,0 +1,18 @@ +from serde import Model, fields + +class Market(Model): + exchange = fields.Str() + item = fields.Str() + currency = fields.Str() + contract = fields.Str() + +class Timestamp(Model): + sent = fields.DateTime() + trade = fields.DateTime() + +class BaseDrakdoo(Model): + title = fields.Str() + message = fields.Str() + period = fields.Str() + market = fields.Nested(Market) + timestamp = fields.Nested(Timestamp) \ No newline at end of file diff --git a/core/views/hooks.py b/core/views/hooks.py index e7c8e78..aef3d0f 100644 --- a/core/views/hooks.py +++ b/core/views/hooks.py @@ -11,6 +11,11 @@ from rest_framework.views import APIView from core.forms import HookForm from core.models import Callback, Hook +from core.lib.serde import drakdoo +from serde import ValidationError +from util import log + +log = log.get_logger(__name__) def get_hooks(user): hooks = Hook.objects.filter(user=user) @@ -21,19 +26,36 @@ class HookAPI(APIView): parser_classes = [JSONParser] def post(self, request, hook_name): - print("DATA", request.data) + log.debug(f"HookAPI POST: {request.data}") + + # Try loading the JSON + try: + loaded_json = orjson.loads(request.data) + except orjson.JSONDecodeError: + return HttpResponseBadRequest("Invalid JSON") + + # Try validating the JSON + try: + hook_resp = drakdoo.BaseDrakdoo.from_dict(loaded_json) + except ValidationError as e: + log.error(f"HookAPI POST: {e}") + return HttpResponseBadRequest(e) + + # Try getting the hook try: hook = Hook.objects.get(hook=hook_name) except Hook.DoesNotExist: return HttpResponseBadRequest("Hook does not exist.") + + # Create the callback object callback = Callback.objects.create( hook=hook, data=request.data, ) callback.save() + # Bump received count hook.received = hook.received + 1 hook.save() - print("SAVED") return HttpResponse("OK") diff --git a/docker/prod/requirements.prod.txt b/docker/prod/requirements.prod.txt index 0bcdfce..242d4e9 100644 --- a/docker/prod/requirements.prod.txt +++ b/docker/prod/requirements.prod.txt @@ -15,3 +15,4 @@ django-debug-toolbar-template-profiler orjson django-otp qrcode +serde[ext]