diff --git a/plexnow.py b/plexnow.py index da65582..c8d0d25 100644 --- a/plexnow.py +++ b/plexnow.py @@ -115,13 +115,18 @@ def summary(info: dict[str, Any]) -> str: return f"Plex: {info['label'] or 'unknown title'} ({info['state']}{where})" +async def session_for_device(names: list[str | None]) -> dict[str, Any] | None: + """The Plex server's session for this device, None when it has none; raises PlexLookupError.""" + sessions = await asyncio.to_thread(_fetch_sessions) + return match_session(sessions, names) + + async def now_playing(names: list[str | None]) -> dict[str, Any]: """Fields for a status body: now_playing text and plex_session, or a plain reason.""" try: - sessions = await asyncio.to_thread(_fetch_sessions) + session = await session_for_device(names) except PlexLookupError as exc: return {"now_playing": f"Plex open (now-playing lookup unavailable: {exc})"} - session = match_session(sessions, names) if session is None: return {"now_playing": NOTHING, "plex_session": None} info = describe(session) diff --git a/tests/test_tools.py b/tests/test_tools.py index 8130074..4d134cb 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1090,3 +1090,81 @@ def test_tvoverlay_screen_while_playing_is_still_in_use( ) -> None: _device_reads(monkeypatch, OVERLAY_FOCUS, "3") assert "in_use" in run(tools.in_use_refusal("shield-a", False))["error"] + + +def _plex_idle_reads( + monkeypatch: pytest.MonkeyPatch, + sessions: list[tuple[str, int]], + server: Any, +) -> None: + """Plex in front; media_session holds the given (package, state) rows; server is the Plex read.""" + dump = "".join( + f" package={pkg}\n active=true\n" + f" state=PlaybackState {{state={state}, position=0}}\n" + for pkg, state in sessions + ) + + async def fake_require(dev: dict[str, Any]) -> str: + return "s" + + async def fake_read(serial: str, command: str) -> str: + if "mWakefulness" in command: + return "mWakefulness=Awake" + if "media_session" in command: + return dump + if "device_name" in command: + return "shield-a" + return PLEX_FOCUS + + async def fake_fetch(names: list[str | None]) -> Any: + if isinstance(server, Exception): + raise server + return server + + monkeypatch.setattr(tools, "_opened", {}) + monkeypatch.setattr(adbops, "require_device", fake_require) + monkeypatch.setattr(adbops, "read", fake_read) + monkeypatch.setattr(plexnow, "session_for_device", fake_fetch) + + +@pytest.mark.parametrize( + "sessions", + [ + [("com.plexapp.android", 3)], + [("com.plexapp.android", 2)], + [("com.plexapp.android", 1)], + [], + ], +) +def test_in_use_false_when_plex_open_and_no_session( + monkeypatch: pytest.MonkeyPatch, sessions: list[tuple[str, int]] +) -> None: + _plex_idle_reads(monkeypatch, sessions, None) + assert run(tools.in_use_refusal("shield-a", False)) is None + + +def test_plex_open_with_a_server_session_is_still_in_use( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _plex_idle_reads(monkeypatch, [("com.plexapp.android", 2)], {"state": "paused"}) + assert "in_use" in run(tools.in_use_refusal("shield-a", False))["error"] + + +def test_plex_open_with_unreadable_server_is_still_in_use( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _plex_idle_reads( + monkeypatch, [("com.plexapp.android", 3)], plexnow.PlexLookupError("x") + ) + assert "in_use" in run(tools.in_use_refusal("shield-a", False))["error"] + + +def test_plex_idle_does_not_hide_another_app_playing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _plex_idle_reads( + monkeypatch, + [("com.plexapp.android", 1), ("org.smarttube.stable", 3)], + None, + ) + assert "in_use" in run(tools.in_use_refusal("shield-a", False))["error"] diff --git a/tools.py b/tools.py index 62d45c4..b2e441b 100644 --- a/tools.py +++ b/tools.py @@ -1604,9 +1604,31 @@ async def _adb_busy(dev: dict[str, Any]) -> bool: ) if not playing and not in_app: return False + if await _plex_idle(dev, serial, focus): + return False return bool(playing) or not _opened_recently(dev["name"], focus) +async def _plex_idle(dev: dict[str, Any], serial: str, focus: str) -> bool: + """Plex in front, the Plex server holds no session for this device, and no other app plays. + + Plex keeps a stale media session (even state 3) after playback ends, so the server is the + authority. An unreadable server returns False: the guard keeps refusing. + """ + if f" {plexnow.PLEX_PREFIX}" not in focus: + return False + try: + if await plexnow.session_for_device(await plex_names(dev)) is not None: + return False + except plexnow.PlexLookupError: + return False + sessions = adbops.parse_sessions(await adbops.read(serial, adbops.SESSIONS_READ)) + return not any( + s["state"] in adbops.ACTIVE_STATES and not plexnow.is_plex(s["package"]) + for s in sessions + ) + + async def device_busy(dev: dict[str, Any]) -> bool: """True when someone may be watching dev. A read failure counts as not busy.""" try: