From dd8680b018e6ea98e4356beaedb7c62483ecd9c3 Mon Sep 17 00:00:00 2001 From: badkid Date: Fri, 27 Nov 2026 20:22:33 -0600 Subject: [PATCH 1/6] feat(friends): real P2P file transfers, bulk platform recovery sync, bidirectional permissions, and netplay dump fetch --- romarr/app.py | 444 ++++++++++++++++++++++++++++++++++++++- romarr/openapi.py | 10 + romarr/ui.py | 150 +++++++++++-- tests/test_federation.py | 96 +++++++++ 4 files changed, 674 insertions(+), 26 deletions(-) diff --git a/romarr/app.py b/romarr/app.py index a5b313f07..9608ed5ac 100644 --- a/romarr/app.py +++ b/romarr/app.py @@ -7178,7 +7178,105 @@ def _calendar_day(day: str, cursor, length: int, counts, today) -> int: def peer_shelf(self, peer) -> list[dict]: """The projection this peer is allowed to see, from the live cache.""" games, _, _ = self._library_cache - return self.federation.project(peer, games or []) + projected = self.federation.project(peer, games or []) + if peer.access == "fetch": + for row in projected: + row["fetchable"] = True + return projected + + def _library_roots(self) -> list[Path]: + """All configured local library roots, deduplicated and resolved.""" + roots: list[Path] = [] + seen: set[str] = set() + candidates = [self.library] + [self.library_root(cfg) for cfg, _ in self.game_libraries] + for root in candidates: + if not root: + continue + try: + resolved = Path(root).resolve() + except OSError: + continue + key = str(resolved) + if key not in seen and resolved.is_dir(): + seen.add(key) + roots.append(resolved) + return roots + + def peer_resolve_file(self, peer, title: str, platform: str = "") -> tuple[Path | None, str, str]: + """Resolve one local ROM file a confirmed `fetch` peer is allowed to download. + + Returns `(path, platform_slug, error)`. Never accepts a filesystem path + from the peer and always verifies containment inside a library root. + """ + if peer is None or not peer.confirmed: + return None, "", "unknown or unconfirmed peer" + if peer.access != "fetch": + return None, "", "this server has not enabled 'Download from me' (fetch) for you" + want_title = str(title or "").strip().lower() + want_plat = str(platform or "").strip().lower() + if not want_title: + return None, "", "missing title" + games, _, _ = self._library_cache + matched = None + for game in (games or []): + if not peer.may_see(game): + continue + g_name = str(getattr(game, "name", "") or "").strip().lower() + g_plat = str(getattr(game, "platform", "") or "").strip().lower() + if g_name == want_title and (not want_plat or g_plat == want_plat): + matched = game + break + if matched is None: + return None, "", "that game is not shared with you" + plat_slug = str(getattr(matched, "platform", "") or want_plat or "").strip().lower() + file_name = str(getattr(matched, "file_name", "") or "").strip() + roots = self._library_roots() + if not roots: + return None, plat_slug, "no readable local library folder on this server" + + def _safe_file(candidate: Path, root: Path) -> Path | None: + try: + if candidate.is_symlink() or not candidate.is_file(): + return None + resolved = candidate.resolve() + if not resolved.is_relative_to(root): + return None + return resolved + except OSError: + return None + + # 1. Exact filename lookup under platform folders (flat & nested layouts) + if file_name: + safe_rel = Path(file_name).name + for root in roots: + search_dirs = [root] + if plat_slug: + search_dirs = [root / plat_slug, root / plat_slug / "roms", root] + for folder in search_dirs: + found = _safe_file(folder / safe_rel, root) + if found is not None: + return found, plat_slug, "" + # Subfolder match (e.g. multi-file or game folder) + if plat_slug and (root / plat_slug).is_dir(): + for child in (root / plat_slug).rglob(safe_rel): + found = _safe_file(child, root) + if found is not None: + return found, plat_slug, "" + + # 2. Stem-based match inside the platform folder (e.g. Title.zip / Title.iso) + for root in roots: + for folder in ([root / plat_slug, root / plat_slug / "roms"] if plat_slug else [root]): + if not folder.is_dir(): + continue + try: + for entry in folder.iterdir(): + if entry.stem.lower() == want_title or entry.name.lower() == want_title: + found = _safe_file(entry, root) + if found is not None: + return found, plat_slug, "" + except OSError: + continue + return None, plat_slug, "file is not stored locally on disk on this friend's server" def peer_request(self, peer, title: str, platform: str) -> dict: """A peer asking me to acquire something. @@ -7815,25 +7913,36 @@ def friend_shelf(self, peer_id: str, *, q: str = "", platform: str = "", "total": 0} if not err: self._friend_shelves[peer.peer_id] = (rows, - time.monotonic()) + time.monotonic(), + "catalogue", "all") rows = self._friend_shelves[peer.peer_id][0] return {**self._slice_shelf(rows, q, platform, offset, limit), "ok": True, "friend": peer.name, "kind": "romm", - "access": "catalogue"} + "access": "catalogue", "my_access": peer.access} body, err = self._call_friend(peer, "GET", "/api/v1/peer/shelf") if body is None: if cached is None: return {"ok": False, "error": err, "items": [], "total": 0} # Serve what we last saw rather than blanking the page. - rows, at = cached + rows = cached[0] + remote_access = cached[2] if len(cached) > 2 else "catalogue" return {**self._slice_shelf(rows, q, platform, offset, limit), "ok": True, "stale": True, "error": err, - "friend": peer.name} + "friend": peer.name, "access": remote_access, + "my_access": peer.access} rows = [r for r in (body.get("items") or []) if isinstance(r, dict)] - self._friend_shelves[peer.peer_id] = (rows, time.monotonic()) - rows = self._friend_shelves[peer.peer_id][0] + remote_access = str(body.get("access") or ( + "fetch" if any(r.get("fetchable") for r in rows) else "catalogue")) + remote_scope = str(body.get("scope") or "") + self._friend_shelves[peer.peer_id] = (rows, time.monotonic(), + remote_access, remote_scope) + entry = self._friend_shelves[peer.peer_id] + rows = entry[0] + remote_access = entry[2] if len(entry) > 2 else "catalogue" + remote_scope = entry[3] if len(entry) > 3 else "" return {**self._slice_shelf(rows, q, platform, offset, limit), - "ok": True, "friend": peer.name, "access": peer.access} + "ok": True, "friend": peer.name, "access": remote_access, + "remote_scope": remote_scope, "my_access": peer.access} @staticmethod def _slice_shelf(rows, q: str, platform: str, offset: int, @@ -7872,6 +7981,258 @@ def friend_want(self, peer_id: str, title: str, platform: str) -> dict: return {"ok": True, "title": title, "platform": platform, "detail": f"added to Wanted -- your indexers will look for it"} + # -- P2P friend file transfers & bulk platform recovery ----------------- + + def _p2p_state(self): + with self._lock: + if not hasattr(self, "_p2p_transfers"): + self._p2p_transfers: list[dict] = [] + self._p2p_cancel: set[str] = set() + self._p2p_worker = None + return self._p2p_transfers, self._p2p_cancel + + def friend_transfers_status(self) -> dict: + """Snapshot of active and recent P2P downloads from friends.""" + transfers, _ = self._p2p_state() + with self._lock: + rows = [dict(t) for t in transfers[-60:]] + active = sum(1 for r in rows if r["state"] in ("queued", "downloading", "importing")) + return {"ok": True, "active": active, "items": list(reversed(rows))} + + def friend_transfers_cancel(self, transfer_id: str = "", cancel_all: bool = False) -> dict: + """Cancel one or all active/queued P2P friend transfers.""" + transfers, cancel_set = self._p2p_state() + cancelled = 0 + with self._lock: + for item in transfers: + if item["state"] not in ("queued", "downloading"): + continue + if cancel_all or item["id"] == transfer_id: + cancel_set.add(item["id"]) + if item["state"] == "queued": + item["state"] = "cancelled" + item["detail"] = "Cancelled before starting" + cancelled += 1 + return {"ok": True, "cancelled": cancelled} + + def friend_fetch(self, peer_id: str, title: str, platform: str = "") -> dict: + """Enqueue a direct P2P download of one game from a friend's server.""" + import secrets + peer, why = self._friend(peer_id) + if peer is None: + return {"ok": False, "error": why} + if peer.kind != "romarr": + return {"ok": False, "error": "Direct P2P fetch requires a ROMarr peer"} + title = str(title or "").strip() + platform = str(platform or "").strip().lower() + if not title: + return {"ok": False, "error": "no title specified"} + transfers, _ = self._p2p_state() + job = { + "id": secrets.token_hex(6), + "peer_id": peer.peer_id, + "friend": peer.name, + "title": title, + "platform": platform, + "filename": "", + "state": "queued", + "bytes_done": 0, + "bytes_total": 0, + "percent": 0.0, + "speed_bps": 0, + "detail": f"Queued from {peer.name}", + "error": "", + "created": datetime.now(timezone.utc).isoformat(timespec="seconds"), + } + with self._lock: + transfers.append(job) + if len(transfers) > 200: + del transfers[:-200] + self._ensure_p2p_worker() + return {"ok": True, "job": dict(job), "detail": f"Queued '{title}' from {peer.name}"} + + def friend_sync_platform(self, peer_id: str, platform: str, *, + dry_run: bool = True, limit: int = 500) -> dict: + """Compare a friend's platform against your library and optionally pull all missing games.""" + plat = str(platform or "").strip().lower() + if not plat: + return {"ok": False, "error": "choose a platform to compare"} + shelf = self.friend_shelf(peer_id, platform=plat, offset=0, limit=1000, refresh=dry_run) + if not shelf.get("ok"): + return {"ok": False, "error": shelf.get("error") or "could not read friend's library"} + remote_items = shelf.get("items") or [] + games, _, _ = self._library_cache + owned = { + str(getattr(g, "name", "") or "").strip().lower() + for g in (games or []) + if str(getattr(g, "platform", "") or "").strip().lower() == plat + } + missing = [ + {"title": r.get("title", ""), "platform": r.get("platform", plat), + "verified": bool(r.get("verified", False))} + for r in remote_items + if str(r.get("title") or "").strip().lower() not in owned + ] + can_fetch = shelf.get("access") == "fetch" + if dry_run: + return { + "ok": True, + "friend": shelf.get("friend") or "", + "platform": plat, + "access": shelf.get("access") or "catalogue", + "can_fetch": can_fetch, + "remote_total": len(remote_items), + "already_have": len(remote_items) - len(missing), + "missing_count": len(missing), + "missing": missing[:200], + } + if not can_fetch: + return { + "ok": False, + "error": f"{shelf.get('friend') or 'This friend'} has not enabled 'Download from me' (fetch) for you yet.", + } + cap = max(1, min(int(limit or 500), 1000)) + queued = 0 + for item in missing[:cap]: + res = self.friend_fetch(peer_id, item["title"], item["platform"]) + if res.get("ok"): + queued += 1 + return { + "ok": True, + "friend": shelf.get("friend") or "", + "platform": plat, + "queued": queued, + "missing_count": len(missing), + "detail": f"Queued {queued} missing {plat} game(s) from {shelf.get('friend') or 'friend'}", + } + + def _ensure_p2p_worker(self) -> None: + with self._lock: + worker = getattr(self, "_p2p_worker", None) + if worker is not None and worker.is_alive(): + return + worker = threading.Thread(target=self._p2p_worker_loop, name="romarr-p2p", daemon=True) + self._p2p_worker = worker + worker.start() + + def _p2p_worker_loop(self) -> None: + transfers, cancel_set = self._p2p_state() + while True: + job = None + with self._lock: + for item in transfers: + if item["state"] == "queued": + if item["id"] in cancel_set: + item["state"] = "cancelled" + continue + item["state"] = "downloading" + item["detail"] = f"Connecting to {item['friend']}…" + job = item + break + if job is None: + return + self._run_one_p2p_transfer(job) + + def _run_one_p2p_transfer(self, job: dict) -> None: + import requests as _rq + import shutil + from urllib.parse import quote + from .federation import url_candidates + + _, cancel_set = self._p2p_state() + peer = self.federation.peers.get(job["peer_id"]) + if peer is None or not peer.confirmed: + job["state"], job["error"] = "failed", "peer is no longer connected" + return + candidates = url_candidates(peer.url) + if not candidates: + job["state"], job["error"] = "failed", "peer has no reachable URL" + return + + qs = f"/api/v1/peer/shelf?download=1&title={quote(job['title'])}&platform={quote(job['platform'])}" + staging_dir = Path(self.store.path).parent / "peer-staging" / job["id"] + try: + response = None + last_err = "" + for base in candidates: + try: + r = _rq.get(base.rstrip("/") + qs, headers=peer.headers(), + stream=True, timeout=(15, 120)) + except _rq.RequestException as exc: + last_err = str(exc) + continue + if r.status_code == 200: + response = r + break + try: + msg = (r.json() or {}).get("error") or f"HTTP {r.status_code}" + except ValueError: + msg = f"HTTP {r.status_code}" + r.close() + last_err = msg + if r.status_code in (401, 403, 404): + break + if response is None: + job["state"] = "failed" + job["error"] = last_err or "could not download from friend" + job["detail"] = job["error"] + return + + raw_name = response.headers.get("X-ROMarr-Filename") or f"{job['title']}.bin" + safe_name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", Path(raw_name).name).strip(" .") or "game.bin" + plat = response.headers.get("X-ROMarr-Platform") or job["platform"] + total = int(response.headers.get("Content-Length") or 0) + job["filename"] = safe_name + job["bytes_total"] = total + staging_dir.mkdir(parents=True, exist_ok=True) + dest = staging_dir / safe_name + + started = time.monotonic() + done = 0 + try: + with dest.open("wb") as handle: + for chunk in response.iter_content(chunk_size=262144): + if job["id"] in cancel_set: + response.close() + job["state"] = "cancelled" + job["detail"] = "Cancelled" + return + if not chunk: + continue + handle.write(chunk) + done += len(chunk) + elapsed = max(0.05, time.monotonic() - started) + job["bytes_done"] = done + job["speed_bps"] = int(done / elapsed) + job["percent"] = round((done / total) * 100.0, 1) if total > 0 else 0.0 + job["detail"] = f"Downloading {safe_name} ({done // 1048576} MB)" + finally: + response.close() + + job["state"] = "importing" + job["percent"] = 100.0 + job["detail"] = f"Verifying & importing {safe_name}…" + adopted = self.adopt(str(dest), plat, force=False) + if adopted.get("ok"): + job["state"] = "done" + job["detail"] = f"Imported {safe_name} from {job['friend']}" + self.store.record(Event( + kind="imported", game=job["title"], platform=plat, + release=safe_name, indexer=f"Friend: {job['friend']}", + detail="Direct P2P transfer from friend")) + self.store.save() + else: + refused = (adopted.get("refused") or [{}])[0] + job["state"] = "failed" + job["error"] = refused.get("reason") or adopted.get("reason") or adopted.get("error") or "Import refused" + job["detail"] = job["error"] + except Exception as exc: # noqa: BLE001 + job["state"] = "failed" + job["error"] = str(exc) + job["detail"] = str(exc) + finally: + shutil.rmtree(staging_dir, ignore_errors=True) + def netplay_invite(self, peer_id: str, title: str, platform: str = "") -> dict: """Offer a friend a game, and report honestly what came back. @@ -11224,8 +11585,58 @@ def _int(name: str, default: int) -> int: self.headers.get("X-Peer-Token", "")) if peer is None: return self._json(401, {"error": "unknown peer"}) + if (query.get("download") or [""])[0] == "1": + title = (query.get("title") or [""])[0] + plat = (query.get("platform") or [""])[0] + fpath, plat_slug, err = service.peer_resolve_file(peer, title, plat) + if fpath is None: + code = 403 if "not enabled" in err else 404 + return self._json(code, {"error": err}) + size = fpath.stat().st_size + start, end = 0, size - 1 + status = 200 + rng = self.headers.get("Range", "") + if rng.startswith("bytes=") and size > 0: + part = rng[6:].split(",", 1)[0].strip() + a, _, b = part.partition("-") + try: + start = int(a) if a else 0 + end = int(b) if b else size - 1 + if 0 <= start <= end < size: + status = 206 + else: + start, end = 0, size - 1 + except ValueError: + start, end = 0, size - 1 + length = max(0, end - start + 1) if size > 0 else 0 + self.send_response(status) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Length", str(length)) + if status == 206: + self.send_header("Content-Range", f"bytes {start}-{end}/{size}") + safe_disp = fpath.name.replace('"', "_").replace("\r", "").replace("\n", "") + self.send_header("Content-Disposition", f'attachment; filename="{safe_disp}"') + self.send_header("X-ROMarr-Filename", safe_disp) + self.send_header("X-ROMarr-Platform", plat_slug) + self.end_headers() + with fpath.open("rb") as handle: + if start: + handle.seek(start) + remaining = length + while remaining > 0: + chunk = handle.read(min(262144, remaining)) + if not chunk: + break + self.wfile.write(chunk) + remaining -= len(chunk) + return return self._json(200, {"items": service.peer_shelf(peer), - "origin": service.federation.name}) + "origin": service.federation.name, + "access": peer.access, + "scope": peer.scope}) + if route.path == "/api/v1/friends/transfers": + return self._json(200, service.friend_transfers_status()) if route.path == "/api/v1/hashes": # What netplay can actually prove. Without this an operator # has no way to tell "we disagree on the dump" apart from @@ -12179,6 +12590,21 @@ def _post(self): str(body.get("peer_id") or ""), str(body.get("title") or ""), str(body.get("platform") or ""))) + if route.path == "/api/v1/friends/fetch": + return self._json(200, service.friend_fetch( + str(body.get("peer_id") or ""), + str(body.get("title") or ""), + str(body.get("platform") or ""))) + if route.path == "/api/v1/friends/sync": + return self._json(200, service.friend_sync_platform( + str(body.get("peer_id") or ""), + str(body.get("platform") or ""), + dry_run=bool(body.get("dry_run", True)), + limit=int(body.get("limit") or 500))) + if route.path == "/api/v1/friends/transfers/cancel": + return self._json(200, service.friend_transfers_cancel( + str(body.get("id") or ""), + cancel_all=bool(body.get("all", False)))) if route.path == "/api/v1/audit/quarantine/move": return self._json(200, service.quarantine_duplicates( str(body.get("platform") or ""), diff --git a/romarr/openapi.py b/romarr/openapi.py index 38761ba19..6a29ef98b 100644 --- a/romarr/openapi.py +++ b/romarr/openapi.py @@ -385,6 +385,16 @@ "/api/v1/friends/netplay": ("POST", "Offer a friend a game to play, " "carrying the SHA1 of your dump so " "both sides agree on the bytes."), + "/api/v1/friends/fetch": ("POST", "Download one game directly P2P from a " + "confirmed friend whose sharing policy " + "grants fetch access."), + "/api/v1/friends/sync": ("POST", "Compare a friend's platform against your " + "library and optionally pull all missing " + "games directly P2P."), + "/api/v1/friends/transfers": ("GET", "Live status and progress of active " + "and recent P2P friend transfers."), + "/api/v1/friends/transfers/cancel": ("POST", "Cancel one or all active/queued " + "P2P friend transfers."), "/api/v1/ecosystem": ("GET", "The projects ROMarr stands on: library " "servers, players, indexers, DAT databases " "-- repo, site and install command for each."), diff --git a/romarr/ui.py b/romarr/ui.py index 0da3fed1c..bb79e5f0d 100644 --- a/romarr/ui.py +++ b/romarr/ui.py @@ -3632,7 +3632,7 @@ def _nav_html() -> str:
${list.length?`

Your friends

- +
NameThey seeThey may
${list.map((p,i)=>` - `).join('')}
NameYou share (scope)You allow (access) State
${esc(p.name)} ${p.kind==='romm'?' RomM':''} @@ -3640,20 +3640,21 @@ def _nav_html() -> str: ${esc(scopeLabel[p.scope]||p.scope)}${ p.scope==='platforms'&&(p.platforms||[]).length ?`
${esc(p.platforms.join(', '))}
`:''}
${esc(accessLabel[p.access]||p.access)}${ + ${p.access==='fetch'?'Download from me':esc(accessLabel[p.access]||p.access)}${ p.delegate_users?' their users too':''} ${p.confirmed?'confirmed' :'awaiting your confirmation'}
- ${p.confirmed?` + >Browse & Pull ` :``}
+
` :'
No friends yet. Invite someone, or paste an invitation they sent you.
'}`; @@ -3838,6 +3839,7 @@ def _nav_html() -> str: } }; seedPoll(); + refreshPeerTransfers(); $('#p-seed').onclick=async()=>{ const b=$('#p-seed'); @@ -3847,6 +3849,7 @@ def _nav_html() -> str: b.disabled=false; b.textContent='Read them again now'; toast(r.detail||r.error||''); seedPoll(); + refreshPeerTransfers(); }; $('#p-romm').onclick=()=>{ @@ -3891,6 +3894,51 @@ def _nav_html() -> str: }; }; +//: Live P2P transfer monitor on the Friends page. +let PEER_XFER_TIMER=null; +async function refreshPeerTransfers(){ + if(PEER_XFER_TIMER){clearTimeout(PEER_XFER_TIMER);PEER_XFER_TIMER=null;} + const box=$('#p-transfers'); + if(!box||location.hash.replace('#','')!=='peers') return; + const d=await j('/api/v1/friends/transfers').catch(()=>null); + if(!d||!d.ok||!box.isConnected) return; + const rows=d.items||[]; + if(!rows.length){box.innerHTML='';return;} + const mb=n=>n>=1073741824?(n/1073741824).toFixed(2)+' GB':n>=1048576?(n/1048576).toFixed(1)+' MB':n>0?(n/1024).toFixed(0)+' KB':'—'; + const pillCls=st=>st==='done'?'imported':st==='failed'||st==='cancelled'?'failed':''; + box.innerHTML=`
+
+ P2P Friend Transfers ${d.active?`(${d.active} active)`:''} +
+ ${d.active?'':''} + +
+
+ + ${rows.slice(0,25).map(t=>` + + + + + + `).join('')}
GameFriendProgressState
${esc(t.title)} ${esc(t.platform||'')} + ${t.detail?`
${esc(t.detail)}
`:''}
${esc(t.friend||'')}${t.state==='downloading' + ?`${t.percent||0}% · ${mb(t.bytes_done)} / ${mb(t.bytes_total)} · ${mb(t.speed_bps)}/s` + :t.bytes_total?mb(t.bytes_total):'—'}${esc(t.state)}${['queued','downloading'].includes(t.state) + ?``:''}
`; + const ref=$('#px-refresh'); if(ref) ref.onclick=refreshPeerTransfers; + const call=$('#px-cancel-all'); + if(call) call.onclick=async()=>{ + await j('/api/v1/friends/transfers/cancel',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({all:true})}); + toast('Cancelled active P2P transfers'); refreshPeerTransfers(); + }; + box.querySelectorAll('[data-pxcancel]').forEach(b=>b.onclick=async()=>{ + await j('/api/v1/friends/transfers/cancel',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({id:b.dataset.pxcancel})}); + refreshPeerTransfers(); + }); + if(d.active>0) PEER_XFER_TIMER=setTimeout(refreshPeerTransfers,2000); +} + //: Browsing a friend's library. Their shelf is fetched once and filtered //: here, so typing in the search box does not bill somebody else's server //: for every keystroke. @@ -3912,20 +3960,39 @@ def _nav_html() -> str: const rows=r.items||[]; const pages=Math.ceil((r.total||0)/100); const page=Math.floor(FSHELF.offset/100)+1; + const canFetch=r.access==='fetch'&&r.kind!=='romm'; + const sortedPlats=(r.platforms||[]).slice().sort((a,b)=>a.localeCompare(b,undefined,{sensitivity:'base',numeric:true})); out.innerHTML=`
-

${esc(r.friend||'Your friend')}’s library

+
+

${esc(r.friend||'Your friend')}’s library

+
+ ${canFetch + ?'✓ They allow Direct P2P Download' + :'They allow: '+esc(r.access||'catalogue')+' (ask them to set Sharing → Download from me)'} +
+

${r.total||0} of ${r.shelf_total||0} shared title(s). - ${r.access==='catalogue' - ? 'You can add anything here to your own Wanted list — your ' - +'indexers fetch it, not your friend.' - : 'They allow: '+esc(r.access||'')} - ${r.stale?'Showing the last copy — their server did not answer.':''}

+ ${canFetch + ? 'You can download individual games directly P2P or pull an entire missing platform collection below.' + : 'You can add anything here to your own Wanted list — your indexers fetch it, not your friend.'} + ${r.stale?' Showing the last copy — their server did not answer.':''}

+ ${sortedPlats.length?`
+
+ Bulk Platform Recovery / Missing Sync: + + + ${canFetch?'':''} +
+
+
`:''}
@@ -3938,6 +4005,8 @@ def _nav_html() -> str: ${g.year||''} ${g.verified?'verified':''}
+ ${canFetch?``:''}
`; + } + if(fetchCtx&&(r.status==='mismatch'||r.status==='missing'||r.status==='unhashed')){ + extra+=`
`; } if(r.sha1){ extra+=`
diff --git a/tests/test_federation.py b/tests/test_federation.py index 1d30a1f57..543c9279f 100644 --- a/tests/test_federation.py +++ b/tests/test_federation.py @@ -419,3 +419,99 @@ def test_a_romm_friend_survives_a_restart_with_its_credential(): back = restarted.peers[peer.peer_id] assert back.kind == "romm" assert (back.username, back.password) == ("me", "secret") + + +def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): + """End-to-end two-server P2P: Borb shares PS2 with fetch; Ant compares and pulls missing.""" + import threading + import time + from http.server import ThreadingHTTPServer + import requests + from romarr.app import ROMarr, make_handler + from romarr.libraries import Game + + borb_lib = tmp_path / "borb_roms" + (borb_lib / "snes").mkdir(parents=True) + payload = b"SNES-ROM-HEADER" + (b"\x01" * 65536) + b"-END" + (borb_lib / "snes" / "Chrono Trigger (USA).sfc").write_bytes(payload) + + ant_lib = tmp_path / "ant_roms" + (ant_lib / "snes").mkdir(parents=True) + + borb = ROMarr({"ROMARR_DATA": str(tmp_path / "borb.json"), + "LIBRARY_PATH": str(borb_lib), "ROMARR_API_KEY": "bk"}) + ant = ROMarr({"ROMARR_DATA": str(tmp_path / "ant.json"), + "LIBRARY_PATH": str(ant_lib), "ROMARR_API_KEY": "ak"}) + ant.store.put_item("libraries", { + "type": "folder", "name": "Ant ROMs", + "path": str(ant_lib), "is_default": True, "enable": True, + }) + ant.reload_libraries() + borb.scheduler.stop() + ant.scheduler.stop() + + borb._library_cache = ([ + Game(id="1", name="Chrono Trigger (USA)", platform="snes", + file_name="Chrono Trigger (USA).sfc"), + ], 9e18, "") + ant._library_cache = ([], 9e18, "") + + b_srv = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(borb)) + a_srv = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(ant)) + threading.Thread(target=b_srv.serve_forever, daemon=True).start() + threading.Thread(target=a_srv.serve_forever, daemon=True).start() + try: + b_url = f"http://127.0.0.1:{b_srv.server_port}" + a_url = f"http://127.0.0.1:{a_srv.server_port}" + + borb.federation.url = b_url + ant.federation.url = a_url + inv = borb.federation.invite("Borb") + ant_peer = ant.federation.redeem(inv.blob()) + borb_peer = borb.federation.accept(inv.peer_id, inv.secret, name="Ant", url=a_url) + borb.federation.confirm(borb_peer.peer_id) + + # Borb initially grants catalogue only; Ant sets outbound fetch -> Ant must see Borb's catalogue, not his own! + ant_peer.access = "fetch" + borb_peer.scope = "all" + borb_peer.access = "catalogue" + shelf = ant.friend_shelf(ant_peer.peer_id, refresh=True) + assert shelf["ok"] is True + assert shelf["access"] == "catalogue" + assert shelf["my_access"] == "fetch" + + # Direct download is refused (403) while Borb is on catalogue + r_denied = requests.get( + f"{b_url}/api/v1/peer/shelf?download=1&title=Chrono+Trigger+(USA)&platform=snes", + headers=ant_peer.headers(), timeout=5) + assert r_denied.status_code == 403 + + # Borb enables fetch -> Range request returns 206, dry-run sync reports 1 missing, pull imports it + borb_peer.access = "fetch" + r_range = requests.get( + f"{b_url}/api/v1/peer/shelf?download=1&title=Chrono+Trigger+(USA)&platform=snes", + headers={**ant_peer.headers(), "Range": "bytes=0-14"}, timeout=5) + assert r_range.status_code == 206 + assert r_range.content == b"SNES-ROM-HEADER" + + preview = ant.friend_sync_platform(ant_peer.peer_id, "snes", dry_run=True) + assert preview["ok"] is True and preview["can_fetch"] is True + assert preview["missing_count"] == 1 and preview["already_have"] == 0 + + pulled = ant.friend_sync_platform(ant_peer.peer_id, "snes", dry_run=False) + assert pulled["ok"] is True and pulled["queued"] == 1 + + deadline = time.monotonic() + 10.0 + while time.monotonic() < deadline: + st = ant.friend_transfers_status() + if st["items"] and st["items"][0]["state"] in ("done", "failed"): + break + time.sleep(0.05) + final = ant.friend_transfers_status()["items"][0] + assert final["state"] == "done", final + imported = list((ant_lib / "snes").glob("*.sfc")) + assert len(imported) == 1 + assert imported[0].read_bytes() == payload + finally: + b_srv.shutdown(); b_srv.server_close() + a_srv.shutdown(); a_srv.server_close() From b32079f4c5fcbd4d1900b41b4795b4c96004685b Mon Sep 17 00:00:00 2001 From: badkid Date: Fri, 27 Nov 2026 20:35:34 -0600 Subject: [PATCH 2/6] fix(friends): address CodeRabbit review findings for P2P resolution, queue safety, range parsing, and UI state --- romarr/app.py | 156 ++++++++++++++++++++++++++++++++++++++++---------- romarr/ui.py | 25 ++++++-- 2 files changed, 146 insertions(+), 35 deletions(-) diff --git a/romarr/app.py b/romarr/app.py index 9608ed5ac..24c0b40ed 100644 --- a/romarr/app.py +++ b/romarr/app.py @@ -7230,8 +7230,48 @@ def peer_resolve_file(self, peer, title: str, platform: str = "") -> tuple[Path return None, "", "that game is not shared with you" plat_slug = str(getattr(matched, "platform", "") or want_plat or "").strip().lower() file_name = str(getattr(matched, "file_name", "") or "").strip() - roots = self._library_roots() - if not roots: + source = str(getattr(matched, "source", "") or "").strip() + + # Select only the owning library when the matched row names a source, + # so two libraries sharing a filename can never serve the wrong file. + lib_entries: list[tuple[Path, dict]] = [] + seen_roots: set[str] = set() + if source: + for cfg, backend in self.game_libraries: + label = str(cfg.get("name") or getattr(backend, "name", "library") or "") + if label != source: + continue + root = self.library_root(cfg) + if not root: + continue + try: + resolved = Path(root).resolve() + except OSError: + continue + if resolved.is_dir() and str(resolved) not in seen_roots: + seen_roots.add(str(resolved)) + lib_entries.append((resolved, cfg)) + if not lib_entries and not source: + for cfg, _ in self.game_libraries: + root = self.library_root(cfg) + if not root: + continue + try: + resolved = Path(root).resolve() + except OSError: + continue + if resolved.is_dir() and str(resolved) not in seen_roots: + seen_roots.add(str(resolved)) + lib_entries.append((resolved, cfg)) + if self.library: + try: + resolved = Path(self.library).resolve() + if resolved.is_dir() and str(resolved) not in seen_roots: + seen_roots.add(str(resolved)) + lib_entries.append((resolved, {})) + except OSError: + pass + if not lib_entries: return None, plat_slug, "no readable local library folder on this server" def _safe_file(candidate: Path, root: Path) -> Path | None: @@ -7245,27 +7285,41 @@ def _safe_file(candidate: Path, root: Path) -> Path | None: except OSError: return None - # 1. Exact filename lookup under platform folders (flat & nested layouts) + def _plat_dirs(root: Path, cfg: dict) -> list[Path]: + dirs: list[Path] = [] + if plat_slug: + pdir = platform_dir( + root, plat_slug, + layout=self.library_layout(cfg), + platform_folders=self.platform_folders(cfg), + ) + for d in (pdir, root / plat_slug, root / plat_slug / "roms", root): + if d not in dirs: + dirs.append(d) + else: + dirs.append(root) + return dirs + + # 1. Exact filename lookup under configured platform folders if file_name: safe_rel = Path(file_name).name - for root in roots: - search_dirs = [root] - if plat_slug: - search_dirs = [root / plat_slug, root / plat_slug / "roms", root] + for root, cfg in lib_entries: + search_dirs = _plat_dirs(root, cfg) for folder in search_dirs: found = _safe_file(folder / safe_rel, root) if found is not None: return found, plat_slug, "" - # Subfolder match (e.g. multi-file or game folder) - if plat_slug and (root / plat_slug).is_dir(): - for child in (root / plat_slug).rglob(safe_rel): + # Subfolder match inside the configured platform directory + if plat_slug and search_dirs and search_dirs[0].is_dir(): + for child in search_dirs[0].rglob(safe_rel): found = _safe_file(child, root) if found is not None: return found, plat_slug, "" - # 2. Stem-based match inside the platform folder (e.g. Title.zip / Title.iso) - for root in roots: - for folder in ([root / plat_slug, root / plat_slug / "roms"] if plat_slug else [root]): + # 2. Stem-based match inside the configured platform folder + for root, cfg in lib_entries: + search_dirs = _plat_dirs(root, cfg) + for folder in search_dirs: if not folder.is_dir(): continue try: @@ -7995,8 +8049,8 @@ def friend_transfers_status(self) -> dict: """Snapshot of active and recent P2P downloads from friends.""" transfers, _ = self._p2p_state() with self._lock: + active = sum(1 for t in transfers if t["state"] in ("queued", "downloading", "importing")) rows = [dict(t) for t in transfers[-60:]] - active = sum(1 for r in rows if r["state"] in ("queued", "downloading", "importing")) return {"ok": True, "active": active, "items": list(reversed(rows))} def friend_transfers_cancel(self, transfer_id: str = "", cancel_all: bool = False) -> dict: @@ -8047,7 +8101,15 @@ def friend_fetch(self, peer_id: str, title: str, platform: str = "") -> dict: with self._lock: transfers.append(job) if len(transfers) > 200: - del transfers[:-200] + terminal = ("done", "failed", "cancelled") + excess = len(transfers) - 200 + pruned = [] + for t in transfers: + if excess > 0 and t["state"] in terminal: + excess -= 1 + continue + pruned.append(t) + transfers[:] = pruned self._ensure_p2p_worker() return {"ok": True, "job": dict(job), "detail": f"Queued '{title}' from {peer.name}"} @@ -8057,15 +8119,23 @@ def friend_sync_platform(self, peer_id: str, platform: str, *, plat = str(platform or "").strip().lower() if not plat: return {"ok": False, "error": "choose a platform to compare"} - shelf = self.friend_shelf(peer_id, platform=plat, offset=0, limit=1000, refresh=dry_run) + shelf = self.friend_shelf(peer_id, platform=plat, offset=0, limit=1, refresh=dry_run) if not shelf.get("ok"): return {"ok": False, "error": shelf.get("error") or "could not read friend's library"} - remote_items = shelf.get("items") or [] + # Compare against ALL rows on the friend's cached shelf for this platform + # (not just the first page), so large platforms (>1,000 titles) never miss games. + cached = self._friend_shelves.get(peer_id) + all_rows = cached[0] if cached else (shelf.get("items") or []) + remote_items = [ + r for r in all_rows + if str(r.get("platform") or "").strip().lower() == plat + ] games, _, _ = self._library_cache owned = { str(getattr(g, "name", "") or "").strip().lower() for g in (games or []) - if str(getattr(g, "platform", "") or "").strip().lower() == plat + if self._is_local(g) + and str(getattr(g, "platform", "") or "").strip().lower() == plat } missing = [ {"title": r.get("title", ""), "platform": r.get("platform", plat), @@ -8129,8 +8199,9 @@ def _p2p_worker_loop(self) -> None: item["detail"] = f"Connecting to {item['friend']}…" job = item break - if job is None: - return + if job is None: + self._p2p_worker = None + return self._run_one_p2p_transfer(job) def _run_one_p2p_transfer(self, job: dict) -> None: @@ -8209,6 +8280,25 @@ def _run_one_p2p_transfer(self, job: dict) -> None: finally: response.close() + # Refuse loose multi-file disc sheets (.cue/.gdi/.m3u) whose + # referenced tracks were not transferred, so we never publish an + # unbootable disc or falsely report `done`. + if dest.suffix.lower() in (".cue", ".gdi", ".m3u"): + from .selection import _cue_and_gdi_names, _playlist_names + raw_sheet = dest.read_text(encoding="utf-8", errors="replace") + refs = (_playlist_names(raw_sheet) if dest.suffix.lower() == ".m3u" + else _cue_and_gdi_names(raw_sheet)) + missing_tracks = [ref for ref in refs if not (staging_dir / Path(ref).name).is_file()] + if missing_tracks or not refs: + sample = ", ".join(missing_tracks[:3]) if missing_tracks else "track files" + job["state"] = "failed" + job["error"] = ( + f"Incomplete multi-file disc sheet ({dest.suffix}): missing {sample}. " + f"Ask your friend to convert to .chd/.iso or archive the set before P2P transfer." + ) + job["detail"] = job["error"] + return + job["state"] = "importing" job["percent"] = 100.0 job["detail"] = f"Verifying & importing {safe_name}…" @@ -11598,16 +11688,24 @@ def _int(name: str, default: int) -> int: rng = self.headers.get("Range", "") if rng.startswith("bytes=") and size > 0: part = rng[6:].split(",", 1)[0].strip() - a, _, b = part.partition("-") - try: - start = int(a) if a else 0 - end = int(b) if b else size - 1 - if 0 <= start <= end < size: - status = 206 - else: + a, sep, b = part.partition("-") + if sep: + try: + if not a and b: + suffix = int(b) + if suffix > 0: + start = max(0, size - suffix) + end = size - 1 + status = 206 + elif a: + start = int(a) + end = min(int(b), size - 1) if b else size - 1 + if 0 <= start <= end < size: + status = 206 + else: + start, end = 0, size - 1 + except ValueError: start, end = 0, size - 1 - except ValueError: - start, end = 0, size - 1 length = max(0, end - start + 1) if size > 0 else 0 self.send_response(status) self.send_header("Content-Type", "application/octet-stream") diff --git a/romarr/ui.py b/romarr/ui.py index bb79e5f0d..6d11df03c 100644 --- a/romarr/ui.py +++ b/romarr/ui.py @@ -3901,7 +3901,11 @@ def _nav_html() -> str: const box=$('#p-transfers'); if(!box||location.hash.replace('#','')!=='peers') return; const d=await j('/api/v1/friends/transfers').catch(()=>null); - if(!d||!d.ok||!box.isConnected) return; + if(!box.isConnected||location.hash.replace('#','')!=='peers') return; + if(!d||!d.ok){ + PEER_XFER_TIMER=setTimeout(refreshPeerTransfers,5000); + return; + } const rows=d.items||[]; if(!rows.length){box.innerHTML='';return;} const mb=n=>n>=1073741824?(n/1073741824).toFixed(2)+' GB':n>=1048576?(n/1048576).toFixed(1)+' MB':n>0?(n/1024).toFixed(0)+' KB':'—'; @@ -4074,21 +4078,30 @@ def _nav_html() -> str: toast(r.ok?('Added — '+(r.detail||'')):(r.error||'Could not add')); }); document.querySelectorAll('[data-fplay]').forEach(b=>b.onclick=async()=>{ + const peer=FSHELF.peer; $('#fs-out').innerHTML='
Comparing dumps…
'; const nv=await j('/api/v1/friends/netplay',{method:'POST', headers:{'content-type':'application/json'}, - body:JSON.stringify({peer_id:FSHELF.peer,title:b.dataset.fplay, + body:JSON.stringify({peer_id:peer,title:b.dataset.fplay, platform:b.dataset.fpplat})}); - $('#fs-out').innerHTML=netplayVerdict(nv, canFetch ? {peer_id:FSHELF.peer,title:b.dataset.fplay,platform:b.dataset.fpplat} : null); + if(FSHELF.peer!==peer) return; + $('#fs-out').innerHTML=netplayVerdict(nv, canFetch ? {peer_id:peer,title:b.dataset.fplay,platform:b.dataset.fpplat} : null); const cp=$('#np-copy-room'); if(cp) cp.onclick=async()=>{try{await navigator.clipboard.writeText(nv.room||'');toast('Room code copied');}catch{toast(nv.room||'');}}; const npf=$('#np-fetch-dump'); if(npf) npf.onclick=async()=>{ + const origLabel=npf.textContent; npf.disabled=true; npf.textContent='Queueing…'; const res=await j('/api/v1/friends/fetch',{method:'POST',headers:{'content-type':'application/json'}, - body:JSON.stringify({peer_id:FSHELF.peer,title:b.dataset.fplay,platform:b.dataset.fpplat})}); - toast(res.ok?'Queued matching dump from friend':(res.error||'Failed')); - if(res.ok) refreshPeerTransfers(); + body:JSON.stringify({peer_id:peer,title:b.dataset.fplay,platform:b.dataset.fpplat})}).catch(()=>({ok:false,error:'Request failed'})); + if(res&&res.ok){ + npf.textContent='Queued ✓'; + toast('Queued matching dump from friend'); + refreshPeerTransfers(); + }else{ + npf.disabled=false; npf.textContent=origLabel; + toast((res&&res.error)||'Failed'); + } }; }); } From f4b53aafce758ab1586bb166b3430e4624608819 Mon Sep 17 00:00:00 2001 From: badkid Date: Fri, 27 Nov 2026 21:55:02 -0600 Subject: [PATCH 3/6] fix(friends): pin P2P fetch to compared SHA1, canonical platform slug, literal nested names, and stale-shelf guards --- romarr/app.py | 37 +++++++++++++++++++++++++++++++------ romarr/federation.py | 1 + romarr/ui.py | 29 ++++++++++++++++++----------- tests/test_federation.py | 15 +++++++++++++++ 4 files changed, 65 insertions(+), 17 deletions(-) diff --git a/romarr/app.py b/romarr/app.py index 24c0b40ed..dcc5fbc22 100644 --- a/romarr/app.py +++ b/romarr/app.py @@ -7202,7 +7202,8 @@ def _library_roots(self) -> list[Path]: roots.append(resolved) return roots - def peer_resolve_file(self, peer, title: str, platform: str = "") -> tuple[Path | None, str, str]: + def peer_resolve_file(self, peer, title: str, platform: str = "", + sha1: str = "") -> tuple[Path | None, str, str]: """Resolve one local ROM file a confirmed `fetch` peer is allowed to download. Returns `(path, platform_slug, error)`. Never accepts a filesystem path @@ -7214,6 +7215,7 @@ def peer_resolve_file(self, peer, title: str, platform: str = "") -> tuple[Path return None, "", "this server has not enabled 'Download from me' (fetch) for you" want_title = str(title or "").strip().lower() want_plat = str(platform or "").strip().lower() + want_sha1 = str(sha1 or "").strip().lower() if not want_title: return None, "", "missing title" games, _, _ = self._library_cache @@ -7224,11 +7226,20 @@ def peer_resolve_file(self, peer, title: str, platform: str = "") -> tuple[Path g_name = str(getattr(game, "name", "") or "").strip().lower() g_plat = str(getattr(game, "platform", "") or "").strip().lower() if g_name == want_title and (not want_plat or g_plat == want_plat): + if want_sha1 and str(getattr(game, "sha1", "") or "").lower() != want_sha1: + continue matched = game break if matched is None: + if want_sha1: + return None, "", "that exact dump (SHA1) is not shared with you" return None, "", "that game is not shared with you" - plat_slug = str(getattr(matched, "platform", "") or want_plat or "").strip().lower() + plat_slug = str( + getattr(matched, "platform_slug", "") + or getattr(matched, "platform", "") + or want_plat + or "" + ).strip().lower() file_name = str(getattr(matched, "file_name", "") or "").strip() source = str(getattr(matched, "source", "") or "").strip() @@ -7311,7 +7322,9 @@ def _plat_dirs(root: Path, cfg: dict) -> list[Path]: return found, plat_slug, "" # Subfolder match inside the configured platform directory if plat_slug and search_dirs and search_dirs[0].is_dir(): - for child in search_dirs[0].rglob(safe_rel): + for child in search_dirs[0].rglob("*"): + if child.name != safe_rel: + continue found = _safe_file(child, root) if found is not None: return found, plat_slug, "" @@ -8069,7 +8082,8 @@ def friend_transfers_cancel(self, transfer_id: str = "", cancel_all: bool = Fals cancelled += 1 return {"ok": True, "cancelled": cancelled} - def friend_fetch(self, peer_id: str, title: str, platform: str = "") -> dict: + def friend_fetch(self, peer_id: str, title: str, platform: str = "", + sha1: str = "") -> dict: """Enqueue a direct P2P download of one game from a friend's server.""" import secrets peer, why = self._friend(peer_id) @@ -8081,6 +8095,9 @@ def friend_fetch(self, peer_id: str, title: str, platform: str = "") -> dict: platform = str(platform or "").strip().lower() if not title: return {"ok": False, "error": "no title specified"} + sha1 = str(sha1 or "").strip().lower() + if sha1 and not re.fullmatch(r"[0-9a-f]{40}", sha1): + return {"ok": False, "error": "sha1 must be 40 hex characters"} transfers, _ = self._p2p_state() job = { "id": secrets.token_hex(6), @@ -8088,6 +8105,7 @@ def friend_fetch(self, peer_id: str, title: str, platform: str = "") -> dict: "friend": peer.name, "title": title, "platform": platform, + "sha1": sha1, "filename": "", "state": "queued", "bytes_done": 0, @@ -8221,6 +8239,8 @@ def _run_one_p2p_transfer(self, job: dict) -> None: return qs = f"/api/v1/peer/shelf?download=1&title={quote(job['title'])}&platform={quote(job['platform'])}" + if job.get("sha1"): + qs += f"&sha1={quote(job['sha1'])}" staging_dir = Path(self.store.path).parent / "peer-staging" / job["id"] try: response = None @@ -8386,6 +8406,9 @@ def netplay_invite(self, peer_id: str, title: str, "sha1": entry.sha1, "detail": str(body.get("detail") or ""), } + their_sha1 = str(body.get("their_sha1") or "").lower() + if their_sha1: + answer["their_sha1"] = their_sha1 if answer["ok"]: answer["room"] = self.federation.netplay_room(peer.peer_id, entry.sha1) @@ -11678,7 +11701,8 @@ def _int(name: str, default: int) -> int: if (query.get("download") or [""])[0] == "1": title = (query.get("title") or [""])[0] plat = (query.get("platform") or [""])[0] - fpath, plat_slug, err = service.peer_resolve_file(peer, title, plat) + fpath, plat_slug, err = service.peer_resolve_file( + peer, title, plat, (query.get("sha1") or [""])[0]) if fpath is None: code = 403 if "not enabled" in err else 404 return self._json(code, {"error": err}) @@ -12692,7 +12716,8 @@ def _post(self): return self._json(200, service.friend_fetch( str(body.get("peer_id") or ""), str(body.get("title") or ""), - str(body.get("platform") or ""))) + str(body.get("platform") or ""), + str(body.get("sha1") or ""))) if route.path == "/api/v1/friends/sync": return self._json(200, service.friend_sync_platform( str(body.get("peer_id") or ""), diff --git a/romarr/federation.py b/romarr/federation.py index 2f98efef1..14bbace9f 100644 --- a/romarr/federation.py +++ b/romarr/federation.py @@ -656,6 +656,7 @@ def netplay_answer(offer: dict, library) -> dict: return { "status": "mismatch", "title": getattr(by_title, "name", title), + "their_sha1": str(getattr(by_title, "sha1", "") or "").lower(), "detail": "you both have this game and they are different " "dumps -- netplay would desync within seconds, " "which usually gets blamed on the connection", diff --git a/romarr/ui.py b/romarr/ui.py index 6d11df03c..ff4175c9f 100644 --- a/romarr/ui.py +++ b/romarr/ui.py @@ -3947,15 +3947,21 @@ def _nav_html() -> str: //: here, so typing in the search box does not bill somebody else's server //: for every keystroke. const FSHELF={peer:'',q:'',platform:'',offset:0}; +let FSHELF_REQ=0; async function friendShelf(peerId, opts){ Object.assign(FSHELF, {peer:peerId}, opts||{}); const out=$('#p-shelf'); if(!out) return; + const reqId=++FSHELF_REQ, ver=(typeof pageVersion==='number'?pageVersion:0); + const stale=()=>reqId!==FSHELF_REQ||!out.isConnected|| + (typeof pageVersion==='number'&&ver!==pageVersion)|| + (typeof activePage!=='undefined'&&activePage&&activePage!=='peers'); out.innerHTML='
Asking your friend’s server…
'; const p=new URLSearchParams({peer_id:FSHELF.peer, q:FSHELF.q, platform:FSHELF.platform, offset:FSHELF.offset, limit:100}); const r=await j('/api/v1/friends/shelf?'+p.toString()).catch(()=>({})); + if(stale()) return; if(!r.ok){ out.innerHTML=`
${ esc(r.error||'Could not reach that friend.')}
`; @@ -4026,11 +4032,11 @@ def _nav_html() -> str:
`; enhancePlatformSelect($('#fs-plat')); - const reload=o=>friendShelf(FSHELF.peer,o); + const reload=o=>friendShelf(peerId,o); $('#fs-q').onchange=e=>reload({q:e.target.value,offset:0}); $('#fs-plat').onchange=e=>reload({platform:e.target.value,offset:0}); $('#fs-refresh').onclick=async()=>{ - const rp=new URLSearchParams({peer_id:FSHELF.peer,refresh:'1',limit:1}); + const rp=new URLSearchParams({peer_id:peerId,refresh:'1',limit:1}); await j('/api/v1/friends/shelf?'+rp.toString()).catch(()=>({})); reload({}); }; @@ -4043,7 +4049,7 @@ def _nav_html() -> str: const sout=$('#fs-sync-out'); sout.innerHTML='Comparing your library with '+esc(r.friend||'friend')+'…'; const res=await j('/api/v1/friends/sync',{method:'POST',headers:{'content-type':'application/json'}, - body:JSON.stringify({peer_id:FSHELF.peer,platform:plat,dry_run:true})}).catch(()=>({error:'Compare failed'})); + body:JSON.stringify({peer_id:peerId,platform:plat,dry_run:true})}).catch(()=>({error:'Compare failed'})); if(!res.ok){sout.innerHTML=''+esc(res.error||'Compare failed')+'';return;} sout.innerHTML=`
${esc(res.friend)} has ${res.remote_total} ${esc(plat)} title(s): you already have ${res.already_have} and are missing ${res.missing_count}.` +(res.missing_count?` Sample: ${res.missing.slice(0,5).map(m=>esc(m.title)).join(', ')}${res.missing_count>5?'…':''}`:' Everything is already in your library!') @@ -4054,7 +4060,7 @@ def _nav_html() -> str: if(!confirm(`Pull all missing ${plat} games directly P2P from ${r.friend||'your friend'}? Existing games in your library are skipped automatically.`)) return; syncPull.disabled=true; syncPull.textContent='Queueing…'; const res=await j('/api/v1/friends/sync',{method:'POST',headers:{'content-type':'application/json'}, - body:JSON.stringify({peer_id:FSHELF.peer,platform:plat,dry_run:false})}).catch(()=>({error:'Sync failed'})); + body:JSON.stringify({peer_id:peerId,platform:plat,dry_run:false})}).catch(()=>({error:'Sync failed'})); syncPull.disabled=false; syncPull.textContent='Pull Missing from '+(r.friend||'Friend'); toast(res.ok?(res.detail||'Queued'):(res.error||'Could not start sync')); if(res.ok) refreshPeerTransfers(); @@ -4064,7 +4070,7 @@ def _nav_html() -> str: b.disabled=true; b.textContent='Queueing…'; const res=await j('/api/v1/friends/fetch',{method:'POST', headers:{'content-type':'application/json'}, - body:JSON.stringify({peer_id:FSHELF.peer,title:b.dataset.ffetch, + body:JSON.stringify({peer_id:peerId,title:b.dataset.ffetch, platform:b.dataset.ffplat})}).catch(()=>({error:'Request failed'})); b.disabled=false; b.textContent=res.ok?'Queued ✓':'Download P2P'; toast(res.ok?(res.detail||'Queued P2P download'):(res.error||'Could not start download')); @@ -4073,19 +4079,20 @@ def _nav_html() -> str: document.querySelectorAll('[data-fwant]').forEach(b=>b.onclick=async()=>{ const r=await j('/api/v1/friends/want',{method:'POST', headers:{'content-type':'application/json'}, - body:JSON.stringify({peer_id:FSHELF.peer,title:b.dataset.fwant, + body:JSON.stringify({peer_id:peerId,title:b.dataset.fwant, platform:b.dataset.fplat})}); toast(r.ok?('Added — '+(r.detail||'')):(r.error||'Could not add')); }); document.querySelectorAll('[data-fplay]').forEach(b=>b.onclick=async()=>{ - const peer=FSHELF.peer; - $('#fs-out').innerHTML='
Comparing dumps…
'; + const peer=peerId; + const fsOut=$('#fs-out'), nver=(typeof pageVersion==='number'?pageVersion:0); + fsOut.innerHTML='
Comparing dumps…
'; const nv=await j('/api/v1/friends/netplay',{method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({peer_id:peer,title:b.dataset.fplay, platform:b.dataset.fpplat})}); - if(FSHELF.peer!==peer) return; - $('#fs-out').innerHTML=netplayVerdict(nv, canFetch ? {peer_id:peer,title:b.dataset.fplay,platform:b.dataset.fpplat} : null); + if(stale()||!fsOut.isConnected||(typeof pageVersion==='number'&&nver!==pageVersion)) return; + fsOut.innerHTML=netplayVerdict(nv, (canFetch&&nv.their_sha1) ? {peer_id:peer,title:b.dataset.fplay,platform:b.dataset.fpplat,sha1:nv.their_sha1} : null); const cp=$('#np-copy-room'); if(cp) cp.onclick=async()=>{try{await navigator.clipboard.writeText(nv.room||'');toast('Room code copied');}catch{toast(nv.room||'');}}; const npf=$('#np-fetch-dump'); @@ -4093,7 +4100,7 @@ def _nav_html() -> str: const origLabel=npf.textContent; npf.disabled=true; npf.textContent='Queueing…'; const res=await j('/api/v1/friends/fetch',{method:'POST',headers:{'content-type':'application/json'}, - body:JSON.stringify({peer_id:peer,title:b.dataset.fplay,platform:b.dataset.fpplat})}).catch(()=>({ok:false,error:'Request failed'})); + body:JSON.stringify({peer_id:peer,title:b.dataset.fplay,platform:b.dataset.fpplat,sha1:nv.their_sha1})}).catch(()=>({ok:false,error:'Request failed'})); if(res&&res.ok){ npf.textContent='Queued ✓'; toast('Queued matching dump from friend'); diff --git a/tests/test_federation.py b/tests/test_federation.py index 543c9279f..3968e1dc6 100644 --- a/tests/test_federation.py +++ b/tests/test_federation.py @@ -494,6 +494,21 @@ def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): assert r_range.status_code == 206 assert r_range.content == b"SNES-ROM-HEADER" + # RFC 9110 suffix range: the LAST n bytes, not the first n+1. + r_suffix = requests.get( + f"{b_url}/api/v1/peer/shelf?download=1&title=Chrono+Trigger+(USA)&platform=snes", + headers={**ant_peer.headers(), "Range": "bytes=-4"}, timeout=5) + assert r_suffix.status_code == 206 and r_suffix.content == b"-END" + + # A SHA1 that no shared file carries must never fall back to title+platform. + r_wrong_dump = requests.get( + f"{b_url}/api/v1/peer/shelf?download=1&title=Chrono+Trigger+(USA)" + f"&platform=snes&sha1={'0' * 40}", + headers=ant_peer.headers(), timeout=5) + assert r_wrong_dump.status_code == 404 + assert ant.friend_fetch(ant_peer.peer_id, "Chrono Trigger (USA)", "snes", + sha1="not-a-hash")["ok"] is False + preview = ant.friend_sync_platform(ant_peer.peer_id, "snes", dry_run=True) assert preview["ok"] is True and preview["can_fetch"] is True assert preview["missing_count"] == 1 and preview["already_have"] == 0 From 9cd1e89897cd6a390de70bd9e9289717de261abd Mon Sep 17 00:00:00 2001 From: BlizzHacker Date: Sat, 28 Nov 2026 04:28:09 +0000 Subject: [PATCH 4/6] fix(friends): verify exact transfers and settle imported requests --- romarr/app.py | 114 ++++++++++++++++++++++++++------------- romarr/federation.py | 5 +- romarr/ui.py | 9 ++-- tests/test_federation.py | 28 ++++++++++ 4 files changed, 114 insertions(+), 42 deletions(-) diff --git a/romarr/app.py b/romarr/app.py index dcc5fbc22..3ad2602d0 100644 --- a/romarr/app.py +++ b/romarr/app.py @@ -5074,7 +5074,8 @@ def _scanned_manual_source(self, source: Path, platform): yield stage, refusal def adopt(self, path: str, platform_slug: str = "", *, - force: bool = False, require_verified: bool = False) -> dict: + force: bool = False, require_verified: bool = False, + friend_request: tuple[str, str] | None = None) -> dict: """Import one file the operator picked out of a manual-import scan. Separate from `import_finished` because the two have different @@ -5191,7 +5192,9 @@ def adopt(self, path: str, platform_slug: str = "", *, self.store.record(Event( kind="imported", game=source.stem, platform=platform.slug, release=source.name, library=label, - detail=(f"manual import ({'FORCED over ' + str(status) if forced else status or 'unknown'})" + indexer=f"Friend: {friend_request[1]}" if friend_request else "", + detail=(f"{'P2P import' if friend_request else 'manual import'} " + f"({'FORCED over ' + str(status) if forced else status or 'unknown'})" f": {outcome.destination} ({outcome.import_method or 'copy'}) {outcome.fallback_reason}"))) self._compress_after_import(outcome.destination, platform.slug, source.stem, target_cfg) imported.append({ @@ -5202,6 +5205,19 @@ def adopt(self, path: str, platform_slug: str = "", *, "fallback_reason": outcome.fallback_reason, }) + if imported and not refused and friend_request: + identities = _fulfil_identities(friend_request[0], outcomes) + for wanted in list(self.store.wanted): + if wanted.platform != platform.slug or not any( + _titles_are_same(wanted.game, identity) for identity in identities): + continue + if platform.slug not in PACKAGE_PLATFORMS: + self.store.fulfil(wanted.game, platform.slug) + continue + request = QueueItem(wanted.game, platform.slug, source.name, 0, + "imported", manual=True) + self._settle_parts(request, platform, outcomes, + self._pending_parts(request, platform)) if imported and self.store.settings.get("rescan_after_import", True): self._rescan_library(target_lib, target_cfg, platform.slug, platform_folders=target_folders) @@ -7213,33 +7229,36 @@ def peer_resolve_file(self, peer, title: str, platform: str = "", return None, "", "unknown or unconfirmed peer" if peer.access != "fetch": return None, "", "this server has not enabled 'Download from me' (fetch) for you" - want_title = str(title or "").strip().lower() - want_plat = str(platform or "").strip().lower() + want_title = str(title or "").strip().casefold() + want_platform = resolve(platform) if platform else None want_sha1 = str(sha1 or "").strip().lower() if not want_title: return None, "", "missing title" + if platform and want_platform is None: + return None, "", "unknown platform" + if want_sha1 and not re.fullmatch(r"[0-9a-f]{40}", want_sha1): + return None, "", "invalid SHA1" games, _, _ = self._library_cache - matched = None - for game in (games or []): + error = ("that exact dump (SHA1) is not shared with you" if want_sha1 + else "that game is not shared with you") + for game in games or (): + if not self._is_local(game) or game.name.strip().casefold() != want_title: + continue + slug = self._slug_of(game) + if want_platform and slug != want_platform.slug: + continue if not peer.may_see(game): continue - g_name = str(getattr(game, "name", "") or "").strip().lower() - g_plat = str(getattr(game, "platform", "") or "").strip().lower() - if g_name == want_title and (not want_plat or g_plat == want_plat): - if want_sha1 and str(getattr(game, "sha1", "") or "").lower() != want_sha1: - continue - matched = game - break - if matched is None: - if want_sha1: - return None, "", "that exact dump (SHA1) is not shared with you" - return None, "", "that game is not shared with you" - plat_slug = str( - getattr(matched, "platform_slug", "") - or getattr(matched, "platform", "") - or want_plat - or "" - ).strip().lower() + found, _, error = self._peer_file_for_game(game, slug, want_sha1) + if found is not None: + return found, slug, "" + return None, "", error + + def _peer_file_for_game(self, matched, plat_slug: str, + want_sha1: str) -> tuple[Path | None, str, str]: + """Find a readable file belonging to a shared local library row.""" + from .dat import hash_file + file_name = str(getattr(matched, "file_name", "") or "").strip() source = str(getattr(matched, "source", "") or "").strip() @@ -7292,6 +7311,8 @@ def _safe_file(candidate: Path, root: Path) -> Path | None: resolved = candidate.resolve() if not resolved.is_relative_to(root): return None + if want_sha1 and hash_file(resolved)["sha1"] != want_sha1: + return None return resolved except OSError: return None @@ -7311,9 +7332,18 @@ def _plat_dirs(root: Path, cfg: dict) -> list[Path]: dirs.append(root) return dirs - # 1. Exact filename lookup under configured platform folders + local_path = str(getattr(matched, "local_path", "") or "") + if local_path: + candidate = Path(local_path) + for root, _ in lib_entries: + found = _safe_file(candidate if candidate.is_absolute() else root / candidate, root) + if found is not None: + return found, plat_slug, "" + return None, plat_slug, "the indexed file is unavailable or its SHA1 differs" + + # 1. Exact filename lookup under configured platform folders. if file_name: - safe_rel = Path(file_name).name + safe_rel = Path(file_name.replace(chr(92), "/")).name for root, cfg in lib_entries: search_dirs = _plat_dirs(root, cfg) for folder in search_dirs: @@ -7337,7 +7367,7 @@ def _plat_dirs(root: Path, cfg: dict) -> list[Path]: continue try: for entry in folder.iterdir(): - if entry.stem.lower() == want_title or entry.name.lower() == want_title: + if matched.name.casefold() in (entry.stem.casefold(), entry.name.casefold()): found = _safe_file(entry, root) if found is not None: return found, plat_slug, "" @@ -7837,11 +7867,13 @@ class _RommDump: could drift into disagreeing about what "mismatch" means. """ - __slots__ = ("sha1", "name", "verified") + __slots__ = ("sha1", "name", "platform", "verified") def __init__(self, row): self.sha1 = row.get("sha1", "") self.name = row.get("title", "") + self.platform = (getattr(resolve(row.get("platform", "")), "slug", "") + or row.get("platform", "")) self.verified = bool(row.get("verified")) def _romm_friend_client(self, peer): @@ -8226,6 +8258,7 @@ def _run_one_p2p_transfer(self, job: dict) -> None: import requests as _rq import shutil from urllib.parse import quote + from .dat import hash_file from .federation import url_candidates _, cancel_set = self._p2p_state() @@ -8248,7 +8281,7 @@ def _run_one_p2p_transfer(self, job: dict) -> None: for base in candidates: try: r = _rq.get(base.rstrip("/") + qs, headers=peer.headers(), - stream=True, timeout=(15, 120)) + stream=True, timeout=(15, 120), allow_redirects=False) except _rq.RequestException as exc: last_err = str(exc) continue @@ -8271,7 +8304,11 @@ def _run_one_p2p_transfer(self, job: dict) -> None: raw_name = response.headers.get("X-ROMarr-Filename") or f"{job['title']}.bin" safe_name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", Path(raw_name).name).strip(" .") or "game.bin" - plat = response.headers.get("X-ROMarr-Platform") or job["platform"] + plat = job["platform"] + reported = response.headers.get("X-ROMarr-Platform") or plat + if resolve(reported) != resolve(plat): + response.close() + raise ValueError("friend returned a different platform") total = int(response.headers.get("Content-Length") or 0) job["filename"] = safe_name job["bytes_total"] = total @@ -8322,15 +8359,13 @@ def _run_one_p2p_transfer(self, job: dict) -> None: job["state"] = "importing" job["percent"] = 100.0 job["detail"] = f"Verifying & importing {safe_name}…" - adopted = self.adopt(str(dest), plat, force=False) + if job.get("sha1") and hash_file(dest)["sha1"] != job["sha1"]: + raise ValueError("the received file does not match the requested SHA1") + adopted = self.adopt(str(dest), plat, force=False, + friend_request=(job["title"], job["friend"])) if adopted.get("ok"): job["state"] = "done" job["detail"] = f"Imported {safe_name} from {job['friend']}" - self.store.record(Event( - kind="imported", game=job["title"], platform=plat, - release=safe_name, indexer=f"Friend: {job['friend']}", - detail="Direct P2P transfer from friend")) - self.store.save() else: refused = (adopted.get("refused") or [{}])[0] job["state"] = "failed" @@ -12667,8 +12702,13 @@ def _post(self): # Judged against the hash index, not the shelf: a library # server's game object has no SHA1, so answering from it # could only ever say "missing". - return self._json(200, service.federation.netplay_answer( - body.get("offer") or {}, service.hashes.entries())) + answer = service.federation.netplay_answer( + body.get("offer") or {}, service.hashes.entries()) + if digest := answer.get("their_sha1"): + entry = service.hashes.by_sha1(digest) + if peer.access != "fetch" or entry is None or not peer.may_see(entry): + answer.pop("their_sha1") + return self._json(200, answer) if route.path == "/api/v1/hashes/seed": # Netplay from the library server's own hashes, so it works # on a shelf too large to audit. Backgrounded: this is diff --git a/romarr/federation.py b/romarr/federation.py index 14bbace9f..e4529dc02 100644 --- a/romarr/federation.py +++ b/romarr/federation.py @@ -630,6 +630,7 @@ def netplay_answer(offer: dict, library) -> dict: """ wanted = str(offer.get("sha1") or "").lower() title = str(offer.get("title") or "") + platform = str(offer.get("platform") or "").casefold() if not wanted: return {"status": "missing", "detail": "the invitation carried no hash, so the dump " @@ -648,8 +649,8 @@ def netplay_answer(offer: dict, library) -> dict: "the bytes match, but one side has not verified " "this dump against a DAT", } - if not by_title and str(getattr(game, "name", "")).lower() \ - == title.lower(): + if (not by_title and str(getattr(game, "name", "")).casefold() == title.casefold() + and (not platform or str(getattr(game, "platform", "")).casefold() == platform)): by_title = game if by_title is not None: diff --git a/romarr/ui.py b/romarr/ui.py index ff4175c9f..cf227dd62 100644 --- a/romarr/ui.py +++ b/romarr/ui.py @@ -4038,18 +4038,21 @@ def _nav_html() -> str: $('#fs-refresh').onclick=async()=>{ const rp=new URLSearchParams({peer_id:peerId,refresh:'1',limit:1}); await j('/api/v1/friends/shelf?'+rp.toString()).catch(()=>({})); + if(stale()) return; reload({}); }; if($('#fs-prev')) $('#fs-prev').onclick=()=>reload({offset:Math.max(0,FSHELF.offset-100)}); if($('#fs-next')) $('#fs-next').onclick=()=>reload({offset:FSHELF.offset+100}); + let syncSeq=0, netplaySeq=0; const syncPrev=$('#fs-sync-preview'), syncPull=$('#fs-sync-pull'); if(syncPrev) syncPrev.onclick=async()=>{ const plat=$('#fs-sync-plat').value; - const sout=$('#fs-sync-out'); + const sout=$('#fs-sync-out'), seq=++syncSeq; sout.innerHTML='Comparing your library with '+esc(r.friend||'friend')+'…'; const res=await j('/api/v1/friends/sync',{method:'POST',headers:{'content-type':'application/json'}, body:JSON.stringify({peer_id:peerId,platform:plat,dry_run:true})}).catch(()=>({error:'Compare failed'})); + if(stale()||!sout.isConnected||seq!==syncSeq) return; if(!res.ok){sout.innerHTML=''+esc(res.error||'Compare failed')+'';return;} sout.innerHTML=`
${esc(res.friend)} has ${res.remote_total} ${esc(plat)} title(s): you already have ${res.already_have} and are missing ${res.missing_count}.` +(res.missing_count?` Sample: ${res.missing.slice(0,5).map(m=>esc(m.title)).join(', ')}${res.missing_count>5?'…':''}`:' Everything is already in your library!') @@ -4085,13 +4088,13 @@ def _nav_html() -> str: }); document.querySelectorAll('[data-fplay]').forEach(b=>b.onclick=async()=>{ const peer=peerId; - const fsOut=$('#fs-out'), nver=(typeof pageVersion==='number'?pageVersion:0); + const fsOut=$('#fs-out'), seq=++netplaySeq; fsOut.innerHTML='
Comparing dumps…
'; const nv=await j('/api/v1/friends/netplay',{method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({peer_id:peer,title:b.dataset.fplay, platform:b.dataset.fpplat})}); - if(stale()||!fsOut.isConnected||(typeof pageVersion==='number'&&nver!==pageVersion)) return; + if(stale()||!fsOut.isConnected||seq!==netplaySeq) return; fsOut.innerHTML=netplayVerdict(nv, (canFetch&&nv.their_sha1) ? {peer_id:peer,title:b.dataset.fplay,platform:b.dataset.fpplat,sha1:nv.their_sha1} : null); const cp=$('#np-copy-room'); if(cp) cp.onclick=async()=>{try{await navigator.clipboard.writeText(nv.room||'');toast('Room code copied');}catch{toast(nv.room||'');}}; diff --git a/tests/test_federation.py b/tests/test_federation.py index 3968e1dc6..8125dc686 100644 --- a/tests/test_federation.py +++ b/tests/test_federation.py @@ -424,6 +424,7 @@ def test_a_romm_friend_survives_a_restart_with_its_credential(): def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): """End-to-end two-server P2P: Borb shares PS2 with fetch; Ant compares and pulls missing.""" import threading + from romarr.dat import hash_file import time from http.server import ThreadingHTTPServer import requests @@ -450,8 +451,12 @@ def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): borb.scheduler.stop() ant.scheduler.stop() + rom_path = borb_lib / "snes" / "Chrono Trigger (USA).sfc" + sha1 = hash_file(rom_path)["sha1"] + ant.store.want("Chrono Trigger (USA)", "snes") borb._library_cache = ([ Game(id="1", name="Chrono Trigger (USA)", platform="snes", + platform_slug="snes", file_name="Chrono Trigger (USA).sfc"), ], 9e18, "") ant._library_cache = ([], 9e18, "") @@ -506,6 +511,12 @@ def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): f"&platform=snes&sha1={'0' * 40}", headers=ant_peer.headers(), timeout=5) assert r_wrong_dump.status_code == 404 + r_exact = requests.get( + f"{b_url}/api/v1/peer/shelf", + params={"download": "1", "title": "Chrono Trigger (USA)", + "platform": "snes", "sha1": sha1}, + headers=ant_peer.headers(), timeout=5) + assert r_exact.status_code == 200 and r_exact.content == payload assert ant.friend_fetch(ant_peer.peer_id, "Chrono Trigger (USA)", "snes", sha1="not-a-hash")["ok"] is False @@ -527,6 +538,23 @@ def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): imported = list((ant_lib / "snes").glob("*.sfc")) assert len(imported) == 1 assert imported[0].read_bytes() == payload + assert ant.store.missing() == [] + imports = [record for record in ant.store.events if record.kind == "imported"] + assert len(imports) == 1 + assert imports[0].indexer == f"Friend: {ant_peer.name}" finally: b_srv.shutdown(); b_srv.server_close() a_srv.shutdown(); a_srv.server_close() + + + +def test_netplay_title_fallback_uses_the_offered_platform(): + """A name shared across platforms does not identify a compatible dump.""" + from romarr.federation import Federation + from romarr.hashes import Entry + + offer = {"title": "Doom", "platform": "snes", "sha1": "a" * 40} + gba = Entry("b" * 40, "Doom", "gba") + snes = Entry("c" * 40, "Doom", "snes") + assert Federation.netplay_answer(offer, [gba])["status"] == "missing" + assert Federation.netplay_answer(offer, [gba, snes])["their_sha1"] == snes.sha1 From dfa06ed426aed48b2be955a1a13bd6479d495df5 Mon Sep 17 00:00:00 2001 From: BlizzHacker Date: Sat, 28 Nov 2026 04:30:23 +0000 Subject: [PATCH 5/6] fix(friends): instantiate the RomM netplay adapter --- romarr/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/romarr/app.py b/romarr/app.py index 3ad2602d0..3fec3f16b 100644 --- a/romarr/app.py +++ b/romarr/app.py @@ -8422,7 +8422,7 @@ def netplay_invite(self, peer_id: str, title: str, time.monotonic()) if err: return {"ok": False, "status": "error", "detail": err} - theirs = [_RommDump(r) for r in rows if r.get("sha1")] + theirs = [self._RommDump(r) for r in rows if r.get("sha1")] body = self.federation.netplay_answer(offer, theirs) else: body, err = self._call_friend(peer, "POST", From baf289655f6f13ab09e8a458b1c1a28dfdad5a30 Mon Sep 17 00:00:00 2001 From: BlizzHacker Date: Sat, 28 Nov 2026 04:43:05 +0000 Subject: [PATCH 6/6] fix(friends): bind imports to their requests and honor late cancellation --- romarr/app.py | 53 +++++++++++++++++++++++++++------------- romarr/federation.py | 11 +++++++-- tests/test_federation.py | 19 +++++++++++--- 3 files changed, 60 insertions(+), 23 deletions(-) diff --git a/romarr/app.py b/romarr/app.py index 3fec3f16b..235d4847d 100644 --- a/romarr/app.py +++ b/romarr/app.py @@ -5075,7 +5075,7 @@ def _scanned_manual_source(self, source: Path, platform): def adopt(self, path: str, platform_slug: str = "", *, force: bool = False, require_verified: bool = False, - friend_request: tuple[str, str] | None = None) -> dict: + friend_request: tuple[str, str, str] | None = None) -> dict: """Import one file the operator picked out of a manual-import scan. Separate from `import_finished` because the two have different @@ -5129,6 +5129,9 @@ def adopt(self, path: str, platform_slug: str = "", *, target_cfg, target_lib = target label = target_cfg.get("name") or getattr(target_lib, "name", "library") target_folders = self.platform_folders(target_cfg) + requested_game = friend_request[0] if friend_request and not friend_request[2] else None + catalog_platforms = ({dat.name: self._dat_platform(dat.name) for dat in self.dats.dats} + if requested_game else None) try: with self._scanned_manual_source(source, platform) as (staged_source, scan_refusal): @@ -5146,6 +5149,8 @@ def adopt(self, path: str, platform_slug: str = "", *, layout=self.library_layout(target_cfg), translation=is_translation(source.name), platform_folders=target_folders, + requested_game=requested_game, + catalog_platforms=catalog_platforms, **self._import_hash_options()) except (OSError, ValueError) as err: reason = f"could not prepare scanned import: {err}" @@ -5206,7 +5211,7 @@ def adopt(self, path: str, platform_slug: str = "", *, }) if imported and not refused and friend_request: - identities = _fulfil_identities(friend_request[0], outcomes) + identities = _fulfil_identities("", outcomes) - {""} for wanted in list(self.store.wanted): if wanted.platform != platform.slug or not any( _titles_are_same(wanted.game, identity) for identity in identities): @@ -7721,7 +7726,10 @@ def index_hashes_from_library(self, progress: dict | None = None) -> dict: good = self.dats.lookup(sha1=row["sha1"]).status == VERIFIED if good: confirmed += 1 - if self.hashes.add(row["sha1"], row["name"], row["platform"], + stored_platform = str(row["platform"] or "") + resolved = resolve(stored_platform) + if self.hashes.add(row["sha1"], row["name"], + resolved.slug if resolved else stored_platform, good, row.get("path", "")): added += 1 if progress is not None: @@ -8124,7 +8132,11 @@ def friend_fetch(self, peer_id: str, title: str, platform: str = "", if peer.kind != "romarr": return {"ok": False, "error": "Direct P2P fetch requires a ROMarr peer"} title = str(title or "").strip() - platform = str(platform or "").strip().lower() + platform = str(platform or "").strip() + chosen = resolve(platform) if platform else None + if platform and chosen is None: + return {"ok": False, "error": "unknown platform"} + platform = chosen.slug if chosen else "" if not title: return {"ok": False, "error": "no title specified"} sha1 = str(sha1 or "").strip().lower() @@ -8166,9 +8178,10 @@ def friend_fetch(self, peer_id: str, title: str, platform: str = "", def friend_sync_platform(self, peer_id: str, platform: str, *, dry_run: bool = True, limit: int = 500) -> dict: """Compare a friend's platform against your library and optionally pull all missing games.""" - plat = str(platform or "").strip().lower() - if not plat: + chosen = resolve(str(platform or "").strip()) + if chosen is None: return {"ok": False, "error": "choose a platform to compare"} + plat = chosen.slug shelf = self.friend_shelf(peer_id, platform=plat, offset=0, limit=1, refresh=dry_run) if not shelf.get("ok"): return {"ok": False, "error": shelf.get("error") or "could not read friend's library"} @@ -8178,14 +8191,14 @@ def friend_sync_platform(self, peer_id: str, platform: str, *, all_rows = cached[0] if cached else (shelf.get("items") or []) remote_items = [ r for r in all_rows - if str(r.get("platform") or "").strip().lower() == plat + if resolve(str(r.get("platform") or "")) == chosen ] games, _, _ = self._library_cache owned = { str(getattr(g, "name", "") or "").strip().lower() for g in (games or []) if self._is_local(g) - and str(getattr(g, "platform", "") or "").strip().lower() == plat + and self._slug_of(g) == plat } missing = [ {"title": r.get("title", ""), "platform": r.get("platform", plat), @@ -8304,11 +8317,12 @@ def _run_one_p2p_transfer(self, job: dict) -> None: raw_name = response.headers.get("X-ROMarr-Filename") or f"{job['title']}.bin" safe_name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", Path(raw_name).name).strip(" .") or "game.bin" - plat = job["platform"] - reported = response.headers.get("X-ROMarr-Platform") or plat - if resolve(reported) != resolve(plat): + requested = job["platform"] + received = resolve(response.headers.get("X-ROMarr-Platform") or requested) + if received is None or (requested and received.slug != requested): response.close() - raise ValueError("friend returned a different platform") + raise ValueError("friend returned an invalid or different platform") + plat = received.slug total = int(response.headers.get("Content-Length") or 0) job["filename"] = safe_name job["bytes_total"] = total @@ -8356,13 +8370,18 @@ def _run_one_p2p_transfer(self, job: dict) -> None: job["detail"] = job["error"] return - job["state"] = "importing" - job["percent"] = 100.0 - job["detail"] = f"Verifying & importing {safe_name}…" - if job.get("sha1") and hash_file(dest)["sha1"] != job["sha1"]: + expected_sha1 = job.get("sha1", "") + if expected_sha1 and hash_file(dest)["sha1"] != expected_sha1: raise ValueError("the received file does not match the requested SHA1") + with self._lock: + if job["id"] in cancel_set: + job["state"], job["detail"] = "cancelled", "Cancelled" + return + job["state"] = "importing" + job["percent"] = 100.0 + job["detail"] = f"Verifying & importing {safe_name}…" adopted = self.adopt(str(dest), plat, force=False, - friend_request=(job["title"], job["friend"])) + friend_request=(job["title"], job["friend"], expected_sha1)) if adopted.get("ok"): job["state"] = "done" job["detail"] = f"Imported {safe_name} from {job['friend']}" diff --git a/romarr/federation.py b/romarr/federation.py index e4529dc02..c4da4d322 100644 --- a/romarr/federation.py +++ b/romarr/federation.py @@ -630,7 +630,14 @@ def netplay_answer(offer: dict, library) -> dict: """ wanted = str(offer.get("sha1") or "").lower() title = str(offer.get("title") or "") - platform = str(offer.get("platform") or "").casefold() + from .platforms import resolve + + def platform_key(value): + text = str(value or "").casefold() + parsed = resolve(text) + return parsed.slug if parsed else text + + platform = platform_key(offer.get("platform")) if not wanted: return {"status": "missing", "detail": "the invitation carried no hash, so the dump " @@ -650,7 +657,7 @@ def netplay_answer(offer: dict, library) -> dict: "this dump against a DAT", } if (not by_title and str(getattr(game, "name", "")).casefold() == title.casefold() - and (not platform or str(getattr(game, "platform", "")).casefold() == platform)): + and (not platform or platform_key(getattr(game, "platform", "")) == platform)): by_title = game if by_title is not None: diff --git a/tests/test_federation.py b/tests/test_federation.py index 8125dc686..60a3398df 100644 --- a/tests/test_federation.py +++ b/tests/test_federation.py @@ -424,7 +424,7 @@ def test_a_romm_friend_survives_a_restart_with_its_credential(): def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): """End-to-end two-server P2P: Borb shares PS2 with fetch; Ant compares and pulls missing.""" import threading - from romarr.dat import hash_file + from romarr.dat import Dat, Game as DatGame, Rom, hash_file import time from http.server import ThreadingHTTPServer import requests @@ -452,7 +452,12 @@ def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): ant.scheduler.stop() rom_path = borb_lib / "snes" / "Chrono Trigger (USA).sfc" - sha1 = hash_file(rom_path)["sha1"] + hashes = hash_file(rom_path) + sha1 = hashes["sha1"] + game = "Chrono Trigger (USA)" + ant.dats.add(Dat("Nintendo - Super Nintendo Entertainment System", games={ + game: DatGame(game, (Rom(rom_path.name, **hashes),)), + })) ant.store.want("Chrono Trigger (USA)", "snes") borb._library_cache = ([ Game(id="1", name="Chrono Trigger (USA)", platform="snes", @@ -524,6 +529,12 @@ def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): assert preview["ok"] is True and preview["can_fetch"] is True assert preview["missing_count"] == 1 and preview["already_have"] == 0 + ant._library_cache = ([ + Game(id="2", name=game, platform="Super Nintendo", platform_slug="snes"), + ], 9e18, "") + assert ant.friend_sync_platform(ant_peer.peer_id, "Super Nintendo")["missing_count"] == 0 + ant._library_cache = ([], 9e18, "") + pulled = ant.friend_sync_platform(ant_peer.peer_id, "snes", dry_run=False) assert pulled["ok"] is True and pulled["queued"] == 1 @@ -534,7 +545,7 @@ def test_p2p_friend_file_fetch_range_and_bulk_platform_sync(tmp_path): break time.sleep(0.05) final = ant.friend_transfers_status()["items"][0] - assert final["state"] == "done", final + assert final["state"] == "done", final["error"] imported = list((ant_lib / "snes").glob("*.sfc")) assert len(imported) == 1 assert imported[0].read_bytes() == payload @@ -555,6 +566,6 @@ def test_netplay_title_fallback_uses_the_offered_platform(): offer = {"title": "Doom", "platform": "snes", "sha1": "a" * 40} gba = Entry("b" * 40, "Doom", "gba") - snes = Entry("c" * 40, "Doom", "snes") + snes = Entry("c" * 40, "Doom", "Super Nintendo") assert Federation.netplay_answer(offer, [gba])["status"] == "missing" assert Federation.netplay_answer(offer, [gba, snes])["their_sha1"] == snes.sha1