File size: 14,731 Bytes
c323ab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
c323ab3
 
 
 
 
 
 
 
 
c49440d
c323ab3
 
 
 
c49440d
c323ab3
 
 
c49440d
c323ab3
 
c49440d
c323ab3
 
c49440d
c323ab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
c323ab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
c323ab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
"""
Muzo Audio/Video CDN Proxy (FastAPI) - mirrors the Cloudflare Worker exactly.

Pure binary stream, full Range (206) support, CORS, plus transparent local disk
caching so repeat requests are served from cache.

Routes (also accepted with /muzo/cdn/... instead of /muzo/cnd/...):
    /muzo/cnd/flac/lossless/{id}   -> lossless/{id}.flac
    /muzo/cnd/m4a/stream/{id}      -> stream/{id}.m4a
    /muzo/cnd/mp4/canvas/{id}      -> canvas/{id}.mp4
    /muzo/cnd/1/flac/lossless/{id} -> lossless_new/{id}.flac
    /muzo/cnd/1/m4a/stream/{id}    -> stream_new/{id}.m4a
    /  and  /health                -> health check (JSON)

Secrets / env:
    MEDIA_SOURCES           REQUIRED. JSON object with the base URLs:
                            {"lossless": "...", "stream": "...", "canvas": "...",
                             "lossless_new": "...", "stream_new": "..."}
    HF_TOKEN (or HFTOKEN)   optional, for private buckets
    CACHE_DIR, PORT         optional

Run:
    uvicorn main:app --host 0.0.0.0 --port 7860
"""

from __future__ import annotations

import os
import re
import json
import asyncio
import hashlib
import logging
from dataclasses import dataclass
from email.utils import formatdate
from pathlib import Path
from urllib.parse import quote, unquote

import aiofiles
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse

# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

BASE_CACHE_DIR = Path(
    os.environ.get("CACHE_DIR", "/data/cache" if os.path.isdir("/data") else "./cache")
)
CHUNK_SIZE = 1024 * 256  # 256 KB
UPSTREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=60.0, pool=10.0)

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("muzo-cdn-proxy")

CORS_HEADERS = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
    "Access-Control-Allow-Headers": "Range, Content-Type, Accept, Authorization, X-Requested-With",
    "Access-Control-Expose-Headers": "Content-Range, Content-Length, Accept-Ranges, Content-Type",
}

CACHE_CONTROL = "public, max-age=31536000, s-maxage=604800, immutable"

URL_SAFE_CHARS = "!*'()"  # matches JS encodeURIComponent

REQUIRED_SOURCE_KEYS = ("lossless", "stream", "canvas", "lossless_new", "stream_new")


def load_base_urls() -> dict[str, str]:
    """Read all base URLs from the single MEDIA_SOURCES secret."""
    raw = os.environ.get("MEDIA_SOURCES")
    if not raw:
        raise RuntimeError("Missing required secret MEDIA_SOURCES (JSON with the 5 base URLs)")
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as e:
        raise RuntimeError(f"MEDIA_SOURCES is not valid JSON: {e}")
    if not isinstance(data, dict):
        raise RuntimeError("MEDIA_SOURCES must be a JSON object")

    bases: dict[str, str] = {}
    for key in REQUIRED_SOURCE_KEYS:
        val = data.get(key)
        if not isinstance(val, str) or not val.strip():
            raise RuntimeError(f"MEDIA_SOURCES is missing a valid '{key}' URL")
        bases[key] = val.strip().rstrip("/")
    return bases


BASE_URLS = load_base_urls()


@dataclass(frozen=True)
class MediaSource:
    name: str   # also the cache subdirectory and the key in MEDIA_SOURCES
    ext: str
    mime: str

    @property
    def base_url(self) -> str:
        return BASE_URLS[self.name]

    @property
    def cache_dir(self) -> Path:
        d = BASE_CACHE_DIR / self.name
        d.mkdir(parents=True, exist_ok=True)
        return d


SOURCES: dict[str, MediaSource] = {
    "lossless":     MediaSource("lossless",     "flac", "audio/flac"),
    "stream":       MediaSource("stream",       "m4a",  "audio/mp4"),
    "canvas":       MediaSource("canvas",       "mp4",  "video/mp4"),
    "lossless_new": MediaSource("lossless_new", "flac", "audio/flac"),
    "stream_new":   MediaSource("stream_new",   "m4a",  "audio/mp4"),
}

# More specific (/1/) routes first; order matters.
ROUTES: list[tuple[re.Pattern, str]] = [
    (re.compile(r"^/muzo/c(?:nd|dn)/1/flac/lossless/(.+)$", re.I), "lossless_new"),
    (re.compile(r"^/muzo/c(?:nd|dn)/1/m4a/stream/(.+)$", re.I), "stream_new"),
    (re.compile(r"^/muzo/c(?:nd|dn)/flac/lossless/(.+)$", re.I), "lossless"),
    (re.compile(r"^/muzo/c(?:nd|dn)/m4a/stream/(.+)$", re.I), "stream"),
    (re.compile(r"^/muzo/c(?:nd|dn)/mp4/canvas/(.+)$", re.I), "canvas"),
]

SUPPORTED_ROUTES = [
    "/muzo/cnd/flac/lossless/{id}",
    "/muzo/cnd/m4a/stream/{id}",
    "/muzo/cnd/mp4/canvas/{id}",
    "/muzo/cnd/1/flac/lossless/{id}",
    "/muzo/cnd/1/m4a/stream/{id}",
]

_INVALID_ID_CHARS = re.compile(r"[/\\?#%\u0000-\u001f\u007f]")

# In-flight download locks: one upstream download per (source, id).
_locks: dict[str, asyncio.Lock] = {}
_locks_guard = asyncio.Lock()

app = FastAPI(title="Muzo Audio CDN Proxy")


class MediaError(Exception):
    def __init__(self, status: int, error: str, headers: dict | None = None, **extra):
        self.status = status
        self.error = error
        self.headers = headers or {}
        self.extra = extra


@app.exception_handler(MediaError)
async def media_error_handler(_: Request, exc: MediaError):
    return json_response({"error": exc.error, **exc.extra}, exc.status, exc.headers)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def json_response(body: dict, status: int = 200, extra_headers: dict | None = None) -> JSONResponse:
    return JSONResponse(body, status_code=status, headers={**CORS_HEADERS, **(extra_headers or {})})


def clean_id(raw_id: str, ext: str) -> str:
    """Decode, strip the route's extension, reject anything that could alter the path."""
    if not raw_id:
        return ""
    try:
        id_ = unquote(raw_id, errors="strict").strip()
    except UnicodeDecodeError:
        return ""
    id_ = re.sub(r"\." + re.escape(ext) + r"$", "", id_, flags=re.I)
    if not id_:
        return ""
    if ".." in id_ or _INVALID_ID_CHARS.search(id_):
        return ""
    return id_


def cache_path_for(source: MediaSource, media_id: str) -> Path:
    if len(media_id) <= 100 and media_id.replace("-", "").replace("_", "").isalnum():
        name = media_id
    else:
        name = hashlib.sha256(media_id.encode()).hexdigest()
    return source.cache_dir / f"{name}.{source.ext}"


def upstream_url_for(source: MediaSource, media_id: str) -> str:
    encoded = quote(media_id, safe=URL_SAFE_CHARS)
    return f"{source.base_url}/{encoded}.{source.ext}"


def upstream_headers() -> dict:
    headers = {"User-Agent": "Muzo-Audio-CDN/1.0 (Direct Streaming)", "Accept": "*/*"}
    token = os.environ.get("HF_TOKEN") or os.environ.get("HFTOKEN")
    if token:
        headers["Authorization"] = f"Bearer {token}"
    return headers


async def get_lock(key: str) -> asyncio.Lock:
    async with _locks_guard:
        lock = _locks.get(key)
        if lock is None:
            lock = asyncio.Lock()
            _locks[key] = lock
        return lock


async def ensure_cached(source: MediaSource, media_id: str) -> Path:
    """Download from upstream into the cache if missing (atomic .part -> rename)."""
    dest = cache_path_for(source, media_id)
    if dest.exists():
        return dest

    lock = await get_lock(f"{source.name}:{media_id}")
    async with lock:
        if dest.exists():
            return dest

        tmp = dest.with_suffix(dest.suffix + ".part")
        url = upstream_url_for(source, media_id)
        log.info(f"[{source.name}] fetching and caching: {media_id}")

        try:
            async with httpx.AsyncClient(timeout=UPSTREAM_TIMEOUT, follow_redirects=True) as client:
                async with client.stream("GET", url, headers=upstream_headers()) as resp:
                    if resp.status_code == 404:
                        raise MediaError(404, "Media not found")
                    if resp.status_code >= 400:
                        raise MediaError(502, f"Upstream error ({resp.status_code}) fetching media")
                    async with aiofiles.open(tmp, "wb") as f:
                        async for chunk in resp.aiter_bytes(CHUNK_SIZE):
                            await f.write(chunk)
            tmp.rename(dest)
        except MediaError:
            tmp.unlink(missing_ok=True)
            raise
        except httpx.HTTPError as e:
            tmp.unlink(missing_ok=True)
            log.error(f"[{source.name}] upstream failure for {media_id}: {e}")
            raise MediaError(502, "Upstream request failed")
        except Exception:
            tmp.unlink(missing_ok=True)
            raise

        log.info(f"[{source.name}] cached {media_id} ({dest.stat().st_size} bytes)")
        return dest


def parse_range_header(range_header: str, file_size: int) -> tuple[int, int]:
    """Parse a single 'bytes=start-end' range into inclusive (start, end)."""
    bad = MediaError(416, "Invalid Range header", {"Content-Range": f"bytes */{file_size}"})
    try:
        units, _, rng = range_header.partition("=")
        if units.strip().lower() != "bytes":
            raise ValueError
        start_s, _, end_s = rng.strip().partition("-")
        if start_s == "":
            length = int(end_s)
            if length <= 0:
                raise ValueError
            start = max(file_size - length, 0)
            end = file_size - 1
        else:
            start = int(start_s)
            end = int(end_s) if end_s else file_size - 1
        end = min(end, file_size - 1)
        if start < 0 or start > end:
            raise ValueError
        return start, end
    except (ValueError, IndexError):
        raise bad


async def file_range_streamer(path: Path, start: int, end: int, chunk_size: int = CHUNK_SIZE):
    remaining = end - start + 1
    async with aiofiles.open(path, "rb") as f:
        await f.seek(start)
        while remaining > 0:
            data = await f.read(min(chunk_size, remaining))
            if not data:
                break
            remaining -= len(data)
            yield data


async def serve(source: MediaSource, media_id: str, request: Request) -> Response:
    path = await ensure_cached(source, media_id)
    st = path.stat()
    file_size = st.st_size

    headers = {
        **CORS_HEADERS,
        "Accept-Ranges": "bytes",
        "Content-Type": source.mime,          # audio/flac, never audio/x-flac
        "Content-Disposition": "inline",
        "Cache-Control": CACHE_CONTROL,
        "ETag": f'"{st.st_size:x}-{int(st.st_mtime):x}"',
        "Last-Modified": formatdate(st.st_mtime, usegmt=True),
    }

    range_header = request.headers.get("range")
    if range_header:
        start, end = parse_range_header(range_header, file_size)
        status = 206
        headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
        headers["Content-Length"] = str(end - start + 1)
    else:
        start, end = 0, file_size - 1
        status = 200
        headers["Content-Length"] = str(file_size)

    if request.method == "HEAD":
        return Response(status_code=status, headers=headers)

    return StreamingResponse(
        file_range_streamer(path, start, end),
        status_code=status,
        headers=headers,
    )


# ---------------------------------------------------------------------------
# Admin routes (extras, not in the Worker)
# ---------------------------------------------------------------------------

@app.get("/cache/stats")
async def cache_stats():
    stats, grand_total = {}, 0
    for name, source in SOURCES.items():
        files = list(source.cache_dir.glob(f"*.{source.ext}"))
        total = sum(f.stat().st_size for f in files)
        grand_total += total
        stats[name] = {
            "cached_items": len(files),
            "total_bytes": total,
            "total_mb": round(total / (1024 * 1024), 2),
            "cache_dir": str(source.cache_dir),
        }
    stats["total_mb_all_sources"] = round(grand_total / (1024 * 1024), 2)
    return json_response(stats)


@app.delete("/cache/{source_name}/{media_id}")
async def evict_cache(source_name: str, media_id: str):
    source = SOURCES.get(source_name)
    if source is None:
        raise MediaError(404, f"Unknown source '{source_name}'")
    media_id = clean_id(media_id, source.ext)
    if not media_id:
        raise MediaError(400, "Invalid or missing track ID")
    path = cache_path_for(source, media_id)
    if path.exists():
        path.unlink()
        return json_response({"deleted": True, "source": source_name, "id": media_id})
    return json_response({"deleted": False, "source": source_name, "id": media_id, "reason": "not cached"})


# ---------------------------------------------------------------------------
# Main router (same logic as the Worker's fetch handler)
# ---------------------------------------------------------------------------

@app.api_route(
    "/{full_path:path}",
    methods=["GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"],
)
async def router(full_path: str, request: Request):
    if request.method == "OPTIONS":
        return Response(status_code=204, headers=CORS_HEADERS)
    if request.method not in ("GET", "HEAD"):
        return json_response({"error": "Method not allowed"}, 405, {"Allow": "GET, HEAD, OPTIONS"})

    # Use the raw (still percent-encoded) path so id decoding/validation matches the Worker
    raw_path = request.scope.get("raw_path")
    pathname = raw_path.decode("latin-1") if raw_path else request.url.path
    pathname = pathname.split("?", 1)[0]

    # Public: health check
    if pathname in ("/", "/health"):
        return json_response({
            "service": "muzo-audio-cdn",
            "status": "online",
            "mode": "direct_media_stream",
            "endpoints": SUPPORTED_ROUTES,
        })

    # Resolve the route
    source, raw_id = None, None
    for pattern, source_key in ROUTES:
        m = pattern.match(pathname)
        if m:
            source, raw_id = SOURCES[source_key], m.group(1)
            break

    if source is None:
        return json_response({
            "error": "Not Found",
            "message": "Endpoint not recognized",
            "supported_routes": SUPPORTED_ROUTES,
        }, 404)

    media_id = clean_id(raw_id, source.ext)
    if not media_id:
        return json_response({"error": "Invalid or missing track ID"}, 400)

    return await serve(source, media_id, request)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))