How cplieger/plex-language-sync works
1. What this service is
- plex-language-sync is a single Go daemon that watches a Plex Media Server and automatically propagates audio/subtitle preferences across episodes.
- It is not a web app and does not expose an inbound API; its only external dependencies are Plex and plex.tv.
2. Top-level runtime shape
- main.go is the orchestration entrypoint.
- config.go loads environment-driven configuration such as Plex URL/token, update scope/strategy, ignore rules, TLS settings, scheduler cadence, and debug logging.
- The binary is built into a minimal distroless container and runs as nonroot, which matters because the app relies on filesystem persistence only for its cache.
3. External integration boundary
- All Plex communication is encapsulated under internal/plex and internal/api.
- The system talks to Plex over HTTP and WebSocket, and to plex.tv for shared-user token refresh.
- There is no internal service mesh or local listener; the process is entirely outbound-driven.
4. Event ingestion path
- internal/notify contains the WebSocket listener, backoff, event classification, and predicates for deciding which Plex events matter.
- Plex playback events and library scan events are the two primary triggers.
- The listener is designed to reconnect with exponential backoff rather than fail the service on transient disconnects.
5. Core processing pipeline
- Incoming events are interpreted into actionable media targets, then routed through the sync logic in internal/sync.
- internal/sync/episode.go, profile.go, and tracks.go represent the episode-level update flow, language profile handling, and track selection application.
- This is where the service decides which episodes should be updated and which stream choices should be applied.
6. Stream matching and selection
- internal/streams is the matching/scoring subsystem.
- It compares audio and subtitle tracks using multiple signals: language, codec, channel layout, titles, forced/hearing-impaired/visual-impaired/descriptive flags, and subtitle codec preferences.
- This subsystem is central to the architecture because it turns “the user chose a track on one episode” into a deterministic choice for other episodes.
7. Learned preference model
- When LANGUAGE_PROFILES is enabled, the service learns audio-to-subtitle habits from playback and stores them as reusable profiles.
- Those profiles are later applied to brand-new shows that have no watch history, so the system can pre-seed preferences before any manual playback occurs.
- This behavior is a separate data path from per-show propagation: one is retrospective within a show, the other is predictive for new content.
8. Persistent state and cache
- internal/cache owns the JSON-backed persistent state written to /config/cache.json.
- The cache stores processed episode tracking, learned language profiles, scheduler state, keys/tokens, and other restart-safe metadata.
- The README’s emphasis on atomic temp-file + rename and graceful shutdown reflects that persistence is a first-class architectural boundary.
9. User/token management
- internal/users manages Plex users and refreshes shared-user tokens.
- This enables multi-user behavior where each user’s preferences are maintained independently.
- internal/api/users.go and the cache token handling show that user identity and authorization are not global; they are part of the app’s state model.
10. Plex domain modeling
- internal/plex is the domain client/model layer for Plex entities such as identities, libraries, history, streams, and shared resources.
- This package isolates Plex API peculiarities from the rest of the application so that sync logic works on normalized media concepts rather than raw API payloads.
11. Filtering and scope boundaries
- internal/ignore/policy.go implements show/library exclusion rules based on Plex labels and library names.
- The sync scope is configurable at two important boundaries: show vs. season, and all episodes vs. future episodes only.
- These filters sit in front of the stream matching so that unwanted libraries/shows are excluded early.
12. Scheduled safety net
- internal/scheduler and internal/cache/scheduler.go coordinate the daily deep-analysis pass.
- The scheduler is a fallback mechanism that re-scans state and re-applies preferences even if an event was missed.
- In architecture terms, this is a reconciliation loop complementing the real-time WebSocket listener.
13. Health and operational behavior
- The container healthcheck is file-based, not network-based: it relies on a marker written after initial Plex connection and admin verification.
- Graceful shutdown stops background loops, then flushes cache state before exit.
- The app’s operational model is therefore “connect, watch, reconcile, persist,” with no exposed HTTP surface.
14. Testing and support structure
- internal/testsupport/fakeapi provides fake Plex/cache implementations for contract-style tests.
- The repository is heavily test-driven around matching, caching, notify classification, and Plex client behavior, which suggests those are the most critical architectural seams.
- CI/security workflows reinforce that this is a small, self-contained binary with strong emphasis on reproducibility and hardening.
Main entry points: episode.go Episode Sync · main.go Main · cache.go Cache · client.go Plex Client
Components 25
Runtime
Entrypoint, configuration, and daemon orchestration.
Integration
Outbound adapters for Plex, Plex TV, and user/token management.
- Plex Client · HTTP/WebSocket client layer for Plex and Plex TV interactions.
internal/plex/client.go - Plex Domain · Normalized Plex entities for history, libraries, identities, streams, and shared resources.
internal/plex/history.go - Plex API · Adapter boundary for Plex-facing operations used by the daemon.
internal/api/plex.go - User API · User and shared-token operations used to keep per-user preferences separate.
internal/api/users.go - Users · Manages Plex users and refreshes shared-user tokens.
internal/users/manager.go
Processing
Event ingestion, filtering, stream matching, and sync decisions.
- Listener · WebSocket listener with reconnect/backoff and event intake from Plex.
internal/notify/listener.go - Classify · Determines which Plex events matter and how to interpret them.
internal/notify/classify.go - Predicates · Reusable checks for playback and library-scan relevance.
internal/notify/predicates.go - Episode Sync · Coordinates episode-level propagation of preferred audio and subtitle tracks.
internal/sync/episode.go - Profiles · Learns and applies reusable language profiles for new or unseen shows.
internal/sync/profile.go - Track Apply · Applies selected track choices to target episodes.
internal/sync/tracks.go - Match · Compares tracks using language, codec, titles, flags, and other signals.
internal/streams/match.go - Score · Ranks candidate audio and subtitle tracks for deterministic selection.
internal/streams/score.go - Select · Chooses the best stream candidates from the scored set.
internal/streams/select.go - Describe · Normalizes stream properties into comparable descriptors.
internal/streams/describe.go - Ignore Policy · Excludes libraries and shows based on labels and configured names.
internal/ignore/policy.go
State
Persistent cache and scheduling metadata.
- Cache · Persistent JSON-backed state for processed episodes, profiles, tokens, and scheduler metadata.
internal/cache/cache.go - Profile Store · Persists learned language profiles and related model state.
internal/cache/profile.go - Processed · Tracks episodes already handled to keep sync idempotent.
internal/cache/processed.go - Tokens · Stores refreshed shared-user tokens and auth material.
internal/cache/tokens.go - Scheduler State · Persists reconciliation cadence and last-run metadata.
internal/cache/scheduler.go - Scheduler · Runs the scheduled deep-analysis pass as a fallback to missed events.
internal/scheduler/scheduler.go
Support
Test harness and fake backends for contract-style tests.
- Fake API · Contract-style fake Plex and cache implementations used by tests.
internal/testsupport/fakeapi/plex.go
Connections 31
- Main → Config: loads · Reads environment-driven configuration before wiring the daemon.
- Main → Plex Client: connects · Creates the outbound Plex/Plex TV client.
- Main → Cache: opens · Initializes persistent cache state.
- Main → Listener: starts · Launches event ingestion and reconnect loops.
- Main → Scheduler: starts · Runs the reconciliation scheduler.
- Main → Users: wires · Coordinates user and token refresh behavior.
- Listener → Classify: parses · Classifies inbound Plex events into actionable triggers.
- Classify → Predicates: uses · Applies event predicates to decide relevance.
- Listener → Plex Client: subscribes · Consumes Plex WebSocket/event updates.
- Listener → Episode Sync: emits · Routes meaningful events into sync processing.
- Episode Sync → Ignore Policy: filters · Drops excluded libraries and shows before matching.
- Episode Sync → Describe: normalizes · Builds comparable track descriptors from Plex streams.
- Episode Sync → Match: matches · Finds equivalent audio/subtitle choices across episodes.
- Episode Sync → Score: scores · Ranks candidate streams for deterministic selection.
- Episode Sync → Select: selects · Chooses the target audio/subtitle streams to apply.
- Episode Sync → Track Apply: applies · Updates episode tracks and propagates preferences.
- Episode Sync → Profiles: learns · Derives reusable language profiles when enabled.
- Profiles → Profile Store: persists · Stores learned preference profiles for future runs.
- Track Apply → Processed: records · Marks episodes as handled for restart-safe idempotency.
- Scheduler → Scheduler State: reads/writes · Keeps reconciliation cadence and last-run state.
- Scheduler → Episode Sync: reconciles · Re-applies sync logic during scheduled passes.
- Plex Client → Plex Domain: models · Uses normalized Plex domain types for libraries, history, and streams.
- Plex Client → Plex API: serves · Backs the Plex-facing API adapter boundary.
- Users → User API: uses · Refreshes shared-user tokens through the user API boundary.
- Users → Tokens: persists · Stores refreshed tokens per user.
- Cache → Processed: contains · Holds processed-episode tracking.
- Cache → Profile Store: contains · Holds learned language profiles.
- Cache → Tokens: contains · Holds token material and auth state.
- Cache → Scheduler State: contains · Holds scheduler reconciliation metadata.
- Fake API → Cache: mocks · Provides fake cache behavior for contract tests.
- Fake API → Plex Client: mocks · Provides fake Plex behavior for contract tests.