-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.py
More file actions
92 lines (71 loc) · 2.97 KB
/
Copy pathserver.py
File metadata and controls
92 lines (71 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import http.server
import os
import socketserver
from urllib.parse import urlparse
from controllers.koreader_sync import KoReaderSyncController
from controllers.opds import LIBRARY_DIR, OPDSController, PAGE_SIZE
from routes import Router, register_routes
PORT = int(os.environ.get('PORT', 8080))
class UnifiedHandler(http.server.BaseHTTPRequestHandler):
"""
Unified HTTP request handler with explicit Laravel-style routing.
"""
# Initialize router with all routes
router = register_routes(Router())
def end_headers(self):
"""Add Connection: close header to all responses for HTTP/1.0 compatibility.
Our server uses HTTP/1.0 but clients (e.g. ESP32 HTTPClient) may send
HTTP/1.1 requests. The explicit header ensures clients properly detect
the end of each response.
"""
self.send_header('Connection', 'close')
super().end_headers()
def __init__(self, *args, **kwargs):
"""Initialize handler with controller instances."""
super().__init__(*args, **kwargs)
# Controllers are created on demand to have access to self
def _get_controller(self, controller_class):
"""Get or create controller instance."""
if controller_class == OPDSController:
return OPDSController(self)
elif controller_class == KoReaderSyncController:
return KoReaderSyncController(self)
else:
raise ValueError(f"Unknown controller: {controller_class}")
def _handle_request(self, method):
"""Handle request by routing to appropriate controller action."""
parsed_url = urlparse(self.path)
path = parsed_url.path
# Find matching route
route = self.router.find_route(method, path)
if route:
# Get controller and call action
controller = self._get_controller(route.controller_class)
action_method = getattr(controller, route.action)
action_method()
else:
controller = self._get_controller(OPDSController)
controller._send_error(404, 'Endpoint not found')
def do_GET(self):
"""Handle GET requests through router."""
self._handle_request('GET')
def do_PUT(self):
"""Handle PUT requests through router."""
self._handle_request('PUT')
def do_POST(self):
"""Handle POST requests through router."""
self._handle_request('POST')
def main():
"""Start the OPDS server with KoReader sync support."""
if not os.path.exists(LIBRARY_DIR):
os.makedirs(LIBRARY_DIR)
print(f"\nAccess the root catalog at http://127.0.0.1:{PORT}/opds")
print(f"KoReader sync available at http://127.0.0.1:{PORT}/koreader/sync\n")
with socketserver.TCPServer(("", PORT), UnifiedHandler) as httpd:
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nShutting down server...")
httpd.shutdown()
if __name__ == '__main__':
main()