Debian Codegraph @

CLAUDE.md

raw symbols SCIP
1 # CLAUDE.md
2
3 This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
5 ## Project
6
7 Python client for the Jellyfin media server API. Originally extracted from Jellyfin Kodi so other projects (e.g. Jellyfin MPV Shim) can consume the API without forking. Distributed on PyPI as `jellyfin-apiclient-python`. The API surface is intentionally incomplete — features get added when consumers need them.
8
9 ## Common commands
10
11 Tests and linting are driven by `tox`:
12
13 - `tox -elint` — ruff lint over `jellyfin_apiclient_python` and `tests`.
14 - `tox -epy39` (or any of `py38,py39,py310,py311,py312`) — run the pytest suite under that interpreter.
15 - `tox -elint,py311` — chain envs.
16 - `pytest tests/test_api.py::test_jellyfin_url_handles_trailing_slash` — run a single test (inside an env or with pytest installed directly). Anything after `--` in `tox -epy311 -- ...` is forwarded to pytest.
17
18 CI (`.github/workflows/ci.yml`) runs the same `tox` matrix on push to `master` and on PRs.
19
20 ## Architecture
21
22 ### Entry points and lifecycle
23
24 Two ways to instantiate:
25
26 - `JellyfinClient()` directly (`jellyfin_apiclient_python/client.py`) — straightforward composition root. Constructs `Config`, `HTTP`, `WSClient`, `ConnectionManager` (as `auth`), `API` (as `jellyfin`), and `TimeSyncManager`. Lifecycle is `authenticate()` → `start(websocket=…, keep_alive=…)` → `stop()`.
27 - `Jellyfin('server_id')` facade in `__init__.py` — **Borg pattern**: all instances share `_shared_state` and a class-level `client` dict keyed by `server_id`. `__getattr__`/`__setattr__` proxy through to the underlying `JellyfinClient`, lazily constructing one via `@ensure_client()`. This is how multi-server callers manage parallel clients without juggling references. Treat it as a registry, not a normal object.
28
29 ### `JellyfinClient` composition
30
31 `config` (`Config`) is a thin `dict` wrapper. Code throughout the package reads/writes string keys directly on `config.data` (`auth.server`, `auth.token`, `auth.user_id`, `app.device_id`, `auth.tls_client_cert`, `auth.ssl`, `http.timeout`, …). There is no schema — keys are a de facto contract spread across `http.py`, `connection_manager.py`, and `ws_client.py`. When adding a config key, grep for siblings to keep naming consistent.
32
33 `http` (`HTTP`) wraps `requests.Session` with retry/backoff and Jellyfin-specific behavior:
34
35 - Builds the `Authorization: MediaBrowser …` header from `app.*` and `auth.token` config in `_get_authenication_header`.
36 - Substitutes `{server}`, `{UserId}`, `{DeviceId}` placeholders in URLs and params via `_replace_user_info` — this is why API mixin handlers can be written as literal strings like `"Users/{UserId}/Items"`.
37 - On 401, distinguishes `AccessRestricted` (header `X-Application-Error-Code` present) from `Unauthorized` (which also calls `auth.revoke_token()`); both fire `client.callback(...)`. 500s are logged and swallowed (return `None`). Connection/read errors retry with a 1s sleep.
38 - Optional mTLS via `auth.tls_client_cert`/`auth.tls_client_key`/`auth.tls_server_ca` — also honored by `WSClient` and `ConnectionManager`.
39
40 `auth` (`ConnectionManager`) owns server discovery, login, and credential storage:
41
42 - `_server_discovery()` does UDP broadcast on port 7359 with `b"who is JellyfinServer?"`.
43 - `connect()` / `connect_to_address()` / `connect_to_server()` return a state dict whose `'State'` is a `CONNECTION_STATE` enum (`Unavailable`, `ServerSelection`, `ServerSignIn`, `SignedIn`).
44 - `Credentials` (`credentials.py`) holds a `{'Servers': [...]}` dict. Server entries carry `Id`, `address`, `AccessToken`, `UserId`, `DateLastAccessed`, etc. `add_update_server` merges by `Id` and is the single place to mutate the server list.
45 - Authentication supports username/password, persisted access tokens, and server-side API keys (omit `app.device_name`/`app.device_id` to use API-key mode — see README).
46
47 `jellyfin` (`api.API`) is **composed by multiple inheritance** from mixins in `api.py`:
48
49 - `InternalAPIMixin` — `_get`/`_post`/`_delete`/`_get_url`/`_get_stream` helpers that route through `client.request(...)`.
50 - `BiggerAPIMixin` — broad endpoints (`sessions`, `users`, `items`, `shows`, `videos`, `artwork`, `audio_url`, library management).
51 - `GranularAPIMixin` — user-scoped helpers like `get_item`, `search_media_items`, `get_userdata_for_item`.
52 - `SyncPlayAPIMixin` — SyncPlay endpoints; coordinates with `TimeSyncManager`.
53 - `ExperimentalAPIMixin` — newer/unstable endpoints.
54 - `CollectionAPIMixin` — collection management.
55
56 When adding endpoints, place them in the mixin that matches their domain. The MRO is fixed by the `class API(InternalAPIMixin, BiggerAPIMixin, GranularAPIMixin, SyncPlayAPIMixin, ExperimentalAPIMixin, CollectionAPIMixin)` declaration at the bottom of `api.py`.
57
58 `wsc` (`WSClient`, `ws_client.py`) is a `threading.Thread` that maintains the realtime websocket. Two modes:
59
60 - Default (`multi_client=False`) — class-level `global_wsc`/`global_stop` ensure one socket process-wide; instantiating a new client closes the previous.
61 - `allow_multiple_clients=True` — per-instance socket; required when using the `Jellyfin` Borg facade with multiple `server_id`s.
62
63 Incoming `MessageId`s are deduped in `self.message_ids`. `ForceKeepAlive` messages start a `KeepAlive` (`keepalive.py`) thread that periodically pings. All messages dispatch via `client.callback(message_type, data)`; consumers reassign `client.callback` to receive events. When the Borg facade is in use, `data['ServerId']` is injected so a single callback can demultiplex.
64
65 `timesync` (`TimeSyncManager`) is a port of jellyfin-web's SyncPlay time sync. Polls `utc_time()`, retains the 8 lowest-delay measurements, exposes `get_time_offset()` / `get_ping()` and a subscriber callback API. Polls greedily (1s) for the first few measurements then drops to 60s.
66
67 ### Cross-cutting conventions
68
69 - **Backward compatibility is a hard rule** for `api.py` — see README's "Contributing" section. Add new parameters with defaults; don't rename or remove existing ones. Document additions in README's "Changes from Jellyfin Kodi" list.
70 - **Logging** uses two logger names inconsistently: `'Jellyfin'` (root, in `__init__.py`/`http.py`/`credentials.py`) and `'JELLYFIN.<module>'` (everywhere else). Follow the surrounding file rather than unifying.
71 - **Callbacks** are the primary out-of-band signal. `client.callback(event, data)` is invoked for `ServerOnline`, `ServerUnreachable`, `AccessRestricted`, `Unauthorized`, `WebSocketConnect`/`Disconnect`/`Error`, and every websocket message type. Default is a no-op; consumers override.
72 - **Python 3.6+** per `pyproject.toml`, but the tox/CI matrix is 3.8–3.12. f-strings and `from __future__` are fine; avoid 3.10-only syntax (match statements, `X | Y` unions in runtime contexts).