From b07e3d6a9437348f5245e8f012b5f5f22de8c523 Mon Sep 17 00:00:00 2001 From: Hay1tsme Date: Sat, 25 Feb 2023 18:50:35 -0500 Subject: [PATCH] add base request/response classes --- titles/diva/handlers/base.py | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 titles/diva/handlers/base.py diff --git a/titles/diva/handlers/base.py b/titles/diva/handlers/base.py new file mode 100644 index 0000000..ff9eff5 --- /dev/null +++ b/titles/diva/handlers/base.py @@ -0,0 +1,38 @@ +from urllib import parse + +class DivaRequestParseException(Exception): + """ + Exception raised when there is a fault in parsing a diva request, + either due to a malformed request, or missing required items + """ + def __init__(self, message: str) -> None: + self.message = message + super().__init__(self.message) + +class BaseRequest: + def __init__(self, raw: str) -> None: + self.raw = dict(parse.parse_qsl(raw)) + + if 'cmd' not in self.raw: + raise DivaRequestParseException(f"cmd not in request data {self.raw}") + self.cmd = raw['cmd'] + + if 'req_id' not in self.raw: + raise DivaRequestParseException(f"req_id not in request data {self.raw}") + self.req_id = raw['req_id'] + +class BaseResponse: + def __init__(self, cmd_id: str, req_id: int) -> None: + self.cmd = cmd_id + self.req_id = req_id + self.stat = "ok" + + def make(self) -> str: + all_vars = vars(self) + all_vars.pop('cmd') + all_vars.pop('req_id') + + ret = f"cmd={self.cmd}&req_id={self.req_id}" + ret += parse.urlencode(all_vars, doseq=True, quote_via=parse.quote) + + return ret