diff options
Diffstat (limited to 'deckit/modules/xbox.py')
| -rw-r--r-- | deckit/modules/xbox.py | 35 |
1 files changed, 35 insertions, 0 deletions
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 |
