# 020 — Account core `wcs/account/` (A05)

Created: 2026-11-06
Updated: 2026-11-06

Contract: WEB `docs/plan/account-sync/04-protocol.md`. Merge rules live only on the server (WEB 03 §6); the addon
records intents and applies the server's state.

## 1. Modules

| Module | Responsibility | Imported by |
|---|---|---|
| `state.py` | `signed_in()` (one `getSetting('account_token')`, cached per process for 2 s), `account_name()` | everything; must stay tiny (main.py fast path) |
| `client.py` `DEFAULT_SERVER` | server URL (default the Hub `https://hosting.pilsfree.net/chudy/milionar/` since S29 / 2.1.136; before it the Mac instance), hidden setting `account_server` overrides), protocol version 1, timeouts | client |
| `contract.py` | op types, entity names, key builders (`movie:<id>`, `tv:<id>:<s>:<e>`, …) | hooks, apply, tests |
| `token.py` | read/write `account_token`, `account_device_id`, `account_name`, `account_email` (hidden settings); never logged | client, switch |
| `client.py` | one `requests.Session`; `X-Milionar-Sync`, `X-Milionar-Client`, bearer; connect 5 s, read: pull `wait + 5`, push 15 s, bootstrap 30 s; learns `offset = server_time − local` from every response; 401 → `signed_out_remote`, 426 → `upgrade_required`, 429 → backoff; logs only method, path and status | worker, switch, pairing |
| `pairing.py` | start, poll (abortable), result → `token.py` | UI (040) |
| `outbox.py` | `sync_outbox` table access (in `library.db`, schema V5), coalescing, batches | hooks, worker |
| `hooks.py` | `record(conn, op)` called by `store.py` inside its transaction | store |
| `docs.py` | base snapshots and 3-way diff of JSON documents | worker |
| `settings_sync.py` | diff of account-scope settings against their base | worker (service `onSettingsChanged`) |
| `apply.py` | pulled rows → store (source `sync`), files, settings | worker, switch |
| `secrets.py` | fetch and write keys; provider flags and statuses afterwards | worker, switch |
| `usage.py` | new `ai_usage.db` rows → `ai_usage_add` ops | worker |
| `foryou.py` | server snapshot (050) | `wcs/foryou/service.py` |
| `worker.py` | the `milionar-sync` thread | `service.py`, `switch.py` |
| `switch.py` | sign-in / sign-out state machine (030) | UI, worker |

## 2. Store integration

- `SCHEMA_V5`: `sync_outbox(id INTEGER PRIMARY KEY, op_id TEXT UNIQUE, type TEXT, key TEXT, at INTEGER, payload TEXT,
  attempts INTEGER DEFAULT 0, next_attempt REAL DEFAULT 0)`, index `(key)`; `sync_state(key TEXT PRIMARY KEY, value
  TEXT)` (cursor, secrets_rev, last server offset, document base hashes).
- Every public write of `store.py` gets `source=None` (default = local). When `state.signed_in()` and `source !=
  'sync'`, it calls `hooks.record(conn, op)` **inside the same `with tx() as conn`**. The op mirrors the function:
  `save_resume` → `progress`, `mark_watched` → `watched`, `mark_unwatched` → `unwatched`, `clear_resume` →
  `clear_resume`, `mark_many` → `mark_many`, `set_in_list`/`replace_list` → `list_set`/`list_move`,
  `set_hidden_from_continue` → `hide_continue`, `set_feedback` → `feedback_set`/`feedback_clear`,
  `log_finish` → `play_log_add` (uuid kept in a new `play_log.uuid` column), `reset_watch_state` (via `reset.py`)
  → `reset_watch`.
- Coalescing: a new `progress` op replaces a pending `progress` op of the same key (UPDATE payload/at/op_id is kept);
  nothing else coalesces. `at` = `time.time()*1000 + offset`.
- Signed out: `hooks` is never imported (keep `main.py`'s fast path and the TV's start time unchanged — measure).

## 3. Documents (JSON files) and settings

- Documents: `mytv_channels.json`, `mycinema_channels.json`, `mytv_history/*`, `mycinema_history/*`,
  `search_history.json` (+ the other live search files A00.1 finds), `global_watch_history.json`,
  `ai_recommendations.json`, `favorite_{actors,directors,writers}.json`.
- `DATA/account/base/<doc>.json` = the last state agreed with the server. A round: if the file's `(mtime, size)`
  changed since the last round, load it, diff against `base` → ops (channels by `id`: create, rename, icon, move,
  delete, item set/unset with position; histories: add/remove/clear; favourites: set), put them into the outbox in one
  transaction **and** write the new base in the same step (base written after the outbox commit, by `os.replace`; a
  crash in between only re-diffs and the ops are idempotent by content-derived `op_id`).
- Applying a pulled document change: update the file (merge the server row into the current file: only the changed
  entity), write the base too; the next round sees no diff.
- Settings: base = values of the account-scope ids (from `GET api/sync/schema`, cached in `sync_state`). On
  `onSettingsChanged` (and each round) diff → `setting_set` / `setting_reset`. Remote settings are applied only when
  `not xbmc.getCondVisibility('Window.IsActive(addonsettings)')` (T20); applied values update the base first, so the
  following `onSettingsChanged` finds nothing.

## 4. Apply

- Pages of `changes` are applied in order. SQLite entities of one page: one `store.tx()`, using the store's own
  functions with `source='sync'` (or a bulk variant with identical effects) so `widget.rev.*` and `widget_titles`
  behave as for a local change — only touched titles redraw. Values equal to the local ones change nothing (the store
  functions already compare).
- Keys with a pending outbox op are skipped in this page (T6); the cursor still advances — the push ack will be
  followed by a pull that contains the server's resolved row for that key (the server bumps `rev` on every applied op).
  Safety net: after a push, keys of rejected ops are re-fetched by a `GET api/sync/changes?since=<cursor_before_page>`
  replay limited to those keys (or a small `entity/key` fetch endpoint if A04 adds one).
- The cursor is stored in `sync_state` inside the same transaction as the page's SQLite changes; file and settings
  changes of the page are applied before the cursor commit and are idempotent.

## 5. Worker thread `milionar-sync`

```
start: skip unless signed_in(); resume switch journal first (030)
loop until abort:
  give_way(monitor)                         # wcs/skin/userfirst.py
  docs/settings/usage round (cheap stat calls)
  push: while outbox has due ops: POST push (≤ 200) → delete applied/duplicate/rejected, backoff on errors
  pull: GET changes?since=cursor&wait=W     # W from A05.6 (T4)
        → apply pages; secrets if secrets_rev changed; logout flag → switch.remote_signout()
  wait on wake_event (set by hooks, skin_rows_changed, onSettingsChanged) or backoff timer, via monitor.waitForAbort
```

- Abort: the thread checks `monitor.abortRequested()` between every step; a long-poll in flight is interrupted by
  closing its socket from the service's abort path (A05.6 proves ≤ 1 s); if that cannot be proven on all platforms,
  `W` = 3 s (short polls) — decided in A05.6 and written into `900-decisions.md`.
- CPU: no busy loops; JSON parsing of a page off the GUI; no Kodi GUI call except `executebuiltin` notifications.
- Errors: logged once per streak (`[Milionář Account]` prefix), never with headers or bodies of secrets.

## 6. Secrets in Kodi

The server returns values by addon setting id (WEB 04 "Secrets"). `secrets.apply(values)`: set every given id,
clear every secret id that is missing, then `provider_keys.write_flags(...)`, `accounts.sync_status(addon)`, Vinyl
status, Webshare `refresh_vip_info` in the background. The Webshare session `token` is **not** a secret of the account
(T9): after `wsuser`/`wspass` change, clear `token` so the existing re-login runs.

## Result

2026-11-06: `wcs/account/` (state, hooks, client, schema, apply, docs, sync, worker, secrets, service, foryou),
store schema V5 (`sync_outbox`, `sync_state`, `play_log.uuid`), ops recorded in the store's transactions. Push and
pull threads in the service; long-poll with a 1 s heartbeat (abort ≤ 2 s). Simulator fixes K4–K6. Log redaction of
keys and tokens in `wcs/net.py`. Verified: every addon test file, `scripts/account_harness/test_two_devices.py`, the
simulator (WEB 11-status), live on the Mac Kodi (propagation ≤ 1 s both ways).
