fix(packs): serialize same-pack upload/delete; clipboard fallback on http dashboard
- per (domain, type) lock held from the Nextcloud PUT/DELETE through the packs.json write,
so two concurrent replaces can't leave the file and its SHA1 out of sync
- navigator.clipboard is missing on http://<LAN-IP>; fall back to execCommand('copy')
and tell the user to copy by hand if that fails too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -40,7 +40,18 @@ PACK_TYPES = {
|
|||||||
"modpack": {"label": "모드팩", "mcmeta": False},
|
"modpack": {"label": "모드팩", "mcmeta": False},
|
||||||
}
|
}
|
||||||
|
|
||||||
_lock = threading.Lock()
|
_lock = threading.Lock() # packs.json 읽기-수정-쓰기 보호
|
||||||
|
_pack_locks: dict[tuple[str, str], threading.Lock] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _pack_lock(name: str, kind: str) -> threading.Lock:
|
||||||
|
"""같은 도메인·종류의 업로드/삭제를 Nextcloud 작업부터 메타 저장까지 한 줄로 세운다.
|
||||||
|
|
||||||
|
두 탭에서 동시에 교체하면 PUT 순서와 packs.json 저장 순서가 엇갈려 파일과 SHA1 이
|
||||||
|
어긋날 수 있어서다. uvicorn 워커가 1개(Dockerfile CMD 기본값)라 프로세스 내 락으로 충분하다.
|
||||||
|
"""
|
||||||
|
with _lock:
|
||||||
|
return _pack_locks.setdefault((name, kind), threading.Lock())
|
||||||
|
|
||||||
|
|
||||||
def _load_packs() -> dict:
|
def _load_packs() -> dict:
|
||||||
@@ -149,27 +160,27 @@ def upload_pack(domain: str, kind: str, file: UploadFile) -> dict:
|
|||||||
detail="zip 최상위에 pack.mcmeta 가 없습니다. 폴더째 압축하지 말고 폴더 안의 내용물을 압축해 주세요.",
|
detail="zip 최상위에 pack.mcmeta 가 없습니다. 폴더째 압축하지 말고 폴더 안의 내용물을 압축해 주세요.",
|
||||||
)
|
)
|
||||||
|
|
||||||
with _client(timeout=None) as client:
|
meta = {
|
||||||
_ensure_dir(client, name)
|
"sha1": sha1.hexdigest(),
|
||||||
tmp.seek(0)
|
"size": size,
|
||||||
r = client.put(
|
"original_name": file.filename or f"{kind}.zip",
|
||||||
_dav_url(name, f"{kind}.zip"),
|
}
|
||||||
content=iter(lambda: tmp.read(1024 * 1024), b""),
|
with _pack_lock(name, kind):
|
||||||
headers={"Content-Length": str(size)},
|
with _client(timeout=None) as client:
|
||||||
)
|
_ensure_dir(client, name)
|
||||||
if r.status_code not in (201, 204):
|
tmp.seek(0)
|
||||||
raise HTTPException(status_code=502, detail=f"Nextcloud 업로드 실패: {r.status_code}")
|
r = client.put(
|
||||||
|
_dav_url(name, f"{kind}.zip"),
|
||||||
meta = {
|
content=iter(lambda: tmp.read(1024 * 1024), b""),
|
||||||
"sha1": sha1.hexdigest(),
|
headers={"Content-Length": str(size)},
|
||||||
"size": size,
|
)
|
||||||
"original_name": file.filename or f"{kind}.zip",
|
if r.status_code not in (201, 204):
|
||||||
"uploaded_at": time.time(),
|
raise HTTPException(status_code=502, detail=f"Nextcloud 업로드 실패: {r.status_code}")
|
||||||
}
|
meta["uploaded_at"] = time.time()
|
||||||
with _lock:
|
with _lock:
|
||||||
packs = _load_packs()
|
packs = _load_packs()
|
||||||
packs.setdefault(name, {})[kind] = meta
|
packs.setdefault(name, {})[kind] = meta
|
||||||
_save_packs(packs)
|
_save_packs(packs)
|
||||||
return {"domain": name, "kind": kind, "pack": {**meta, "url": _pack_url(kind, name)}}
|
return {"domain": name, "kind": kind, "pack": {**meta, "url": _pack_url(kind, name)}}
|
||||||
|
|
||||||
|
|
||||||
@@ -178,18 +189,19 @@ def delete_pack(domain: str, kind: str) -> Response:
|
|||||||
_require_storage()
|
_require_storage()
|
||||||
_check_kind(kind)
|
_check_kind(kind)
|
||||||
name = domain.strip().lower()
|
name = domain.strip().lower()
|
||||||
with _lock:
|
with _pack_lock(name, kind):
|
||||||
packs = _load_packs()
|
if kind not in _load_packs().get(name, {}):
|
||||||
if kind not in packs.get(name, {}):
|
|
||||||
raise HTTPException(status_code=404, detail="pack not found")
|
raise HTTPException(status_code=404, detail="pack not found")
|
||||||
with _client() as client:
|
with _client() as client:
|
||||||
r = client.delete(_dav_url(name, f"{kind}.zip"))
|
r = client.delete(_dav_url(name, f"{kind}.zip"))
|
||||||
if r.status_code not in (204, 404):
|
if r.status_code not in (204, 404):
|
||||||
raise HTTPException(status_code=502, detail=f"Nextcloud 삭제 실패: {r.status_code}")
|
raise HTTPException(status_code=502, detail=f"Nextcloud 삭제 실패: {r.status_code}")
|
||||||
packs[name].pop(kind)
|
with _lock:
|
||||||
if not packs[name]:
|
packs = _load_packs()
|
||||||
packs.pop(name)
|
packs[name].pop(kind, None)
|
||||||
_save_packs(packs)
|
if not packs[name]:
|
||||||
|
packs.pop(name)
|
||||||
|
_save_packs(packs)
|
||||||
return Response(status_code=204)
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,25 @@ function propsSnippet(pack) {
|
|||||||
].join('\n')
|
].join('\n')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 대시보드는 http://<내부IP> 라 보안 컨텍스트가 아니어서 navigator.clipboard 가 없다.
|
||||||
|
// 그럴 땐 임시 textarea + execCommand('copy') 로 복사한다.
|
||||||
|
async function copyToClipboard(text) {
|
||||||
|
if (navigator.clipboard && window.isSecureContext) {
|
||||||
|
try { await navigator.clipboard.writeText(text); return true } catch { /* 아래로 */ }
|
||||||
|
}
|
||||||
|
const ta = document.createElement('textarea')
|
||||||
|
ta.value = text
|
||||||
|
ta.setAttribute('readonly', '')
|
||||||
|
ta.style.position = 'fixed'
|
||||||
|
ta.style.opacity = '0'
|
||||||
|
document.body.appendChild(ta)
|
||||||
|
ta.select()
|
||||||
|
let ok = false
|
||||||
|
try { ok = document.execCommand('copy') } catch { ok = false }
|
||||||
|
document.body.removeChild(ta)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
// fetch 는 업로드 진행률을 못 주므로 XHR 사용
|
// fetch 는 업로드 진행률을 못 주므로 XHR 사용
|
||||||
function uploadPack(domain, kind, file, onProgress) {
|
function uploadPack(domain, kind, file, onProgress) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
@@ -89,7 +108,10 @@ export default function Packs() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function copy(key, text) {
|
async function copy(key, text) {
|
||||||
await navigator.clipboard.writeText(text)
|
if (!(await copyToClipboard(text))) {
|
||||||
|
setError('복사하지 못했습니다. 위 칸의 내용을 직접 선택해서 복사해 주세요.')
|
||||||
|
return
|
||||||
|
}
|
||||||
setCopied(key)
|
setCopied(key)
|
||||||
setTimeout(() => setCopied(null), 1500)
|
setTimeout(() => setCopied(null), 1500)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user