Files
LastRecc/lastrecc/server.py
T

272 lines
11 KiB
Python

from __future__ import annotations
import hashlib
import json
import mimetypes
import sys
import threading
import traceback
import urllib.error
import urllib.parse
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from .cache import is_fresh, load_json, save_json
from .config import Settings
from .navidrome import Navidrome
from .net import HttpError
from .recommend import build_feed
class App:
def __init__(self, settings: Settings):
self.settings = settings
self.nav = Navidrome(settings)
self.build_lock = threading.Lock()
self.cover_dir = settings.cache_dir / "covers"
self.cover_dir.mkdir(parents=True, exist_ok=True)
def feed(self, days: int | None = None, refresh: bool = False) -> dict:
settings = self.settings.with_days(days) if days else self.settings
with self.build_lock:
return build_feed(settings, force=refresh)
class Handler(BaseHTTPRequestHandler):
server_version = "LastRecc/0.1"
protocol_version = "HTTP/1.1"
@property
def app(self) -> App:
return self.server.app # type: ignore[attr-defined]
def log_message(self, fmt: str, *args) -> None:
sys.stderr.write(f"[http] {self.address_string()} {fmt % args}\n")
# ------------------------------------------------------------------ helpers
def _json(self, status: int, data: dict) -> None:
payload = json.dumps(data, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(payload)
def _error(self, status: int, message: str) -> None:
self._json(status, {"error": message})
def _serve_file(self, path: Path) -> None:
if not path.is_file():
self._error(HTTPStatus.NOT_FOUND, "Not found")
return
content_type = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
payload = path.read_bytes()
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(payload)))
self.send_header("Cache-Control", "no-cache" if path.name.endswith(".html") else "public, max-age=300")
self.end_headers()
self.wfile.write(payload)
# --------------------------------------------------------------------- GET
def do_GET(self) -> None: # noqa: N802
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
query = urllib.parse.parse_qs(parsed.query)
if path in ("/", "/index.html"):
self._serve_file(self.app.settings.web_dir / "index.html")
return
if path.startswith("/static/"):
relative = path[len("/static/") :]
target = (self.app.settings.web_dir / relative).resolve()
web_root = self.app.settings.web_dir.resolve()
if web_root not in target.parents and target != web_root:
self._error(HTTPStatus.FORBIDDEN, "Forbidden")
return
self._serve_file(target)
return
if path == "/api/health":
cached = load_json(self.app.settings.cache_dir / "feed.json")
self._json(
HTTPStatus.OK,
{
"ok": True,
"user": self.app.settings.navidrome_user,
"cached_feed": bool(cached),
"generated_at": (cached or {}).get("generated_at"),
},
)
return
if path == "/api/feed":
days = None
if query.get("days"):
try:
days = int(query["days"][0])
except ValueError:
self._error(HTTPStatus.BAD_REQUEST, "days must be an integer")
return
refresh = query.get("refresh", ["0"])[0].lower() in ("1", "true", "yes")
try:
feed = self.app.feed(days=days, refresh=refresh)
except Exception as exc: # noqa: BLE001
traceback.print_exc()
self._error(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc))
return
self._json(HTTPStatus.OK, feed)
return
if path.startswith("/api/cover/"):
cover_id = urllib.parse.unquote(path[len("/api/cover/") :])
try:
size = int(query.get("size", ["300"])[0])
except ValueError:
size = 300
size = max(100, min(size, 600))
self._cover(cover_id, size)
return
if path.startswith("/api/stream/"):
song_id = urllib.parse.unquote(path[len("/api/stream/") :])
self._stream(song_id)
return
self._error(HTTPStatus.NOT_FOUND, "Not found")
def do_HEAD(self) -> None: # noqa: N802
# Good enough for browsers probing covers/audio.
parsed = urllib.parse.urlparse(self.path)
if parsed.path in ("/", "/index.html"):
path = self.app.settings.web_dir / "index.html"
elif parsed.path.startswith("/static/"):
web_root = self.app.settings.web_dir.resolve()
path = (web_root / parsed.path[len("/static/") :]).resolve()
if web_root not in path.parents and path != web_root:
self.send_response(HTTPStatus.FORBIDDEN)
self.send_header("Content-Length", "0")
self.end_headers()
return
else:
self.send_response(HTTPStatus.NOT_FOUND)
self.send_header("Content-Length", "0")
self.end_headers()
return
if not path.is_file():
self.send_response(HTTPStatus.NOT_FOUND)
self.send_header("Content-Length", "0")
self.end_headers()
return
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", mimetypes.guess_type(str(path))[0] or "application/octet-stream")
self.send_header("Content-Length", str(path.stat().st_size))
self.end_headers()
def do_POST(self) -> None: # noqa: N802
parsed = urllib.parse.urlparse(self.path)
if parsed.path == "/api/refresh":
try:
feed = self.app.feed(refresh=True)
except Exception as exc: # noqa: BLE001
traceback.print_exc()
self._error(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc))
return
self._json(HTTPStatus.OK, feed)
return
self._error(HTTPStatus.NOT_FOUND, "Not found")
# ------------------------------------------------------------------- proxy
def _cover(self, cover_id: str, size: int) -> None:
if not cover_id:
self._error(HTTPStatus.BAD_REQUEST, "Missing cover id")
return
cache_key = hashlib.sha256(f"{cover_id}:{size}".encode()).hexdigest()
cache_path = self.app.cover_dir / f"{cache_key}.bin"
content_type = "image/jpeg"
if cache_path.exists() and is_fresh(cache_path, 7 * 24 * 3600):
meta_path = cache_path.with_suffix(".json")
meta = load_json(meta_path, {}) or {}
content_type = meta.get("content_type", content_type)
payload = cache_path.read_bytes()
else:
url = self.app.nav.cover_url(cover_id, size)
try:
_, headers, payload = self.app.nav.http.request(url)
except (HttpError, urllib.error.HTTPError, urllib.error.URLError, OSError) as exc:
self._error(HTTPStatus.BAD_GATEWAY, f"Cover fetch failed: {exc}")
return
content_type = headers.get("Content-Type", content_type)
cache_path.write_bytes(payload)
save_json(cache_path.with_suffix(".json"), {"content_type": content_type})
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(payload)))
self.send_header("Cache-Control", "public, max-age=604800")
self.end_headers()
self.wfile.write(payload)
def _stream(self, song_id: str) -> None:
if not song_id:
self._error(HTTPStatus.BAD_REQUEST, "Missing song id")
return
url = self.app.nav.stream_url(song_id)
headers = {}
range_header = self.headers.get("Range")
if range_header:
headers["Range"] = range_header
try:
upstream = self.app.nav.http.open(url, headers=headers)
except urllib.error.HTTPError as exc:
self._error(exc.code, f"Stream failed: {exc.reason}")
return
except (urllib.error.URLError, OSError) as exc:
self._error(HTTPStatus.BAD_GATEWAY, f"Stream failed: {exc}")
return
with upstream:
status = upstream.status
self.send_response(status)
content_length = upstream.headers.get("Content-Length")
for header in (
"Content-Type",
"Content-Length",
"Content-Range",
"Accept-Ranges",
"ETag",
"Last-Modified",
):
value = upstream.headers.get(header)
if value:
self.send_header(header, value)
self.send_header("Cache-Control", "no-store")
if not content_length:
self.send_header("Connection", "close")
self.close_connection = True
self.end_headers()
try:
while True:
chunk = upstream.read(64 * 1024)
if not chunk:
break
self.wfile.write(chunk)
except (BrokenPipeError, ConnectionResetError):
pass
class Server(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
def __init__(self, address, handler, app: App):
super().__init__(address, handler)
self.app = app
def serve(settings: Settings, host: str = "127.0.0.1", port: int = 8787) -> None:
app = App(settings)
server = Server((host, port), Handler, app)
print(f"LastRecc → http://{host}:{port}", file=sys.stderr)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nbye", file=sys.stderr)
finally:
server.server_close()