# cplieger/plex-language-sync architecture

> Architecture diagram of the GitHub repository cplieger/plex-language-sync, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-09). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/cplieger/plex-language-sync
- Repository: https://github.com/cplieger/plex-language-sync

## Overview

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: [`internal/sync/episode.go`](https://github.com/cplieger/plex-language-sync/blob/main/internal/sync/episode.go) (Episode Sync), [`main.go`](https://github.com/cplieger/plex-language-sync/blob/main/main.go) (Main), [`internal/cache/cache.go`](https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/cache.go) (Cache), [`internal/plex/client.go`](https://github.com/cplieger/plex-language-sync/blob/main/internal/plex/client.go) (Plex Client)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime"]
  node_main["Main<br/>daemon entrypoint<br/>[main.go]"]
  node_config["Config<br/>[config.go]"]
end

subgraph group_integration["Integration"]
  node_plex_client["Plex Client<br/>plex adapter<br/>[client.go]"]
  node_plex_domain["Plex Domain<br/>plex model<br/>[history.go]"]
  node_api_plex["Plex API<br/>api boundary<br/>[plex.go]"]
  node_api_users["User API<br/>auth boundary<br/>[users.go]"]
  node_users_manager["Users<br/>token manager<br/>[manager.go]"]
end

subgraph group_processing["Processing"]
  node_notify_listener["Listener<br/>ws ingestion<br/>[listener.go]"]
  node_notify_classify{{"Classify<br/>event filter<br/>[classify.go]"}}
  node_notify_predicates{{"Predicates<br/>event rules<br/>[predicates.go]"}}
  node_sync_episode["Episode Sync<br/>sync flow<br/>[episode.go]"]
  node_sync_profile["Profiles<br/>preference model<br/>[profile.go]"]
  node_sync_tracks["Track Apply<br/>track update<br/>[tracks.go]"]
  node_streams_match{{"Match<br/>[match.go]"}}
  node_streams_score{{"Score<br/>ranking logic<br/>[score.go]"}}
  node_streams_select{{"Select<br/>[select.go]"}}
  node_streams_describe["Describe<br/>track model<br/>[describe.go]"]
  node_ignore_policy{{"Ignore Policy<br/>scope filter<br/>[policy.go]"}}
end

subgraph group_state["State"]
  node_cache_store[("Cache<br/>json state<br/>[cache.go]")]
  node_cache_profiles[("Profile Store<br/>state store<br/>[profile.go]")]
  node_cache_processed[("Processed<br/>state store<br/>[processed.go]")]
  node_cache_tokens[("Tokens<br/>state store<br/>[tokens.go]")]
  node_cache_scheduler[("Scheduler State<br/>state store<br/>[scheduler.go]")]
  node_scheduler(("Scheduler<br/>reconcile loop<br/>[scheduler.go]"))
end

subgraph group_support["Support"]
  node_fakeapi["Fake API<br/>test harness<br/>[plex.go]"]
end

node_main -->|"loads"| node_config
node_main -->|"connects"| node_plex_client
node_main -->|"opens"| node_cache_store
node_main -->|"starts"| node_notify_listener
node_main -->|"starts"| node_scheduler
node_main -->|"wires"| node_users_manager
node_notify_listener -->|"parses"| node_notify_classify
node_notify_classify -->|"uses"| node_notify_predicates
node_notify_listener -->|"subscribes"| node_plex_client
node_notify_listener -->|"emits"| node_sync_episode
node_sync_episode -->|"filters"| node_ignore_policy
node_sync_episode -->|"normalizes"| node_streams_describe
node_sync_episode -->|"matches"| node_streams_match
node_sync_episode -->|"scores"| node_streams_score
node_sync_episode -->|"selects"| node_streams_select
node_sync_episode -->|"applies"| node_sync_tracks
node_sync_episode -->|"learns"| node_sync_profile
node_sync_profile -->|"persists"| node_cache_profiles
node_sync_tracks -->|"records"| node_cache_processed
node_scheduler -->|"reads/writes"| node_cache_scheduler
node_scheduler -->|"reconciles"| node_sync_episode
node_plex_client -->|"models"| node_plex_domain
node_plex_client -->|"serves"| node_api_plex
node_users_manager -->|"uses"| node_api_users
node_users_manager -->|"persists"| node_cache_tokens
node_cache_store -->|"contains"| node_cache_processed
node_cache_store -->|"contains"| node_cache_profiles
node_cache_store -->|"contains"| node_cache_tokens
node_cache_store -->|"contains"| node_cache_scheduler
node_fakeapi -.->|"mocks"| node_cache_store
node_fakeapi -.->|"mocks"| node_plex_client

click node_main "https://github.com/cplieger/plex-language-sync/blob/main/main.go"
click node_config "https://github.com/cplieger/plex-language-sync/blob/main/config.go"
click node_notify_listener "https://github.com/cplieger/plex-language-sync/blob/main/internal/notify/listener.go"
click node_notify_classify "https://github.com/cplieger/plex-language-sync/blob/main/internal/notify/classify.go"
click node_notify_predicates "https://github.com/cplieger/plex-language-sync/blob/main/internal/notify/predicates.go"
click node_sync_episode "https://github.com/cplieger/plex-language-sync/blob/main/internal/sync/episode.go"
click node_sync_profile "https://github.com/cplieger/plex-language-sync/blob/main/internal/sync/profile.go"
click node_sync_tracks "https://github.com/cplieger/plex-language-sync/blob/main/internal/sync/tracks.go"
click node_streams_match "https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/match.go"
click node_streams_score "https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/score.go"
click node_streams_select "https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/select.go"
click node_streams_describe "https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/describe.go"
click node_ignore_policy "https://github.com/cplieger/plex-language-sync/blob/main/internal/ignore/policy.go"
click node_plex_client "https://github.com/cplieger/plex-language-sync/blob/main/internal/plex/client.go"
click node_plex_domain "https://github.com/cplieger/plex-language-sync/blob/main/internal/plex/history.go"
click node_api_plex "https://github.com/cplieger/plex-language-sync/blob/main/internal/api/plex.go"
click node_api_users "https://github.com/cplieger/plex-language-sync/blob/main/internal/api/users.go"
click node_users_manager "https://github.com/cplieger/plex-language-sync/blob/main/internal/users/manager.go"
click node_cache_store "https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/cache.go"
click node_cache_profiles "https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/profile.go"
click node_cache_processed "https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/processed.go"
click node_cache_tokens "https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/tokens.go"
click node_cache_scheduler "https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/scheduler.go"
click node_scheduler "https://github.com/cplieger/plex-language-sync/blob/main/internal/scheduler/scheduler.go"
click node_fakeapi "https://github.com/cplieger/plex-language-sync/blob/main/internal/testsupport/fakeapi/plex.go"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_config toneBlue
class node_plex_client,node_plex_domain,node_api_plex,node_api_users,node_users_manager toneAmber
class node_notify_listener,node_notify_classify,node_notify_predicates,node_sync_episode,node_sync_profile,node_sync_tracks,node_streams_match,node_streams_score,node_streams_select,node_streams_describe,node_ignore_policy toneMint
class node_cache_store,node_cache_profiles,node_cache_processed,node_cache_tokens,node_cache_scheduler,node_scheduler toneRose
class node_fakeapi toneIndigo
```

## Components

### Runtime

Entrypoint, configuration, and daemon orchestration.

- [Main](https://github.com/cplieger/plex-language-sync/blob/main/main.go): daemon entrypoint · Bootstraps the service, wires dependencies, and drives shutdown. · `main.go`
- [Config](https://github.com/cplieger/plex-language-sync/blob/main/config.go): env config · Loads runtime settings such as Plex credentials, scope, TLS, cadence, and logging. · `config.go`

### Integration

Outbound adapters for Plex, Plex TV, and user/token management.

- [Plex Client](https://github.com/cplieger/plex-language-sync/blob/main/internal/plex/client.go): plex adapter · HTTP/WebSocket client layer for Plex and Plex TV interactions. · `internal/plex/client.go`
- [Plex Domain](https://github.com/cplieger/plex-language-sync/blob/main/internal/plex/history.go): plex model · Normalized Plex entities for history, libraries, identities, streams, and shared resources. · `internal/plex/history.go`
- [Plex API](https://github.com/cplieger/plex-language-sync/blob/main/internal/api/plex.go): api boundary · Adapter boundary for Plex-facing operations used by the daemon. · `internal/api/plex.go`
- [User API](https://github.com/cplieger/plex-language-sync/blob/main/internal/api/users.go): auth boundary · User and shared-token operations used to keep per-user preferences separate. · `internal/api/users.go`
- [Users](https://github.com/cplieger/plex-language-sync/blob/main/internal/users/manager.go): token manager · Manages Plex users and refreshes shared-user tokens. · `internal/users/manager.go`

### Processing

Event ingestion, filtering, stream matching, and sync decisions.

- [Listener](https://github.com/cplieger/plex-language-sync/blob/main/internal/notify/listener.go): ws ingestion · WebSocket listener with reconnect/backoff and event intake from Plex. · `internal/notify/listener.go`
- [Classify](https://github.com/cplieger/plex-language-sync/blob/main/internal/notify/classify.go): event filter · Determines which Plex events matter and how to interpret them. · `internal/notify/classify.go`
- [Predicates](https://github.com/cplieger/plex-language-sync/blob/main/internal/notify/predicates.go): event rules · Reusable checks for playback and library-scan relevance. · `internal/notify/predicates.go`
- [Episode Sync](https://github.com/cplieger/plex-language-sync/blob/main/internal/sync/episode.go): sync flow · Coordinates episode-level propagation of preferred audio and subtitle tracks. · `internal/sync/episode.go`
- [Profiles](https://github.com/cplieger/plex-language-sync/blob/main/internal/sync/profile.go): preference model · Learns and applies reusable language profiles for new or unseen shows. · `internal/sync/profile.go`
- [Track Apply](https://github.com/cplieger/plex-language-sync/blob/main/internal/sync/tracks.go): track update · Applies selected track choices to target episodes. · `internal/sync/tracks.go`
- [Match](https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/match.go): scoring match · Compares tracks using language, codec, titles, flags, and other signals. · `internal/streams/match.go`
- [Score](https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/score.go): ranking logic · Ranks candidate audio and subtitle tracks for deterministic selection. · `internal/streams/score.go`
- [Select](https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/select.go): selection logic · Chooses the best stream candidates from the scored set. · `internal/streams/select.go`
- [Describe](https://github.com/cplieger/plex-language-sync/blob/main/internal/streams/describe.go): track model · Normalizes stream properties into comparable descriptors. · `internal/streams/describe.go`
- [Ignore Policy](https://github.com/cplieger/plex-language-sync/blob/main/internal/ignore/policy.go): scope filter · Excludes libraries and shows based on labels and configured names. · `internal/ignore/policy.go`

### State

Persistent cache and scheduling metadata.

- [Cache](https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/cache.go): json state · Persistent JSON-backed state for processed episodes, profiles, tokens, and scheduler metadata. · `internal/cache/cache.go`
- [Profile Store](https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/profile.go): state store · Persists learned language profiles and related model state. · `internal/cache/profile.go`
- [Processed](https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/processed.go): state store · Tracks episodes already handled to keep sync idempotent. · `internal/cache/processed.go`
- [Tokens](https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/tokens.go): state store · Stores refreshed shared-user tokens and auth material. · `internal/cache/tokens.go`
- [Scheduler State](https://github.com/cplieger/plex-language-sync/blob/main/internal/cache/scheduler.go): state store · Persists reconciliation cadence and last-run metadata. · `internal/cache/scheduler.go`
- [Scheduler](https://github.com/cplieger/plex-language-sync/blob/main/internal/scheduler/scheduler.go): reconcile loop · 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](https://github.com/cplieger/plex-language-sync/blob/main/internal/testsupport/fakeapi/plex.go): test harness · Contract-style fake Plex and cache implementations used by tests. · `internal/testsupport/fakeapi/plex.go`

## Connections

- 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.
