"""The daily full watch reconcile (`run_plex_watch_reconcile`) — the one pass that DELETES watch state: a mirrored row Plex no longer has a record for is read as "Plex un-watched it" and cleared. E32 S2 found it trusting a scan a Plex hiccup had cut short; these hold what it may and may not clear. """ import pytest from sqlalchemy import select from app import sysconfig from app.models import PlexItem, PlexLibrary, PlexLink, PlexState, User from app.plex import watch_sync class _FakePlex: """A PlexClient stand-in: one movie section whose listing reports `total` (more than it hands over = a walk cut short), and a record of every write the reconcile sends back to Plex.""" def __init__(self, leaves: list[dict], total: int | None = None): self.leaves = leaves self.total = len(leaves) if total is None else total self.calls: list[tuple] = [] def __enter__(self): return self def __exit__(self, *exc): return False def sections(self): return [{"type": "movie", "key": "1"}] def section_items(self, key, item_type, start, size): return self.leaves[start : start + size], self.total def scrobble(self, rk): self.calls.append(("scrobble", rk)) def unscrobble(self, rk): self.calls.append(("unscrobble", rk)) def set_timeline(self, rk, time_ms, duration_ms): self.calls.append(("timeline", rk, time_ms)) @pytest.fixture def world(db): """Five mirrored movies and the owner's link; each test sets the local states it needs.""" sysconfig.set_value(db, "plex_enabled", True) lib = PlexLibrary(plex_key="1", title="Movies", kind="movie", enabled=True) user = User(email="reconcile@example.com") db.add_all([lib, user]) db.flush() items = {} for rk in ("m1", "m2", "m3", "m4", "m5"): items[rk] = PlexItem( rating_key=rk, library_id=lib.id, kind="movie", title=rk, duration_s=6000 ) db.add(items[rk]) db.add( PlexLink( user_id=user.id, uses_admin=True, sync_enabled=True, initial_import_done=True, plex_account_id=1, ) ) db.flush() def state(rk, **kw): db.add(PlexState(user_id=user.id, item_id=items[rk].id, **kw)) def rows(): db.expire_all() by_id = {i.id: rk for rk, i in items.items()} return { by_id[s.item_id]: (s.status, s.position_seconds, s.synced_to_plex) for s in db.execute(select(PlexState).where(PlexState.user_id == user.id)).scalars() } return state, rows def _run(db, monkeypatch, plex): monkeypatch.setattr(watch_sync, "PlexClient", lambda _db: plex) return watch_sync.run_plex_watch_reconcile(db) def _local_states(state): state("m1", status="watched", synced_to_plex=True) # mirrored; Plex has no record now state("m2", status="watched", synced_to_plex=False) # local change that never reached Plex state("m3", status="hidden", synced_to_plex=True) # Siftlode-only, never cleared state("m5", status="new", position_seconds=300, synced_to_plex=True) # Plex says otherwise def test_a_complete_scan_clears_what_plex_unwatched_and_keeps_the_rest(db, monkeypatch, world): state, rows = world _local_states(state) db.commit() plex = _FakePlex( [ {"ratingKey": "m3"}, # listed, no watch signal {"ratingKey": "m4", "viewCount": 1, "lastViewedAt": 1_700_000_000}, {"ratingKey": "m5", "viewOffset": 120_000, "lastViewedAt": 1_700_000_000}, ] ) out = _run(db, monkeypatch, plex) assert rows() == { "m2": ("watched", 0, True), # re-pushed, then settled "m3": ("hidden", 0, True), "m4": ("watched", 0, True), # pulled in "m5": ("new", 120, True), # Plex's position wins } assert ("scrobble", "m2") in plex.calls assert out["cleared"] == 1 and out["repushed"] == 1 and "incomplete" not in out def test_a_scan_cut_short_clears_nothing(db, monkeypatch, world): state, rows = world _local_states(state) db.commit() # The server said 5, the walk got 3: m1 may simply not have been reached. plex = _FakePlex( [ {"ratingKey": "m3"}, {"ratingKey": "m4", "viewCount": 1, "lastViewedAt": 1_700_000_000}, {"ratingKey": "m5", "viewOffset": 120_000, "lastViewedAt": 1_700_000_000}, ], total=5, ) out = _run(db, monkeypatch, plex) after = rows() assert after["m1"] == ("watched", 0, True) # NOT un-watched on a partial picture assert after["m4"] == ("watched", 0, True) and after["m5"] == ("new", 120, True) # pulls stand assert after["m2"] == ("watched", 0, True) # the dirty row is still pushed up assert out["cleared"] == 0 and out["incomplete"] == 1 def test_an_empty_listing_is_not_a_library_of_unwatched_titles(db, monkeypatch, world): state, rows = world state("m1", status="watched", synced_to_plex=True) db.commit() out = _run(db, monkeypatch, _FakePlex([])) assert rows() == {"m1": ("watched", 0, True)} assert out["cleared"] == 0 def test_a_dirty_resume_is_re_pushed_as_a_timeline_and_a_dirty_reset_as_an_unscrobble( db, monkeypatch, world ): state, rows = world state("m1", status="new", position_seconds=300, synced_to_plex=False) state("m2", status="new", position_seconds=2, synced_to_plex=False) # under the 5 s floor db.commit() plex = _FakePlex([{"ratingKey": rk} for rk in ("m1", "m2", "m3", "m4", "m5")]) _run(db, monkeypatch, plex) assert ("timeline", "m1", 300_000) in plex.calls assert ("unscrobble", "m2") in plex.calls assert {rk: synced for rk, (_s, _p, synced) in rows().items()} == {"m1": True, "m2": True} def test_watch_fields_map_to_a_state_only_when_plex_holds_a_signal(): to = watch_sync._plex_watch_to_state assert to(None, None, None) is None assert to(0, 4_000, None) is None # a stray few seconds is not "in progress" assert to(0, 90_000, 1_700_000_000)[:2] == ("new", 90) assert to("2", 90_000, 1_700_000_000)[:2] == ("watched", 0) # watched wins over an offset