diff options
| -rw-r--r-- | AGENTS.md | 4 | ||||
| -rw-r--r-- | deckit/modules/xbox.py | 35 | ||||
| -rw-r--r-- | static/deck.css | 1 | ||||
| -rw-r--r-- | static/modules/xbox.js | 27 | ||||
| -rw-r--r-- | tests/test_xbox.py | 22 |
5 files changed, 83 insertions, 6 deletions
@@ -106,7 +106,9 @@ Keep the server dependency-free apart from that one package. takes the uploaded screenshots and clips (mediahub `screenshots`/`gameclips` search, `OwnerXuid eq <xuid>`); their CDN URIs are signed, so the tab shows and downloads them straight from Microsoft, in a `<dialog closedby="any">` - outside the redrawn part. Only captures the console uploaded appear; Xbox + outside the redrawn part. Its "Save to PC" is the `save` action: the PC + downloads a listed capture into `xdg-user-dir` PICTURES/Xbox or + VIDEOS/Xbox and answers the path. Only captures the console uploaded appear; Xbox keeps them 90 days (`expirationDate`). Xbox Live has no system software version. The profile and console cards share `.xb-hero`, whose background is the gamerpic (Xbox's own profile background is it blurred) diff --git a/deckit/modules/xbox.py b/deckit/modules/xbox.py index fcf7d28..5f9545a 100644 --- a/deckit/modules/xbox.py +++ b/deckit/modules/xbox.py @@ -31,6 +31,8 @@ documents none of them for third parties. import http.client import json import os +import shutil +import subprocess import threading import time import urllib.error @@ -117,6 +119,15 @@ def _http(url, data=None, headers=None, timeout=10): return json.loads(raw) if raw else {} +def user_dir(name: str) -> Path: + """An XDG user directory (PICTURES, VIDEOS), else ~/Pictures or ~/Videos.""" + try: + p = subprocess.run(["xdg-user-dir", name], capture_output=True, text=True, timeout=5).stdout.strip() + except (OSError, subprocess.SubprocessError): + p = "" + return Path(p) if p and Path(p) != Path.home() else Path.home() / name.title() + + def foreground(presence: dict) -> dict | None: """The title filling a console's screen, if any.""" for dev in presence.get("devices") or []: @@ -242,6 +253,7 @@ def make(cfg: dict) -> Module: x = Xbox(cfg, cfg.get("http", _http)) actions = {name: (lambda body, n=name: x.command(n, body)) for name in COMMANDS} actions["login"] = x.start_login + actions["save"] = x.save return Module(name="xbox", title="Xbox", state=x.state, actions=actions, start=x.start, stop=x.stop) @@ -538,6 +550,29 @@ class Xbox: self.quick_until = time.monotonic() + QUICK_FOR self.wake.set() + # --- saving a capture on the PC ------------------------------------- + def save(self, body: dict) -> dict: + """Download a listed capture into the PC's Pictures/Xbox or + Videos/Xbox; the answer names the file.""" + c = next((c for c in self.data.get("captures") or [] if c["id"] == (body or {}).get("id")), None) + if c is None: + raise ModuleError("unknown capture") + clip = c["kind"] == "clip" + name = " ".join(filter(None, [c.get("title"), (c.get("date") or c["id"])[:19].replace(":", "-")])) + name = "".join(ch if ch.isalnum() or ch in " -_.T" else "_" for ch in name).strip(" .") + path = user_dir("VIDEOS" if clip else "PICTURES") / "Xbox" / f"{name}.{'mp4' if clip else 'png'}" + tmp = path.with_name("." + path.name + ".part") + try: + path.parent.mkdir(parents=True, exist_ok=True) + with urllib.request.urlopen(urllib.request.Request(c["url"], headers={"User-Agent": "deck-it"}), + timeout=30) as r, open(tmp, "wb") as f: + shutil.copyfileobj(r, f) + os.replace(tmp, path) + except (OSError, http.client.HTTPException) as e: + tmp.unlink(missing_ok=True) + raise ModuleError(f"save failed: {e}") from e + return {"path": str(path)} + # --- the reader thread ---------------------------------------------- def next_read(self) -> float: return QUICK if time.monotonic() < self.quick_until else FAST diff --git a/static/deck.css b/static/deck.css index 02c91aa..6e46154 100644 --- a/static/deck.css +++ b/static/deck.css @@ -972,6 +972,7 @@ dialog.vm-sheet::backdrop { background: color-mix(in srgb, var(--udt-crust) 55%, .xbox dialog.xb-view::backdrop { background: color-mix(in srgb, var(--udt-crust) 70%, transparent); } .xbox .xb-vmedia { width: 100%; max-height: 75vh; object-fit: contain; border-radius: 12px; background: var(--udt-crust); } .xbox .xb-vfoot { display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.xbox .xb-vbtns { display: flex; gap: 8px; flex: none; } .xbox .xb-vdl { display: inline-flex; align-items: center; padding: 0 18px; font-size: 1rem; font-weight: 600; text-decoration: none; } .xbox .xb-gname {font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .xbox .xb-gmeta { color: var(--udt-subtext0); font-size: 0.857rem; } diff --git a/static/modules/xbox.js b/static/modules/xbox.js index 094b1c0..ad6eda2 100644 --- a/static/modules/xbox.js +++ b/static/modules/xbox.js @@ -213,14 +213,33 @@ function gameTile(t) { function view(c, dlg) { const media = c.kind === "clip" ? h("video", "xb-vmedia") : img(c.url, "xb-vmedia"); if (c.kind === "clip") Object.assign(media, { src: c.url, controls: true, autoplay: true, playsInline: true }); - const a = h("a", "ib xb-vdl", "Download"); + const a = h("a", "ib xb-vdl", "Tablet"); a.href = c.url; a.download = `${c.id}.${c.kind === "clip" ? "mp4" : "png"}`; a.referrerPolicy = "no-referrer"; + const meta = [c.title, new Date(c.date).toLocaleString(), + c.expires ? `kept until ${new Date(c.expires).toLocaleDateString()}` : null].filter(Boolean).join(" · "); + const info = h("div", "xb-gmeta", meta); + // The PC downloads it into Pictures/Xbox or Videos/Xbox; the answer names the file. + const pc = h("button", "ib xb-vdl", "Save to PC"); + pc.onclick = async () => { + pc.disabled = true; + info.textContent = "Saving…"; + try { + const r = await fetch("/api/xbox/save", { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: c.id }), + }); + if (!r.ok) throw new Error((await r.text()) || "save failed"); + info.textContent = `Saved: ${(await r.json()).path}`; + } catch (e) { + info.textContent = e.message; + } + pc.disabled = false; + }; const foot = h("div", "xb-vfoot"); - foot.append(h("div", "xb-gmeta", [c.title, new Date(c.date).toLocaleString(), - c.expires ? `kept until ${new Date(c.expires).toLocaleDateString()}` : null].filter(Boolean).join(" · "))); - foot.append(a); + const btns = h("div", "xb-vbtns"); + btns.append(pc, a); + foot.append(info, btns); const close = h("button", "ib nf xb-vclose", "\u{F0156}"); close.setAttribute("aria-label", "Close"); close.onclick = () => dlg.close(); diff --git a/tests/test_xbox.py b/tests/test_xbox.py index a05ba60..85146a4 100644 --- a/tests/test_xbox.py +++ b/tests/test_xbox.py @@ -412,6 +412,26 @@ class Tick(Base): self.assertEqual(self.status.read_text(), "0") +class Save(Base): + def test_a_listed_capture_is_saved_under_its_user_dir(self): + x = self.xbox() + x.tick() + d = Path(tempfile.mkdtemp()) + src = d / "src.mp4" + src.write_bytes(b"clip") + x.data["captures"][0]["url"] = src.as_uri() # C1, the clip + old = xb.user_dir + xb.user_dir = lambda name: d / name + try: + path = Path(x.save({"id": "C1"})["path"]) + with self.assertRaises(xb.ModuleError): + x.save({"id": "NOPE"}) + finally: + xb.user_dir = old + self.assertEqual(path, d / "VIDEOS" / "Xbox" / "Some Game 2026-11-23T10-00-00.mp4") + self.assertEqual(path.read_bytes(), b"clip") + + class Commands(Base): def test_a_command_goes_to_xccs(self): x = self.xbox() @@ -458,7 +478,7 @@ class Commands(Base): def test_make_lists_the_actions(self): m = xb.make({"xbox": {"client_id": ""}}) - self.assertEqual(set(m.actions), {"login", *xb.COMMANDS}) + self.assertEqual(set(m.actions), {"login", "save", *xb.COMMANDS}) self.assertEqual(m.state(), {"offline": True, "unconfigured": True}) |
