feat(plex): Phase A — one-time Plex→Siftlode watch-state import

Plex records watch state per Plex account; Siftlode per user in plex_states. A new plex_link table
maps a Siftlode user to a Plex account; for the owner (MVP) the row uses the server admin token
(uses_admin=True), so no separate Plex login. app/plex/watch_sync.py reads the owner account's
viewCount/viewOffset/lastViewedAt (already present in the catalog mirror's section listing) and
upserts them into the owner's plex_states — 'Plex is master' on this first import, but only where
Plex has a watch record (Siftlode-only states are preserved; union on the intersection). Idempotent.

Admin routes: GET/POST /api/plex/watch/link (status + enable/disable; first enable runs the import)
and POST /api/plex/watch/import (re-run). Migration 0051_plex_link. Two-way push (Phase B) and the
incremental Plex→Siftlode reconcile (Phase C) build on this in later ships.
This commit is contained in:
npeter83 2026-07-09 14:42:18 +02:00
parent 8675e24663
commit 04fb3fb16e
6 changed files with 278 additions and 0 deletions

View file

@ -0,0 +1,50 @@
"""plex_link: per-user Plex account link for two-way watch-state sync
Phase A of the Plex Siftlode watch-state sync. One row per Siftlode user who syncs their watch
state with a Plex account. The owner MVP uses the server admin token (uses_admin=True, no personal
token); a personal token column is reserved for later friend-account linking (PIN OAuth). See the
PlexLink model docstring.
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "0051_plex_link"
down_revision: Union[str, None] = "0050_asset_poster"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"plex_link",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"user_id",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("uses_admin", sa.Boolean(), server_default="true", nullable=False),
sa.Column("plex_token_enc", sa.Text(), nullable=True),
sa.Column("plex_account_id", sa.Integer(), nullable=True),
sa.Column("plex_username", sa.String(length=255), nullable=True),
sa.Column("sync_enabled", sa.Boolean(), server_default="false", nullable=False),
sa.Column("initial_import_done", sa.Boolean(), server_default="false", nullable=False),
sa.Column("last_watch_sync_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("linked_at", sa.DateTime(timezone=True), nullable=True),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.UniqueConstraint("user_id", name="uq_plex_link_user"),
)
op.create_index("ix_plex_link_user_id", "plex_link", ["user_id"])
def downgrade() -> None:
op.drop_index("ix_plex_link_user_id", table_name="plex_link")
op.drop_table("plex_link")