Files
mc_domain_proxy/api/routes/packs.py
claude-bot 03ab32f8ab feat(packs): pack types (resourcepack/datapack/modpack), URL /pack/<type>.zip?domain=<domain>
Files move to <NEXTCLOUD_DIR>/<domain>/<type>.zip; packs.json is {domain: {type: meta}}.
Only resourcepack shows the server.properties snippet; datapack/modpack show the URL.
modpack skips the pack.mcmeta check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:51:52 +09:00

225 lines
8.0 KiB
Python

"""도메인별 팩(리소스팩/데이터팩/모드팩): Nextcloud(share.tkrmagid.kr) 에 저장하고 공개 경로로 내려준다.
- 업로드/삭제/목록은 대시보드용 /api/packs (인증 없음, 내부망 전용)
- 다운로드는 /pack/<종류>.zip?domain=<도메인> (외부 공개). Nextcloud 에서 받아 그대로 스트리밍한다.
Nextcloud 공유 링크의 /download 는 http:// 로 303 리다이렉트를 주는데,
MC 클라이언트(HttpURLConnection)는 https→http 리다이렉트를 따라가지 않아서 직접 중계한다.
"""
from __future__ import annotations
import hashlib
import json
import os
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("/")
# 종류별 설정. mcmeta=True 면 zip 최상위에 pack.mcmeta 가 있어야 한다.
PACK_TYPES = {
"resourcepack": {"label": "리소스팩", "mcmeta": True},
"datapack": {"label": "데이터팩", "mcmeta": True},
"modpack": {"label": "모드팩", "mcmeta": False},
}
_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, *extra: str) -> None:
# NC_DIR(+extra) 의 각 단계를 순서대로 MKCOL (이미 있으면 405)
parts = [*NC_DIR.split("/"), *extra]
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(kind: str, domain: str) -> str:
return f"{PUBLIC_BASE}/{kind}.zip?domain={quote(domain, safe='')}"
def _check_kind(kind: str) -> None:
if kind not in PACK_TYPES:
raise HTTPException(status_code=404, detail="unknown pack type")
@router.get("/packs")
def list_packs() -> dict:
packs = _load_packs()
items = []
for d in load_config().get("allowed_domains", []):
name = d["domain"].lower()
stored = packs.get(name, {})
items.append({
"domain": name,
"packs": {
kind: {**stored[kind], "url": _pack_url(kind, name)} if kind in stored else None
for kind in PACK_TYPES
},
})
return {
"storage_configured": bool(NC_USER and NC_PASSWORD),
"types": {k: v["label"] for k, v in PACK_TYPES.items()},
"domains": items,
}
@router.put("/packs/{domain}/{kind}")
def upload_pack(domain: str, kind: str, file: UploadFile) -> dict:
_require_storage()
_check_kind(kind)
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 PACK_TYPES[kind]["mcmeta"] and not has_meta:
raise HTTPException(
status_code=400,
detail="zip 최상위에 pack.mcmeta 가 없습니다. 폴더째 압축하지 말고 폴더 안의 내용물을 압축해 주세요.",
)
with _client(timeout=None) as client:
_ensure_dir(client, name)
tmp.seek(0)
r = client.put(
_dav_url(name, f"{kind}.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"{kind}.zip",
"uploaded_at": time.time(),
}
with _lock:
packs = _load_packs()
packs.setdefault(name, {})[kind] = meta
_save_packs(packs)
return {"domain": name, "kind": kind, "pack": {**meta, "url": _pack_url(kind, name)}}
@router.delete("/packs/{domain}/{kind}", status_code=204)
def delete_pack(domain: str, kind: str) -> Response:
_require_storage()
_check_kind(kind)
name = domain.strip().lower()
with _lock:
packs = _load_packs()
if kind not in packs.get(name, {}):
raise HTTPException(status_code=404, detail="pack not found")
with _client() as client:
r = client.delete(_dav_url(name, f"{kind}.zip"))
if r.status_code not in (204, 404):
raise HTTPException(status_code=502, detail=f"Nextcloud 삭제 실패: {r.status_code}")
packs[name].pop(kind)
if not packs[name]:
packs.pop(name)
_save_packs(packs)
return Response(status_code=204)
@public_router.get("/pack/{filename}")
def download_pack(filename: str, domain: str = "") -> StreamingResponse:
if not filename.endswith(".zip"):
raise HTTPException(status_code=404)
kind = filename[: -len(".zip")]
name = domain.strip().lower()
if kind not in _load_packs().get(name, {}) 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(name, f"{kind}.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="{kind}.zip"'}
if "content-length" in upstream.headers:
headers["Content-Length"] = upstream.headers["content-length"]
return StreamingResponse(body(), media_type="application/zip", headers=headers)