import os import json import logging from http.server import HTTPServer, BaseHTTPRequestHandler from .dispatcher import dispatchRequest from .createresponse import buildResponse from plugins.rmass.listeners import synapselistener from core.server.createlistener import buildListener #from plugins.rmass.actions import pingsynapse port = int(os.environ.get("SERVER_PORT", 19001)) class RequestHandler(BaseHTTPRequestHandler): def do_POST(self): #lifecycles = {} print("POST request received") max_request_size = 1024 content_length = self.headers.get("Content-Length") # Check whether Content-Length exists if content_length is None: response = { "status": "error", "message": "Content length required" } status = 411 else: # Attempt to convert the header into an integer try: length = int(content_length) except ValueError: length = None # Validate the converted length if length is None: response = { "status": "error", "message": "Invalid Content-Length" } status = 400 elif length < 0: response = { "status": "error", "message": "Bad Request" } status = 400 elif length > max_request_size: response = { "status": "error", "message": "Content exceeds maximum request size" } status = 413 else: # Content-Length is valid, so read the body data = self.rfile.read(length) try: request = json.loads(data) except json.JSONDecodeError: response = { "status": "error", "message": "Invalid JSON received" } status = 400 else: # Only valid JSON reaches the dispatcher thread, lifecycles, module, mode = dispatchRequest( request, lifecycles ) response = buildResponse(module, thread, mode) status = 200 # Serialize the response responsebytes = json.dumps(response).encode("utf-8") # Send one HTTP response self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(responsebytes))) self.end_headers() self.wfile.write(responsebytes) def do_PUT(self): #print("PUT request received") outputs = buildListener(synapselistener, self) def startServer(): server = HTTPServer(("0.0.0.0", port), RequestHandler) logging.info(f"Server listening on port {port}") #outputs = {} #outputs, response = buildAction(pingsynapse, outputs) server.serve_forever()