SYNC_PROVIDERS_EXTENDED.md
docs/features/SYNC_PROVIDERS_EXTENDED.md
1# Extended sync providers23Settings → Sync → Server provider now offers, next to Yokan Hub and Mangayomi, **SyncYomi** and **Google Drive**. Both are whole-library state sync: each run downloads the remote copy, merges it into the local library, and uploads the merged library. Local data is only merged into, never replaced; a remote deletion does not delete anything locally. Code: `services/sync/SyncYomiSyncService.kt`, `GoogleDriveSyncService.kt`, shared run/guard helpers in `StateSyncSupport.kt`, routing in `HybridSyncService.kt`.45Both follow the profile-ownership invariants (`docs/architecture/PROFILE_OWNERSHIP.md`): each run captures the exact account (provider, server, account, credential, device id) and re-claims its account lease before any request; the account is re-checked at every transfer boundary; the remote merge is applied through `BackupService.applyBackupIf(plan, RestoreMode.Merge, accepts)`, whose predicate runs on the snapshot the atomic commit expects (no safety snapshot, so scheduled runs don't evict restore points); `lastSync*` is written only by a guarded update. Sign-in claims the lease right before the guarded credential write. Credentials live only in the sync preference, which no backup or export contains. Automatic sync, the sync triggers and the manual Sync / Upload only / Download only buttons work unchanged (`syncOn` + non-blank `authToken`).67## SyncYomi89Self-hosted SyncYomi server, the same one Mihon/Aniyomi/Animetail use. Sign in with the server URL (`https://` assumed) and API key; sign-in validates the key with `GET /api/sync/content` (200 or 404 accepted, 401/403 rejected). Stored as `server` = normalized host, `authToken` = API key.1011A run:12131. `GET {host}/api/sync/content` with `X-API-Token`. 404 → no remote data. 2xx must carry an `ETag` (otherwise the run fails). A body that is not a readable backup is overwritten, as upstream does.142. The remote Tachiyomi protobuf `Backup` is merged into the library.153. The library is exported as raw protobuf (`BackupFormat.Tachiyomi`, compression level 0; history/updates per the toggles) and sent with `PUT`, `Content-Type: application/octet-stream`, `If-Match: <etag>` whenever the GET returned data.164. `412 Precondition Failed` means another device uploaded meanwhile: the whole run restarts (3 passes in total), then reports "SyncYomi data kept changing on the server". The ETag is kept only for the run.1718Upload only skips the merge but still uses a fresh GET's ETag; Download only never uploads.1920Limits: the protobuf format carries manga and anime only — novels and Yokan-only fields (private notes, custom covers, settings, etc.) never travel through SyncYomi, and the settings toggle is disabled. Lease key: `syncyomi|<host>|<first 8 bytes of SHA-256(API key)>`.2122## Google Drive state sync2324Separate from the existing Google Drive cloud backups (`cloud://google-drive`, unchanged). One file, `yokan_sync.json.gz`, in the `appDataFolder` of the user's Google account, in Yokan's native backup format (private notes excluded; settings when the settings toggle is on). `appDataFolder` is private to the OAuth client, so another app (e.g. Animetail) can never read it; the native format keeps everything Yokan has. Its `appProperties.deviceId` names the device that wrote it.2526Sign-in uses the user's own OAuth client — nothing is embedded:27281. In Google Cloud Console enable the Drive API, configure the consent screen (add yourself as a test user while it is in testing), and create an OAuth client of type **Desktop app**.292. In Yokan enter the client ID and secret and tap **Open Google sign-in**. The authorization-code + PKCE (S256) URL requests `drive.appdata`, `access_type=offline`, `prompt=consent`, redirect `http://127.0.0.1`.303. After allowing access the browser opens `http://127.0.0.1/?state=…&code=…`, which fails to load. Copy that whole address (or just the code) into Yokan and tap **Sign in**. The pasted state must match; the attempt is single-use.3132The refresh token and client secret are stored as JSON in `authToken`, the client ID in `server`, the account email (`about.user`) in `email`, and a random device id in `deviceId`. Each run refreshes an access token in memory.3334A run:35361. Lock: `yokan_sync.lock` in `appDataFolder` with `appProperties` `deviceId` and `expiresAt` (10 minutes). Expired locks are deleted; a live lock of another device fails the run with "Sync is in progress on another device"; after creating its lock the device lists locks again and backs off (deleting its own) if another device's live lock was created earlier — Drive allows duplicate names, so this settles simultaneous starts.372. The sync file, if present and written by another device, is downloaded and merged. Our own last upload is not merged back. An unreadable file is overwritten.383. The library is exported and uploaded: multipart `POST upload/drive/v3/files` the first time, `PATCH upload/drive/v3/files/{id}?uploadType=multipart` afterwards.394. The lock is always released (non-cancellable `finally`); a lock left by a crash expires after 10 minutes.4041Lease key: `gdrive|<client id>|<account email>`. Deleting the remote sync data from the app is not offered; remove it in Google Drive → Settings → Manage apps, or just sign in again (an unreadable or stale file is overwritten on the next run).4243## Platform blockers4445- **Web (wasmJs):** requests go through the browser's `fetch`, so a self-hosted SyncYomi server must send CORS headers allowing the `X-API-Token`, `If-Match` and `Content-Type` request headers and the `PUT` method, and must expose `ETag` (`Access-Control-Expose-Headers: ETag`); without the exposed header every sync fails with "missing its ETag". Google's token and Drive endpoints are called cross-origin as well (unverified here). The browser build cannot gzip synchronously, so its Drive uploads are plain JSON under the same name; every platform reads both.46- **Google sign-in, all platforms:** the loopback redirect is not intercepted — the browser shows a connection error page and the user copies its address. Embedded web views are not used (Google blocks OAuth in them). Android/iOS custom-scheme redirects would need Android/iOS-type OAuth clients and are not used; the Desktop-app client works everywhere with paste. Consent screens in "testing" mode expire refresh tokens after 7 days; publish the consent screen or sign in again.47- **Extra profiles:** each profile can connect a different SyncYomi key or Google account; one account in two profiles is refused by the lease.48- Nothing here was verified against a live SyncYomi server or Google account; protocol behavior is covered by scripted fake HTTP tests (`SyncYomiSyncServiceTest`, `GoogleDriveSyncServiceTest`, `HybridSyncServiceTest`).4950## Sync triggers5152Settings → Sync → **Sync triggers** offers six switches, all off by default (upstream `SyncTriggerOptions`): chapter read, chapter open, episode seen, episode open, app start and app resume. They are stored in `DbFeaturePreferences.syncTriggers` (`DbSyncTriggerPreferences`); the whole `features` group is device-local (`SyncPaths.settingsDeviceLocal`), so triggers are never synced and a restore keeps this device's choice.5354`services/sync/SyncTriggerCoordinator.kt` is owned by the profile session and cancelled with it. A trigger only acts when its switch is on and the sync preference has `syncOn` and credentials (the scheduler's predicate). It then runs the scheduler's provider-agnostic sync path (`periodicTasks.sync()`), so Yokan Hub, Mangayomi, cloud, SyncYomi and Google Drive all work. Runs are single-flight: chapter/episode events are debounced for 5 s and start/resume for 1 s (each event restarts the wait), consecutive runs are at least 60 s apart, and events arriving during a run or the gap queue at most one follow-up. Failures are logged and never reach the reader/player.5556Hooks live at repository level, so reader/player code is unchanged: opening a chapter/episode (`DefaultYokanRepository.chapterOpened`, skipped in incognito) emits chapter open (manga/novel) or episode open (anime); an unread → read transition in `setChaptersRead` (reading progress and manual marks), library bulk marks and Updates marks emits chapter read or episode seen. App start fires from `YokanRuntime.startForeground`; app resume from the Compose lifecycle `ON_START` in `ui/App.kt` (Android activity start, iOS foreground, desktop window restore from minimized, browser page becoming visible). Triggered runs post the same in-place "Automatic sync" notification as scheduled sync and do not apply the Wi-Fi-only restriction (as upstream's immediate sync).5758## Mihon/Aniyomi protobuf export5960Create backup offers a third format, **Mihon/Aniyomi (.tachibk)** (`BackupFormat.Tachiyomi`, `services/backup/TachiyomiBackupEncoder.kt`). It writes Animetail's `Backup` protobuf message, which Mihon (manga part) and Aniyomi/Animetail (manga and anime) restore: `yokan_<timestamp>.tachibk` gzipped, or raw `yokan_<timestamp>.proto` at compression level 0 (the SyncYomi body). Encryption is only available for the Yokan format. Yokan's importer reads both forms, so a `.tachibk`/`.proto` can be restored back into Yokan.6162Exported: titles (source id, URL, title, author/artist, description, genres, status, cover, date added, favorite, categories), chapters/episodes (URL, name, scanlator, read/seen, bookmark, last page or position, fetch/upload dates, number, source order, episode filler), history (last read, read duration), tracker bindings mapped to Animetail tracker ids, manga and anime categories, and source names. Not exported: novels (no upstream model; skipped and logged), settings/preferences, extensions, custom buttons, private notes, custom covers, seasons and anime background art, and the Yokan-only metadata pseudo-tracker. Tracker scores are passed through unchanged. Source ids are the real Tachiyomi ids for Mihon sources; other sources use a stable positive hash of the source name.6364Importing Tachiyomi-family backups now also reads tracks, history, the favorite flag, fetch dates, chapter numbers and episode filler/summary/preview, and fixes units: dates added/uploaded are milliseconds upstream and Mihon pages are 0-based. In the browser build gzip compression is unavailable, so the web `.tachibk` is raw protobuf; Mihon-family apps detect gzip by its magic bytes and also accept raw protobuf. Restoring in an actual Mihon/Aniyomi/Animetail app was not verified; field numbers and wire types are checked against the upstream models in `TachiyomiBackupEncoderTest`.65