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>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"""도메인별 리소스팩: Nextcloud(share.tkrmagid.kr) 에 저장하고 공개 경로로 내려준다.
|
||||
"""도메인별 팩(리소스팩/데이터팩/모드팩): Nextcloud(share.tkrmagid.kr) 에 저장하고 공개 경로로 내려준다.
|
||||
|
||||
- 업로드/삭제/목록은 대시보드용 /api/packs (인증 없음, 내부망 전용)
|
||||
- 클라이언트 다운로드는 /pack/<domain>.zip (외부 공개). Nextcloud 에서 받아 그대로 스트리밍한다.
|
||||
- 다운로드는 /pack/<종류>.zip?domain=<도메인> (외부 공개). Nextcloud 에서 받아 그대로 스트리밍한다.
|
||||
Nextcloud 공유 링크의 /download 는 http:// 로 303 리다이렉트를 주는데,
|
||||
MC 클라이언트(HttpURLConnection)는 https→http 리다이렉트를 따라가지 않아서 직접 중계한다.
|
||||
"""
|
||||
@@ -10,7 +10,6 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
@@ -34,6 +33,13 @@ 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()
|
||||
|
||||
|
||||
@@ -69,9 +75,9 @@ def _require_storage() -> None:
|
||||
)
|
||||
|
||||
|
||||
def _ensure_dir(client: httpx.Client) -> None:
|
||||
# NC_DIR 의 각 단계를 순서대로 MKCOL (이미 있으면 405)
|
||||
parts = NC_DIR.split("/")
|
||||
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]
|
||||
@@ -85,8 +91,13 @@ 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"
|
||||
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")
|
||||
@@ -95,17 +106,25 @@ def list_packs() -> dict:
|
||||
items = []
|
||||
for d in load_config().get("allowed_domains", []):
|
||||
name = d["domain"].lower()
|
||||
meta = packs.get(name)
|
||||
stored = packs.get(name, {})
|
||||
items.append({
|
||||
"domain": name,
|
||||
"pack": {**meta, "url": _pack_url(name)} if meta else None,
|
||||
"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), "packs": items}
|
||||
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}")
|
||||
def upload_pack(domain: str, file: UploadFile) -> dict:
|
||||
@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")
|
||||
@@ -124,17 +143,17 @@ def upload_pack(domain: str, file: UploadFile) -> dict:
|
||||
has_meta = "pack.mcmeta" in zf.namelist()
|
||||
except zipfile.BadZipFile:
|
||||
raise HTTPException(status_code=400, detail="zip 파일이 아닙니다.")
|
||||
if not has_meta:
|
||||
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)
|
||||
_ensure_dir(client, name)
|
||||
tmp.seek(0)
|
||||
r = client.put(
|
||||
_dav_url(f"{name}.zip"),
|
||||
_dav_url(name, f"{kind}.zip"),
|
||||
content=iter(lambda: tmp.read(1024 * 1024), b""),
|
||||
headers={"Content-Length": str(size)},
|
||||
)
|
||||
@@ -144,44 +163,48 @@ def upload_pack(domain: str, file: UploadFile) -> dict:
|
||||
meta = {
|
||||
"sha1": sha1.hexdigest(),
|
||||
"size": size,
|
||||
"original_name": file.filename or f"{name}.zip",
|
||||
"original_name": file.filename or f"{kind}.zip",
|
||||
"uploaded_at": time.time(),
|
||||
}
|
||||
with _lock:
|
||||
packs = _load_packs()
|
||||
packs[name] = meta
|
||||
packs.setdefault(name, {})[kind] = meta
|
||||
_save_packs(packs)
|
||||
return {"domain": name, "pack": {**meta, "url": _pack_url(name)}}
|
||||
return {"domain": name, "kind": kind, "pack": {**meta, "url": _pack_url(kind, name)}}
|
||||
|
||||
|
||||
@router.delete("/packs/{domain}", status_code=204)
|
||||
def delete_pack(domain: str) -> Response:
|
||||
@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 name not in 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(f"{name}.zip"))
|
||||
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.pop(name)
|
||||
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) -> StreamingResponse:
|
||||
def download_pack(filename: str, domain: 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:
|
||||
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(f"{name}.zip"), headers={"Accept-Encoding": "identity"}
|
||||
"GET", _dav_url(name, f"{kind}.zip"), headers={"Accept-Encoding": "identity"}
|
||||
), stream=True)
|
||||
if upstream.status_code != 200:
|
||||
upstream.close()
|
||||
@@ -195,7 +218,7 @@ def download_pack(filename: str) -> StreamingResponse:
|
||||
upstream.close()
|
||||
client.close()
|
||||
|
||||
headers = {"Content-Disposition": f'attachment; filename="{name}.zip"'}
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user