diff --git a/server.py b/server.py index 3a68dd7..6f83f1f 100644 --- a/server.py +++ b/server.py @@ -525,6 +525,15 @@ class RobustProxyHandler(http.server.SimpleHTTPRequestHandler): self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Cookie, X-QB-Target-Host, X-Custom-LLM-Base, Accept-Encoding, x-api-key, anthropic-version, anthropic-beta') self.send_header('Access-Control-Max-Age', '86400') + def send_json_response(self, code, data): + resp_bytes = json.dumps(data).encode('utf-8') + self.send_response(code) + self.send_cors_headers() + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(resp_bytes))) + self.end_headers() + self.wfile.write(resp_bytes) + def do_OPTIONS(self): self.send_response(204) self.send_cors_headers() @@ -564,10 +573,6 @@ class RobustProxyHandler(http.server.SimpleHTTPRequestHandler): target_base = normalize_url_base(raw_target) self.proxy_external_api(target_base, '/custom-llm-proxy/', method='GET') elif self.path == '/server-status': - self.send_response(200) - self.send_header('Content-Type', 'application/json') - self.send_cors_headers() - self.end_headers() status_data = { "status": "online", "target": DEFAULT_QB_HOST, @@ -576,13 +581,14 @@ class RobustProxyHandler(http.server.SimpleHTTPRequestHandler): "stash_url": DEFAULT_STASH_URL, "db": os.path.exists(DB_PATH) } - self.wfile.write(json.dumps(status_data).encode('utf-8')) + self.send_json_response(200, status_data) elif self.path == '/' or self.path == '': self.path = '/qbittorrent_performer_sorter.html' super().do_GET() else: super().do_GET() + def do_POST(self): # Database Cache Save/Delete APIs if self.path == '/api/db/save': self.handle_db_save() @@ -655,17 +661,9 @@ class RobustProxyHandler(http.server.SimpleHTTPRequestHandler): } conn.close() - self.send_response(200) - self.send_header('Content-Type', 'application/json') - self.send_cors_headers() - self.end_headers() - self.wfile.write(json.dumps({"cache": cache_map, "count": len(cache_map)}).encode('utf-8')) + self.send_json_response(200, {"cache": cache_map, "count": len(cache_map)}) except Exception as e: - self.send_response(500) - self.send_header('Content-Type', 'application/json') - self.send_cors_headers() - self.end_headers() - self.wfile.write(json.dumps({"error": f"Failed reading SQLite cache: {str(e)}"}).encode('utf-8')) + self.send_json_response(500, {"error": f"Failed reading SQLite cache: {str(e)}"}) def handle_db_save(self): content_length = int(self.headers.get('Content-Length', 0))