"""도메인별 리소스팩: Nextcloud(share.tkrmagid.kr) 에 저장하고 공개 경로로 내려준다. - 업로드/삭제/목록은 대시보드용 /api/packs (인증 없음, 내부망 전용) - 클라이언트 다운로드는 /pack/.zip (외부 공개). Nextcloud 에서 받아 그대로 스트리밍한다. Nextcloud 공유 링크의 /download 는 http:// 로 303 리다이렉트를 주는데, MC 클라이언트(HttpURLConnection)는 https→http 리다이렉트를 따라가지 않아서 직접 중계한다. """ from __future__ import annotations import hashlib import json import os import shutil import tempfile import threading import time import zipfile from pathlib import Path from urllib.parse import quote import httpx from fastapi import APIRouter, HTTPException, Response, UploadFile from fastapi.responses import StreamingResponse from config_io import load_config router = APIRouter() # /api 아래 public_router = APIRouter() # /pack 공개 다운로드 PACKS_PATH = Path(os.environ.get("MC_PACKS_PATH", "/data/packs.json")) NC_URL = os.environ.get("NEXTCLOUD_URL", "http://192.168.10.10:8080").rstrip("/") NC_USER = os.environ.get("NEXTCLOUD_USER", "") NC_PASSWORD = os.environ.get("NEXTCLOUD_PASSWORD", "") NC_DIR = os.environ.get("NEXTCLOUD_DIR", "/claude/mc_domain_proxy/packs").strip("/") PUBLIC_BASE = os.environ.get("PACK_PUBLIC_BASE", "https://mc.tkrmagid.kr/pack").rstrip("/") _lock = threading.Lock() def _load_packs() -> dict: if not PACKS_PATH.exists(): return {} with PACKS_PATH.open("r", encoding="utf-8") as f: return json.load(f) def _save_packs(packs: dict) -> None: PACKS_PATH.parent.mkdir(parents=True, exist_ok=True) tmp = PACKS_PATH.with_suffix(".json.tmp") with tmp.open("w", encoding="utf-8") as f: json.dump(packs, f, ensure_ascii=False, indent=2) os.replace(tmp, PACKS_PATH) def _dav_url(*parts: str) -> str: path = "/".join(quote(p, safe="") for p in [*NC_DIR.split("/"), *parts] if p) return f"{NC_URL}/remote.php/dav/files/{quote(NC_USER, safe='')}/{path}" def _client(timeout: float | None = 30.0) -> httpx.Client: return httpx.Client(auth=(NC_USER, NC_PASSWORD), timeout=timeout) def _require_storage() -> None: if not NC_USER or not NC_PASSWORD: raise HTTPException( status_code=503, detail="Nextcloud 계정이 설정되지 않았습니다 (NEXTCLOUD_USER / NEXTCLOUD_PASSWORD).", ) def _ensure_dir(client: httpx.Client) -> None: # NC_DIR 의 각 단계를 순서대로 MKCOL (이미 있으면 405) parts = NC_DIR.split("/") for i in range(1, len(parts) + 1): url = f"{NC_URL}/remote.php/dav/files/{quote(NC_USER, safe='')}/" + "/".join( quote(p, safe="") for p in parts[:i] ) r = client.request("MKCOL", url) if r.status_code not in (201, 405): raise HTTPException(status_code=502, detail=f"Nextcloud 폴더 생성 실패: {r.status_code}") def _domain_names() -> set[str]: return {d["domain"].lower() for d in load_config().get("allowed_domains", [])} def _pack_url(domain: str) -> str: return f"{PUBLIC_BASE}/{quote(domain, safe='')}.zip" @router.get("/packs") def list_packs() -> dict: packs = _load_packs() items = [] for d in load_config().get("allowed_domains", []): name = d["domain"].lower() meta = packs.get(name) items.append({ "domain": name, "pack": {**meta, "url": _pack_url(name)} if meta else None, }) return {"storage_configured": bool(NC_USER and NC_PASSWORD), "packs": items} @router.put("/packs/{domain}") def upload_pack(domain: str, file: UploadFile) -> dict: _require_storage() name = domain.strip().lower() if name not in _domain_names(): raise HTTPException(status_code=404, detail="domain not found") with tempfile.NamedTemporaryFile(suffix=".zip") as tmp: sha1 = hashlib.sha1() size = 0 while chunk := file.file.read(1024 * 1024): sha1.update(chunk) size += len(chunk) tmp.write(chunk) tmp.flush() try: with zipfile.ZipFile(tmp.name) as zf: has_meta = "pack.mcmeta" in zf.namelist() except zipfile.BadZipFile: raise HTTPException(status_code=400, detail="zip 파일이 아닙니다.") if not has_meta: raise HTTPException( status_code=400, detail="zip 최상위에 pack.mcmeta 가 없습니다. 폴더째 압축하지 말고 폴더 안의 내용물을 압축해 주세요.", ) with _client(timeout=None) as client: _ensure_dir(client) tmp.seek(0) r = client.put( _dav_url(f"{name}.zip"), content=iter(lambda: tmp.read(1024 * 1024), b""), headers={"Content-Length": str(size)}, ) if r.status_code not in (201, 204): raise HTTPException(status_code=502, detail=f"Nextcloud 업로드 실패: {r.status_code}") meta = { "sha1": sha1.hexdigest(), "size": size, "original_name": file.filename or f"{name}.zip", "uploaded_at": time.time(), } with _lock: packs = _load_packs() packs[name] = meta _save_packs(packs) return {"domain": name, "pack": {**meta, "url": _pack_url(name)}} @router.delete("/packs/{domain}", status_code=204) def delete_pack(domain: str) -> Response: _require_storage() name = domain.strip().lower() with _lock: packs = _load_packs() if name not in packs: raise HTTPException(status_code=404, detail="pack not found") with _client() as client: r = client.delete(_dav_url(f"{name}.zip")) if r.status_code not in (204, 404): raise HTTPException(status_code=502, detail=f"Nextcloud 삭제 실패: {r.status_code}") packs.pop(name) _save_packs(packs) return Response(status_code=204) @public_router.get("/pack/{filename}") def download_pack(filename: str) -> StreamingResponse: if not filename.endswith(".zip"): raise HTTPException(status_code=404) name = filename[: -len(".zip")].lower() if name not in _load_packs() or not NC_USER: raise HTTPException(status_code=404) client = _client(timeout=httpx.Timeout(30.0, read=None)) upstream = client.send(client.build_request( "GET", _dav_url(f"{name}.zip"), headers={"Accept-Encoding": "identity"} ), stream=True) if upstream.status_code != 200: upstream.close() client.close() raise HTTPException(status_code=404 if upstream.status_code == 404 else 502) def body(): try: yield from upstream.iter_bytes(1024 * 1024) finally: upstream.close() client.close() headers = {"Content-Disposition": f'attachment; filename="{name}.zip"'} if "content-length" in upstream.headers: headers["Content-Length"] = upstream.headers["content-length"] return StreamingResponse(body(), media_type="application/zip", headers=headers)