17 Commits
Author SHA1 Message Date
venture a34220bf2d release 1.1.0 : sync V2 (upload, download, purge, placements, rétention, groupes)
Release / release-apk (push) Successful in 9m25s
Release / release-docker (push) Successful in 33s
CI / docker (push) Successful in 7s
CI / lint-backend (push) Successful in 1m29s
CI / lint-mobile (push) Failing after 7m46s
CI / test-backend (push) Successful in 1m30s
CI / test-mobile (push) Successful in 9m27s
CI / build-backend (push) Successful in 47s
2026-09-25 20:27:14 +02:00
venture b28fcdc774 V2-5 : rétention auto (règle, worker quotidien, réglages stockage) 2026-09-25 19:56:21 +02:00
venture 88e89b9567 fix : 401 sans session ignoré (mode local non éjecté vers login) 2026-09-25 19:50:39 +02:00
venture a91ddf7aa8 V2-4 : placements multi-device (report_bytes, tables 000015, copies UI) 2026-09-25 19:45:33 +02:00
venture 0f90aad938 V2-2/V2-3 : download hors-ligne SAF + purge sûre (Room v18, DownloadWorker, release) 2026-09-25 19:27:08 +02:00
venture dd053a50c8 V2 : flag serveur has_content (migration 000014, lazy healing, FileDto) 2026-09-25 18:49:57 +02:00
venture c77af98a68 V2-1 : upload auto des octets (BytesUploadWorker, Room v17, SafMultipart) 2026-09-25 18:20:57 +02:00
venture d0957e90d0 release 1.0.0 : fin du périmètre V1
Release / release-apk (push) Successful in 9m23s
Release / release-docker (push) Successful in 38s
CI / docker (push) Successful in 7s
CI / lint-backend (push) Successful in 1m23s
CI / lint-mobile (push) Failing after 7m45s
CI / test-backend (push) Successful in 1m24s
CI / test-mobile (push) Successful in 9m16s
CI / build-backend (push) Successful in 58s
2026-09-25 18:13:36 +02:00
venture a50eb830f4 consolidation V1 : docs resync, PDF streaming multi-pages, recherche sans accents, parser https 2026-09-25 18:13:30 +02:00
venture c642763035 api use
CI / lint-backend (push) Successful in 1m24s
CI / lint-mobile (push) Failing after 7m28s
CI / test-backend (push) Successful in 1m25s
CI / test-mobile (push) Successful in 9m9s
CI / build-backend (push) Successful in 45s
CI / docker (push) Successful in 33s
2026-09-25 17:34:35 +02:00
venture b869f70922 streaming d'un fichier 2026-09-25 15:34:28 +02:00
venture 9e8b01b135 chage floatting footer into scanned files
CI / lint-backend (push) Successful in 1m19s
CI / lint-mobile (push) Successful in 8m44s
CI / test-backend (push) Successful in 1m21s
CI / test-mobile (push) Successful in 8m55s
CI / build-backend (push) Successful in 45s
CI / docker (push) Successful in 9s
2026-09-25 14:09:12 +02:00
venture 456579880e improve documents
CI / lint-backend (push) Successful in 1m19s
CI / lint-mobile (push) Canceled after 5m8s
CI / test-backend (push) Canceled after 0s
CI / test-mobile (push) Canceled after 0s
CI / build-backend (push) Canceled after 0s
CI / docker (push) Canceled after 0s
2026-09-25 14:02:41 +02:00
venture 25aedb431e hide sync status is local mode app
CI / lint-backend (push) Successful in 1m21s
CI / lint-mobile (push) Successful in 20m43s
CI / test-backend (push) Successful in 1m50s
CI / test-mobile (push) Successful in 8m49s
CI / build-backend (push) Successful in 45s
CI / docker (push) Successful in 3m50s
2026-09-25 12:09:14 +02:00
venture 25bab43b21 split serveur config and login
CI / lint-backend (push) Successful in 1m42s
CI / lint-mobile (push) Canceled after 5m5s
CI / test-backend (push) Canceled after 0s
CI / test-mobile (push) Canceled after 0s
CI / build-backend (push) Canceled after 0s
CI / docker (push) Canceled after 0s
2026-09-25 12:02:23 +02:00
venture cbc94c8722 feat(mobile): refonte UI phases 0-4 + nav sans transitions
CI / lint-backend (push) Successful in 1m37s
CI / lint-mobile (push) Successful in 11m18s
CI / test-backend (push) Successful in 1m34s
CI / test-mobile (push) Successful in 13m11s
CI / build-backend (push) Successful in 1m6s
CI / docker (push) Successful in 9s
- Phase 0: design system (Color/Theme/Type complets light/dark,
  Shapes/Dimens, KazierCard, formatFileSize centralise)
- Phase 1: composants partages sur colorScheme (badges, dialogs,
  nav flottante factorisee, contentDescriptions)
- Phase 2: ecrans principaux (cartes unifiees, boutons M3,
  LoginForm partage, recherche avec compteur/clear)
- Phase 3: flows secondaires (dashboard sync, review animee,
  scan 360dp + sortie cul-de-sac camera, PdfBuilder checkbox/
  recherche/fin auto-nav, share ExposedDropdownMenu + confirmation,
  watched rescan + erreur import)
- Phase 4: a11y (selection semantics), dialogs saveable, cibles 48dp
- NavHost: transitions d'ecran desactivees (Enter/Exit None)
2026-09-24 20:32:08 +02:00
venture d1b0807d38 fix feedback bugs
CI / lint-backend (push) Successful in 1m27s
CI / lint-mobile (push) Successful in 10m24s
CI / test-backend (push) Successful in 1m33s
CI / test-mobile (push) Failing after 12m6s
CI / build-backend (push) Successful in 59s
CI / docker (push) Successful in 8s
2026-09-24 19:40:13 +02:00
154 changed files with 14060 additions and 1844 deletions
+22 -20
View File
@@ -2,7 +2,7 @@
## Project Status ## Project Status
`backend/` (Go) et `mobile-kotlin/` (Kotlin/Android) ont du scaffolding en place. Le client mobile est **local-first** : il reflète le SAF dans une base Room (v7, migrations, DAO) et pousse les **métadonnées** de ses mutations locales via un **outbox transactionnel** (`pending_operations` + worker WorkManager → `POST /sync/ops`). Pas d'upload physique, pas d'OCR ni de recherche serveur côté client en V1. `backend/` (Go) et `mobile-kotlin/` (Kotlin/Android) ont du scaffolding en place. Le client mobile est **local-first** : il reflète le SAF dans une base Room (v16, migrations, DAO) et pousse les **métadonnées** de ses mutations locales via un **outbox transactionnel** (`pending_operations` + worker WorkManager → `POST /sync/ops`). Upload physique ciblée (pipeline OCR : `POST /files/upload` + `resourceId`), streaming lecture des fichiers distants (`GET /files/:id/content`, jamais persisté), OCR serveur consommé côté client, recherche locale via Room (+ recherche serveur exposée mais non consommée).
## Architecture ## Architecture
@@ -38,11 +38,11 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
- `config/` — env (`godotenv`, optionnel) + defaults: `PORT`, `DATABASE_URL`, `UPLOAD_DIR`, `MAX_FILE_SIZE_MB`, `OCR_LANG`, `AUTH_SECRET` (secret des tokens paseto), `ADMIN_USERNAME`/`ADMIN_PASSWORD` (bootstrap du premier admin) - `config/` — env (`godotenv`, optionnel) + defaults: `PORT`, `DATABASE_URL`, `UPLOAD_DIR`, `MAX_FILE_SIZE_MB`, `OCR_LANG`, `AUTH_SECRET` (secret des tokens paseto), `ADMIN_USERNAME`/`ADMIN_PASSWORD` (bootstrap du premier admin)
- `models/` — domain entities (users, devices, documents/resources, clients) - `models/` — domain entities (users, devices, documents/resources, clients)
- `service/` — business logic (permissions, upload, create folder, move, **sync outbox + snapshot**, bootstrap admin) - `service/` — business logic (permissions, upload, create folder, move, **sync outbox + snapshot**, bootstrap admin)
- `handlers/` — HTTP handlers (health, devices register, **auth/login**, **users resolve + change password**, files CRUD/upload/search, folders, **sync/ops + sync/permissions, ocr/jobs** — réels) ; middleware `RequireAuth` - `handlers/` — HTTP handlers (health, devices register, **auth/login**, **users resolve + change password**, files CRUD/upload/search, folders, **sync/ops + sync/permissions, ocr/jobs, files/:id/content, files/:id/shares, files/:id/links, files/:id/placements, groups CRUD + membres** — réels) ; middleware `RequireAuth`
- `repository/` — Postgres persistence (`repository.Resources` : insert/list/get/soft-delete scoping `owner_id`, search, move, rename, root-name unique index, `ListOwned` pour le snapshot ; `repository.Devices` : Upsert, Exists, MarkUser ; `repository.Operations` : trace outbox idempotente `(device_id, operation_id)` ; `repository.OcrJobs` : jobs queued→processing→done/failed ; `repository.Users` : GetByUsernameNormalized, ResolveExact, UpdatePassword) ; IDs sont TEXT 32-hex, `NewID()` = `crypto/rand` 16 octets hex (jamais UUID conversion, cf. `docs/api-v1.md`) - `repository/` — Postgres persistence (`repository.Resources` : insert/list/get/soft-delete scoping `owner_id`, search, move, rename, root-name unique index, `ListOwned` pour le snapshot, `OpenContent` (bytes streaming + lazy healing `has_content`), `ListShares`/`ListLinks` (owner-only), `SetHasContent` ; `repository.Devices` : Upsert, Exists, MarkUser ; `repository.Operations` : trace outbox idempotente `(device_id, operation_id)` ; `repository.OcrJobs` : jobs queued→processing→done/failed ; `repository.Users` : GetByUsernameNormalized, ResolveExact, UpdatePassword ; `repository.Shares` : Upsert/UpsertGroup/Revoke, CreateLink/RevokeLink, ListActiveForResource, ListActiveLinksForResource, snapshot `ListEffectivePermissions` (grants user + groupe) ; `repository.Groups` : Create/ListForUser/AddMember/RemoveMember/Delete (V2-6, un niveau, sans imbrication) ; `repository.Placements` : EnsureLocation/Report/ListForResource (V2 multi-device) ; IDs sont TEXT 32-hex, `NewID()` = `crypto/rand` 16 octets hex (jamais UUID conversion, cf. `docs/api-v1.md`)
- `db/` — package migrations (`golang-migrate/v4`, embarquées via `embed` dans `db/migrations/*.sql`, 000001→000008) : `db.MigrateDatabase(url)` au boot du serveur ; test harness `db/migrations_test.go` (up → assertions schéma → down, `TEST_DATABASE_URL`, skip si PG indisponible) ; `dbtest/` — helper cross-package pour les tests repo/handlers (crée la DB test si absente, reset schema, migrate ; skip si PG down) - `db/` — package migrations (`golang-migrate/v4`, embarquées via `embed` dans `db/migrations/*.sql`, 000001→000016) : `db.MigrateDatabase(url)` au boot du serveur ; test harness `db/migrations_test.go` (up → assertions schéma → down, `TEST_DATABASE_URL`, skip si PG indisponible) ; `dbtest/` — helper cross-package pour les tests repo/handlers (crée la DB test si absente, reset schema, migrate ; skip si PG down)
- `ocr/` — OCR engine behind an interface (Tesseract system call, `OCR_LANG` défaut `fra+eng`) - `ocr/` — OCR engine behind an interface (Tesseract system call, `OCR_LANG` défaut `fra+eng`)
- `pkg/api/` — response helpers (`response.go`) ; `pkg/auth/` — tokens **paseto v4-local** (subject = `user_id`, claim = `device_id`, TTL 7j, voir `docs/api-v1.md`) ; `pkg/passwd/` — hashing/vérification bcrypt (timing-equal) - `pkg/api/` — response helpers (`response.go`) ; `pkg/auth/` — tokens **paseto v4-local** (subject = `user_id`, claim = `device_id`, TTL 7j, voir `docs/api-v1.md`) ; `pkg/passwd/` — hashing/vérification argon2id (comparaison `subtle`, délai égalisé)
- File uploads stored in `backend/uploads/` - File uploads stored in `backend/uploads/`
- Standard JSON response envelope: `{ "data": ..., "meta": { "page": ..., "total": ... } }` - Standard JSON response envelope: `{ "data": ..., "meta": { "page": ..., "total": ... } }`
- Error format: `{ "error": { "code": "...", "message": "..." } }` - Error format: `{ "error": { "code": "...", "message": "..." } }`
@@ -52,39 +52,41 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
- Entry point: `app/src/main/java/com/kazier/mobile/KazierApplication.kt` (Hilt + `HiltWorkerFactory`) + `MainActivity.kt` (Hilt) ; navigation Compose dans `ui/navigation/` (`NavGraph.kt`, `KazierApp.kt`) - Entry point: `app/src/main/java/com/kazier/mobile/KazierApplication.kt` (Hilt + `HiltWorkerFactory`) + `MainActivity.kt` (Hilt) ; navigation Compose dans `ui/navigation/` (`NavGraph.kt`, `KazierApp.kt`)
- Data layer — `data/`: - Data layer — `data/`:
- `data/local/` — Room SQLite (DB `dot.db`, **version 7**, `Migrations.kt` : tables `folders`, `files`, `user_preferences`, `pending_operations`) : entités Folder/File/UserPreference/PendingOperation, DAO, tri (`FileOrdering`) ; flag `processed` sur `files` (mode review « traiter », local au device, **gate de sync** : un fichier pas encore traité n'est jamais poussé) ; outbox transactionnel `pending_operations` (v7) - `data/local/` — Room SQLite (DB `dot.db`, **version 18**, `Migrations.kt` : tables `folders`, `files` (+ `category`, `processed`, `content`, `ocr_text`, `ocr_attempts`, `ocr_queued_at`, `bytes_uploaded`, `bytes_upload_attempts`, `has_content_server`, `wanted_offline`), `user_preferences`, `pending_operations` (+ `device_id`, `parent_resource_id`), `scan_sessions`, `scan_pages`, `resource_permissions`) : entités + DAO, tri (`FileOrdering`), schéma exporté (`app/schemas/`, m19) ; flag `processed` sur `files` (mode review « traiter », local au device, **gate de sync** : un fichier pas encore traité n'est jamais poussé) ; outbox transactionnel `pending_operations`
- `data/remote/` — Retrofit/Moshi : `ApiService.kt` + `dto/Dtos.kt` = **contrat HTTP** (`{ data, meta }`, erreurs `{ error: { code, message } }`) ; `ApiClient.kt` normalise les réponses ; interceptors OkHttp (`AuthInterceptor`, `ServerUrlInterceptor`) - `data/remote/` — Retrofit/Moshi : `ApiService.kt` + `dto/Dtos.kt` = **contrat HTTP** (`{ data, meta }`, erreurs `{ error: { code, message } }`) ; `ApiClient.kt` normalise les réponses ; interceptors OkHttp (`AuthInterceptor`, `ServerUrlInterceptor`) ; `SafMultipart.kt` (multipart SAF paresseux partagé upload OCR + V2)
- `data/repository/` — `FolderRepository`, `FileRepository`, `AuthRepository`, `OutboxRepository` (enqueue `create_resource`/`move_resource`/`delete_resource`, écrivains dans la même transaction Room que la mutation parente ; pour un fichier SAF, la mutation parente du `create_resource` est le **garder** de la review (`markProcessed`), et `hasCreateOperation` en garde l'unicité) - `data/repository/` — `FolderRepository`, `FileRepository`, `AuthRepository`, `OutboxRepository` (enqueue `create_resource`/`move_resource`/`delete_resource` + ops partage `share`/`update_share`/`revoke_share`/`create_link`/`revoke_link` + `report_bytes` V2 (`{ hasBytes }`, nouvel `operation_id` par état), écrivains dans la même transaction Room que la mutation parente ; pour un fichier SAF, la mutation parente du `create_resource` est le **garder** de la review (`markProcessed`), et `hasCreateOperation` en garde l'unicité), `ShareRepository` (hydratation + delta + `canAccess` depuis `GET /sync/permissions`), `OcrRepository` (upload ciblé + jobs + `syncFromServer`), `RemoteContentRepository` (streaming `GET /files/:id/content`, jamais persisté ; **upload V2** des octets après metadata synced, `bytes_uploaded` ; **download V2** vers SAF + rattachement, `wanted_offline`)
- `features/` — logique descendue côté client : - `features/` — logique descendue côté client :
- `sync/DeviceSync.kt` + `SafScanner.kt` — sync device↔SAF : **two-pass walk** (listing hors transaction puis upserts Room dans une seule transaction), réconciliation `exists = 0` (jamais de suppression), single-flight via `Mutex` ; les nouveaux **dossiers** sont journalisés dans l'outbox à la découverte, les **fichiers** uniquement au « garder » de la review (gate `processed`) - `sync/DeviceSync.kt` + `SafScanner.kt` — sync device↔SAF : **two-pass walk** (listing hors transaction puis upserts Room dans une seule transaction), réconciliation `exists = 0` (jamais de suppression), single-flight via `Mutex` ; les nouveaux **dossiers** sont journalisés dans l'outbox à la découverte, les **fichiers** uniquement au « garder » de la review (gate `processed`)
- `saf/` — `SafUris`, `SafFolderCreator`, `FileMover` (relocalisation SAF `DocumentsContract.moveDocument`, repli métadonnée seule ; le déplacement est poussé en `move_resource`), `SafFileDeleter` (suppression SAF + `delete_resource` atomique) - `saf/` — `SafUris`, `SafFolderCreator`, `FileMover` (relocalisation SAF `DocumentsContract.moveDocument`, repli métadonnée seule ; le déplacement est poussé en `move_resource`), `SafFileDeleter` (suppression SAF + `delete_resource` atomique), `FileDeleter.releaseLocalCopies` (purge sûre V2-3 : gate `isReleasable`, détachement cloud-only, zéro outbox)
- `sync/OutboxSyncWorker.kt` — worker WorkManager (`enqueueUniqueWork` KEEP, single-flight, `NetworkType.CONNECTED`, backoff 30s) qui draine `pending_operations` vers `POST /sync/ops` (batch 20, dead-letter immédiat `failed` sur erreur 4xx non-idempotente — `attempts` diagnostic, purge synced > 7 jours) ; **schedulé** au login/restauration de session (`AuthViewModel`) et après chaque `syncAll()` (`SyncViewModel`) - `sync/OutboxSyncWorker.kt` — worker WorkManager (`enqueueUniqueWork` KEEP, single-flight, `NetworkType.CONNECTED`, backoff 30s) qui draine `pending_operations` vers `POST /sync/ops` (batch 20, dead-letter immédiat `failed` sur erreur 4xx non-idempotente — `attempts` diagnostic, purge synced > 7 jours, **sauf `report_bytes` : dead-letter + suite du batch, jamais bloquant**) ; **schedulé** au login/restauration de session (`AuthViewModel`) et après chaque `syncAll()` (`SyncViewModel`) ; enchaîne `OcrAutoWorker` + `BytesUploadWorker` quand un fichier est promu (`DownloadWorker` sur demande hors-ligne) ; `RetentionWorker` (passe quotidienne, purge sûre des copies anciennes selon `RetentionStore`, sans réseau)
- `sync/SyncViewModel.kt` — état du sync exposé à l'UI (`SyncStatus` : marche en cours, ops en attente, dernières opérations) via le badge header `ui/components/SyncStatusBadge.kt` + `SyncOperationsDialog.kt` (« liste des sync ») - `sync/SyncViewModel.kt` — état du sync exposé à l'UI (`SyncStatus` : marche en cours, ops en attente, dernières opérations) via le badge header `ui/components/SyncStatusBadge.kt` + `SyncOperationsDialog.kt` (« liste des sync »)
- `auth/` — session (login user + token paseto) : `SessionManager`, `SecureTokenStore`, `TokenProvider` - `auth/` — session (login user + token paseto + **re-login silencieux** sur 401 via identifiants chiffrés persistés, single-flight, événements `Reauthenticated`/`SessionExpired`) : `SessionManager`, `SecureTokenStore`, `TokenProvider`, `TokenStore` (+ `Credentials`)
- `ui/` — écrans Compose : `folderlist`, `folderdetail`, `document` (contenu PDF/image/texte + placeholder cloud-only), `search` (**recherche locale** via Room, sans endpoint serveur), `settings` (URL serveur + thème), `pdfbuilder` (multi-select → génération PDF), `auth` (login, mode local), `components`, `theme` - `ui/` — écrans Compose : `folderlist`, `folderdetail`, `document` (contenu PDF/image/texte local + streaming distant image/texte/PDF multi-pages via `RemoteDocumentViewer`, autres types non supportés en streaming), `search` (**recherche locale** via Room, sans endpoint serveur), `settings` (URL serveur + thème + stockage/retention), `pdfbuilder` (multi-select → génération PDF), `auth` (login, mode local, avis d'expiration), `share` (`ShareBottomSheet` : grants + liens + ouverture de lien + copies V2 + groupes V2-6 ; `OpenLinkScreen` + deep-link `kazier://share/<token>`), `components`, `theme`
- `domain/` — stores de préférences: `DeviceIdentity`, `ActiveUserStore`, `LocalModeStore`, `ServerConfigStore`, `ThemePreferenceStore`, `GenerateId` (identifiants 32-hex) - `domain/` — stores de préférences: `DeviceIdentity`, `ActiveUserStore`, `LocalModeStore`, `ServerConfigStore`, `ThemePreferenceStore`, `RetentionStore` (`all` | `last_months:N`), `GenerateId` (identifiants 32-hex)
- `di/` — modules Hilt (`AppModule`, `DatabaseModule`, `NetworkModule`) - `di/` — modules Hilt (`AppModule`, `DatabaseModule`, `NetworkModule`)
- Base URL serveur **configurée à l'exécution** dans les Réglages (`ServerConfigStore`, persistée en `user_preferences`), défaut `http://10.0.2.2:8080/api/v1` (pas de variable d'env) - Base URL serveur **configurée à l'exécution** dans les Réglages (`ServerConfigStore`, persistée en `user_preferences`), défaut `http://10.0.2.2:8080/api/v1` (pas de variable d'env)
- Client **local-first** : lecture via `GET /files/folders`, `GET /files` ; mutations locales poussées via l'outbox `POST /sync/ops` (`create_resource`/`move_resource`/`delete_resource`) ; `POST /devices`, `POST /auth/login` ; download/upload physique hors scope - Client **local-first** : lecture via `GET /files/folders`, `GET /files` (+ streaming distant `GET /files/:id/content` pour les fichiers cloud-only, jamais persisté) ; mutations locales poussées via l'outbox `POST /sync/ops` (`create_resource`/`move_resource`/`delete_resource` + ops partage) ; `POST /devices`, `POST /auth/login` ; upload physique limité au pipeline OCR (`POST /files/upload` + `resourceId` ciblé)
## Data Conventions ## Data Conventions
- Canonical identity for folders/files is `resource_id`: opaque 32-hex, generated locally (`GenerateId`), never reused. The physical `uri` (SAF) is nullable (NULL = cloud-only) and is the reconciliation key for the SAF walk (unique index, NULLs distincts). - Canonical identity for folders/files is `resource_id`: opaque 32-hex, generated locally (`GenerateId`), never reused. The physical `uri` (SAF) is nullable (NULL = cloud-only) and is the reconciliation key for the SAF walk (unique index, NULLs distincts).
- Similarly, `pending_operations.operation_id` is a client-generated 32-hex (`GenerateId`), the idempotency key of the outbox `UNIQUE(device_id, operation_id)` lettre contre les rejeux du worker. - `pending_operations.operation_id` est un **TEXT 32-hex** généré par le client (`^[0-9a-f]{32}$`, CHECK-enforced côté serveur depuis la migration `000008`), distinct de `resource_id`. L'idempotence outbox reste **par device** : `UNIQUE(device_id, operation_id)` (colonne `device_id` côté mobile depuis Room v12).
- `owner_id` is **nullable** in the Room schema; it is set at runtime from `DeviceIdentity.getOrCreate()` during the SAF walk. - `owner_id` is **nullable** in the Room schema; it is set at runtime from `DeviceIdentity.getOrCreate()` during the SAF walk.
- Folder/file `sync_status` is a **placement** state: `local` | `cloud` | `local-cloud`. It is not a push progress marker. - Folder/file `sync_status` is a **placement** state: `local` | `cloud` | `local-cloud`. It is not a push progress marker.
- Client storage: `user_preferences` (clé/valeur) pour l'identité device, le compte actif, l'URL serveur, le thème, le mode local. - Client storage: `user_preferences` (clé/valeur) pour l'identité device, le compte actif, l'URL serveur, le thème, le mode local.
- Outbox atomique : `create_resource`/`move_resource`/`delete_resource` sont écrits dans la **même transaction Room** que la mutation parente ; l'écrivain (repository) et le worker partagent ce contrat. En mode local (pas de token), le worker est no-op. **Gate `processed`** : un fichier SAF nouvellement découvert est importé localement mais poussé seulement au « garder » (`markProcessed`, qui enqueue le `create_resource` dans la même transaction, une seule fois via `hasCreateOperation`) — d'où le filtrage des documents par l'utilisateur avant toute synchro. Un `delete_resource` n'est journalisé que si un `create_resource` a existé (jamais pour un fichier non poussé). - Outbox atomique : `create_resource`/`move_resource`/`delete_resource` sont écrits dans la **même transaction Room** que la mutation parente ; l'écrivain (repository) et le worker partagent ce contrat. En mode local (pas de token), le worker est no-op. **Gate `processed`** : un fichier SAF nouvellement découvert est importé localement mais poussé seulement au « garder » (`markProcessed`, qui enqueue le `create_resource` dans la même transaction, une seule fois via `hasCreateOperation`) — d'où le filtrage des documents par l'utilisateur avant toute synchro. Un `delete_resource` n'est journalisé que si un `create_resource` a existé (jamais pour un fichier non poussé).
- Pas de cache de permissions côté client en V1 : le serveur reste la source de vérité pour l'accès (`GET /sync/permissions` non consommé par le client Kotlin). - Cache de permissions côté client : `ShareRepository` hydrate `resource_permissions` depuis `GET /sync/permissions` (delta + pull complet, TTL 24h → downgrade lecture seule) et expose `canAccess` ; le serveur reste la source de vérité.
## API Contract (V1) ## API Contract (V1)
- **Le client mobile est le contrat**: les formes d'endpoints dans `mobile-kotlin/.../data/remote/ApiService.kt` + `dto/Dtos.kt` sont autoritatives et doivent matcher exactement ; le serveur ne renégocie pas. Spec consolidée: `docs/api-v1.md`. - **Le client mobile est le contrat**: les formes d'endpoints dans `mobile-kotlin/.../data/remote/ApiService.kt` + `dto/Dtos.kt` sont autoritatives et doivent matcher exactement ; le serveur ne renégocie pas. Spec consolidée: `docs/api-v1.md`.
- **Identity (user-first, V1 finale)**: le device s'enregistre (`POST /devices`, `{ "deviceId" }` seul, sans token), puis `POST /auth/login` (`username` + `password` + `device_id`) émet le seul token paseto **v4-local** — subject = `user_id` (autorise, scoping de toutes les ressources), claim `device_id` (porté, non autorisant seul), **TTL 7j sans refresh**. À expiration, le client re-logine. - **Identity (user-first, V1 finale)**: le device s'enregistre (`POST /devices`, `{ "deviceId" }` seul, sans token), puis `POST /auth/login` (`username` + `password` + `device_id`) émet le seul token paseto **v4-local** — subject = `user_id` (autorise, scoping de toutes les ressources), claim `device_id` (porté, non autorisant seul), **TTL 7j sans refresh**. À expiration, le client re-logine **silencieusement** via les identifiants chiffrés persistés (`SecureTokenStore`, single-flight, événements `Reauthenticated`/`SessionExpired`), sans rejouer la requête en vol.
- **Bootstrap**: au premier démarrage, si `users` est vide, `ADMIN_USERNAME`/`ADMIN_PASSWORD` (env) créent le premier admin ; absents → le serveur refuse de démarrer. L'env n'écrase jamais un compte existant. Usernames résolus sur `username_normalized` (lowercase + trim), `GET /users/resolve` exact uniquement (pas d'énumération). - **Bootstrap**: au premier démarrage, si `users` est vide, `ADMIN_USERNAME`/`ADMIN_PASSWORD` (env) créent le premier admin ; absents → le serveur refuse de démarrer. L'env n'écrase jamais un compte existant. Usernames résolus sur `username_normalized` (lowercase + trim), `GET /users/resolve` exact uniquement (pas d'énumération).
- **Identifiers**: `resource_id` / `device_user_id` / `user_id` / share-link `token` / `operation_id` sont des **lowercase 32-hex** TEXT (`^[0-9a-f]{32}$`, CHECK-enforced), stockés tels quels côté serveur (pas de conversion UUID). Le mobile génère toujours 32-hex. - **Identifiers**: `resource_id` / `device_user_id` / `user_id` / share-link `token` / `operation_id` sont des **lowercase 32-hex** TEXT (`^[0-9a-f]{32}$`, CHECK-enforced), stockés tels quels côté serveur (pas de conversion UUID). Le mobile génère toujours 32-hex.
- **Outbox idempotence + ordering**: le serveur applique les batchs de `pending_operations` **séquentiellement**, s'arrête à la première erreur non-idempotente et retourne l'index atteint. Consommé par le client Kotlin (`OutboxSyncWorker` → `POST /sync/ops`, batch 20, dead-letter immédiat sur 4xx non-idempotente, purge > 7 jours). `create_resource` porte le `parentResourceId` optionnel (racine si absent) — le walk SAF garantit parent avant enfant dans l'ordre d'`id`. - **Outbox idempotence + ordering**: le serveur applique les batchs de `pending_operations` **séquentiellement**, s'arrête à la première erreur non-idempotente et retourne l'index atteint. Consommé par le client Kotlin (`OutboxSyncWorker` → `POST /sync/ops`, batch 20, dead-letter immédiat sur 4xx non-idempotente, purge > 7 jours). `create_resource` porte le `parentResourceId` optionnel (racine si absent) ; `report_bytes` (`{ hasBytes }`, V2 placements, nouvel `operation_id` par état) ; `share`/`update_share` acceptent `granteeUserId` XOR `granteeGroupId` (V2-6) — le walk SAF garantit parent avant enfant dans l'ordre d'`id`.
- **Permissions snapshot**: le serveur pousse des snapshots `resource_permissions` (`effective_access` ranking viewer < commenter < editor < owner, `inherit`, `expires_at`, TTL 24h → read-only downgrade). (Endpoint existant côté serveur ; pas encore consommé par le client Kotlin.) - **Permissions snapshot**: le serveur pousse des snapshots `resource_permissions` (`effective_access` ranking viewer < commenter < editor < owner, `inherit`, `expires_at`, TTL 24h → read-only downgrade). Consommé par le client Kotlin (`ShareRepository` : hydratation + delta + `canAccess`).
- **Lecture partagée** : `GET /files/:id/shares` + `GET /files/:id/links` (owner uniquement, 404 sinon) exposent grants et liens au propriétaire ; `GET /files/:id/content` streame les octets (viewer+, `Range` supporté).
## Non-Goals (V1) ## Non-Goals (V1)
@@ -92,7 +94,7 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
- On-device OCR - On-device OCR
- Full multi-tenant federation / public discovery - Full multi-tenant federation / public discovery
- Multi-writer sync conflicts (single-owner device identity) - Multi-writer sync conflicts (single-owner device identity)
- Upload physique client→cloud (métadonnées seules via l'outbox, download, OCR jobs, permissions) côté mobile Kotlin - Upload physique généralisé client→cloud et download persistant (seuls l'upload ciblé OCR et le streaming lecture existent, cf. `docs/api-v1.md`)
## References ## References
+22 -2
View File
@@ -5,10 +5,27 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve
## [Unreleased] ## [Unreleased]
### Changé ## [1.1.0] - 2026-09-25
- **Renommage : VaultDrop → Kazier.** Marque, package Android (`com.kazier.mobile`), module Go (`github.com/kazier/backend`), binaire/image `kazier-server`, creds Postgres par défaut. Le code interne `dot.db` est conservé.
### Ajouté ### Ajouté
- Upload V2 des octets : worker `BytesUploadWorker` (fichier par fichier, overwrite ciblée idempotente, cap 3 échecs, backoff), marqueurs `bytes_uploaded`/`bytes_upload_attempts` (Room v17, migration 16→17), multipart SAF mutualisé (`SafMultipart.kt`).
- Flag serveur `has_content` (migration `000014`, lazy healing : TRUE à l'upload / au `OpenContent` réussi, FALSE si octets disparus), exposé en `FileDto.hasContent` + miroir Room `has_content_server` (v18).
- Download V2 hors-ligne : `DownloadWorker` (fichier par fichier, écriture SAF dossier propre sinon racine, rattachement même `resource_id`, walk convergent par URI), marqueurs `has_content_server`/`wanted_offline` (Room v18, migration 17→18), bouton « Rendre disponible hors-ligne » dans le viewer distant.
- Purge sûre V2-3 « libérer de l'espace » : gate `isReleasable` (copie serveur connue), détachement cloud-only sans op outbox, bouton viewer + action multi-sélection.
- Placements multi-device : tables `storage_locations` + `resource_placements` (migration `000015`), op outbox `report_bytes` (viewer+, nouvel `operation_id` par état, dead-letter sans bloquer la file), `GET /files/:id/placements` (owner-only), reporting auto (upload/download/release/delete locale), section copies dans le sheet de partage.
- Rétention auto : règle `all` | `last_months:N` (`RetentionStore`), passe quotidienne `RetentionWorker` (purge sûre, sans réseau), réglages stockage (stats récupérables + libération manuelle).
- Groupes V2-6 (backend) : tables `groups` + `group_members` (migration `000016`, un niveau), CRUD + membres (owner-only), partage vers groupe via outbox (`granteeGroupId`, snapshot + enforcement étendus), `GROUP_NOT_FOUND`, lecture grants avec `granteeKind`.
- Groupes V2-6 (mobile) : section groupes du sheet (création, membres, suppression, partage au groupe), badge groupe sur les grants, endpoints CRUD + membres.
### Corrigé
- 401 sans session (mode local / jamais connecté) : ignoré sans purge ni événement — un appel égaré n'éjecte plus vers le login.
## [1.0.0] - 2026-09-25
### Ajouté
- Streaming lecture des fichiers distants : `GET /files/:id/content` (binaire brut, `Range`, viewer+), viewer mobile à la demande sans persistance (image/texte/PDF multi-pages, autres types non supportés).
- Gestion du partage côté owner : `GET /files/:id/shares` + `GET /files/:id/links`, sheet mobile (grants modifiables/révocables, liens création/copie/révocation, ouverture de lien, badge pending outbox), deep-link `kazier://share/<token>` + écran de résolution.
- Re-login silencieux : identifiants chiffrés persistés, renouvellement auto sur 401 (single-flight, file conservée si même compte), écran login avec avis d'expiration + username pré-rempli.
- Pipeline de release CI (GitLab) : lint, tests backend/mobile, build Docker, signature APK release, publication GitLab Release + Docker Hub. - Pipeline de release CI (GitLab) : lint, tests backend/mobile, build Docker, signature APK release, publication GitLab Release + Docker Hub.
- `backend/Dockerfile` multi-stage : image de production avec Tesseract (fra+eng) embarqué, user non-root, labels OCI. - `backend/Dockerfile` multi-stage : image de production avec Tesseract (fra+eng) embarqué, user non-root, labels OCI.
- Service `backend` actif dans `docker-compose.yml` (déploiement conteneurisé). - Service `backend` actif dans `docker-compose.yml` (déploiement conteneurisé).
@@ -17,6 +34,9 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve
- Licence AGPLv3, badge README, `CHANGELOG.md`. - Licence AGPLv3, badge README, `CHANGELOG.md`.
- Versioning Android aligné sur le `VERSION` racine (versionCode dérivé). - Versioning Android aligné sur le `VERSION` racine (versionCode dérivé).
### Changé
- **Renommage : VaultDrop → Kazier.** Marque, package Android (`com.kazier.mobile`), module Go (`github.com/kazier/backend`), binaire/image `kazier-server`, creds Postgres par défaut. Le code interne `dot.db` est conservé.
### Corrigé ### Corrigé
- Docs : en-tête `docs/api-v1.md` (référence à l'ancien client Expo remplacée par le client Kotlin), quickstart et docker de la doc Starlight. - Docs : en-tête `docs/api-v1.md` (référence à l'ancien client Expo remplacée par le client Kotlin), quickstart et docker de la doc Starlight.
- `.gitignore` racine (uploads, binaires, keystore, artifacts). - `.gitignore` racine (uploads, binaires, keystore, artifacts).
+120 -164
View File
@@ -1,190 +1,146 @@
# FEEDBACK — Audit bugs mobile-kotlin (local-first) # FEEDBACK — Audit bugs mobile-kotlin (local-first)
> Généré le 2026-09-22 par 5 agents d'exploration parallèles (scopes : Room/DB, sync/outbox/SAF, réseau/auth/repos, UI/navigation/VM, scan/pdf/review/thumbnails). > Généré le 2026-09-22 par 5 agents d'exploration parallèles (scopes : Room/DB, sync/outbox/SAF, réseau/auth/repos, UI/navigation/VM, scan/pdf/review/thumbnails).
> Chaque finding est vérifié avec preuve `file:line`. Méthode : lecture intégrale des fichiers + croisement `docs/api-v1.md`, `AGENTS.md`, handlers Go. > Mise à jour le 2026-09-24 : les items corrigés par `d89c0d0 (fix 1 to 6)` et `22286aa (fix mobile audit review)` ont été re-vérifiés code en main et retirés. Ce document ne liste que le **reliquat confirmé**.
> Scope : `mobile-kotlin/` uniquement. Pas de fix appliqué — diagnostic seul. > Màj 2026-09-24 (soir) : tout le reliquat ci-dessous est **corrigé et testé** (`:app:testDebugUnitTest` : 162/162 verts, DB v16, schéma `app/schemas/16.json` exporté). Les sections 🟠/🟡/🛠️ sont conservées comme traçabilité.
> Légende : 🔴 Critique (data loss / crash / sync bloquée) · 🟠 Majeur (divergence silencieuse, contrat violé) · 🟡 Mineur (UX, perf, dette). > Chaque finding restant est vérifié avec preuve `file:line`.
> Scope : `mobile-kotlin/` uniquement.
> Légende : 🟠 Majeur (divergence silencieuse, contrat violé) · 🟡 Mineur (UX, perf, dette).
Base paths : `mobile-kotlin/app/src/main/java/com/kazier/mobile/…` Base paths : `mobile-kotlin/app/src/main/java/com/kazier/mobile/…`
--- ---
## 🔴 Critiques (à corriger en priorité) ## ✅ Corrigés et retirés (vérifiés le 2026-09-24)
### C1 — `domain/GenerateId.kt:19` — IDs 32-hex non conformes (sign-extension `Byte` → `%02x`) ### 🔴 Critiques : 9/9 corrigés
`bytes.joinToString("") { "%02x".format(it) }` promeut chaque `Byte` signé en `int` : tout octet négatif produit `ffffffxx` (8 chars). Longueur 32→128, P(32 exact) ≈ 1/65536. - **C1** `domain/GenerateId.kt:19` — masque `and 0xFF` contre la sign-extension, 32-hex conforme.
Impact : `resource_id` / `operation_id` / `device_user_id` violent `^[0-9a-f]{32}$` (CHECK serveur) → `POST /sync/ops` rejetés, outbox bloquée, identités invalides. - **C2** `features/sync/OutboxSyncWorker.kt:139-145` — erreurs non-attribuables (`INVALID_RESPONSE`, 429/408, 4xx batch-level) → `Result.retry()` sans toucher aux ops.
Repro : boucler `newResourceId()` et tester `length == 32 && matches([0-9a-f]{32})` → échec quasi systématique. - **C3** `data/local/dao/PendingOperationDao.kt:66-72` — `purgeSynced` exclut les `create_resource` (tombstones), gates `countCreateOperations` préservés.
- **C4** `features/saf/FileDeleter.kt:122-128` + `FolderDeleter.kt:122-124` — journal-first (`withTransaction` avant suppression SAF) + `sweepPendingPhysicalDeletes`.
- **C5** `auth/SessionManager.kt:70-77` — `clear()` purge les ops non poussées (`pending`/`failed`), appelé par `AuthViewModel.signOut/signOutToLocal`.
- **C6** `OutboxSyncWorker.kt:185-188` — stop au 1er échec (`return success()`, jamais `continue`) + cascade transitive `cascadeCreateFailure` via `parent_resource_id`/payload.
- **C7** `OutboxSyncWorker.kt:152,170-174,193-196` — `applied.coerceIn`, `failedIndex < 0 → stop`, `applied == 0 → stop` (anti busy-loop/crash).
- **C8** Scan export — `ScanExport.pendingForExport` idempotent, `shouldFinishSession` gate `DONE`, `uniquePageFile()` UUID, `deletePage` DB-d'abord, `exportPdf` ne marque que les succès.
- **C9** `features/scan/ScanImageProcessor.kt:91-92` + `ScanViewModel.kt:213` — jamais de `recycle()` sur l'alias affiché (`!==` check).
### C2 — `features/sync/OutboxSyncWorker.kt:101-106` — dead-letter abusive sur erreurs non-attribuables ### 🟠 Majeurs corrigés (31)
Le `else` dead-letter `pending.first()` pour toute `ApiException` non-`NETWORK_ERROR`/5xx/401. `INVALID_RESPONSE` (200 sans enveloppe `{data}`) et `HTTP_429`/`408` (transitoires) tombent dedans. La faute est imputée à la 1re op du batch quelle que soit l'op rejetée. M1 (garde pending-move dossiers), M2 (gate `create` avant `move`), M3 (`FileMover` sans repli mensonger), M4 (exclusion `exists=0` pending seul), M6 (parent inconnu → `continue`), M7 (`importRoot` schedule le drain), M8 (fichiers 0-octet acceptés), M10 (`DeviceIdentity` mutex + `insertIgnore`), M11 (décision assumée : pas de backfill `create_resource`), M12 (`upsertTolerant` sur `resource_id`/`uri`), M14 (colonne `device_id`, `UNIQUE(device_id, operation_id)` + migration 11→12), M15 (`failDescendants` élargi, cf. C6), M21 (boucle `listFilesPaged` + `meta.total`), M22 (`ApiClient` distingue `CancellationException`/`JsonDataException`/`IOException`), M23 (`activeUserStore` vs `ownerId`, plus de confusion device/user), M24 (`normalizePayloadNumbers` Double→Long), M25 (`SessionManager` possède `onUnauthorized`), M26 (`ServerUrlInterceptor` `runBlocking load()` anti-race), M28 (validation URL `toHttpUrl()`), M29 (`pendingDefaultPick` saveable), M30 (pager `rememberSaveable`), M31 (debounce sur résultats seuls), M32 (gate `canShare` FolderDetail), M33 (`refreshShareGate` au login/logout), M34 (`selection.clear()` + chips figés en sélection), M35 (`resolveViewerPage` clamp), M36 (sélecteur thème 3 états), M37 (flag `dirty` anti-écrasement saisie), M38 (`MAX(sortOrder)+1`), M42 (`processed=true` PDF builder), M43 (réinsertion optimiste review), M44 (`remember(existingIds)` stable).
Impact : op saine → `failed` à vie sur erreur batch-level ou transitoire ; inclut le cas `429 RATE_LIMITED` (login/devices/sync) qui devrait suivre le chemin `retry()`.
Repro : serveur 200 sans `data` ou 429 → 1re op dead-lettrée.
### C3 — `features/sync/OutboxSyncWorker.kt:83` + `data/local/dao/PendingOperationDao.kt:42-43` — purge >7j qui casse le gate `processed`/`hasCreateOperation` ### 🟡 Mineurs corrigés dans `d89c0d0` (voir `git show --stat d89c0d0`)
`purgeSynced` efface les lignes `synced`, or `countCreateOperations` (`IN ('pending','synced')`) fonde les gates delete/create dessus. m4 (gardes cursor SAF), m6 (`deleteLocally` transactionnel), m8 (`FileOrdering` aligné SQL), m9 (commentaire `attempts` diagnostic), m10-m14 (`updateUri`, `LocalModeStore`, `load` réarmable, `StateFlow` après succès DB, clé `SYNC_MODE` retirée), m16-m18 (index, `defaultValue processed`, `swapOrder` contraint), m22 (`ApiService` endpoints contrat ajoutés), m23 (`registerDevice` erreurs visibles), m24 (garde mode local), m25 (logging sans PII), m26 (`Bearer` hors routes publiques), m27 (`expiresAt` persisté), m28 (`SecureTokenStore` lazy + Direct Boot), m29-m31 (nav `pdfbuilder/empty`, `launchSingleTop`, controller hoisté), m33-m39 (side-effects `buildPhase`, dialogs `rememberSaveable`, badge collectes, saisie serveur debouncée, flash thème, bandeau import, `FileStatus.LOCAL`), m40-m56 (scan/camera/thumbnails : résolution bornée, `toBitmap` throttlé, listener retiré, `else` rotation, garde `sourceRect`, arrondi crop, `combine` nettoyé, purge `ABANDONED`, unicité session active, `FileCategory` CSV cohérent, purge map `Mutex`, `.tmp` nettoyés, `isUpToDate` taille+mtime, `runCatching` close, commentaire `max`, `release()` sur exception, deck conservé sur erreur).
Impact : (a) fichier poussé puis purgé → `SafFileDeleter`/`FileDeleter`/`treeMarkMissing` omettent le `delete_resource` → fantôme serveur indélébile ; (b) `markProcessed` ré-enqueue un `create_resource` dupliqué.
Repro : pousser un fichier, attendre 7j, le supprimer → aucun `delete_resource`, serveur garde la ressource.
### C4 — `features/saf/FolderDeleter.kt:106-124` + `features/saf/FileDeleter.kt:109-119` — suppression physique avant transaction, delete perdu sur crash
`deleteTreePhysically` (SAF, irréversible) avant `withTransaction { treeMarkMissing }`.
Impact : kill/crash entre les deux → octets supprimés, aucun `delete_resource` journalisé, walk suivant marque `exists=0` sans outbox (aucun chemin walk→enqueue) → fantôme serveur + divergence définitive.
Repro : `deleteFull` puis kill avant commit Room → serveur jamais notifié.
### C5 — `ui/auth/AuthViewModel.kt:112-121` — pas de vidage outbox au sign-out, replay cross-account
`signOut`/`signOutToLocal` purgent session et mode local mais aucune suppression de `pending_operations`. Les ops du compte A survivent au login du compte B (même `device_id`, `UNIQUE(device_id, operation_id)` sans historique partagé).
Impact : ops de A appliquées dans le scope de B (`NOT_FOUND`/`NAME_CONFLICT`, voire créations croisées).
Repro : enqueue offline sous A → sign-out → login B → drain pousse les ops de A sous token B.
### C6 — `features/sync/OutboxSyncWorker.kt:118-133` — drain poursuivi après échec + cascade limitée au même `resource_id`
Après `markFailed`, `continue` envoie le batch suivant, et `failDescendants` (`PendingOperationDao.kt:38`) ne cible que `resource_id = :resourceId` alors que les enfants portent un autre `resource_id` (lien dans le payload).
Impact : viole « serveur stop à la 1re erreur, client reprend à cet index » — creates enfants poussés et rejetés `NOT_FOUND` un par un, head-of-line blocking + dead-letters en cascade.
Repro : `create` dossier-parent en échec → le run pousse quand même les creates enfants au tour suivant.
### C7 — `features/sync/OutboxSyncWorker.kt:112-131` — gardes absents sur réponse serveur (boucle infinie / crash)
(a) `result.failed.operationId` absent du batch (`indexOfFirst < 0`) → silence + re-sélection du même batch → boucle serrée sans backoff ; (b) `result.applied > pending.size` → `pending[i]` lève `IndexOutOfBoundsException` → crash worker.
Impact : (a) drain CPU/batterie ; (b) batch jamais acquitté. Complété par `data/remote` : `while(true)` sans garde `applied==0 && failed==null` → busy-loop si serveur renvoie `{applied:0, failed:null}`.
Repro : mocker `syncOps → applied=0, failed=null` ou `operation_id` inconnu → boucle infinie ; `applied` incohérent → crash.
### C8 — Scan : perte de données à l'export
- `ui/scan/ScanViewModel.kt:387-389` (`exportPdf`) — pages en échec seulement loggées (`failedIds`), puis **toutes** marquées `EXPORTED` + session `DONE` → PDF incomplet, sources abandonnées.
- `ui/scan/ScanViewModel.kt:259-298` (`export`) — retry non idempotent : `getPages` retourne aussi les `EXPORTED`, chaque retry crée un nouvel URI SAF → documents + lignes Room + ops outbox dupliqués.
- `ui/scan/ScanViewModel.kt:263` — fichier temp manquant → page sautée sans marquage mais `finishSession` ferme la session → page `PENDING` dans session `DONE`, jamais reprise ni nettoyée.
- `ui/scan/ScanViewModel.kt:186-201` — nom page `page_$order.jpg` avec `order = pageCount+1` → collision après suppression (A,B → del A → C écrase B) → deux entités même `tempUri`, `deletePage` orpheline B.
Repro : cf. chaque item (export partiel, retry après perte permission SAF, temp supprimé, capture-suppression-capture).
### C9 — `features/scan/ScanImageProcessor.kt:87-88` + `ui/scan/ScanViewModel.kt:192` — `recycle()` du bitmap encore affiché quand OpenCV indisponible
`process()` retourne l'instance d'entrée si `!isAvailable()` ; l'appelant `recycle()` le `processed` qui alias le draft dessiné par `CropStage` → crash `recycled bitmap`.
Repro : device sans lib OpenCV → valider un crop → crash au retour caméra.
--- ---
## 🟠 Majeurs ## 🟠 Majeurs restants (4) — ✅ tous corrigés le 2026-09-24 (162/162 tests verts)
### Sync / Outbox / SAF - **M5 — `features/saf/FileDeleter.kt:88-104` + `features/saf/FolderDeleter.kt:91-103`** : `deleteInCloud` sans tombstone locale (`exists` reste 1) → ressource toujours affichée, walk la revoit, `refreshFromServer` ne supprime jamais de lignes → fantôme local vs serveur supprimé.
- **M1 — `features/sync/DeviceSync.kt:85-91` + `data/repository/FolderRepository.kt:99-134`** : le walk écrase le parent des dossiers sans garde pending-move (`saveFolder` écrase toujours, `reparentSubFolders` métadonnée-seule sans déplacement SAF). Les fichiers ont `hasPendingMoveOperation` (`FileRepository.kt:190`), les dossiers rien → tout reparent/merge revert au tick 30s suivant, divergence disque/serveur permanente. - **M9 — `features/saf/FolderMerger.kt:59,65-101`** : merge toujours multi-transactions (create, moves, deletes séparés) ; seule idempotence `findExistingMerged:154-161` ajoutée, pas d'atomicité → crash à mi-fusion = état partiel poussé.
- **M2 — `data/repository/FileRepository.kt:238-250`** : `applyMove` enqueue `move_resource` sans gate `create` (contrairement aux deletes) → move d'un fichier jamais poussé = `NOT_FOUND`/no-op serveur + ligne figée par `hasPendingMoveOperation`. Même cause `reparentSubFolders` (`FolderRepository.kt:144-157`) pour dossier au `create` purgé (>7j). - **M13 — entités `exists: Int? = null` + filtres `= 1`** (`FolderEntity.kt:36`, `FileEntity.kt:46`, `FolderDao.kt:43,50`, `FileDao.kt:27,44`) : toute ligne sans `exists` explicite disparaît UI/recherche/review — perte fonctionnelle silencieuse.
- **M3 — `features/saf/FileMover.kt:47-53`** : repli métadonnée-seule incohérent (nouveau parent + ancienne uri quand `moveDocument` refusé) → Room ment durablement, walk bloqué par le garde pending-move, divergence serveur/disque. - **M27 — `data/repository/ShareRepository.kt:47` + `data/remote/dto/Dtos.kt:150-151`** : snapshot permissions sans delta (`after` jamais passé), `sharedById`/`expiresAt` en `Any?` jamais lus, `cachedAt` jamais persisté, aucun downgrade 24h ni `canAccess` → grant révoqué/expiré reste visible et ouvrable (`404`) jusqu'au prochain login.
- **M4 — `features/sync/DeviceSync.kt:122-134`** : réconciliation `exists=0` asymétrique — fichiers exclus via `hasMoveOperation` (pending **ou** synced → à vie après un move syncé, fichier supprimé ensuite = fantôme `exists=1` éternel) ; dossiers sans exclusion (move en transition marqué `missing` à tort).
- **M5 — `features/saf/FileDeleter.kt:88-100` + `features/saf/FolderDeleter.kt:91-103`** : `deleteInCloud` sans tombstone locale (`exists` reste 1) → ressource toujours affichée, walk la revoit, `refreshFromServer` ne supprime jamais de lignes → fantôme local vs serveur supprimé.
- **M6 — `features/sync/DeviceSync.kt:84`** : `?: root.resourceId` masque toute violation parent-avant-enfant (parent absent de `resourceIdByUri` → enfant rattaché racine) → arbre serveur corrompu silencieusement.
- **M7 — `features/sync/SyncViewModel.kt:135-156`** : `importRoot` ne schedule jamais le drain (contraire `syncAll:110`, login `AuthViewModel:54,77`) → `create_resource` racine dort jusqu'au prochain tick, badge faussement à jour.
- **M8 — `features/sync/SafScanner.kt:146`** : `if (size == 0L) continue` → fichiers vides légitimes exclus du miroir, jamais reviewés ni poussés (perte silencieuse).
- **M9 — `features/saf/FolderMerger.kt:45-85`** : merge multi-transactions non-atomique, non-idempotent (`createMergedFolder` recrée un dossier à chaque appel) → crash à mi-fusion = état partiel poussé, relance = dossier dupliqué côté serveur.
### Room / DB / Domain
- **M10 — `domain/DeviceIdentity.kt:18-26`** : `getOrCreate()` non atomique (read/insert/re-read hors transaction) + fallback `newResourceId()` jamais persisté → deux identités concurrentes, `owner_id` incohérents, outbox sous identité fantôme (aggravé par C1).
- **M11 — `data/local/migration/Migrations.kt:90-96`** : `MIGRATION_5_6` fait `UPDATE files SET processed = 1` sans `create_resource` rétroactif → backlog jamais poussé, invisible de la review (`getUnprocessed`) et du serveur, à vie.
- **M12 — `data/local/dao/FolderDao.kt:50-54` + `data/local/dao/FileDao.kt:48-49`** : `@Upsert` résout sur PK (`id`) pas sur uniques `resource_id`/`uri` ; pattern read-then-upsert (`id=0`) → deux inserts concurrents même `uri` = `SQLiteConstraintException` (crash walk SAF / refresh serveur).
- **M13 — entités `exists: Int? = null` + filtres `= 1`** (`FolderEntity.kt:36`, `FileEntity.kt:45`, `FolderDao.kt:34,41`, `FileDao.kt:15,18,21,32,42,95,98,108,135`, `Migrations.kt:51-72` sans DEFAULT) : toute ligne sans `exists` explicite disparaît UI/recherche/review — perte fonctionnelle silencieuse.
- **M14 — `data/local/entity/PendingOperationEntity.kt:28-53` + `Migrations.kt:101-123`** : pas de colonne `device_id`, unicité locale sur `operation_id` seul vs contrat `UNIQUE(device_id, operation_id)` → après régénération `device_user_id`, rejeu = `create_resource` dupliqués serveur.
- **M15 — `data/local/dao/PendingOperationDao.kt:38`** : `failDescendants` ne cascade que sur le même `resource_id`, pas les enfants (cf. C6).
- **M16 — `data/local/dao/FileDao.kt:133-145` + `Migrations.kt:75-82`** : `category` ajoutée sans backfill, `getOcrAutoCandidates()` exige `category IN (…)` → tout PDF/image/texte pré-v4 exclu de l'OCR auto à vie.
- **M17 — `data/local/dao/FileDao.kt:151-152`** : `clearOcrQueued` reset `ocr_attempts = 0` inconditionnellement (contredit commentaire `:130-132`) → échec permanent rejoué indéfiniment.
- **M18 — pas de FK `files → folders`** (`FileEntity.kt:18-26`, `FolderEntity.kt:18-25`, `FolderDao.kt:95-96`, `FileDao.kt:92-93` deletes physiques) → `remove(dossier)` laisse orphelins, `moveToFolder` vers parent inexistant accepté, cycles possibles.
- **M19 — `FolderDao.kt:56-57` + `FileDao.kt:51-52`** : `markMissing` = `SET exists = 0` seul (ni `sync_status` ni annulation `create` pending) → ressource disparue quand même poussée (fantôme serveur), placement `local-cloud` mensonger.
- **M20 — `data/local/dao/ScanDao.kt:12-64` + `entity/ScanSessionEntity.kt:15-20`** : sessions `active` multiples possibles (aucun index unique/partiel), aucun `deleteSession` → doubles inserts concurrents = session orpheline + pages fuyantes.
### Réseau / Auth / Repos
- **M21 — `data/repository/FileRepository.kt:261-272` + `data/remote/ApiClient.kt:64-65`** : pagination jetée (`pageSize=50` sans `page`, `meta` ignoré) alors que le serveur pagine → dossiers > 50 fichiers ne convergent jamais, silencieusement.
- **M22 — `data/remote/ApiClient.kt:119-125`** : `catch (Exception) → NETWORK_ERROR` attrape aussi `JsonDataException` (Moshi) et `InterruptedIOException` (annulation) → parsing cassé = `retry()` infini, coroutine annulée = `ApiException` au lieu de `CancellationException` (scope/WorkManager corrompus).
- **M23 — `data/repository/ShareRepository.kt:45,99-104` + `FolderRepository.kt:115`** : confusion `device_id` vs `user_id` — `syncSnapshot` compare `deviceIdentity.getOrCreate()` (device) à `perm.ownerId` (user serveur), `saveFolder` stocke le device dans `ownerId`, `ActiveUserStore` ignoré. Le snapshot serveur **exclut les ressources possédées** → toute ligne cloud-only au vrai `ownerId=user` est `markMissing` à chaque login/restore (ex. note `createNote(ownerId=userId)` disparaît).
- **M24 — `features/sync/OutboxSyncWorker.kt:159-170` + `data/repository/OutboxRepository.kt:29-31`** : round-trip `expiresAt` Long→Double (Moshi `Map<String,Any?>`) → `enqueueShare(expiresAt: Long)` réémis `1.7E12` → serveur `*int64` refuse → `400 INVALID_REQUEST` → **tout partage avec expiration dead-lettered**.
- **M25 — `ui/auth/AuthViewModel.kt:43,123-125`** : callback 401 singleton possédé par un ViewModel (`apiClient.onUnauthorized`, `ApiClient` `@Singleton` survit au VM, annulé dans `onCleared`) → après destruction, 401 ne purge plus la session → token expiré réutilisé, worker `success()` sur 401 fige l'outbox, utilisateur jamais déconnecté.
- **M26 — `domain/ServerConfigStore.kt:32-43` + `data/remote/ServerUrlInterceptor.kt:25-38`** : race `load()` — interceptor lit `current` (défaut `10.0.2.2`) sur thread OkHttp pendant que `load()` restaure l'URL ; `registerDevice()` part avant `load()` → cold start avec URL custom = premières requêtes (y compris `Authorization: Bearer` restauré) vers l'hôte par défaut (**fuite du bearer**).
- **M27 — `data/repository/ShareRepository.kt:44-93` + `data/remote/dto/Dtos.kt:120-132`** : snapshot permissions sans delta (`after` jamais passé), `sharedById`/`expiresAt` en `Any?` jamais lus, `cachedAt` jamais persisté, aucun downgrade 24h ni `canAccess` → grant révoqué/expiré reste visible et ouvrable (`404`) jusqu'au prochain login.
- **M28 — `domain/ServerConfigStore.kt:46-59`** : `set()` persiste URL non validée (`"http://"` → `"http:"`, `"foo bar"` → `"http://foo bar"`) → app semi-brickée jusqu'à correction manuelle (recoupé par 2 agents).
### UI / Navigation / VM
- **M29 — `ui/folderlist/FolderListScreen.kt:202+220`** : onboarding racine bloqué après rotation — `pendingDefaultPick` en `remember` (non-saveable), `LaunchedEffect` polling annulé à la rotation, import SAF continu en fond mais `setDefaultRoot()` jamais rappelé → écran figé sur `DefaultRootOnboarding`, re-picker = doublon d'import.
- **M30 — `ui/document/DocumentViewerScreen.kt:130-137`** : position pager perdue à la rotation (`jumpPending = remember`), re-scroll vers `initialResourceId` → page N → retour page initiale. Fix : `rememberSaveable` / mémoriser index courant.
- **M31 — `ui/search/SearchScreen.kt:276-284` + `SearchViewModel.kt:55-72`** : `TextField` branché sur la valeur **debouncée** (300 ms) → frappe affichée par à-coups, IME/autocorrect écrasés. Correct : champ sur requête brute, debounce pour Room seule.
- **M32 — `ui/folderdetail/FolderDetailScreen.kt:196-202`** : Partager sans gate `isShareable` (contraire FolderList `canShare`, `:154-159`) → partage d'un dossier local-only/reçu = op `share` vouée au dead-letter `NOT_FOUND`.
- **M33 — `ui/folderlist/FolderListViewModel.kt:165-173`** : `canShare` stale au login/logout (combine `_defaultRootId`/`_browseFolderId` sans token/auth) → « Partager » reste désactivé jusqu'à navigation après connexion depuis Réglages.
- **M34 — `ui/folderlist/FolderListScreen.kt:333-375 vs 326-330`** : suppression multi-dossiers filtre les items **visibles** alors que `selection.ids` survit à `openBrowseFolder` (jamais clear) → sélection hors-vue abandonnée silencieusement avec snackbar succès. Même classe `ui/search/SearchScreen.kt:290-305` (chips actifs en mode sélection, delete par snapshot).
- **M35 — `ui/document/DocumentViewerScreen.kt:131-144`** : pas de clamp après suppression — supprimer le dernier doc (page 2/2) laisse `pagerState` hors bornes → viewer vide au lieu de retomber sur 1er ou `onBack`.
- **M36 — `ui/settings/SettingsScreen.kt:120-128`** : préférence `SYSTEM` inatteignable (Switch DARK/LIGHT depuis `darkNow`, store + thème supportent SYSTEM) → impossible de revenir à « suivre le système ».
- **M37 — `ui/settings/SettingsViewModel.kt:30-36`** : `load()` écrase une saisie serveur en cours (`_serverUrl` init défaut puis réassigné après `load()` en `init`).
### Scan / PDF / Review / Thumbnails
- **M38 — `data/repository/ScanRepository.kt:63-78`** : `addPage` avec `sortOrder = pageCount` → doublons après suppression (`ORDER BY sort_order` instable, `swapOrder` ambigu). Cause : compteur au lieu de `MAX+1`.
- **M39 — `ui/scan/ScanViewModel.kt:180/199`** : dimensions stockées (pré-scale) ≠ réelles (downscale 2400px dans `process()`) → fiche `W×H` fausse pour grands quads.
- **M40 — `ui/scan/ScanViewModel.kt:177-203`** : écriture JPEG hors transaction Room (orphelins si insert échoue) ; `deletePage` supprime le fichier **avant** la ligne DB (crash = ligne vers fichier absent → rejoint C8).
- **M41 — `data/repository/FileRepository.kt:206`** : `saveLocalFile` ne remonte jamais `cloud` → `local-cloud` (`existing?.syncStatus ?: …`) → fichier cloud-only réimporté en SAF reste badgé « cloud », ignoré vignette/OCR (`sync_status='local-cloud'` requis, `FileDao.kt:137`).
- **M42 — `ui/pdfbuilder/PdfBuilderViewModel.kt:227-237`** : PDF assemblé importé `processed=false` (défaut omis, contraire export scan `true`) → atterrit en review alors que l'utilisateur vient de le construire.
- **M43 — `ui/review/SwipeReviewViewModel.kt:68-74,94-100`** : retrait optimiste sans réinsertion sur échec (`keep`/`markAllProcessed`, contraire `delete` qui réinsère) → carte perdue jusqu'au prochain `load()` (init seule).
- **M44 — `ui/pdfbuilder/PdfBuilderScreen.kt:248`** : `remember(files)` réinitialise la sélection à chaque update Room → cases cochées effacées pendant un refresh serveur.
- **M45 — `ui/pdfbuilder/PdfBuilderEngine.kt:104-107`** : pages PDF sources plafonnées à 1200pt malgré commentaire « format conservé » (`min(1, 1200/max, 3000/max)`, le 1200 gagne toujours) → pixellisation A3/300dpi.
- **M46 — `features/scan/CornerGeometry.kt:19-26`** : `orderPoints` sans validation dégénérescence (doublons/quad aplati) → `outputSize = 0` → bitmap 1×1 validé (page blanche) au lieu d'erreur.
- **M47 — `ui/scan/CameraStage.kt:162-181`** : overlay calibré sur flux `ImageAnalysis` (hypothèse `FILL_CENTER`) alors que `PreviewView` affiche le flux `Preview` (ratio/crop différents) → quad décalé systématiquement quand les ratios diffèrent.
--- ---
## 🟡 Mineurs (UX, perf, dette) ## 🟡 Mineurs restants (8) — ✅ tous corrigés le 2026-09-24 (162/162 tests verts)
### Sync / Worker / SAF ### Sync / Worker / SAF
- **m1 — `features/sync/SyncViewModel.kt:103-121`** : `_walkInProgress` sans `finally` (reste `true` si scope annulé) → badge « syncing » collé ; la fenêtre inclut l'appel réseau partage. - **m1 — `features/sync/SyncViewModel.kt:108-133`** : `_walkInProgress` sans `finally` dans la boucle (reste `true` si scope annulé ; seul `importRoot:173` a un `finally`) → badge « syncing » collé ; la fenêtre inclut l'appel réseau partage.
- **m2 — `features/sync/SyncViewModel.kt:106-112`** : `OutboxSyncWorker.enqueue` + `OcrAutoWorker.enqueue` à chaque tick même sans changement → réveils WorkManager / 30s pour rien. - **m2 — `features/sync/SyncViewModel.kt:110-116`** : `OutboxSyncWorker.enqueue` + `OcrAutoWorker.enqueue` à chaque tick même sans changement → réveils WorkManager / 30s pour rien.
- **m3 — `features/sync/OutboxSyncWorker.kt:97-100`** : 401 → `success()` sans re-signal, ops pendantes figées jusqu'au prochain tick/login (bénin, `AuthViewModel` ré-enqueue au re-login). - **m5 — `features/sync/DeviceSync.kt:76-162`** : « transaction courte » en réalité géante (N upserts + `getAll()` dossiers **et** fichiers par racine sous verrou écriture) → lecteurs Room bloqués, jank/ANR sur grosses arborescences.
- **m4 — `features/sync/SafScanner.kt:132-139`** : `cursor.getString(iDoc)` sans garde `iDoc == -1`, `name` plateforme-nullable déréférencé → provider dégénéré = crash de tout `scanTree` à chaque tick.
- **m5 — `features/sync/DeviceSync.kt:75-137`** : « transaction courte » en réalité géante (N upserts + `getAll()` dossiers **et** fichiers par racine, O(racines×DB) sous verrou écriture) → lecteurs Room bloqués, jank/ANR sur grosses arborescences.
- **m6 — `features/saf/FolderDeleter.kt:74-88`** : `deleteLocally` multi-writes hors transaction (contraire `treeMarkMissing`) → kill à mi-chemin = `exists` partiel.
### Room / Domain / DI ### Room / Domain / DI
- **m7 — `data/local/dao/FileDao.kt:30-37`** : `searchWithFilters` `LIKE` brut sans `ESCAPE`, casse ASCII-only → `%`/`_` = jokers (match-all), « ete » ne trouve pas « ÉTÉ ». - **m7 — `data/local/dao/FileDao.kt:45`** : `searchWithFilters` `LIKE` brut sans `ESCAPE`, casse ASCII-only → `%`/`_` = jokers (match-all), « ete » ne trouve pas « ÉTÉ ».
- **m8 — `data/local/FileOrdering.kt:5-11`** : tri mémoire (`referenceDate` seule) divergent du SQL (`name ASC` tiebreak, `FileDao.kt:21,43`) ; `lastModified = 0` SAF trié comme plus vieux → ordre incohérent + fichiers `0` enfouis. - **m15 — `di/DatabaseModule.kt:25-28`** : aucune stratégie de downgrade → APK plus ancien sur DB v14 = crash `IllegalStateException` au lieu de dégradation contrôlée.
- **m9 — `data/local/dao/PendingOperationDao.kt:30-32`** : commentaire `MAX_PENDING_ATTEMPTS` contredit le code (`markFailed()` = dead-letter immédiate, `attempts` diagnostique) — trompeur pour futurs appelants (cohérent avec worker, seul le commentaire est faux). - **m19 — `data/local/AppDatabase.kt:36-37`** : `version=14, exportSchema=false`, migrations non snapshotées → dérives indétectables en CI.
- **m10 — `data/local/dao/FileDao.kt:89`** : `updateUri` ne touche pas `updated_at` → ordre de convergence faussé après move.
- **m11 — `domain/LocalModeStore.kt:24`** : `get()` teste `!= null` au lieu de `== "1"` → toute valeur parasite (`"0"`, `""`) = mode local actif à tort.
- **m12 — `domain/ServerConfigStore.kt:40-44` + `domain/ThemePreferenceStore.kt:28-32`** : `load()` once-only (`AtomicBoolean`, sans réarmement) → après wipe/logout, URL/thème périmés en mémoire.
- **m13 — `domain/ThemePreferenceStore.kt:34-39`** : `set()` publie le `StateFlow` avant succès DB → divergence UI/DB si upsert échoue.
- **m14 — `domain/PrefKeys.kt:8`** : clé `SYNC_MODE` morte (0 usage, grep vérifié) → dérive spec/impl.
- **m15 — `di/DatabaseModule.kt:25-28`** : aucune stratégie de downgrade → APK plus ancien sur DB v11 = crash `IllegalStateException` au lieu de dégradation contrôlée.
- **m16 — index composites manquants** (`PendingOperationEntity.kt:20-27`, `FileEntity.kt:18-26`, `PendingOperationDao.kt:13`, `FileDao.kt:133-145`) : `selectPending` et `getOcrAutoCandidates` = full-table scan → jank/batterie à 10k lignes.
- **m17 — `data/local/entity/FileEntity.kt:56-57` vs `Migrations.kt:92`** : `processed` sans `defaultValue` Room alors que la migration met `DEFAULT 0` (contraire `createdInApp`, `FolderEntity.kt:43`) → fresh-install ≠ migré.
- **m18 — `data/local/dao/ScanDao.kt:48-57`** : `swapOrder` sans contrôle d'appartenance ni transaction → swap inter-sessions corrompt `sort_order`, concurrence = doublons.
- **m19 — `data/local/AppDatabase.kt:27-34`** : `exportSchema = false`, migrations non snapshotées → dérives indétectables en CI.
- **m20 — `data/repository/OcrRepository.kt:66-73`** : `poll()` infini (`while(true)` + 3s, sans timeout) alors qu'un job peut rester `processing` 15 min (stale claim serveur) → coroutine tenue indéfiniment.
- **m21 — `data/repository/OutboxRepository.kt`** : ops contrat non émissibles (`update_metadata`, `update_share`, `create_link`, `revoke_link` — §6.1 = 9 ops, 5 helpers) → rename partagé, update share, liens publics inopérants.
- **m22 — `data/remote/ApiService.kt`** : endpoints contrat absents (`PATCH /users/me/password`, `GET/DELETE /files/:id`, `GET /files/search`, `GET /shares/links/:token`) → changement mot de passe impossible avec tokens 7j non révoqués.
- **m23 — `data/repository/AuthRepository.kt:21-35`** : `registerDevice` best-effort avale tout (y compris 400/429) → `INVALID_DEVICE_ID`/`RATE_LIMITED` invisibles, 401 trompeur plus tard.
- **m24 — `ui/auth/AuthViewModel.kt:52-55`** : `registerDevice()` émis même en mode local (pas de garde contrairement à `syncSnapshot`).
- **m25 — `di/NetworkModule.kt:37-43`** : logging `BASIC` en DEBUG loggue les query PII (`GET /users/resolve?username=…`) dans logcat.
- **m26 — `data/remote/AuthInterceptor.kt:20-26`** : `Bearer` joint aux routes publiques (`POST /devices`, `POST /auth/login`) — serveur l'ignore mais hygiène + amplification de la fuite M26.
- **m27 — `auth/SessionManager.kt:33-38`** : `expiresAt` du login jeté (paseto TTL 7j) → expiration découverte par 401 brutal, impossible de pré-relancer.
- **m28 — `auth/SecureTokenStore.kt:27-36`** : init Keystore/`EncryptedSharedPreferences` au construct Hilt + I/O synchrone possiblement Main (`MasterKeys` déprécié) → ANR au restore, crash Direct Boot avant déverrouillage.
### UI ### Sync contrat / OCR
- **m29 — `ui/navigation/NavGraph.kt:50`** : `pdfBuilder(listOf())` → `"pdfbuilder/"` ne matche pas `"pdfbuilder/{ids}"` (protégé aujourd'hui par `enabled = ids.isNotEmpty()` — contrat implicite fragile). - **m20 — `data/repository/OcrRepository.kt:66-73`** : `poll()` infini (`while(true)` + 3s, sans timeout) alors qu'un job peut rester `processing` longtemps (stale claim serveur) → coroutine tenue indéfiniment.
- **m30 — `ui/navigation/NavGraph.kt:53-59,165`** : `folder/…` sans `launchSingleTop` → double-tap = doublon de pile. - **m21 — `data/repository/OutboxRepository.kt:72-147`** : ops contrat non émissibles (`update_metadata`, `update_share`, `create_link`, `revoke_link` — §6.1 = 9 ops, helpers partiels) → rename partagé, update share, liens publics inopérants.
- **m31 — `ui/navigation/KazierApp.kt:54-63`** : `rememberNavController()` par branche SignedIn↔Local → `signOutToLocal()` perd la position d'exploration (hoister le controller).
- **m32 — `ui/folderdetail/FolderDetailScreen.kt:395-429`** : dossiers non sélectionnables dans le détail (vs FolderList) — incohérence partage/multi-suppression inter-écrans.
- **m33 — `ui/pdfbuilder/PdfBuilderScreen.kt:104-114`** : `LaunchedEffect(buildPhase)` rejoue side-effects à la recomposition racine (rotation → `Failed` re-snackbar, `Saved` re-`onOpenDocument` = double navigation possible).
- **m34 — dialogs `remember` perdus à la rotation** (`SyncStatusBadge.kt:129`, `showDeleteWarning/Confirm`, `showMoveDialog`, `showShareSheet`, `showNameDialog`) — sûr mais UX ; `showOcrDialog` en `rememberSaveable` = bon exemple.
- **m35 — `ui/components/WatchedFoldersBadge.kt:36-40` + `WatchedFoldersViewModel.kt:25-27`** : double instance VM + `SharingStarted.Eagerly` collecte Room en continu même sur autres onglets.
- **m36 — `ui/settings/SettingsViewModel.kt:43-48`** : `onServerUrlChange` écrit en prefs à chaque frappe (churn IO) ; commentaire `testConnection` obsolète.
- **m37 — `MainActivity.kt:27-33`** : `themePreferenceStore.load()` fire-and-forget → flash de thème aux premières frames.
- **m38 — `ui/navigation/NavGraph.kt:213-219`** : bandeau import global chevauchant la FloatingNavBar, doublon des indicateurs par-écran.
- **m39 — `ui/pdfbuilder/PdfBuilderViewModel.kt:236`** : `syncStatus="local"` en littéral au lieu de `FileStatus.LOCAL` — fonctionne mais casse silencieusement à toute renommée.
### Scan / PDF / Thumbnails ---
- **m40 — `ui/scan/CameraStage.kt:86-91`** : `ImageCapture` forcé 1920×1080 paysage → sur portrait, bitmap pleine-rés + copie tournée (×2 mémoire ~16 Mo) → OOM petits devices.
- **m41 — `ui/scan/CameraStage.kt:165-181`** : `toBitmap()` pleine-rés à chaque frame d'analyse (~30fps) puis downscale interne → churn GC + batterie. ## 🛠️ Plans de correction (reliquat) — ✅ implémentés le 2026-09-24
- **m42 — `ui/scan/CameraStage.kt:99-101`** : `addOnLayoutChangeListener` jamais retiré → fuite mineure du listener.
- **m43 — `ui/scan/CameraStage.kt:200-211`** : `when` rotation sans `else` → angle inattendu = copie silencieuse au lieu d'erreur. Ordre suivi : M13 → M5 → M27+m21 → M9 → mineurs par lot (m1+m2, m5, m7, m20, m15+m19).
- **m44 — `ui/scan/ScanGeometry.kt:42-69`** : division par zéro si `sourceRect` dégénérée (`Infinity/NaN` dans le quad ; inatteignable via `initialViewport` mais API publique exposée). Écarts d'implémentation vs plan : M13 sans rewrite (colonne restée nullable, défaut Kotlin 1 + backfill — pas de bump de contrainte) ; m7 `COLLATE NOCASE` sans colonne normalisée (repli Unicode « ete » → « ÉTÉ » toujours ouvert, voir suivi) ; M27 `cachedAt` persisté = heure locale du pull (pas l'horloge serveur, skew).
- **m45 — `ui/scan/CropStage.kt:188-193`** : arrondi `roundToInt` viewport indépendant de l'offset → dépassement 1px en bordure (frange noire sur images impaires).
- **m46 — `ui/scan/ScanViewModel.kt:111-122`** : `combine(pages, pageCount)` avec count ignoré → réassignations `_pages` redondantes. ### M5 — `deleteInCloud` sans tombstone locale
- **m47 — `ui/scan/ScanViewModel.kt:409-418`** : `abandon()` laisse sessions vides `ABANDONED` jamais purgées + `sessionDir()` fait `mkdirs()` en getter (recrée ce qu'on supprime). Fichiers : `features/saf/FileDeleter.kt:88-104`, `features/saf/FolderDeleter.kt:91-103` (+ descendants via `collectDescendants`).
- **m48 — `data/repository/ScanRepository.kt:27-40`** : race `getOrCreateActiveSession` (double `active` possible, aucune unicité partielle ; fenêtre étroite). Constat : `deleteInCloud` enqueue `delete_resource` mais laisse `exists = 1` ; la ressource reste affichée et le walk la revoit.
- **m49 — `domain/FileCategory.kt:19-27`** : CSV classé `TEXT` (par MIME) ou `OFFICE` (par extension) selon le chemin → icône/filtres/OCR divergents pour le même fichier. Plan :
- **m50 — `features/thumbnails/ThumbnailStore.kt:51`** : map de `Mutex` jamais purgée → fuite lente par `resourceId`. 1. Dans `FileDeleter.deleteInCloud`, après `enqueueDeleteResource`, appeler `fileRepository.markMissing(resourceId, now)` dans la même transaction Room (ou `appDatabase.withTransaction` comme `deleteFull`).
- **m51 — `features/thumbnails/ThumbnailStore.kt:104-112`** : `.tmp` orphelin si `renameTo` échoue → résidus `*.webp.tmp`. 2. Dans `FolderDeleter.deleteInCloud`, idem pour le dossier ET sa descendance Room (`treeMarkMissing`-léger : `markMissing` sur fichiers + sous-dossiers, sans `delete_resource` supplémentaire sauf si `hasSyncedCreateOperation`).
- **m52 — `features/thumbnails/ThumbnailStore.kt:83-87`** : `isUpToDate` sur `mtime` seule (granularité seconde SAF) → vignette périmée après édition rapide (pas de taille/hash). 3. Vérifier que le walk ne ressuscite pas : les lignes `exists = 0` + `delete_resource` pending doivent être ignorées par la réconciliation (garde `hasPendingDeleteOperation`, cf. `OutboxRepository.kt:204`).
- **m53 — `ui/pdfbuilder/PdfBuilderEngine.kt:121-124`** : `renderer?.close()` non protégé (si `close()` lève, `pfd.close()` sautée → fd leak ; `ThumbnailStore.renderPdfPage` fait `runCatching`). 4. UI : vérifier que les listes filtrent `exists = 1` (déjà le cas) → la ligne disparaît aussitôt.
- **m54 — `features/scan/CornerGeometry.kt:40-45`** : commentaire « moyenne » mais code `max` → warp légèrement étiré vs réel. Tests : étendre `ProcessedGateTest` ou nouveau `DeleteInCloudTest` — `deleteInCloud` puis assert `exists == 0` + op `delete_resource` présente ; walk simulé ne ressuscite pas.
- **m55 — `features/scan/ScanImageProcessor.kt:126-181`** : mats de contours non libérés sur exception (`c.release()` chemin nominal seul) → fuite native OpenCV.
- **m56 — `ui/review/SwipeReviewViewModel.kt:52-64`** : échec de reload écrase le deck (`update{cards=files}` même sur `emptyList` d'erreur) → deck vidé à tort. ### M9 — `FolderMerger` multi-transactions non-atomique
Fichier : `features/saf/FolderMerger.kt:53-106`.
Constat : `createMergedFolder` (transaction 1), moves (N transactions via `FileMover`/`reparentSubFolders`), deletes (N transactions). Un crash à mi-fusion laisse un état partiel ; la relance est idempotente (dossier réutilisé) mais ne reprend pas les moves manquants proprement.
Plan :
1. Envelopper `mergeSelectedFolders` dans `appDatabase.withTransaction` pour la partie Room (create + reparent + `treeMarkMissing`) — nécessite d'injecter `AppDatabase` dans `FolderMerger` et de rendre `FileMover.moveFiles` / `reparentSubFolders` appelables dans une transaction existante (ou journaliser les `move_resource`/`delete_resource` dans la transaction et n'exécuter le SAF physique qu'avant/après selon le sens crash-safe : journal-first comme C4).
2. Ordre crash-safe : (a) transaction Room = create + moves logiques + deletes logiques (`exists = 0` + outbox), (b) exécution SAF physique (moves + deletes), (c) sweep au prochain tick pour les physiques manqués (réutiliser `sweepPendingPhysicalDeletes`).
3. Garder l'idempotence `findExistingMerged` pour les relances.
4. À défaut d'une transaction unique (SAF non transactionnel), a minima : rendre chaque étape reprise-safe (skip les sources déjà vides, skip les moves déjà journalisés via `hasPendingMoveOperation`).
Tests : nouveau `FolderMergerTest` — fusion 2 dossiers avec fichiers + sous-dossier, assert `movedFiles/deletedFolders`, relance idempotente (pas de doublon), crash simulé entre étape 2 et 3 → reprise sans perte.
### M13 — `exists: Int? = null` invisible
Fichiers : `data/local/entity/FolderEntity.kt:36`, `data/local/entity/FileEntity.kt:46`, DAO (`FolderDao`, `FileDao` filtres `= 1`), `Migrations.kt` (créations tables sans `DEFAULT 1` / `NOT NULL`).
Constat : toute ligne insérée sans `exists` explicite (défaut Kotlin `null`) est cachée par les requêtes `WHERE exists = 1`.
Plan :
1. Durcir les entités : `exists: Int = 1` (non-null, défaut 1) dans `FolderEntity` et `FileEntity`.
2. Migration v14→v15 : `UPDATE folders SET exists = 1 WHERE exists IS NULL`, idem `files`, puis recréation ou `NOT NULL DEFAULT 1` (Room : via `autoMigrations` ou SQL `ALTER` + table rewrite selon la version SQLite ; le plus simple : `UPDATE` + contrainte applicative + défaut entité, sans rewrite si Room accepte le changement nullable→non-null via migration manuelle avec recréation de table).
3. Auditer tous les `saveFolder`/`saveLocalFile`/`upsertShared*` pour passer `exists = 1` explicitement.
4. Option : ajouter un test `ExistsDefaultTest` — insert sans `exists`, assert visible dans `observeByFolder`/`searchWithFilters`.
Note : migration à tester via `Migration13To14Test`-style (nouveau `Migration14To15Test`) + `:app:testDebugUnitTest`.
### M27 — snapshot permissions sans delta ni `canAccess`
Fichiers : `data/repository/ShareRepository.kt:44-47`, `data/remote/dto/Dtos.kt:144-156` (`sharedById`/`expiresAt: Any?`), `data/remote/ApiService.kt:74-78`, `ApiClient.kt:106-108`.
Constat : `syncPermissions()` sans `after`, champs `sharedById`/`expiresAt` jamais lus, `cachedAt` jamais persisté, aucun downgrade TTL 24h ni `canAccess` → grants révoqués/expirés visibles jusqu'au prochain login.
Plan :
1. DTO : typer `sharedById: String?`, `expiresAt: Long?` (le serveur renvoie ms epoch ou null — vérifier `docs/api-v1.md §6.2` et adapter avec un adapter Moshi tolérant `Any?`→Long).
2. Persistance : stocker `cachedAt`/`expiresAt`/`sharedById`/`effectiveAccess` — soit colonnes sur `files`/`folders`, soit nouvelle table `resource_permissions` (préférable : ne pas polluer les entités). A minima `user_preferences` : `permissions_cached_at`.
3. Delta : `syncSnapshot(after: Long? = cachedAt)` → `apiClient.syncPermissions(after)` ; pull complet (`after = null`) au login/restauration + quand `now - cachedAt > 24h` (TTL).
4. Expiration locale : au tick, marquer `exists = 0` les lignes dont `expiresAt < now` ; downgrade lecture seule après TTL sans reseed (gate `canAccess` : à exposer via `ShareRepository.canAccess(resourceId, required)` utilisé par les VM avant open/share/rename).
5. `canAccess` : ranking viewer < commenter < editor < owner, `ownerId == currentUser` → owner.
Tests : étendre `ShareRepositoryTest` — delta `after`, révocation (absent du snapshot → `markMissing`), expiration (`expiresAt` passé → masqué), `canAccess` ranking.
### m1+m2 — badge sync et réveils WorkManager
Fichier : `features/sync/SyncViewModel.kt:100-137`.
Plan :
1. m1 : envelopper le corps de boucle dans `try { … } finally { _walkInProgress.value = false }` (comme `importRoot:173-176`), et sortir `syncSnapshot` de la fenêtre `_walkInProgress` (flag séparé ou `syncing` = walk || drain déjà calculé via WorkManager).
2. m2 : n'enqueuer `OutboxSyncWorker`/`OcrAutoWorker` que si le tick a produit quelque chose (`results.any { folders+files+missing > 0 }` ou `pendingOperationDao.countPending() > 0` / fichier promu). Éviter les réveils /30s à vide.
Tests : Robolectric `SyncViewModelTest` — annulation du scope → flag retombe ; tick sans changement → `WorkManager` non sollicité (mock/static ou extraction d'un `SyncScheduler` testable).
### m5 — walk : transaction géante + `getAll()` par racine
Fichier : `features/sync/DeviceSync.kt:67-163`.
Plan :
1. Découper la phase 2 : upserts dossiers/fichiers par batch (ex. 200) en transactions courtes successives au lieu d'une transaction unique ; la réconciliation `missing` en passe séparée.
2. Remplacer `folderRepository.getAll()` + `fileRepository.getAll()` (full-table scan par racine) par des requêtes scopées à la racine (`getByRootUri`/`getDescendants`) — à ajouter aux DAO avec index sur `uri` (déjà unique) ; filtrer en SQL plutôt qu'en mémoire (`isChildOf` en `LIKE rootUri || '/%'`).
3. Conserver le `Mutex` single-flight ; vérifier `ensureActive()` dans les boucles longues pour annulation propre.
Tests : `SafScannerTest`-style perf — 5k fichiers simulés, assert temps/absence d'ANR ; test de convergence identique avant/après.
### m7 — recherche `LIKE` sans `ESCAPE`
Fichier : `data/local/dao/FileDao.kt:42-49`.
Plan : échapper `%`, `_`, `\` dans `:query` côté repository (`searchFiles`) + `LIKE … ESCAPE '\'` dans la requête ; ajouter `COLLATE NOCASE` (ou normalisation) pour « ete » → « ÉTÉ ». Tester : `%`, `_`, `\`, accents, casse.
Tests : `SearchFieldTest` ou nouveau `SearchEscapeTest` — `%` littéral ne matche pas tout, `_` littéral, insensible à la casse.
### m20 — `OcrRepository.poll()` infini
Fichier : `data/repository/OcrRepository.kt:66-73`.
Plan : ajouter timeout (ex. 10 min) + nombre max de polls + backoff ; lever `OcrTimeoutException` ou retourner le dernier état ; coopérer avec l'annulation (`ensureActive`). Mettre à jour les appelants (viewer auto) pour afficher « OCR indisponible, réessayer ».
Tests : `OcrRepositoryTest` — job restant `processing` → timeout au bout de N polls (fake `ApiClient` + virtual time/delays courts).
### m15+m19 — robustesse DB (downgrade + `exportSchema`)
Fichiers : `di/DatabaseModule.kt:25-28`, `data/local/AppDatabase.kt:31-38`.
Plan :
1. m19 : `exportSchema = true` + `schemas/` commité ; ajouter un test `Migration13To14Test`-style qui échoue en cas de dérive (CI).
2. m15 : stratégie downgrade explicite et documentée — soit `fallbackToDestructiveMigrationOnDowngrade()` (avec avertissement perte de données locales, acceptable car miroir SAF + outbox non poussée à préserver → plutôt refuser le démarrage avec message), soit crash contrôlé avec écran « mettez à jour l'app ». Choisir et documenter ; ne jamais laisser `IllegalStateException` brut.
Tests : build avec `exportSchema=true` + `room.schemaLocation` ; test downgrade (ouverture v15 avec APK v14 → comportement attendu).
### m21 — ops contrat non émissibles
Fichiers : `data/repository/OutboxRepository.kt:72-147`, `data/local/entity/PendingOperationEntity.kt:76-86` (constantes déjà présentes : `UPDATE_METADATA`, `UPDATE_SHARE`, `CREATE_LINK`, `REVOKE_LINK`).
Plan : ajouter `enqueueUpdateMetadata(resourceId, resourceType, name?)`, `enqueueUpdateShare(...)`, `enqueueCreateLink(resourceId, resourceType, token, access, expiresAt?)`, `enqueueRevokeLink(...)` avec payloads §6.1 (`granteeUserId/access/inherit/expiresAt`, `token/access/expiresAt`) ; brancher les appelants (rename partagé, update share, liens publics) ; `GenerateId` pour `token` 32-hex côté client.
Tests : `OutboxSyncWorkerTest`-style — sérialisation payload, `normalizePayloadNumbers` (`expiresAt` Long exact, non `1.7E12`), round-trip `POST /sync/ops` mocké.
--- ---
@@ -195,7 +151,7 @@ Repro : device sans lib OpenCV → valider un crop → crash au retour caméra.
- Ordre interceptors `serverUrl → auth → logging`, `BASIC` ne log ni headers ni bodies — OK. - Ordre interceptors `serverUrl → auth → logging`, `BASIC` ne log ni headers ni bodies — OK.
- Contrat HTTP conforme sur endpoints déclarés (query `folderId/page/pageSize`, `deviceId` camel vs `device_id` login, multipart `file`/`resourceId`/`folderId`, enveloppes `{data,meta}`/`{error:{code,message}}`, codes) — OK. - Contrat HTTP conforme sur endpoints déclarés (query `folderId/page/pageSize`, `deviceId` camel vs `device_id` login, multipart `file`/`resourceId`/`folderId`, enveloppes `{data,meta}`/`{error:{code,message}}`, codes) — OK.
- `device_id` claim jamais utilisé comme preuve, seul le `Bearer` parle — conforme middleware. - `device_id` claim jamais utilisé comme preuve, seul le `Bearer` parle — conforme middleware.
- Worker no-op en mode local (`OutboxSyncWorker.kt:71`), batch 20 ≤ 100 serveur, statuts OCR, `resolveUser` trim compatible, password jamais trimé — OK. - Worker no-op en mode local (`OutboxSyncWorker.kt:111`), batch 20 ≤ 100 serveur, statuts OCR, `resolveUser` trim compatible, password jamais trimé — OK.
- Deep-links : aucun défini (absence, pas de bug) ; args nav `folderResourceId`/`documentResourceId`/`ids` cohérents, 32-hex sans `/`. - Deep-links : aucun défini (absence, pas de bug) ; args nav `folderResourceId`/`documentResourceId`/`ids` cohérents, 32-hex sans `/`.
- Hilt : `MainActivity @AndroidEntryPoint`, tous `hiltViewModel()` ↔ `@HiltViewModel`, scopes corrects — aucune injection manquante. - Hilt : `MainActivity @AndroidEntryPoint`, tous `hiltViewModel()` ↔ `@HiltViewModel`, scopes corrects — aucune injection manquante.
- Pas de recomposition infinie trouvée ; `collectAsStateWithLifecycle` partout ; placeholder cloud-only correct (`DocumentContentViewer.kt:39-47`) ; recherche 100 % locale conforme V1 ; back stack onglets correct (`saveState`/`restoreState`) ; `SelectionState` volatile documenté volontaire. - Pas de recomposition infinie trouvée ; `collectAsStateWithLifecycle` partout ; placeholder cloud-only correct (`DocumentContentViewer.kt:39-47`) ; recherche 100 % locale conforme V1 ; back stack onglets correct (`saveState`/`restoreState`) ; `SelectionState` volatile documenté volontaire.
+1 -1
View File
@@ -29,5 +29,5 @@ cd mobile-kotlin && ./gradlew :app:testDebugUnitTest
| Backend entry | `backend/cmd/server/main.go` — wiring gin + routes | | Backend entry | `backend/cmd/server/main.go` — wiring gin + routes |
| Sync outbox | `mobile-kotlin/.../features/sync/OutboxSyncWorker.kt` — worker WorkManager → `POST /sync/ops` | | Sync outbox | `mobile-kotlin/.../features/sync/OutboxSyncWorker.kt` — worker WorkManager → `POST /sync/ops` |
| SAF scan | `mobile-kotlin/.../features/sync/DeviceSync.kt` — two-pass walk SAF ↔ Room | | SAF scan | `mobile-kotlin/.../features/sync/DeviceSync.kt` — two-pass walk SAF ↔ Room |
| Room DB | `mobile-kotlin/.../data/local/AppDatabase.kt` — version 7, migrations, DAO | | Room DB | `mobile-kotlin/.../data/local/AppDatabase.kt` — version 16, migrations, DAO |
| API Retrofit | `mobile-kotlin/.../data/remote/ApiService.kt` — interface Retrofit (contrat client) | | API Retrofit | `mobile-kotlin/.../data/remote/ApiService.kt` — interface Retrofit (contrat client) |
+1 -1
View File
@@ -1 +1 @@
0.1.0 1.1.0
+2 -1
View File
@@ -8,7 +8,8 @@ MAX_FILE_SIZE_MB=50
OCR_LANG=fra+eng OCR_LANG=fra+eng
# Sécurité — à changer en production (jamais commité) # Sécurité — à changer en production (jamais commité)
AUTH_SECRET=dev-secret-change-me # ≥ 32 caractères, ex. `openssl rand -hex 32`. Doit matcher config.go (min 32).
AUTH_SECRET=dev-secret-change-me-please-set-in-prod
# Premier admin (créé UNIQUEMENT si la table users est vide). Obligatoires au # Premier admin (créé UNIQUEMENT si la table users est vide). Obligatoires au
# premier démarrage ; ignorés ensuite (l'env n'écrase jamais un compte). # premier démarrage ; ignorés ensuite (l'env n'écrase jamais un compte).
+11
View File
@@ -17,12 +17,23 @@ var expectedRoutes = []string{
"GET /api/v1/files/folders", "GET /api/v1/files/folders",
"GET /api/v1/files/:id", "GET /api/v1/files/:id",
"GET /api/v1/files/:id/ocr", "GET /api/v1/files/:id/ocr",
"GET /api/v1/files/:id/content",
"GET /api/v1/files/:id/shares",
"GET /api/v1/files/:id/links",
"GET /api/v1/files/:id/placements",
"DELETE /api/v1/files/:id", "DELETE /api/v1/files/:id",
"POST /api/v1/files/upload", "POST /api/v1/files/upload",
"GET /api/v1/users/resolve", "GET /api/v1/users/resolve",
"PATCH /api/v1/users/me/password", "PATCH /api/v1/users/me/password",
"POST /api/v1/groups",
"GET /api/v1/groups",
"POST /api/v1/groups/:id/members",
"GET /api/v1/groups/:id/members",
"DELETE /api/v1/groups/:id/members/:userId",
"DELETE /api/v1/groups/:id",
"POST /api/v1/ocr/jobs", "POST /api/v1/ocr/jobs",
"GET /api/v1/ocr/jobs/:id", "GET /api/v1/ocr/jobs/:id",
@@ -0,0 +1 @@
ALTER TABLE resources DROP COLUMN IF EXISTS has_content;
@@ -0,0 +1,6 @@
-- V2 placements : `has_content` = « octets vus présents » (lazy healing).
-- TRUE à chaque upload (nouveau ou ciblé), healen FALSE→TRUE au premier
-- `OpenContent` réussi, TRUE→FALSE quand les octets ont disparu sous
-- UPLOAD_DIR. Les lignes existantes partent à FALSE (inconnu, pas absent) :
-- le premier accès les heal, aucun scan au boot.
ALTER TABLE resources ADD COLUMN has_content BOOLEAN NOT NULL DEFAULT FALSE;
@@ -0,0 +1,2 @@
DROP TABLE IF EXISTS resource_placements;
DROP TABLE IF EXISTS storage_locations;
@@ -0,0 +1,25 @@
-- V2 placements multi-device : où existent les octets d'une ressource.
-- `storage_locations` modélise chaque device (le serveur reste implicite via
-- `resources.has_content`, pas de ligne). `resource_placements` matérialise
-- les reports clients (`report_bytes` via l'outbox) : hint de présence,
-- jamais une preuve — le serveur ne vérifie pas les octets du device.
CREATE TABLE storage_locations (
id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'),
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
device_id TEXT NOT NULL UNIQUE CHECK (device_id ~ '^[0-9a-f]{32}$'),
type TEXT NOT NULL DEFAULT 'mobile' CHECK (type IN ('mobile', 'desktop', 'server')),
last_seen_at TIMESTAMPTZ DEFAULT NOW(),
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_storage_locations_user ON storage_locations(user_id);
CREATE TABLE resource_placements (
resource_id TEXT NOT NULL REFERENCES resources(resource_id) ON DELETE CASCADE,
location_id TEXT NOT NULL REFERENCES storage_locations(id) ON DELETE CASCADE,
has_bytes BOOLEAN NOT NULL,
updated_at TIMESTAMPTZ DEFAULT NOW(),
PRIMARY KEY (resource_id, location_id)
);
CREATE INDEX idx_placements_location ON resource_placements(location_id);
@@ -0,0 +1,6 @@
DROP INDEX IF EXISTS idx_shares_active_group;
ALTER TABLE shares DROP CONSTRAINT IF EXISTS shares_grantee_xor_check;
ALTER TABLE shares ALTER COLUMN grantee_user_id SET NOT NULL;
ALTER TABLE shares DROP COLUMN IF EXISTS grantee_group_id;
DROP TABLE IF EXISTS group_members;
DROP TABLE IF EXISTS groups;
@@ -0,0 +1,32 @@
-- V2-6 groupes : partage vers un ensemble d'utilisateurs (famille, équipe).
-- `groups` : identité nommée possédée (created_by) ; `group_members` :
-- appartenances (pas de groupes imbriqués — un niveau, documenté).
-- `shares` accepte une cible groupe : exactement une des deux cibles est
-- renseignée (CHECK), avec un index d'unicité active par cible.
CREATE TABLE groups (
id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'),
name TEXT NOT NULL CHECK (name <> '' AND char_length(name) <= 255),
created_by TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE group_members (
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT NOW(),
PRIMARY KEY (group_id, user_id)
);
CREATE INDEX idx_group_members_user ON group_members(user_id);
ALTER TABLE shares ADD COLUMN grantee_group_id TEXT REFERENCES groups(id) ON DELETE CASCADE;
ALTER TABLE shares ALTER COLUMN grantee_user_id DROP NOT NULL;
ALTER TABLE shares
ADD CONSTRAINT shares_grantee_xor_check
CHECK (
(grantee_user_id IS NOT NULL AND grantee_group_id IS NULL)
OR (grantee_user_id IS NULL AND grantee_group_id IS NOT NULL)
);
CREATE UNIQUE INDEX idx_shares_active_group
ON shares(resource_id, grantee_group_id) WHERE revoked_at IS NULL AND grantee_group_id IS NOT NULL;
+36
View File
@@ -333,6 +333,42 @@ func TestMigrationsUpDown(t *testing.T) {
t.Error("index unique partiel (id) WHERE revoked_at IS NULL manquant sur share_links") t.Error("index unique partiel (id) WHERE revoked_at IS NULL manquant sur share_links")
} }
// --- 000014 : has_content + 000015 : placements -------------------------
var hasContentCol int
err = conn.QueryRow(`
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'resources' AND column_name = 'has_content'`).Scan(&hasContentCol)
if err != nil {
t.Fatalf("has_content column: %v", err)
}
if hasContentCol == 0 {
t.Error("colonne resources.has_content manquante après 000014")
}
assertTables(t, conn, "users", "devices", "resources", "operations", "ocr_jobs", "shares", "share_links", "storage_locations", "resource_placements", "schema_migrations")
assertHexCheck(t, conn, "storage_locations", "id")
assertHexCheck(t, conn, "storage_locations", "device_id")
assertHexCheck(t, conn, "groups", "id")
// shares XOR : exactement une cible (user ou groupe).
var xorCheck int
err = conn.QueryRow(`
SELECT COUNT(*) FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
WHERE t.relname = 'shares'
AND pg_get_constraintdef(c.oid) LIKE '%grantee_user_id%'
AND pg_get_constraintdef(c.oid) LIKE '%grantee_group_id%'`).Scan(&xorCheck)
if err != nil {
t.Fatalf("shares xor check: %v", err)
}
if xorCheck == 0 {
t.Error("CHECK XOR (grantee_user_id / grantee_group_id) manquant sur shares après 000016")
}
// --- 000016 : groupes + cible groupe sur shares -------------------------
assertTables(t, conn, "users", "devices", "resources", "operations", "ocr_jobs", "shares", "share_links", "storage_locations", "resource_placements", "groups", "group_members", "schema_migrations")
if err := MigrateDownDatabase(url); err != nil { if err := MigrateDownDatabase(url); err != nil {
t.Fatalf("migrate down: %v", err) t.Fatalf("migrate down: %v", err)
} }
+27
View File
@@ -107,6 +107,33 @@ func FilesGetOcr(c *gin.Context) {
api.OK(c, dto) api.OK(c, dto)
} }
// FilesContent streame les octets physiques d'un fichier visible (viewer+,
// own ou shared) : GET /files/:id/content. Réponse binaire (Content-Type du
// fichier, Content-Disposition inline) — jamais d'enveloppe {data}. Supporte
// Range via http.ServeContent (Gin c.File). Sans bytes serveur (ressource
// metadata-only jamais uploadée) → 404 NOT_FOUND, comme invisible (pas
// d'énumération). V1 streaming : le client ne persiste rien.
func FilesContent(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
info, err := Store.OpenContent(userID, id)
if err != nil {
writeError(c, err)
return
}
c.Header("Content-Type", info.MimeType)
c.Header("Content-Disposition", "inline; filename=\""+info.Name+"\"")
c.File(info.Path)
}
func FilesDelete(c *gin.Context) { func FilesDelete(c *gin.Context) {
if Store == nil { if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized") api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
+279
View File
@@ -7,6 +7,8 @@ import (
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"path/filepath"
"testing" "testing"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -686,3 +688,280 @@ func TestSearchQTooLong(t *testing.T) {
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/search?q="+string(long), token, nil, "") rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/search?q="+string(long), token, nil, "")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "search-q-too-long") expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "search-q-too-long")
} }
func TestFilesContentStreaming(t *testing.T) {
r, _, repo := setup(t)
ownerDevice := repository.NewID()
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "ct"), "content-test-password", ownerDevice)
granteeDevice := repository.NewID()
granteeToken, grantee := registerAndLogin(t, r, repo, testUserUsername(granteeDevice, "cg"), "content-test-password-b", granteeDevice)
outsiderDevice := repository.NewID()
outsiderToken, _ := registerAndLogin(t, r, repo, testUserUsername(outsiderDevice, "ch"), "content-test-password-c", outsiderDevice)
// Ressource metadata-only (outbox) puis upload ciblé des octets (≤10o, cf. setup).
fileID := repository.NewID()
if err := repo.Resources.InsertFile(owner, fileID, "note.txt", "", 0, nil, nil); err != nil {
t.Fatalf("insert file: %v", err)
}
rec := uploadMultipartToResource(t, r, ownerToken, fileID, "note.txt", []byte("hello"))
if rec.Code != http.StatusOK {
t.Fatalf("upload ciblé: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
}
// Owner : octets + Content-Type.
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", ownerToken, nil, "")
if rec.Code != http.StatusOK {
t.Fatalf("content-owner: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
}
if rec.Body.String() != "hello" {
t.Errorf("content-owner = %q, attendu %q", rec.Body.String(), "hello")
}
if ct := rec.Header().Get("Content-Type"); ct == "" {
t.Errorf("content-owner: Content-Type manquant")
}
// Grantée viewer : mêmes octets (résolution dir owner, pas requester).
if err := repo.Shares.Upsert(fileID, grantee, "viewer", false, nil, owner); err != nil {
t.Fatalf("share: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", granteeToken, nil, "")
if rec.Code != http.StatusOK || rec.Body.String() != "hello" {
t.Errorf("content-grantee: attendu 200 hello, got %d %q", rec.Code, rec.Body.String())
}
// Outsider : 404 (pas d'énumération).
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", outsiderToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-outsider")
// Metadata-only sans octets : 404 (jamais uploadé).
bareID := repository.NewID()
if err := repo.Resources.InsertFile(owner, bareID, "vide.txt", "", 0, nil, nil); err != nil {
t.Fatalf("insert bare: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+bareID+"/content", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-no-bytes")
// ID invalide → 404 ; sans token → 401.
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/content", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-invalid-id")
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", "", nil, "")
if rec.Code != http.StatusUnauthorized {
t.Errorf("content-sans-token: attendu 401, got %d", rec.Code)
}
}
func TestFilesHasContentLazy(t *testing.T) {
r, store, repo := setup(t)
ownerDevice := repository.NewID()
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "hc"), "hascontent-password", ownerDevice)
getHasContent := func(fileID, label string) bool {
t.Helper()
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID, ownerToken, nil, "")
env := expectOK(t, rec, label)
var dto struct {
HasContent bool `json:"hasContent"`
}
if err := json.Unmarshal(env.Data, &dto); err != nil {
t.Fatalf("%s: unmarshal: %v", label, err)
}
return dto.HasContent
}
// Upload avec octets → TRUE ; metadata-only → FALSE.
fileID := repository.NewID()
if err := repo.Resources.InsertFile(owner, fileID, "note.txt", "", 0, nil, nil); err != nil {
t.Fatalf("insert file: %v", err)
}
if getHasContent(fileID, "hascontent-bare") {
t.Errorf("metadata-only : hasContent attendu false")
}
rec := uploadMultipartToResource(t, r, ownerToken, fileID, "note.txt", []byte("hello"))
if rec.Code != http.StatusOK {
t.Fatalf("upload ciblé: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
}
if !getHasContent(fileID, "hascontent-uploaded") {
t.Errorf("après upload : hasContent attendu true")
}
// Suppression manuelle sous UPLOAD_DIR puis GET content → 404 + heal FALSE.
matches, _ := filepath.Glob(filepath.Join(store.UploadDir, owner, fileID+".*"))
if len(matches) == 0 {
t.Fatalf("fichier physique introuvable sous %s", store.UploadDir)
}
if err := os.Remove(matches[0]); err != nil {
t.Fatalf("remove physique: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "hascontent-missing-bytes")
if getHasContent(fileID, "hascontent-healed-down") {
t.Errorf("octets disparus : hasContent attendu false après heal")
}
// Octets replacés à la main sur une ligne FALSE → GET content 200 + heal TRUE.
bareID := repository.NewID()
if err := repo.Resources.InsertFile(owner, bareID, "manuel.txt", "", 0, nil, nil); err != nil {
t.Fatalf("insert bare: %v", err)
}
if err := os.MkdirAll(filepath.Join(store.UploadDir, owner), 0o700); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := os.WriteFile(filepath.Join(store.UploadDir, owner, bareID+".txt"), []byte("hi"), 0o600); err != nil {
t.Fatalf("write: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+bareID+"/content", ownerToken, nil, "")
if rec.Code != http.StatusOK || rec.Body.String() != "hi" {
t.Fatalf("content-heal-up: attendu 200 hi, got %d %q", rec.Code, rec.Body.String())
}
if !getHasContent(bareID, "hascontent-healed-up") {
t.Errorf("octets constatés : hasContent attendu true après heal")
}
}
func TestFilesSharesLinksListing(t *testing.T) {
r, _, repo := setup(t)
ownerDevice := repository.NewID()
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "sl"), "shares-list-password", ownerDevice)
granteeDevice := repository.NewID()
granteeToken, grantee := registerAndLogin(t, r, repo, testUserUsername(granteeDevice, "sg"), "shares-list-password-b", granteeDevice)
outsiderDevice := repository.NewID()
outsiderToken, _ := registerAndLogin(t, r, repo, testUserUsername(outsiderDevice, "sh"), "shares-list-password-c", outsiderDevice)
fileID := repository.NewID()
if err := repo.Resources.InsertFile(owner, fileID, "shared.txt", "", 4, nil, nil); err != nil {
t.Fatalf("insert file: %v", err)
}
// Vide au départ (pas d'erreur).
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", ownerToken, nil, "")
env := expectOK(t, rec, "shares-empty")
var emptyShares []map[string]any
if err := json.Unmarshal(env.Data, &emptyShares); err != nil {
t.Fatalf("shares-empty: unmarshal: %v", err)
}
if len(emptyShares) != 0 {
t.Errorf("shares-empty = %d grants, attendu 0", len(emptyShares))
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/links", ownerToken, nil, "")
env = expectOK(t, rec, "links-empty")
var emptyLinks []map[string]any
if err := json.Unmarshal(env.Data, &emptyLinks); err != nil {
t.Fatalf("links-empty: unmarshal: %v", err)
}
if len(emptyLinks) != 0 {
t.Errorf("links-empty = %d links, attendu 0", len(emptyLinks))
}
// Un grant + un lien côté serveur (comme après des ops `share`/`create_link`).
if err := repo.Shares.Upsert(fileID, grantee, "editor", true, nil, owner); err != nil {
t.Fatalf("share: %v", err)
}
linkToken := repository.NewID()
if err := repo.Shares.CreateLink(linkToken, fileID, "viewer", nil, owner); err != nil {
t.Fatalf("create link: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", ownerToken, nil, "")
env = expectOK(t, rec, "shares-owner")
var grants []struct {
GranteeUserID string `json:"granteeUserId"`
Username string `json:"username"`
Access string `json:"access"`
}
if err := json.Unmarshal(env.Data, &grants); err != nil {
t.Fatalf("shares-owner: unmarshal: %v", err)
}
if len(grants) != 1 || grants[0].GranteeUserID != grantee || grants[0].Access != "editor" || grants[0].Username == "" {
t.Errorf("shares-owner = %+v, attendu 1 grant editor du grantee", grants)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/links", ownerToken, nil, "")
env = expectOK(t, rec, "links-owner")
var links []struct {
Token string `json:"token"`
Access string `json:"access"`
}
if err := json.Unmarshal(env.Data, &links); err != nil {
t.Fatalf("links-owner: unmarshal: %v", err)
}
if len(links) != 1 || links[0].Token != linkToken || links[0].Access != "viewer" {
t.Errorf("links-owner = %+v, attendu 1 lien viewer", links)
}
// Granté et outsider : 404 (pas d'énumération).
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", granteeToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "shares-grantee")
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/links", granteeToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "links-grantee")
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", outsiderToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "shares-outsider")
// ID invalide → 404.
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/shares", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "shares-invalid-id")
}
func TestFilesPlacementsListing(t *testing.T) {
r, _, repo := setup(t)
ownerDevice := repository.NewID()
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "pl"), "placements-password", ownerDevice)
granteeDevice := repository.NewID()
granteeToken, grantee := registerAndLogin(t, r, repo, testUserUsername(granteeDevice, "pg"), "placements-password-b", granteeDevice)
outsiderDevice := repository.NewID()
outsiderToken, _ := registerAndLogin(t, r, repo, testUserUsername(outsiderDevice, "ph"), "placements-password-c", outsiderDevice)
fileID := repository.NewID()
if err := repo.Resources.InsertFile(owner, fileID, "placed.txt", "", 4, nil, nil); err != nil {
t.Fatalf("insert file: %v", err)
}
// Sans report : seule l'entrée serveur (hasContent false, metadata-only).
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", ownerToken, nil, "")
env := expectOK(t, rec, "placements-server-only")
var only []map[string]any
if err := json.Unmarshal(env.Data, &only); err != nil {
t.Fatalf("placements-server-only: unmarshal: %v", err)
}
if len(only) != 1 || only[0]["locationType"] != "server" || only[0]["hasBytes"] != false {
t.Errorf("placements-server-only = %v, attendu 1 entrée serveur false", only)
}
// Report via l'outbox (owner) : l'entrée device apparaît.
reportBody := fmt.Sprintf(
`{"operations":[{"operation_id":%q,"resource_id":%q,"resource_type":"file","operation":"report_bytes","payload":{"hasBytes":true}}]}`,
repository.NewID(), fileID,
)
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/sync/ops", ownerToken, []byte(reportBody), "application/json")
if rec.Code != http.StatusOK {
t.Fatalf("sync/ops report: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", ownerToken, nil, "")
env = expectOK(t, rec, "placements-owner")
var entries []struct {
LocationType string `json:"locationType"`
DeviceID string `json:"deviceId"`
HasBytes bool `json:"hasBytes"`
}
if err := json.Unmarshal(env.Data, &entries); err != nil {
t.Fatalf("placements-owner: unmarshal: %v", err)
}
if len(entries) != 2 || entries[0].LocationType != "server" {
t.Fatalf("placements-owner = %+v, attendu serveur + 1 device", entries)
}
if entries[1].LocationType != "mobile" || !entries[1].HasBytes || entries[1].DeviceID != ownerDevice {
t.Errorf("placements-owner[1] = %+v, attendu device owner true", entries[1])
}
// Granté et outsider : 404 (owner-only, pas d'énumération).
if err := repo.Shares.Upsert(fileID, grantee, "viewer", false, nil, owner); err != nil {
t.Fatalf("share: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", granteeToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "placements-grantee")
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", outsiderToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "placements-outsider")
// ID invalide → 404.
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/placements", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "placements-invalid-id")
}
+143
View File
@@ -0,0 +1,143 @@
package handlers
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
"github.com/kazier/backend/service"
)
// groupIDParam validates a 32-hex group id path param (404, never 400 —
// group ids are unguessable, no enumeration).
func groupIDParam(c *gin.Context, name string) (string, bool) {
id := c.Param(name)
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "group not found")
return "", false
}
return id, true
}
// GroupsCreate stores an owned group : POST /groups {name}.
func GroupsCreate(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
var body struct {
Name string `json:"name"`
}
if err := c.ShouldBindJSON(&body); err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid JSON body")
return
}
dto, err := Store.CreateGroup(c.GetString(UserIDKey), body.Name)
if err != nil {
if errors.Is(err, service.ErrInvalidUpload) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid group name")
return
}
writeError(c, err)
return
}
api.OK(c, dto)
}
// GroupsList returns owned + joined groups : GET /groups.
func GroupsList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
dtos, err := Store.ListGroups(c.GetString(UserIDKey))
if err != nil {
writeError(c, err)
return
}
api.OK(c, dtos)
}
// GroupMembersAdd adds an existing user : POST /groups/:id/members {userId}.
func GroupMembersAdd(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
groupID, ok := groupIDParam(c, "id")
if !ok {
return
}
var body struct {
UserID string `json:"userId"`
}
if err := c.ShouldBindJSON(&body); err != nil || !deviceIDPattern.MatchString(body.UserID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid `userId`")
return
}
if err := Store.AddGroupMember(c.GetString(UserIDKey), groupID, body.UserID); err != nil {
writeError(c, err)
return
}
api.OK(c, gin.H{"id": groupID})
}
// GroupMembersRemove removes a membership :
// DELETE /groups/:id/members/:userId.
func GroupMembersRemove(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
groupID, ok := groupIDParam(c, "id")
if !ok {
return
}
memberID, ok := groupIDParam(c, "userId")
if !ok {
return
}
if err := Store.RemoveGroupMember(c.GetString(UserIDKey), groupID, memberID); err != nil {
writeError(c, err)
return
}
api.OK(c, gin.H{"id": groupID})
}
// GroupsDelete removes an owned group : DELETE /groups/:id.
func GroupsDelete(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
groupID, ok := groupIDParam(c, "id")
if !ok {
return
}
if err := Store.DeleteGroup(c.GetString(UserIDKey), groupID); err != nil {
writeError(c, err)
return
}
api.OK(c, gin.H{"id": groupID})
}
// GroupMembersList returns memberships of an owned group :
// GET /groups/:id/members.
func GroupMembersList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
groupID, ok := groupIDParam(c, "id")
if !ok {
return
}
members, err := Store.ListMembers(c.GetString(UserIDKey), groupID)
if err != nil {
writeError(c, err)
return
}
api.OK(c, members)
}
+108
View File
@@ -0,0 +1,108 @@
package handlers_test
import (
"encoding/json"
"fmt"
"net/http"
"testing"
"github.com/kazier/backend/repository"
)
// V2-6 : CRUD groupes + membres via HTTP, scoping owner, 404 sans énumération.
func TestGroupsHttpFlow(t *testing.T) {
r, _, repo := setup(t)
ownerDevice := repository.NewID()
ownerToken, _ := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "go"), "groups-http-password", ownerDevice)
otherDevice := repository.NewID()
otherToken, _ := registerAndLogin(t, r, repo, testUserUsername(otherDevice, "gx"), "groups-http-password-b", otherDevice)
// Création (nom trimé).
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/groups", ownerToken, []byte(`{"name":" Famille "}`), "application/json")
env := expectOK(t, rec, "groups-create")
var created struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
}
if err := json.Unmarshal(env.Data, &created); err != nil {
t.Fatalf("groups-create: unmarshal: %v", err)
}
if created.Name != "Famille" || created.Role != "owner" {
t.Errorf("groups-create = %+v", created)
}
// Nom vide → 400.
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/groups", ownerToken, []byte(`{"name":" "}`), "application/json")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "groups-create-blank")
// Liste owner (1, owner) ; tiers (0).
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/groups", ownerToken, nil, "")
env = expectOK(t, rec, "groups-list-owner")
var listed []map[string]any
if err := json.Unmarshal(env.Data, &listed); err != nil {
t.Fatalf("groups-list: unmarshal: %v", err)
}
if len(listed) != 1 {
t.Errorf("groups-list-owner = %d, attendu 1", len(listed))
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/groups", otherToken, nil, "")
env = expectOK(t, rec, "groups-list-other")
listed = nil
if err := json.Unmarshal(env.Data, &listed); err != nil {
t.Fatalf("groups-list-other: unmarshal: %v", err)
}
if len(listed) != 0 {
t.Errorf("groups-list-other = %d, attendu 0", len(listed))
}
// Ajout membre : besoin d'un user existant — on le crée via un login.
memberDevice := repository.NewID()
_, memberID := registerAndLogin(t, r, repo, testUserUsername(memberDevice, "gm"), "groups-http-password-c", memberDevice)
rec, _ = doRequest(
t, r, http.MethodPost, "/api/v1/groups/"+created.ID+"/members", ownerToken,
[]byte(fmt.Sprintf(`{"userId":%q}`, memberID)), "application/json",
)
expectOK(t, rec, "groups-add-member")
// Liste membres (owner) : le membre ajouté ; tiers → 404.
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/groups/"+created.ID+"/members", ownerToken, nil, "")
envMembers := expectOK(t, rec, "groups-list-members")
var members []map[string]any
if err := json.Unmarshal(envMembers.Data, &members); err != nil {
t.Fatalf("groups-list-members: unmarshal: %v", err)
}
if len(members) != 1 || members[0]["id"] != memberID {
t.Errorf("groups-list-members = %v, attendu 1 membre", members)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/groups/"+created.ID+"/members", otherToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "groups-list-members-other")
// Non-owner → 404.
rec, _ = doRequest(
t, r, http.MethodPost, "/api/v1/groups/"+created.ID+"/members", otherToken,
[]byte(fmt.Sprintf(`{"userId":%q}`, memberID)), "application/json",
)
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "groups-add-other")
// Membre inconnu → GRANTEE_NOT_FOUND.
rec, _ = doRequest(
t, r, http.MethodPost, "/api/v1/groups/"+created.ID+"/members", ownerToken,
[]byte(fmt.Sprintf(`{"userId":%q}`, repository.NewID())), "application/json",
)
expectError(t, rec, http.StatusNotFound, "GRANTEE_NOT_FOUND", "groups-add-unknown")
// Groupe inconnu → 404 partout (pas d'énumération).
unknown := repository.NewID()
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/groups/"+unknown+"/members", ownerToken,
[]byte(fmt.Sprintf(`{"userId":%q}`, memberID)), "application/json")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "groups-add-unknown-group")
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/groups/"+unknown, ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "groups-delete-unknown")
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/groups/not-hex", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "groups-invalid-id")
// Retrait puis suppression.
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/groups/"+created.ID+"/members/"+memberID, ownerToken, nil, "")
expectOK(t, rec, "groups-remove-member")
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/groups/"+created.ID, otherToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "groups-delete-other")
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/groups/"+created.ID, ownerToken, nil, "")
expectOK(t, rec, "groups-delete")
}
+11
View File
@@ -33,12 +33,23 @@ func RegisterRoutes(r *gin.Engine) {
protected.GET("/files/folders", FoldersList) protected.GET("/files/folders", FoldersList)
protected.GET("/files/:id", FilesGet) protected.GET("/files/:id", FilesGet)
protected.GET("/files/:id/ocr", FilesGetOcr) protected.GET("/files/:id/ocr", FilesGetOcr)
protected.GET("/files/:id/content", FilesContent)
protected.GET("/files/:id/shares", SharesList)
protected.GET("/files/:id/links", LinksList)
protected.GET("/files/:id/placements", PlacementsList)
protected.DELETE("/files/:id", FilesDelete) protected.DELETE("/files/:id", FilesDelete)
protected.POST("/files/upload", FilesUpload) protected.POST("/files/upload", FilesUpload)
protected.GET("/users/resolve", ResolveUser) protected.GET("/users/resolve", ResolveUser)
protected.PATCH("/users/me/password", ChangePassword) protected.PATCH("/users/me/password", ChangePassword)
protected.POST("/groups", GroupsCreate)
protected.GET("/groups", GroupsList)
protected.POST("/groups/:id/members", GroupMembersAdd)
protected.GET("/groups/:id/members", GroupMembersList)
protected.DELETE("/groups/:id/members/:userId", GroupMembersRemove)
protected.DELETE("/groups/:id", GroupsDelete)
protected.POST("/ocr/jobs", OcrJobsCreate) protected.POST("/ocr/jobs", OcrJobsCreate)
protected.GET("/ocr/jobs/:id", OcrJobsGet) protected.GET("/ocr/jobs/:id", OcrJobsGet)
+74
View File
@@ -0,0 +1,74 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
)
// SharesList exposes the active user-to-user grants of a resource the caller
// OWNS : GET /files/:id/shares. Non-owner (or unknown resource) → 404
// NOT_FOUND (no enumeration, same scoping as the share outbox ops).
func SharesList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
grants, err := Store.ListShares(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, grants)
}
// LinksList exposes the active public links of a resource the caller OWNS :
// GET /files/:id/links. Same owner-only scoping as SharesList.
func LinksList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
links, err := Store.ListLinks(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, links)
}
// PlacementsList exposes byte presence of a resource the caller OWNS
// (server entry + device reports, newest first) : GET /files/:id/placements.
// Owner-only (404 otherwise, no enumeration).
func PlacementsList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
placements, err := Store.ListPlacements(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, placements)
}
+2
View File
@@ -24,6 +24,8 @@ func writeError(c *gin.Context, err error) {
api.Error(c, 404, "NOT_FOUND", "resource not found") api.Error(c, 404, "NOT_FOUND", "resource not found")
case errors.Is(err, repository.ErrGranteeNotFound): case errors.Is(err, repository.ErrGranteeNotFound):
api.Error(c, 404, "GRANTEE_NOT_FOUND", "the specified user does not exist") api.Error(c, 404, "GRANTEE_NOT_FOUND", "the specified user does not exist")
case errors.Is(err, repository.ErrGroupNotFound):
api.Error(c, 404, "GROUP_NOT_FOUND", "the specified group does not exist")
case errors.Is(err, repository.ErrNameConflict): case errors.Is(err, repository.ErrNameConflict):
api.Error(c, 409, "NAME_CONFLICT", "a resource with this name already exists here") api.Error(c, 409, "NAME_CONFLICT", "a resource with this name already exists here")
case errors.Is(err, service.ErrFileTooLarge): case errors.Is(err, service.ErrFileTooLarge):
+185
View File
@@ -0,0 +1,185 @@
package repository
import (
"database/sql"
"errors"
)
// Group is a named set of users (V2-6) : sharing to a group grants every
// member. One level only (no nested groups). The creator owns the group
// (member management + deletion) ; membership confers no admin rights.
type Group struct {
ID string
Name string
CreatedBy string
}
// Groups implements group persistence.
type Groups struct {
DB *sql.DB
}
// Create stores a group owned by ownerID and returns its id.
func (g *Groups) Create(name, ownerID string) (string, error) {
id := NewID()
_, err := g.DB.Exec(
`INSERT INTO groups (id, name, created_by) VALUES ($1, $2, $3)`,
id, name, ownerID,
)
if err != nil {
return "", err
}
return id, nil
}
// Get returns a group by id. No-rows → ErrNotFound.
func (g *Groups) Get(groupID string) (Group, error) {
var group Group
err := g.DB.QueryRow(
`SELECT id, name, created_by FROM groups WHERE id = $1`,
groupID,
).Scan(&group.ID, &group.Name, &group.CreatedBy)
if errors.Is(err, sql.ErrNoRows) {
return Group{}, ErrNotFound
}
return group, err
}
// IsOwner reports whether userID created the group.
func (g *Groups) IsOwner(groupID, userID string) (bool, error) {
var n int
err := g.DB.QueryRow(
`SELECT COUNT(*) FROM groups WHERE id = $1 AND created_by = $2`,
groupID, userID,
).Scan(&n)
return n > 0, err
}
// IsMember reports group membership (owner excluded : ownership is separate).
func (g *Groups) IsMember(groupID, userID string) (bool, error) {
var n int
err := g.DB.QueryRow(
`SELECT COUNT(*) FROM group_members WHERE group_id = $1 AND user_id = $2`,
groupID, userID,
).Scan(&n)
return n > 0, err
}
// GroupWithRole is a group listing row (owned or joined).
type GroupWithRole struct {
Group
Role string // "owner" | "member"
}
// ListForUser returns groups the user owns or joins, owned first.
func (g *Groups) ListForUser(userID string) ([]GroupWithRole, error) {
rows, err := g.DB.Query(
`SELECT id, name, created_by,
CASE WHEN created_by = $1 THEN 'owner' ELSE 'member' END AS role
FROM groups
WHERE created_by = $1 OR id IN (SELECT group_id FROM group_members WHERE user_id = $1)
ORDER BY created_at ASC`,
userID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var out []GroupWithRole
for rows.Next() {
var gr GroupWithRole
if err := rows.Scan(&gr.ID, &gr.Name, &gr.CreatedBy, &gr.Role); err != nil {
return nil, err
}
out = append(out, gr)
}
return out, rows.Err()
}
// AddMember inserts a membership. Idempotent on replay (ON CONFLICT DO
// NOTHING) ; returns rows-affected style via ErrNotFound when the group or
// the user does not exist (FK violation mapped).
func (g *Groups) AddMember(groupID, userID string) error {
_, err := g.DB.Exec(
`INSERT INTO group_members (group_id, user_id) VALUES ($1, $2)
ON CONFLICT DO NOTHING`,
groupID, userID,
)
if isForeignKeyViolation(err) {
return ErrNotFound
}
return err
}
// RemoveMember deletes a membership. Missing row → ErrNotFound.
func (g *Groups) RemoveMember(groupID, userID string) error {
result, err := g.DB.Exec(
`DELETE FROM group_members WHERE group_id = $1 AND user_id = $2`,
groupID, userID,
)
if err != nil {
return err
}
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return ErrNotFound
}
return nil
}
// Member is a group membership row (owner view).
type Member struct {
UserID string
Username string
}
// ListMembers returns memberships of a group, ordered by username.
func (g *Groups) ListMembers(groupID string) ([]Member, error) {
rows, err := g.DB.Query(
`SELECT u.id, COALESCE(u.username, u.id)
FROM group_members gm
JOIN users u ON u.id = gm.user_id AND u.deleted_at IS NULL
WHERE gm.group_id = $1
ORDER BY COALESCE(u.username, u.id) ASC`,
groupID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Member
for rows.Next() {
var m Member
if err := rows.Scan(&m.UserID, &m.Username); err != nil {
return nil, err
}
out = append(out, m)
}
return out, rows.Err()
}
// Errors specific to groups.
var ErrGroupNotFound = errors.New("group not found")
// Delete removes a group (owner only — caller checks). Shares targeting it
// cascade (FK), placements are untouched (device-scoped, not group-scoped).
func (g *Groups) Delete(groupID, ownerID string) error {
result, err := g.DB.Exec(
`DELETE FROM groups WHERE id = $1 AND created_by = $2`,
groupID, ownerID,
)
if err != nil {
return err
}
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return ErrNotFound
}
return nil
}
+85
View File
@@ -0,0 +1,85 @@
package repository
import (
"database/sql"
"time"
)
// Placement is one device's reported byte presence on a resource.
type Placement struct {
LocationType string
DeviceID string
HasBytes bool
UpdatedAt time.Time
}
// Placements implements the V2 multi-device presence hints
// (`storage_locations` + `resource_placements`, cf. V2.md §3.4-3.5, réduit :
// pas de `status` pending, juste `has_bytes` + fraîcheur).
type Placements struct {
DB *sql.DB
}
// EnsureLocation returns the location id for (user, device), creating it on
// first report. `user_id` tracks the last reporter (a device may change
// accounts) ; rows of departed users stay but are filtered at read time by
// resource visibility.
func (p *Placements) EnsureLocation(userID, deviceID string) (string, error) {
var id string
err := p.DB.QueryRow(
`INSERT INTO storage_locations (id, user_id, device_id, type)
VALUES ($1, $2, $3, 'mobile')
ON CONFLICT (device_id) DO UPDATE SET user_id = EXCLUDED.user_id, last_seen_at = NOW()
RETURNING id`,
NewID(), userID, deviceID,
).Scan(&id)
if err != nil {
return "", err
}
return id, nil
}
// Report upserts a device's byte presence for a resource. Naturally
// idempotent (same state twice = no-op) ; the outbox replay guard (A9)
// requires a FRESH operation_id per state change, documented in api-v1.md.
func (p *Placements) Report(userID, deviceID, resourceID string, hasBytes bool) error {
locationID, err := p.EnsureLocation(userID, deviceID)
if err != nil {
return err
}
_, err = p.DB.Exec(
`INSERT INTO resource_placements (resource_id, location_id, has_bytes, updated_at)
VALUES ($1, $2, $3, NOW())
ON CONFLICT (resource_id, location_id)
DO UPDATE SET has_bytes = EXCLUDED.has_bytes, updated_at = NOW()`,
resourceID, locationID, hasBytes,
)
return err
}
// ListForResource returns all device placements of a resource, newest first.
// Server-side bytes (`resources.has_content`) are NOT a row — the caller
// prepends the implicit server entry.
func (p *Placements) ListForResource(resourceID string) ([]Placement, error) {
rows, err := p.DB.Query(
`SELECT sl.type, sl.device_id, rp.has_bytes, rp.updated_at
FROM resource_placements rp
JOIN storage_locations sl ON sl.id = rp.location_id
WHERE rp.resource_id = $1
ORDER BY rp.updated_at DESC`,
resourceID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Placement
for rows.Next() {
var pl Placement
if err := rows.Scan(&pl.LocationType, &pl.DeviceID, &pl.HasBytes, &pl.UpdatedAt); err != nil {
return nil, err
}
out = append(out, pl)
}
return out, rows.Err()
}
+4
View File
@@ -12,6 +12,8 @@ type Repository struct {
OcrJobs *OcrJobs OcrJobs *OcrJobs
Users *Users Users *Users
Shares *Shares Shares *Shares
Placements *Placements
Groups *Groups
} }
func NewRepository(conn *sql.DB) *Repository { func NewRepository(conn *sql.DB) *Repository {
@@ -22,5 +24,7 @@ func NewRepository(conn *sql.DB) *Repository {
OcrJobs: &OcrJobs{DB: conn}, OcrJobs: &OcrJobs{DB: conn},
Users: &Users{DB: conn}, Users: &Users{DB: conn},
Shares: &Shares{DB: conn}, Shares: &Shares{DB: conn},
Placements: &Placements{DB: conn},
Groups: &Groups{DB: conn},
} }
} }
+29 -4
View File
@@ -60,6 +60,7 @@ type FileRow struct {
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
OcrText string OcrText string
HasContent bool
} }
type FolderRow struct { type FolderRow struct {
@@ -112,7 +113,7 @@ const grantedCTE = `
sh.inherit, 0 sh.inherit, 0
FROM shares sh FROM shares sh
JOIN resources r ON r.resource_id = sh.resource_id JOIN resources r ON r.resource_id = sh.resource_id
WHERE sh.grantee_user_id = $1 AND sh.revoked_at IS NULL WHERE ` + granteeMatch + ` AND sh.revoked_at IS NULL
AND (sh.expires_at IS NULL OR sh.expires_at > NOW()) AND (sh.expires_at IS NULL OR sh.expires_at > NOW())
AND r.deleted_at IS NULL AND r.deleted_at IS NULL
), ),
@@ -172,11 +173,11 @@ func (r *Resources) InsertFolder(ownerID, id, name, parentResourceID string) err
return r.insert(ownerID, id, name, parentResourceID, "folder", 0, nil, nil) return r.insert(ownerID, id, name, parentResourceID, "folder", 0, nil, nil)
} }
const fileColumns = `resource_id, name, size_bytes, COALESCE(mime_type, ''), COALESCE(parent_id, ''), created_at, updated_at, COALESCE(ocr_text, '')` const fileColumns = `resource_id, name, size_bytes, COALESCE(mime_type, ''), COALESCE(parent_id, ''), created_at, updated_at, COALESCE(ocr_text, ''), COALESCE(has_content, FALSE)`
func (r *Resources) scanFile(scan func(...any) error) (FileRow, error) { func (r *Resources) scanFile(scan func(...any) error) (FileRow, error) {
var row FileRow var row FileRow
err := scan(&row.ID, &row.Name, &row.Size, &row.MimeType, &row.FolderID, &row.CreatedAt, &row.UpdatedAt, &row.OcrText) err := scan(&row.ID, &row.Name, &row.Size, &row.MimeType, &row.FolderID, &row.CreatedAt, &row.UpdatedAt, &row.OcrText, &row.HasContent)
return row, err return row, err
} }
@@ -500,9 +501,10 @@ func (r *Resources) UpdateNameByID(resourceID, name string) error {
// (size_bytes / mime_type / extension) after a targeted re-upload — used so a // (size_bytes / mime_type / extension) after a targeted re-upload — used so a
// resource created metadata-only (outbox create_resource) receives its bytes // resource created metadata-only (outbox create_resource) receives its bytes
// for server-side OCR. Absent / not owned → ErrNotFound. Never renames or moves. // for server-side OCR. Absent / not owned → ErrNotFound. Never renames or moves.
// Des octets viennent d'arriver : `has_content` passe à TRUE (V2 lazy).
func (r *Resources) UpdatePhysical(ownerID, resourceID string, size int64, mimeType, extension *string) error { func (r *Resources) UpdatePhysical(ownerID, resourceID string, size int64, mimeType, extension *string) error {
result, err := r.DB.Exec( result, err := r.DB.Exec(
`UPDATE resources SET size_bytes = $3, mime_type = $4, extension = $5, updated_at = NOW() `UPDATE resources SET size_bytes = $3, mime_type = $4, extension = $5, has_content = TRUE, updated_at = NOW()
WHERE resource_id = $1 AND user_id = $2 AND type = 'file' AND deleted_at IS NULL`, WHERE resource_id = $1 AND user_id = $2 AND type = 'file' AND deleted_at IS NULL`,
resourceID, ownerID, size, mimeType, extension, resourceID, ownerID, size, mimeType, extension,
) )
@@ -519,6 +521,29 @@ func (r *Resources) UpdatePhysical(ownerID, resourceID string, size int64, mimeT
return nil return nil
} }
// SetHasContent flips the V2 `has_content` flag (lazy healing) : TRUE quand
// des octets sont constatés (upload, OpenContent réussi), FALSE quand ils ont
// disparu sous UPLOAD_DIR. Best-effort côté service (jamais d'erreur vers le
// client). Absent / not owned → ErrNotFound (ignoré par l'appelant).
func (r *Resources) SetHasContent(ownerID, resourceID string, has bool) error {
result, err := r.DB.Exec(
`UPDATE resources SET has_content = $3, updated_at = NOW()
WHERE resource_id = $1 AND user_id = $2 AND type = 'file' AND deleted_at IS NULL`,
resourceID, ownerID, has,
)
if err != nil {
return err
}
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return ErrNotFound
}
return nil
}
// UpdateOcrText writes the server-computed OCR extract onto the resource // UpdateOcrText writes the server-computed OCR extract onto the resource
// (owner-scoped, bumping updated_at so the change flows through the sync // (owner-scoped, bumping updated_at so the change flows through the sync
// snapshot). The text is then readable by every device of the user AND by // snapshot). The text is then readable by every device of the user AND by
+102 -9
View File
@@ -71,11 +71,19 @@ type ResourceAccess struct {
Inherit bool Inherit bool
} }
// Shares implements share persistence for user-to-user grants. // Shares implements share persistence for user-to-user AND user-to-group
// grants (V2-6). A grant targets exactly one principal (shares XOR CHECK) :
// `grantee_user_id` for a user, `grantee_group_id` for a group (every member
// inherits, one level, no nesting).
type Shares struct { type Shares struct {
DB *sql.DB DB *sql.DB
} }
// granteeMatch matches the grants visible to a user: direct user grants plus
// grants to any group they belong to. `$1` is always the user id in the
// enclosing query (snapshot, enforcement, visibility CTEs).
const granteeMatch = `(sh.grantee_user_id = $1 OR sh.grantee_group_id IN (SELECT group_id FROM group_members WHERE user_id = $1))`
// Upsert inserts or updates an active share. On conflict (active row for // Upsert inserts or updates an active share. On conflict (active row for
// same resource + grantee) the access, inherit, and expires_at are updated. // same resource + grantee) the access, inherit, and expires_at are updated.
func (s *Shares) Upsert(resourceID, granteeUserID, access string, inherit bool, expiresAt *time.Time, createdBy string) error { func (s *Shares) Upsert(resourceID, granteeUserID, access string, inherit bool, expiresAt *time.Time, createdBy string) error {
@@ -96,12 +104,13 @@ func (s *Shares) Upsert(resourceID, granteeUserID, access string, inherit bool,
return err return err
} }
// Revoke soft-revokes the active share between a resource and a grantee. // Revoke soft-revokes the active share between a resource and a grantee
func (s *Shares) Revoke(resourceID, granteeUserID string) error { // (user id or group id — ids are unguessable 32-hex, globally unique).
func (s *Shares) Revoke(resourceID, granteeID string) error {
result, err := s.DB.Exec( result, err := s.DB.Exec(
`UPDATE shares SET revoked_at = NOW(), updated_at = NOW() `UPDATE shares SET revoked_at = NOW(), updated_at = NOW()
WHERE resource_id = $1 AND grantee_user_id = $2 AND revoked_at IS NULL`, WHERE resource_id = $1 AND (grantee_user_id = $2 OR grantee_group_id = $2) AND revoked_at IS NULL`,
resourceID, granteeUserID, resourceID, granteeID,
) )
if err != nil { if err != nil {
return err return err
@@ -153,7 +162,7 @@ seeded(id, type, updated_at, parent_id, grant_rank, created_by, expires_at, gran
sh.created_by, sh.expires_at, sh.inherit, r.name, TRUE sh.created_by, sh.expires_at, sh.inherit, r.name, TRUE
FROM shares sh FROM shares sh
JOIN resources r ON r.resource_id = sh.resource_id JOIN resources r ON r.resource_id = sh.resource_id
WHERE sh.grantee_user_id = $1 AND sh.revoked_at IS NULL WHERE `+granteeMatch+` AND sh.revoked_at IS NULL
AND (sh.expires_at IS NULL OR sh.expires_at > NOW()) AND (sh.expires_at IS NULL OR sh.expires_at > NOW())
AND r.deleted_at IS NULL AND r.deleted_at IS NULL
), ),
@@ -263,7 +272,7 @@ direct AS (
SELECT CASE sh.access WHEN 'viewer' THEN 1 WHEN 'commenter' THEN 2 WHEN 'editor' THEN 3 ELSE 0 END AS rank SELECT CASE sh.access WHEN 'viewer' THEN 1 WHEN 'commenter' THEN 2 WHEN 'editor' THEN 3 ELSE 0 END AS rank
FROM shares sh FROM shares sh
JOIN resources r ON r.resource_id = sh.resource_id JOIN resources r ON r.resource_id = sh.resource_id
WHERE sh.resource_id = $2 AND sh.grantee_user_id = $1 WHERE sh.resource_id = $2 AND `+granteeMatch+`
AND sh.revoked_at IS NULL AND sh.revoked_at IS NULL
AND (sh.expires_at IS NULL OR sh.expires_at > NOW()) AND (sh.expires_at IS NULL OR sh.expires_at > NOW())
AND r.deleted_at IS NULL AND r.deleted_at IS NULL
@@ -276,7 +285,7 @@ inherited(id, grant_rank, depth) AS (
SELECT r.parent_id, SELECT r.parent_id,
COALESCE((SELECT CASE sh.access WHEN 'viewer' THEN 1 WHEN 'commenter' THEN 2 WHEN 'editor' THEN 3 ELSE 0 END COALESCE((SELECT CASE sh.access WHEN 'viewer' THEN 1 WHEN 'commenter' THEN 2 WHEN 'editor' THEN 3 ELSE 0 END
FROM shares sh FROM shares sh
WHERE sh.resource_id = r.parent_id AND sh.grantee_user_id = $1 WHERE sh.resource_id = r.parent_id AND `+granteeMatch+`
AND sh.revoked_at IS NULL AND sh.inherit AND sh.revoked_at IS NULL AND sh.inherit
AND (sh.expires_at IS NULL OR sh.expires_at > NOW())), 0), AND (sh.expires_at IS NULL OR sh.expires_at > NOW())), 0),
0 0
@@ -286,7 +295,7 @@ inherited(id, grant_rank, depth) AS (
SELECT r.parent_id, SELECT r.parent_id,
COALESCE((SELECT CASE sh.access WHEN 'viewer' THEN 1 WHEN 'commenter' THEN 2 WHEN 'editor' THEN 3 ELSE 0 END COALESCE((SELECT CASE sh.access WHEN 'viewer' THEN 1 WHEN 'commenter' THEN 2 WHEN 'editor' THEN 3 ELSE 0 END
FROM shares sh FROM shares sh
WHERE sh.resource_id = ag.id AND sh.grantee_user_id = $1 WHERE sh.resource_id = ag.id AND `+granteeMatch+`
AND sh.revoked_at IS NULL AND sh.inherit AND sh.revoked_at IS NULL AND sh.inherit
AND (sh.expires_at IS NULL OR sh.expires_at > NOW())), 0), AND (sh.expires_at IS NULL OR sh.expires_at > NOW())), 0),
ag.depth + 1 ag.depth + 1
@@ -455,5 +464,89 @@ func (s *Shares) ListActiveLinksForResource(resourceID string) ([]LinkInfo, erro
return links, rows.Err() return links, rows.Err()
} }
// ShareGrant is one active grant on a resource (owner view). Exactly one of
// GranteeUserID / GranteeGroupID is set (mirrors the shares XOR CHECK).
type ShareGrant struct {
GranteeUserID string
GranteeGroupID string
Username string
Access string
Inherit bool
ExpiresAt *time.Time
UpdatedAt time.Time
}
// GrantKind returns "group" for group-targeted grants, "user" otherwise.
func (g ShareGrant) GrantKind() string {
if g.GranteeGroupID != "" {
return "group"
}
return "user"
}
// UpsertGroup inserts or updates an active group-targeted share. Same
// idempotent semantics as Upsert, keyed by (resource, group).
func (s *Shares) UpsertGroup(resourceID, groupID, access string, inherit bool, expiresAt *time.Time, createdBy string) error {
var expires any
if expiresAt != nil {
expires = *expiresAt
}
_, err := s.DB.Exec(
`INSERT INTO shares (id, resource_id, grantee_group_id, access, inherit, created_by, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (resource_id, grantee_group_id) WHERE revoked_at IS NULL AND grantee_group_id IS NOT NULL
DO UPDATE SET access = EXCLUDED.access,
inherit = EXCLUDED.inherit,
expires_at = EXCLUDED.expires_at,
updated_at = NOW()`,
NewID(), resourceID, groupID, access, inherit, createdBy, expires,
)
return err
}
// ListActiveForResource returns the active (non-revoked) grants on a resource,
// oldest first. Expired grants are included (the owner sees what will lapse);
// the caller filters display. Empty (not error) when nothing is shared.
func (s *Shares) ListActiveForResource(resourceID string) ([]ShareGrant, error) {
rows, err := s.DB.Query(
`SELECT s.grantee_user_id, s.grantee_group_id,
COALESCE(u.username, gr.name, COALESCE(s.grantee_user_id, s.grantee_group_id)),
s.access, s.inherit, s.expires_at, s.updated_at
FROM shares s
LEFT JOIN users u ON u.id = s.grantee_user_id AND u.deleted_at IS NULL
LEFT JOIN groups gr ON gr.id = s.grantee_group_id
WHERE s.resource_id = $1 AND s.revoked_at IS NULL
ORDER BY s.created_at ASC`,
resourceID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var grants []ShareGrant
for rows.Next() {
var (
g ShareGrant
granteeUser sql.NullString
granteeGrp sql.NullString
expiresAt sql.NullTime
)
if err := rows.Scan(&granteeUser, &granteeGrp, &g.Username, &g.Access, &g.Inherit, &expiresAt, &g.UpdatedAt); err != nil {
return nil, err
}
if granteeUser.Valid {
g.GranteeUserID = granteeUser.String
}
if granteeGrp.Valid {
g.GranteeGroupID = granteeGrp.String
}
if expiresAt.Valid {
g.ExpiresAt = &expiresAt.Time
}
grants = append(grants, g)
}
return grants, rows.Err()
}
// Errors specific to shares. // Errors specific to shares.
var ErrGranteeNotFound = errors.New("grantee user not found") var ErrGranteeNotFound = errors.New("grantee user not found")
+114
View File
@@ -0,0 +1,114 @@
package service
import (
"errors"
"strings"
"github.com/kazier/backend/repository"
)
// GroupDTO serializes a group for GET /groups.
type GroupDTO struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"` // "owner" | "member"
}
// sanitizeGroupName trims + caps display names (same spirit as file names).
func sanitizeGroupName(name string) (string, error) {
n := strings.TrimSpace(name)
if n == "" || len(n) > 255 {
return "", ErrInvalidUpload
}
return n, nil
}
// CreateGroup stores a group owned by userID.
func (s *Resources) CreateGroup(userID, name string) (GroupDTO, error) {
clean, err := sanitizeGroupName(name)
if err != nil {
return GroupDTO{}, err
}
id, err := s.Repository.Groups.Create(clean, userID)
if err != nil {
return GroupDTO{}, err
}
return GroupDTO{ID: id, Name: clean, Role: "owner"}, nil
}
// ListGroups returns groups the user owns or joins.
func (s *Resources) ListGroups(userID string) ([]GroupDTO, error) {
groups, err := s.Repository.Groups.ListForUser(userID)
if err != nil {
return nil, err
}
out := make([]GroupDTO, 0, len(groups))
for _, gr := range groups {
out = append(out, GroupDTO{ID: gr.ID, Name: gr.Name, Role: gr.Role})
}
return out, nil
}
// AddGroupMember adds an existing active user to a group the caller owns.
// Unknown group (or not owned) → ErrNotFound (no enumeration) ; unknown
// member → ErrGranteeNotFound (same code as share recipients).
func (s *Resources) AddGroupMember(userID, groupID, memberID string) error {
owner, err := s.Repository.Groups.IsOwner(groupID, userID)
if err != nil {
return err
}
if !owner {
return repository.ErrNotFound
}
if _, err := s.Repository.Users.GetByID(memberID); err != nil {
if errors.Is(err, repository.ErrNotFound) {
return repository.ErrGranteeNotFound
}
return err
}
return s.Repository.Groups.AddMember(groupID, memberID)
}
// RemoveGroupMember removes a membership (group must be owned by caller).
// Missing membership → ErrNotFound (idempotent-safe callers treat as done).
func (s *Resources) RemoveGroupMember(userID, groupID, memberID string) error {
owner, err := s.Repository.Groups.IsOwner(groupID, userID)
if err != nil {
return err
}
if !owner {
return repository.ErrNotFound
}
return s.Repository.Groups.RemoveMember(groupID, memberID)
}
// MemberDTO serializes a membership for GET /groups/:id/members.
type MemberDTO struct {
ID string `json:"id"`
Username string `json:"username"`
}
// ListMembers returns memberships of a group the caller owns.
func (s *Resources) ListMembers(userID, groupID string) ([]MemberDTO, error) {
owner, err := s.Repository.Groups.IsOwner(groupID, userID)
if err != nil {
return nil, err
}
if !owner {
return nil, repository.ErrNotFound
}
members, err := s.Repository.Groups.ListMembers(groupID)
if err != nil {
return nil, err
}
out := make([]MemberDTO, 0, len(members))
for _, m := range members {
out = append(out, MemberDTO{ID: m.UserID, Username: m.Username})
}
return out, nil
}
// DeleteGroup removes an owned group (member shares cascade via FK).
func (s *Resources) DeleteGroup(userID, groupID string) error {
return s.Repository.Groups.Delete(groupID, userID)
}
+195
View File
@@ -0,0 +1,195 @@
package service
import (
"testing"
"github.com/kazier/backend/repository"
)
// V2-6 : partage vers un groupe — les membres voient la ressource
// (snapshot + enforcement), les non-membres non. Révocation et suppression
// du groupe convergent.
func TestGroupShareSnapshotAndEnforcement(t *testing.T) {
s := newServiceStore(t)
ownerID := mustCreateUser(t, s.Repository, "grp-owner")
memberID := mustCreateUser(t, s.Repository, "grp-member")
outsiderID := mustCreateUser(t, s.Repository, "grp-outsider")
deviceID := mustRegisterDevice(t, s.Repository, shareTestDeviceID)
groupID, err := s.Repository.Groups.Create("Famille", ownerID)
if err != nil {
t.Fatalf("create group: %v", err)
}
if err := s.Repository.Groups.AddMember(groupID, memberID); err != nil {
t.Fatalf("add member: %v", err)
}
fileID := repository.NewID()
if _, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpCreateResource, "file", map[string]any{"name": "g.txt"}),
syncOp(repository.NewID(), fileID, OpShare, "file", map[string]any{
"granteeGroupId": groupID,
"access": "editor",
}),
}); err != nil {
t.Fatalf("create+share-group: %v", err)
}
// Snapshot membre : rang editor hérité du groupe.
perms, err := s.Snapshot(memberID, 0)
if err != nil {
t.Fatalf("Snapshot member: %v", err)
}
if len(perms) != 1 || perms[0].EffectiveAccess != "editor" {
t.Fatalf("snapshot membre = %+v, attendu 1 editor", perms)
}
// Enforcement : le membre lit (GET file), l'outsider non.
ra, err := s.Repository.Shares.EffectiveAccess(memberID, fileID)
if err != nil || !ra.Accessible || ra.EffectiveRank != repository.AccessEditor {
t.Errorf("EffectiveAccess membre = %+v err=%v, attendu editor", ra, err)
}
row, err := s.Repo.GetFileVisible(memberID, fileID)
if err != nil || row.ID != fileID {
t.Errorf("membre doit voir le fichier : %+v err=%v", row, err)
}
if _, err := s.Repo.GetFileVisible(outsiderID, fileID); err == nil {
t.Errorf("outsider ne doit pas voir le fichier")
}
// Owner listing : grant kind=group au nom du groupe.
grants, err := s.ListShares(ownerID, fileID)
if err != nil || len(grants) != 1 {
t.Fatalf("ListShares = %+v err=%v", grants, err)
}
if grants[0].GranteeKind != "group" || grants[0].GranteeUserID != groupID || grants[0].Username != "Famille" {
t.Errorf("grant groupe = %+v", grants[0])
}
// Retrait du membre → disparaît du snapshot au pull complet.
if err := s.Repository.Groups.RemoveMember(groupID, memberID); err != nil {
t.Fatalf("remove member: %v", err)
}
perms, err = s.Snapshot(memberID, 0)
if err != nil {
t.Fatalf("Snapshot après retrait: %v", err)
}
if len(perms) != 0 {
t.Errorf("snapshot après retrait = %+v, attendu vide", perms)
}
// Suppression du groupe → plus de partage (cascade FK).
member2 := mustCreateUser(t, s.Repository, "grp-member2")
if err := s.Repository.Groups.AddMember(groupID, member2); err != nil {
t.Fatalf("add member2: %v", err)
}
if _, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpShare, "file", map[string]any{
"granteeGroupId": groupID,
"access": "viewer",
}),
}); err != nil {
t.Fatalf("re-share: %v", err)
}
if err := s.DeleteGroup(ownerID, groupID); err != nil {
t.Fatalf("delete group: %v", err)
}
perms, err = s.Snapshot(member2, 0)
if err != nil {
t.Fatalf("Snapshot après delete: %v", err)
}
if len(perms) != 0 {
t.Errorf("snapshot après delete groupe = %+v, attendu vide", perms)
}
}
func TestGroupShareValidation(t *testing.T) {
s := newServiceStore(t)
ownerID := mustCreateUser(t, s.Repository, "grpval-owner")
deviceID := mustRegisterDevice(t, s.Repository, shareTestDeviceID)
fileID := repository.NewID()
if _, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpCreateResource, "file", map[string]any{"name": "v.txt"}),
}); err != nil {
t.Fatalf("create: %v", err)
}
apply := func(payload map[string]any) (SyncResult, error) {
return s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpShare, "file", payload),
})
}
// Groupe inconnu → GROUP_NOT_FOUND.
denied, err := apply(map[string]any{"granteeGroupId": repository.NewID(), "access": "viewer"})
if err != nil || denied.Applied != 0 || denied.Failed == nil || denied.Failed.Code != "GROUP_NOT_FOUND" {
t.Errorf("groupe inconnu: attendu halt GROUP_NOT_FOUND, got %+v err=%v", denied, err)
}
// Deux cibles → INVALID_REQUEST.
both, err := apply(map[string]any{
"granteeUserId": ownerID, "granteeGroupId": repository.NewID(), "access": "viewer",
})
if err != nil || both.Applied != 0 || both.Failed == nil || both.Failed.Code != "INVALID_REQUEST" {
t.Errorf("deux cibles: attendu halt INVALID_REQUEST, got %+v err=%v", both, err)
}
// Aucune cible → INVALID_REQUEST.
none, err := apply(map[string]any{"access": "viewer"})
if err != nil || none.Applied != 0 || none.Failed == nil || none.Failed.Code != "INVALID_REQUEST" {
t.Errorf("sans cible: attendu halt INVALID_REQUEST, got %+v err=%v", none, err)
}
}
func TestGroupManagementScoping(t *testing.T) {
s := newServiceStore(t)
ownerID := mustCreateUser(t, s.Repository, "gm-owner")
otherID := mustCreateUser(t, s.Repository, "gm-other")
memberID := mustCreateUser(t, s.Repository, "gm-member")
group, err := s.CreateGroup(ownerID, " Équipe ")
if err != nil {
t.Fatalf("create: %v", err)
}
if group.Name != "Équipe" || group.Role != "owner" {
t.Errorf("groupe = %+v (nom trimé attendu)", group)
}
if _, err := s.CreateGroup(ownerID, " "); err == nil {
t.Errorf("nom vide attendu rejeté")
}
// Non-owner ne peut ni ajouter ni supprimer.
if err := s.AddGroupMember(otherID, group.ID, memberID); err == nil {
t.Errorf("add par non-owner attendu refusé")
}
if err := s.AddGroupMember(ownerID, group.ID, memberID); err != nil {
t.Fatalf("add: %v", err)
}
// Membre inexistant → GRANTEE_NOT_FOUND.
if err := s.AddGroupMember(ownerID, group.ID, repository.NewID()); err != repository.ErrGranteeNotFound {
t.Errorf("membre inconnu: attendu ErrGranteeNotFound, got %v", err)
}
if err := s.RemoveGroupMember(otherID, group.ID, memberID); err == nil {
t.Errorf("remove par non-owner attendu refusé")
}
// Listes : owner voit (owner), membre voit (member), tiers ne voit rien.
owned, _ := s.ListGroups(ownerID)
if len(owned) != 1 || owned[0].Role != "owner" {
t.Errorf("list owner = %+v", owned)
}
joined, _ := s.ListGroups(memberID)
if len(joined) != 1 || joined[0].Role != "member" {
t.Errorf("list member = %+v", joined)
}
none, _ := s.ListGroups(otherID)
if len(none) != 0 {
t.Errorf("list tiers = %+v, attendu vide", none)
}
if err := s.DeleteGroup(otherID, group.ID); err == nil {
t.Errorf("delete par non-owner attendu refusé")
}
if err := s.DeleteGroup(ownerID, group.ID); err != nil {
t.Fatalf("delete: %v", err)
}
}
+56
View File
@@ -0,0 +1,56 @@
package service
import (
"time"
"github.com/kazier/backend/repository"
)
// PlacementDTO serializes one byte-presence entry for
// GET /files/:id/placements. The `server` entry is implicit (derived from
// `resources.has_content`, no row) ; device entries come from client reports
// (`report_bytes` ops). `updatedAt` is RFC3339 (server entry: resource
// timestamp ; device entries: report timestamp).
type PlacementDTO struct {
LocationType string `json:"locationType"`
DeviceID string `json:"deviceId,omitempty"`
HasBytes bool `json:"hasBytes"`
UpdatedAt string `json:"updatedAt,omitempty"`
}
// ListPlacements returns byte presence of a resource the user OWNS (server
// entry + device reports, newest first). Non-owner → ErrNotFound (same
// owner-only scoping as shares/links reads).
func (s *Resources) ListPlacements(userID, resourceID string) ([]PlacementDTO, error) {
ownerID, err := s.Repo.GetResourceOwner(resourceID)
if err != nil {
return nil, err
}
if ownerID != userID {
return nil, repository.ErrNotFound
}
row, err := s.Repo.GetFileVisible(userID, resourceID)
if err != nil {
return nil, err
}
out := []PlacementDTO{
{
LocationType: "server",
HasBytes: row.HasContent,
UpdatedAt: row.UpdatedAt.UTC().Format(time.RFC3339),
},
}
placements, err := s.Repository.Placements.ListForResource(resourceID)
if err != nil {
return nil, err
}
for _, p := range placements {
out = append(out, PlacementDTO{
LocationType: p.LocationType,
DeviceID: p.DeviceID,
HasBytes: p.HasBytes,
UpdatedAt: p.UpdatedAt.UTC().Format(time.RFC3339),
})
}
return out, nil
}
+79
View File
@@ -30,6 +30,7 @@ type FileDTO struct {
MimeType string `json:"mimeType,omitempty"` MimeType string `json:"mimeType,omitempty"`
FolderID string `json:"folderId,omitempty"` FolderID string `json:"folderId,omitempty"`
Tags []string `json:"tags,omitempty"` Tags []string `json:"tags,omitempty"`
HasContent bool `json:"hasContent"`
CreatedAt string `json:"createdAt,omitempty"` CreatedAt string `json:"createdAt,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"` UpdatedAt string `json:"updatedAt,omitempty"`
} }
@@ -146,6 +147,79 @@ type FileOcrDTO struct {
UpdatedAt string `json:"updatedAt,omitempty"` UpdatedAt string `json:"updatedAt,omitempty"`
} }
// ContentInfo describes the physical bytes of a file the user can see
// (viewer+, own or shared) for GET /files/:id/content (streaming lecture,
// jamais persisté côté client en V1 streaming).
type ContentInfo struct {
Path string
Name string
MimeType string
Size int64
}
// OpenContent resolves the physical file of a visible resource. Auth is
// viewer+ (GetFileVisible, own or shared) ; the bytes live under the OWNER
// dir (UPLOAD_DIR/<owner_id>/<resource_id>.<ext>), never under the requester.
// No physical file (metadata-only outbox resource, never uploaded) →
// repository.ErrNotFound (handler maps to 404 NOT_FOUND, same as invisible).
func (s *Resources) OpenContent(userID, resourceID string) (ContentInfo, error) {
row, err := s.Repo.GetFileVisible(userID, resourceID)
if err != nil {
return ContentInfo{}, err
}
ownerID, err := s.Repo.GetResourceOwner(resourceID)
if err != nil {
return ContentInfo{}, err
}
if !idPattern.MatchString(ownerID) || !idPattern.MatchString(resourceID) {
return ContentInfo{}, repository.ErrNotFound
}
base, err := filepath.EvalSymlinks(s.UploadDir)
if err != nil {
return ContentInfo{}, repository.ErrNotFound
}
matches, err := filepath.Glob(filepath.Join(s.UploadDir, ownerID, resourceID+".*"))
if err != nil {
return ContentInfo{}, repository.ErrNotFound
}
for _, m := range matches {
if !strings.HasPrefix(filepath.Base(m), resourceID+".") {
continue
}
fi, err := os.Lstat(m)
if err != nil || !fi.Mode().IsRegular() {
continue
}
resolved, err := filepath.EvalSymlinks(m)
if err != nil {
continue
}
rel, err := filepath.Rel(base, resolved)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
continue
}
mime := row.MimeType
if mime == "" {
mime = "application/octet-stream"
}
// Octets constatés : heal `has_content` → TRUE (V2 lazy, best-effort).
if !row.HasContent {
if herr := s.Repo.SetHasContent(ownerID, resourceID, true); herr != nil {
log.Printf("content: heal has_content(%s): %v", resourceID, herr)
}
}
return ContentInfo{Path: resolved, Name: row.Name, MimeType: mime, Size: fi.Size()}, nil
}
// Aucun octet mais flag TRUE (suppression manuelle sous UPLOAD_DIR) :
// heal → FALSE (V2 lazy, best-effort).
if row.HasContent {
if herr := s.Repo.SetHasContent(ownerID, resourceID, false); herr != nil {
log.Printf("content: heal has_content(%s): %v", resourceID, herr)
}
}
return ContentInfo{}, repository.ErrNotFound
}
// GetFileOcr returns the OCR text of a file the user can see (viewer+, own or // GetFileOcr returns the OCR text of a file the user can see (viewer+, own or
// shared). Absent text → Text empty ("") with 200 (the caller decides). // shared). Absent text → Text empty ("") with 200 (the caller decides).
func (s *Resources) GetFileOcr(ownerID, id string) (FileOcrDTO, error) { func (s *Resources) GetFileOcr(ownerID, id string) (FileOcrDTO, error) {
@@ -267,6 +341,10 @@ func (s *Resources) Upload(ownerID string, file *multipart.FileHeader, folderID,
err = s.Repo.UpdatePhysical(ownerID, resourceID, written, &mimeType, extPtr) err = s.Repo.UpdatePhysical(ownerID, resourceID, written, &mimeType, extPtr)
} else { } else {
err = s.Repo.InsertFile(ownerID, resourceID, name, folderID, written, &mimeType, extPtr) err = s.Repo.InsertFile(ownerID, resourceID, name, folderID, written, &mimeType, extPtr)
if err == nil {
// Upload avec octets : `has_content` TRUE (V2 lazy).
err = s.Repo.SetHasContent(ownerID, resourceID, true)
}
} }
if err != nil { if err != nil {
// Best-effort : supprime le nouveau fichier sauf s'il préexistait à l'identique. // Best-effort : supprime le nouveau fichier sauf s'il préexistait à l'identique.
@@ -367,6 +445,7 @@ func toFileDTO(row repository.FileRow) FileDTO {
Size: row.Size, Size: row.Size,
MimeType: row.MimeType, MimeType: row.MimeType,
FolderID: row.FolderID, FolderID: row.FolderID,
HasContent: row.HasContent,
CreatedAt: row.CreatedAt.UTC().Format(time.RFC3339), CreatedAt: row.CreatedAt.UTC().Format(time.RFC3339),
UpdatedAt: row.UpdatedAt.UTC().Format(time.RFC3339), UpdatedAt: row.UpdatedAt.UTC().Format(time.RFC3339),
} }
+106
View File
@@ -0,0 +1,106 @@
package service
import (
"time"
"github.com/kazier/backend/repository"
)
// ShareGrantDTO serializes one active grant for GET /files/:id/shares.
// Milliseconds epoch (null = never), mirroring the permissions snapshot
// (docs/api-v1.md §6.2) for cheap client-side expiry checks.
// `granteeKind` is "user" or "group" (V2-6) ; `granteeUserId` carries the
// principal id either way, `username` its display name.
type ShareGrantDTO struct {
GranteeUserID string `json:"granteeUserId"`
GranteeKind string `json:"granteeKind"`
Username string `json:"username"`
Access string `json:"access"`
Inherit bool `json:"inherit"`
ExpiresAt *int64 `json:"expiresAt"`
UpdatedAt int64 `json:"updatedAt"`
}
// LinkDTO serializes one active public link for GET /files/:id/links —
// same shape as the public GET /shares/links/:token resolution.
type LinkDTO struct {
Token string `json:"token"`
ResourceID string `json:"resource_id"`
ResourceType string `json:"resourceType"`
Name string `json:"name"`
Access string `json:"access"`
ExpiresAt *string `json:"expiresAt"`
}
// ListShares returns the active grants on a resource the user OWNS.
// Non-owner (or unknown resource) → repository.ErrNotFound (no enumeration,
// same scoping as the share outbox ops).
func (s *Resources) ListShares(userID, resourceID string) ([]ShareGrantDTO, error) {
ownerID, err := s.Repo.GetResourceOwner(resourceID)
if err != nil {
return nil, err
}
if ownerID != userID {
return nil, repository.ErrNotFound
}
grants, err := s.Repository.Shares.ListActiveForResource(resourceID)
if err != nil {
return nil, err
}
out := make([]ShareGrantDTO, 0, len(grants))
for _, g := range grants {
var expires *int64
if g.ExpiresAt != nil {
ms := g.ExpiresAt.UnixMilli()
expires = &ms
}
granteeID := g.GranteeUserID
if g.GranteeGroupID != "" {
granteeID = g.GranteeGroupID
}
out = append(out, ShareGrantDTO{
GranteeUserID: granteeID,
GranteeKind: g.GrantKind(),
Username: g.Username,
Access: g.Access,
Inherit: g.Inherit,
ExpiresAt: expires,
UpdatedAt: g.UpdatedAt.UnixMilli(),
})
}
return out, nil
}
// ListLinks returns the active public links of a resource the user OWNS.
// Same owner-only scoping as ListShares.
func (s *Resources) ListLinks(userID, resourceID string) ([]LinkDTO, error) {
ownerID, err := s.Repo.GetResourceOwner(resourceID)
if err != nil {
return nil, err
}
if ownerID != userID {
return nil, repository.ErrNotFound
}
links, err := s.Repository.Shares.ListActiveLinksForResource(resourceID)
if err != nil {
return nil, err
}
out := make([]LinkDTO, 0, len(links))
for _, l := range links {
var expires *string
if l.ExpiresAt != nil {
// Même forme que ShareLinkGet (time.Time marshaled en RFC3339).
str := l.ExpiresAt.UTC().Format(time.RFC3339)
expires = &str
}
out = append(out, LinkDTO{
Token: l.Token,
ResourceID: l.ResourceID,
ResourceType: l.ResourceType,
Name: l.Name,
Access: l.Access,
ExpiresAt: expires,
})
}
return out, nil
}
+67 -13
View File
@@ -23,6 +23,8 @@ const (
OpUpdateShare = "update_share" OpUpdateShare = "update_share"
OpCreateLink = "create_link" OpCreateLink = "create_link"
OpRevokeLink = "revoke_link" OpRevokeLink = "revoke_link"
// V2 placements : un device signale la présence de ses octets.
OpReportBytes = "report_bytes"
) )
// SyncOperation is one outbox entry (shadow of mobile PendingOperationRow). // SyncOperation is one outbox entry (shadow of mobile PendingOperationRow).
@@ -66,6 +68,7 @@ type movePayload struct {
type sharePayload struct { type sharePayload struct {
GranteeUserID string `json:"granteeUserId"` GranteeUserID string `json:"granteeUserId"`
GranteeGroupID string `json:"granteeGroupId"`
Access string `json:"access"` Access string `json:"access"`
Inherit *bool `json:"inherit"` Inherit *bool `json:"inherit"`
ExpiresAt *int64 `json:"expiresAt"` ExpiresAt *int64 `json:"expiresAt"`
@@ -85,6 +88,10 @@ type revokeLinkPayload struct {
Token string `json:"token"` Token string `json:"token"`
} }
type reportBytesPayload struct {
HasBytes *bool `json:"hasBytes"`
}
func classifySyncError(err error) (string, string) { func classifySyncError(err error) (string, string) {
switch { switch {
case errors.Is(err, repository.ErrNameConflict): case errors.Is(err, repository.ErrNameConflict):
@@ -93,6 +100,8 @@ func classifySyncError(err error) (string, string) {
return "NOT_FOUND", "target resource or folder not found" return "NOT_FOUND", "target resource or folder not found"
case errors.Is(err, repository.ErrGranteeNotFound): case errors.Is(err, repository.ErrGranteeNotFound):
return "GRANTEE_NOT_FOUND", "the specified user does not exist" return "GRANTEE_NOT_FOUND", "the specified user does not exist"
case errors.Is(err, repository.ErrGroupNotFound):
return "GROUP_NOT_FOUND", "the specified group does not exist"
case errors.Is(err, repository.ErrPayloadMismatch): case errors.Is(err, repository.ErrPayloadMismatch):
return "INVALID_REQUEST", "operation replayed with different payload" return "INVALID_REQUEST", "operation replayed with different payload"
case errors.Is(err, errCycle): case errors.Is(err, errCycle):
@@ -166,7 +175,7 @@ func (s *Resources) ApplyBatch(userID, deviceID string, ops []SyncOperation) (Sy
// Trace 'failed' à payload identique : la première tentative est // Trace 'failed' à payload identique : la première tentative est
// morte avant MarkApplied (crash) → on ré-applique (recovery). // morte avant MarkApplied (crash) → on ré-applique (recovery).
} }
if err := s.applySyncOp(userID, op); err != nil { if err := s.applySyncOp(userID, deviceID, op); err != nil {
code, message := classifySyncError(err) code, message := classifySyncError(err)
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}}, nil return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}}, nil
} }
@@ -190,7 +199,8 @@ func validateSyncOp(op *SyncOperation) error {
} }
switch op.Operation { switch op.Operation {
case OpCreateResource, OpUpdateMetadata, OpMoveResource, OpDeleteResource, case OpCreateResource, OpUpdateMetadata, OpMoveResource, OpDeleteResource,
OpShare, OpRevokeShare, OpUpdateShare, OpCreateLink, OpRevokeLink: OpShare, OpRevokeShare, OpUpdateShare, OpCreateLink, OpRevokeLink,
OpReportBytes:
default: default:
return errors.New("unknown operation " + op.Operation) return errors.New("unknown operation " + op.Operation)
} }
@@ -200,7 +210,7 @@ func validateSyncOp(op *SyncOperation) error {
return nil return nil
} }
func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error { func (s *Resources) applySyncOp(ownerID, deviceID string, op *SyncOperation) error {
resourceID := derefString(op.ResourceID) resourceID := derefString(op.ResourceID)
switch op.Operation { switch op.Operation {
case OpCreateResource: case OpCreateResource:
@@ -333,11 +343,36 @@ func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error {
case OpRevokeLink: case OpRevokeLink:
return s.applyRevokeLinkOp(ownerID, resourceID, op) return s.applyRevokeLinkOp(ownerID, resourceID, op)
case OpReportBytes:
return s.applyReportBytesOp(ownerID, deviceID, resourceID, op)
default: default:
return errors.New("unknown operation " + op.Operation) return errors.New("unknown operation " + op.Operation)
} }
} }
// applyReportBytesOp handles OpReportBytes: a device reports its byte
// presence (V2 placements). Scope is viewer+ (owned or shared,
// GetFileVisible) — a grantee downloading a shared file reports too.
// Invisible → ErrNotFound (no enumeration). Naturally idempotent ; the A9
// replay guard requires a FRESH operation_id per state change.
func (s *Resources) applyReportBytesOp(userID, deviceID, resourceID string, op *SyncOperation) error {
if derefString(op.ResourceType) != "file" {
return errors.New("resource_type must be 'file' for report_bytes")
}
if _, err := s.Repo.GetFileVisible(userID, resourceID); err != nil {
return err
}
var p reportBytesPayload
if err := json.Unmarshal(op.Payload, &p); err != nil {
return errors.New("invalid payload: " + err.Error())
}
if p.HasBytes == nil {
return errors.New("payload.hasBytes required")
}
return s.Repository.Placements.Report(userID, deviceID, resourceID, *p.HasBytes)
}
// applyShareOp handles OpShare and OpUpdateShare: upsert a user-to-user grant. // applyShareOp handles OpShare and OpUpdateShare: upsert a user-to-user grant.
func (s *Resources) applyShareOp(ownerID, resourceID string, op *SyncOperation) error { func (s *Resources) applyShareOp(ownerID, resourceID string, op *SyncOperation) error {
exists, err := s.Repo.ExistsOwner(ownerID, resourceID) exists, err := s.Repo.ExistsOwner(ownerID, resourceID)
@@ -351,23 +386,22 @@ func (s *Resources) applyShareOp(ownerID, resourceID string, op *SyncOperation)
if err := json.Unmarshal(op.Payload, &p); err != nil { if err := json.Unmarshal(op.Payload, &p); err != nil {
return errors.New("invalid payload: " + err.Error()) return errors.New("invalid payload: " + err.Error())
} }
if p.GranteeUserID == "" { // Cible : exactement un principal (user XOR groupe, V2-6).
return errors.New("payload.granteeUserId required") isUser := p.GranteeUserID != ""
isGroup := p.GranteeGroupID != ""
if isUser == isGroup {
return errors.New("payload requires exactly one of granteeUserId, granteeGroupId")
} }
if !resourceIDPattern.MatchString(p.GranteeUserID) { if isUser && !resourceIDPattern.MatchString(p.GranteeUserID) {
return errors.New("payload.granteeUserId must be 32 lowercase hex chars") return errors.New("payload.granteeUserId must be 32 lowercase hex chars")
} }
if isGroup && !resourceIDPattern.MatchString(p.GranteeGroupID) {
return errors.New("payload.granteeGroupId must be 32 lowercase hex chars")
}
rank := repository.AccessFromString(p.Access) rank := repository.AccessFromString(p.Access)
if rank < repository.AccessViewer || rank > repository.AccessEditor { if rank < repository.AccessViewer || rank > repository.AccessEditor {
return errors.New("payload.access must be viewer, commenter, or editor") return errors.New("payload.access must be viewer, commenter, or editor")
} }
// Validate grantee exists and is active.
if _, err := s.Repository.Users.GetByID(p.GranteeUserID); err != nil {
if errors.Is(err, repository.ErrNotFound) {
return repository.ErrGranteeNotFound
}
return err
}
inherit := true inherit := true
if p.Inherit != nil { if p.Inherit != nil {
inherit = *p.Inherit inherit = *p.Inherit
@@ -380,9 +414,29 @@ func (s *Resources) applyShareOp(ownerID, resourceID string, op *SyncOperation)
} }
expiresAt = &t expiresAt = &t
} }
if isUser {
// Validate grantee exists and is active.
if _, err := s.Repository.Users.GetByID(p.GranteeUserID); err != nil {
if errors.Is(err, repository.ErrNotFound) {
return repository.ErrGranteeNotFound
}
return err
}
if err := s.Repository.Shares.Upsert(resourceID, p.GranteeUserID, p.Access, inherit, expiresAt, ownerID); err != nil { if err := s.Repository.Shares.Upsert(resourceID, p.GranteeUserID, p.Access, inherit, expiresAt, ownerID); err != nil {
return err return err
} }
} else {
// Validate group exists (any group : ids are unguessable, no enum).
if _, err := s.Repository.Groups.Get(p.GranteeGroupID); err != nil {
if errors.Is(err, repository.ErrNotFound) {
return repository.ErrGroupNotFound
}
return err
}
if err := s.Repository.Shares.UpsertGroup(resourceID, p.GranteeGroupID, p.Access, inherit, expiresAt, ownerID); err != nil {
return err
}
}
// Bump resource updated_at so the grantee's delta snapshot picks it up. // Bump resource updated_at so the grantee's delta snapshot picks it up.
// Scopé owner (ExistsOwner vérifié plus haut) : TouchOwned, jamais le // Scopé owner (ExistsOwner vérifié plus haut) : TouchOwned, jamais le
// TouchResource non-scopé. // TouchResource non-scopé.
+73
View File
@@ -1485,3 +1485,76 @@ func TestDeleteAbsentIsIdempotentNoop(t *testing.T) {
t.Errorf("delete absent: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err) t.Errorf("delete absent: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
} }
} }
func TestApplyBatchReportBytes(t *testing.T) {
s := newServiceStore(t)
ownerID := mustCreateUser(t, s.Repository, "report-owner")
granteeID := mustCreateUser(t, s.Repository, "report-grantee")
outsiderID := mustCreateUser(t, s.Repository, "report-outsider")
deviceID := mustRegisterDevice(t, s.Repository, shareTestDeviceID)
otherDevice := mustRegisterDevice(t, s.Repository, "b0000000000000000000000000000001")
fileID := repository.NewID()
if _, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpCreateResource, "file", map[string]any{"name": "r.txt"}),
syncOp(repository.NewID(), fileID, OpShare, "file", map[string]any{"granteeUserId": granteeID, "access": "viewer"}),
}); err != nil {
t.Fatalf("setup: %v", err)
}
report := func(user, device, res string, hasBytes bool) (SyncResult, error) {
return s.ApplyBatch(user, device, []SyncOperation{
syncOp(repository.NewID(), res, OpReportBytes, "file", map[string]any{"hasBytes": hasBytes}),
})
}
// Owner + grantee (viewer) peuvent reporter ; l'owner lit serveur + device.
if result, err := report(ownerID, deviceID, fileID, true); err != nil || result.Applied != 1 || result.Failed != nil {
t.Fatalf("report owner: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
}
if result, err := report(granteeID, otherDevice, fileID, true); err != nil || result.Applied != 1 || result.Failed != nil {
t.Fatalf("report grantee: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
}
placements, err := s.ListPlacements(ownerID, fileID)
if err != nil {
t.Fatalf("ListPlacements: %v", err)
}
if len(placements) != 3 {
t.Fatalf("attendu serveur + 2 devices, got %+v", placements)
}
if placements[0].LocationType != "server" || placements[0].HasBytes {
t.Errorf("entrée serveur = %+v, attendu hasBytes=false", placements[0])
}
// Changement d'état (drop) avec un NOUVEL operation_id ; hasBytes manquant → halt.
if result, err := report(ownerID, deviceID, fileID, false); err != nil || result.Applied != 1 || result.Failed != nil {
t.Fatalf("report drop: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
}
bad, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpReportBytes, "file", map[string]any{}),
})
if err != nil || bad.Applied != 0 || bad.Failed == nil || bad.Failed.Code != "INVALID_REQUEST" {
t.Errorf("hasBytes manquant: attendu halt INVALID_REQUEST, got %+v err=%v", bad, err)
}
// Outsider (invisible) → halt NOT_FOUND, sans énumération.
denied, err := report(outsiderID, otherDevice, fileID, true)
if err != nil || denied.Applied != 0 || denied.Failed == nil || denied.Failed.Code != "NOT_FOUND" {
t.Errorf("report outsider: attendu halt NOT_FOUND, got %+v err=%v", denied, err)
}
// Rejeu à l'identique → idempotent (skip, pas d'erreur).
replayID := repository.NewID()
first, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(replayID, fileID, OpReportBytes, "file", map[string]any{"hasBytes": true}),
})
if err != nil || first.Applied != 1 || first.Failed != nil {
t.Fatalf("report initial: %+v err=%v", first, err)
}
second, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(replayID, fileID, OpReportBytes, "file", map[string]any{"hasBytes": true}),
})
if err != nil || second.Applied != 1 || second.Failed != nil {
t.Errorf("rejeu identique: attendu skip idempotent, got %+v err=%v", second, err)
}
}
+3 -3
View File
@@ -30,9 +30,9 @@ services:
UPLOAD_DIR: /app/uploads UPLOAD_DIR: /app/uploads
MAX_FILE_SIZE_MB: ${MAX_FILE_SIZE_MB:-50} MAX_FILE_SIZE_MB: ${MAX_FILE_SIZE_MB:-50}
OCR_LANG: ${OCR_LANG:-fra+eng} OCR_LANG: ${OCR_LANG:-fra+eng}
AUTH_SECRET: ${AUTH_SECRET:?AUTH_SECRET requis (voir backend/.env.example)} AUTH_SECRET: ${AUTH_SECRET:-dev-secret-change-me-please-set-in-prod}
ADMIN_USERNAME: ${ADMIN_USERNAME:?ADMIN_USERNAME requis au premier démarrage} ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD requis au premier démarrage} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-change-me}
volumes: volumes:
- backend-uploads:/app/uploads - backend-uploads:/app/uploads
depends_on: depends_on:
+17 -4
View File
@@ -37,6 +37,7 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
| PATCH | `/users/me/password` | `{ "current_password", "new_password" }` | `{ "id" }` | `INVALID_PASSWORD` (403) | | PATCH | `/users/me/password` | `{ "current_password", "new_password" }` | `{ "id" }` | `INVALID_PASSWORD` (403) |
| GET | `/files` | query `folderId?`, `page?`, `pageSize?`, `sort?` | `FileDto[]` (+ `meta`) | — | | GET | `/files` | query `folderId?`, `page?`, `pageSize?`, `sort?` | `FileDto[]` (+ `meta`) | — |
| GET | `/files/:id` | — | `FileDto` | `NOT_FOUND` | | GET | `/files/:id` | — | `FileDto` | `NOT_FOUND` |
| GET | `/files/:id/content` | — (binaire brut, hors enveloppe `{data}` ; `Range` supporté) | octets physiques (`Content-Type` du fichier, `Content-Disposition: inline`) — streaming lecture seule, jamais persisté côté client | `NOT_FOUND` (invisible OU metadata-only jamais uploadé — indistinguables) |
| DELETE | `/files/:id` | — | `{ "id": "…" }` | `NOT_FOUND` | | DELETE | `/files/:id` | — | `{ "id": "…" }` | `NOT_FOUND` |
| GET | `/files/search` | query `q` (obligatoire), `page?`, `pageSize?` | `FileDto[]` (+ `meta`) | — | | GET | `/files/search` | query `q` (obligatoire), `page?`, `pageSize?` | `FileDto[]` (+ `meta`) | — |
| GET | `/files/folders` | — | `FolderDto[]` (racines) | — | | GET | `/files/folders` | — | `FolderDto[]` (racines) | — |
@@ -44,6 +45,15 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
| POST | `/ocr/jobs` | `{ "fileId": "…" }` | `OcrJob` | — | | POST | `/ocr/jobs` | `{ "fileId": "…" }` | `OcrJob` | — |
| GET | `/ocr/jobs/:id` | — | `OcrJob` | `NOT_FOUND` | | GET | `/ocr/jobs/:id` | — | `OcrJob` | `NOT_FOUND` |
| GET | `/files/:id/ocr` | — | `FileOcr` (`{ text, updatedAt }`) | `NOT_FOUND` | | GET | `/files/:id/ocr` | — | `FileOcr` (`{ text, updatedAt }`) | `NOT_FOUND` |
| GET | `/files/:id/shares` | — (owner uniquement) | `ShareGrant[]` (`{ granteeUserId, granteeKind: "user"&#124;"group", username, access, inherit, expiresAt (ms&#124;null), updatedAt (ms) }`) | `NOT_FOUND` (non-owner ou inconnue — pas d'énumération) |
| GET | `/files/:id/links` | — (owner uniquement) | `ShareLink[]` (même forme que `GET /shares/links/:token`) | `NOT_FOUND` (non-owner ou inconnue) |
| GET | `/files/:id/placements` | — (owner uniquement) | `Placement[]` (`{ locationType: "server"&#124;"mobile", deviceId?, hasBytes, updatedAt }`, entrée serveur en premier) | `NOT_FOUND` (non-owner ou inconnue) |
| POST | `/groups` | `{ "name" }` | `{ "id", "name", "role": "owner" }` | `INVALID_REQUEST` (nom vide/trop long) |
| GET | `/groups` | — | `Group[]` (`{ "id", "name", "role": "owner"&#124;"member" }`, possédés + rejoints) | — |
| POST | `/groups/:id/members` | `{ "userId": "…32-hex" }` | `{ "id": "…" }` | `NOT_FOUND` (groupe d'autrui/inconnu), `GRANTEE_NOT_FOUND` (membre inconnu) |
| GET | `/groups/:id/members` | — (owner uniquement) | `Member[]` (`{ "id", "username" }`) | `NOT_FOUND` |
| DELETE | `/groups/:id/members/:userId` | — | `{ "id": "…" }` | `NOT_FOUND` |
| DELETE | `/groups/:id` | — | `{ "id": "…" }` | `NOT_FOUND` (d'autrui/inconnu) |
| POST | `/sync/ops` | voir §6 | voir §6 | — | | POST | `/sync/ops` | voir §6 | voir §6 | — |
| GET | `/sync/permissions` | query `after?` (cached_at ms) | `ResourcePermission[]` | — | | GET | `/sync/permissions` | query `after?` (cached_at ms) | `ResourcePermission[]` | — |
@@ -59,6 +69,7 @@ type FileDto = {
mimeType?: string | null; mimeType?: string | null;
folderId?: string | null; // resource_id 32-hex folderId?: string | null; // resource_id 32-hex
tags?: string[]; tags?: string[];
hasContent: boolean; // V2 : octets vus présents (lazy healing, FALSE = jamais constatés)
createdAt?: string; createdAt?: string;
updatedAt?: string; updatedAt?: string;
}; };
@@ -104,7 +115,7 @@ type FileOcr = { text: string; updatedAt?: string | null };
} }
``` ```
- `operation` ∈ `create_resource | update_metadata | delete_resource | move_resource | share | revoke_share | update_share | create_link | revoke_link` (cf. `PendingOperationType` mobile). - `operation` ∈ `create_resource | update_metadata | delete_resource | move_resource | share | revoke_share | update_share | create_link | revoke_link | report_bytes` (cf. `PendingOperationType` mobile).
- **Identifiants** : `operation_id` est un **TEXT 32-hex** généré par le client (`^[0-9a-f]{32}$`, CHECK-enforced depuis la migration `000008`), distinct de `resource_id`. L'idempotence outbox reste **par device** : `UNIQUE(device_id, operation_id)` (la réinscription d'un device avec un login différent ne réutilise pas l'historique outbox d'un autre compte). Pour chaque op : si déjà traitée → **no-op** (comptée comme appliquée, les doublons arrivent à cause du backoff/retry). Sinon appliquée si valide. - **Identifiants** : `operation_id` est un **TEXT 32-hex** généré par le client (`^[0-9a-f]{32}$`, CHECK-enforced depuis la migration `000008`), distinct de `resource_id`. L'idempotence outbox reste **par device** : `UNIQUE(device_id, operation_id)` (la réinscription d'un device avec un login différent ne réutilise pas l'historique outbox d'un autre compte). Pour chaque op : si déjà traitée → **no-op** (comptée comme appliquée, les doublons arrivent à cause du backoff/retry). Sinon appliquée si valide.
- **Ordre** : les opérations sont appliquées **séquentiellement**, dans l'ordre du batch. Le serveur **s'arrête à la première erreur non-idempotente** et renvoie l'index atteint — le client reprend à cet index. - **Ordre** : les opérations sont appliquées **séquentiellement**, dans l'ordre du batch. Le serveur **s'arrête à la première erreur non-idempotente** et renvoie l'index atteint — le client reprend à cet index.
- Réponse : `2xx` avec `{ "applied": int, "failed": { "operation_id": "…32-hex", "code": string, "message": string } | null }` (`applied` = index de la prochaine op à envoyer). - Réponse : `2xx` avec `{ "applied": int, "failed": { "operation_id": "…32-hex", "code": string, "message": string } | null }` (`applied` = index de la prochaine op à envoyer).
@@ -113,13 +124,14 @@ type FileOcr = { text: string; updatedAt?: string | null };
- `create_resource` : crée la ressource ; **déjà présente → no-op** (rejeu idempotent). `payload.name` obligatoire ; `payload.parentResourceId` (32-hex, optionnel) = dossier parent — absent → racine. **Parent inexistant → `NOT_FOUND`** (cohérent avec `move_resource`). Ordre garanti par construction client : le walk SAF émet les `create` des dossiers (ordre préfixe) avant ceux des fichiers, dans la même transaction Room → `id ASC` = parent avant enfant. - `create_resource` : crée la ressource ; **déjà présente → no-op** (rejeu idempotent). `payload.name` obligatoire ; `payload.parentResourceId` (32-hex, optionnel) = dossier parent — absent → racine. **Parent inexistant → `NOT_FOUND`** (cohérent avec `move_resource`). Ordre garanti par construction client : le walk SAF émet les `create` des dossiers (ordre préfixe) avant ceux des fichiers, dans la même transaction Room → `id ASC` = parent avant enfant.
- `update_metadata` : ressource absente → **no-op** (état terminal atteint) ; **ressource partagée : nécessite `editor+`** (§6.2) — sinon `NOT_FOUND` (une ressource visible mais sans droit de mutation n'est pas renommée) ; une ressource sans relation applicable (ni owner, ni grant) reste un no-op (pas d'énumération). `move_resource` / `delete_resource` restent **owner-only** (scoping par `user_id`, les ops d'un non-owner sont des no-op). - `update_metadata` : ressource absente → **no-op** (état terminal atteint) ; **ressource partagée : nécessite `editor+`** (§6.2) — sinon `NOT_FOUND` (une ressource visible mais sans droit de mutation n'est pas renommée) ; une ressource sans relation applicable (ni owner, ni grant) reste un no-op (pas d'énumération). `move_resource` / `delete_resource` restent **owner-only** (scoping par `user_id`, les ops d'un non-owner sont des no-op).
- `delete_resource` : **idempotent** — suppression d'une ressource absente = succès. - `delete_resource` : **idempotent** — suppression d'une ressource absente = succès.
- **Partage** (`share` / `update_share`, même sémantique d'upsert) : `payload = { "granteeUserId": "…32-hex", "access": "viewer"|"commenter"|"editor", "inherit"?: bool, "expiresAt"?: ms }`. La ressource doit **appartenir** au user appelant (sinon `NOT_FOUND`) ; le grantee doit exister (sinon `GRANTEE_NOT_FOUND`) ; accès déjà partagé → mis à jour (idempotent). Privilégier `viewer` < `commenter` < `editor` (< `owner` réservé à l'ownership, non partageable → `INVALID_REQUEST`). - **Partage** (`share` / `update_share`, même sémantique d'upsert) : `payload = { "granteeUserId"?: "…32-hex", "granteeGroupId"?: "…32-hex", "access": "viewer"|"commenter"|"editor", "inherit"?: bool, "expiresAt"?: ms }` — **exactement un** principal (user XOR groupe, V2-6). La ressource doit **appartenir** au user appelant (sinon `NOT_FOUND`) ; le grantee user doit exister (sinon `GRANTEE_NOT_FOUND`), le groupe doit exister (sinon `GROUP_NOT_FOUND`) ; accès déjà partagé → mis à jour (idempotent). Privilégier `viewer` < `commenter` < `editor` (< `owner` réservé à l'ownership, non partageable → `INVALID_REQUEST`). Les membres d'un groupe partagé héritent du grant (un niveau, sans imbrication) dans le snapshot comme dans l'enforcement.
- `revoke_share` : `payload = { "granteeUserId": "…32-hex" }`. **Idempotent** (déjà révoqué/absent → no-op). - `revoke_share` : `payload = { "granteeUserId": "…32-hex" }`. **Idempotent** (déjà révoqué/absent → no-op).
- `create_link` : `payload = { "token": "…32-hex", "access": "viewer"|"commenter"|"editor", "expiresAt"?: ms }`. Le token est **généré côté client** (`GenerateId`), c'est l'identifiant du lien (colonne `id` de `share_links`). - `create_link` : `payload = { "token": "…32-hex", "access": "viewer"|"commenter"|"editor", "expiresAt"?: ms }`. Le token est **généré côté client** (`GenerateId`), c'est l'identifiant du lien (colonne `id` de `share_links`).
- `revoke_link` : `payload = { "token": "…32-hex" }`. **Idempotent**. - `revoke_link` : `payload = { "token": "…32-hex" }`. **Idempotent**.
- **Présence multi-device** (`report_bytes`) : `payload = { "hasBytes": bool }` (**requis**). Le device signale ses octets locaux pour un fichier visible (`viewer+`, own ou partagé — sinon `NOT_FOUND`). Upsert idempotent par `(device, resource)` ; le rejeu à l'identique est no-op, mais chaque **changement d'état exige un nouvel `operation_id`** (garde anti-rejeu A9). Portée `file` uniquement.
- Validation (deuxième champ `operation_id`, hex32 pour `resource_id` **et** `operation_id`, enum `operation`) → échec `INVALID_REQUEST` avec arrêt du batch. - Validation (deuxième champ `operation_id`, hex32 pour `resource_id` **et** `operation_id`, enum `operation`) → échec `INVALID_REQUEST` avec arrêt du batch.
- Nom déjà pris (même parent, ou à la racine) → échec `NAME_CONFLICT`.** - Nom déjà pris (même parent, ou à la racine) → échec `NAME_CONFLICT`.**
- **Lien public** : `GET /shares/links/:token` est **sans authentification** (résolution publique d'un lien) et renvoie `{ "token", "resource_id", "resourceType", "name", "access", "expiresAt" }`. `NOT_FOUND` si le lien est inconnu, révoqué ou expiré. - **Lien public** : `GET /shares/links/:token` est **sans authentification** (résolution publique d'un lien) et renvoie `{ "token", "resource_id", "resourceType", "name", "access", "expiresAt" }`. `NOT_FOUND` si le lien est inconnu, révoqué ou expiré. Le client partage les liens sous forme de deep-link `kazier://share/<token>` (custom scheme, pas d'App Links https) : indépendant du domaine du serveur, donc compatible self-hosting (chaque instance a son propre host).
### 6.2 Snapshot — `GET /sync/permissions?after=<cached_at_ms>` ### 6.2 Snapshot — `GET /sync/permissions?after=<cached_at_ms>`
@@ -153,12 +165,13 @@ type ResourcePermission = {
### 6.3 Placements ### 6.3 Placements
- Le statut de placement (`sync_status` mobile : `local` | `cloud` | `local-cloud`) est le reflet du `resource_placements` serveur (statuts V2 : `local_only`, `synced`, `cloud_only`, `pending_upload`, `pending_download`). La matérialisation se fait via l'outbox (`create_resource` → `synced`/`pending_upload` ; suppression physique locale ≠ suppression serveur). - Le statut de placement (`sync_status` mobile : `local` | `cloud` | `local-cloud`) est le reflet du `resource_placements` serveur (statuts V2 : `local_only`, `synced`, `cloud_only`, `pending_upload`, `pending_download`). La matérialisation se fait via l'outbox (`create_resource` → `synced`/`pending_upload` ; suppression physique locale ≠ suppression serveur).
- **Présence multi-device (V2)** : les devices reportent leurs octets via l'op `report_bytes` (tables `storage_locations` + `resource_placements`, migration `000015`) ; le propriétaire lit `GET /files/:id/placements` (entrée `server` implicite depuis `has_content` + reports devices, owner-only). Hint de présence, jamais preuve — le serveur ne vérifie pas les octets distants.
## 7. Codes d'erreur courants ## 7. Codes d'erreur courants
- Authentification : `UNAUTHORIZED` (**401** — token manquant/invalide/expiré, compte supprimé, OU identifiants de login erronés : **indistinguables par design**, même code+message), `INVALID_DEVICE_ID` (**400** — device non enregistré au login). - Authentification : `UNAUTHORIZED` (**401** — token manquant/invalide/expiré, compte supprimé, OU identifiants de login erronés : **indistinguables par design**, même code+message), `INVALID_DEVICE_ID` (**400** — device non enregistré au login).
- Ressources : `NOT_FOUND` (404), `NAME_CONFLICT` (409 — même nom dans le même parent, cf. `UNIQUE(parent_id, name)`, **ou à la racine**, index partiel `(user_id, name) WHERE parent_id IS NULL`), `FILE_TOO_LARGE` (413), `INVALID_PASSWORD` (403 sur `PATCH /users/me/password`). - Ressources : `NOT_FOUND` (404), `NAME_CONFLICT` (409 — même nom dans le même parent, cf. `UNIQUE(parent_id, name)`, **ou à la racine**, index partiel `(user_id, name) WHERE parent_id IS NULL`), `FILE_TOO_LARGE` (413), `INVALID_PASSWORD` (403 sur `PATCH /users/me/password`).
- Partage : `GRANTEE_NOT_FOUND` (404 — grantee inexistant sur une op share), `NOT_FOUND` (404 — ressource non possédée sur une op share : scoping, pas d'énumération). - Partage : `GRANTEE_NOT_FOUND` (404 — grantee inexistant sur une op share), `GROUP_NOT_FOUND` (404 — groupe inexistant sur une op share ou un endpoint membres), `NOT_FOUND` (404 — ressource non possédée sur une op share : scoping, pas d'énumération).
- Client-only : `NETWORK_ERROR`, `INVALID_RESPONSE` (2xx mais corps d'enveloppe invalide), `HTTP_<status>` (fallback). Statut `SERVICE_UNAVAILABLE` (503) si le backend n'est pas initialisé. - Client-only : `NETWORK_ERROR`, `INVALID_RESPONSE` (2xx mais corps d'enveloppe invalide), `HTTP_<status>` (fallback). Statut `SERVICE_UNAVAILABLE` (503) si le backend n'est pas initialisé.
- **V1 finale : toutes les routes sont réelles** (pas de 501 restant). - **V1 finale : toutes les routes sont réelles** (pas de 501 restant).
+26 -3
View File
@@ -1,7 +1,7 @@
[tasks.up_backend] [tasks.up_backend]
description = "Start PostgreSQL + backend API (Go/Gin)" description = "Start PostgreSQL + backend API (Go/Gin)"
run = [ run = [
"docker compose up -d postgres --wait", "if [ -f backend/.env ]; then docker compose --env-file backend/.env up -d postgres --wait; else docker compose up -d postgres --wait; fi",
"cd backend && go run cmd/server/main.go", "cd backend && go run cmd/server/main.go",
] ]
@@ -21,9 +21,32 @@ set -euo pipefail
./gradlew :app:assembleDebug -q ./gradlew :app:assembleDebug -q
APK="app/build/outputs/apk/debug/app-debug.apk" APK="app/build/outputs/apk/debug/app-debug.apk"
if [ "${usage_target?}" = "emulator" ]; then if [ "${usage_target?}" = "emulator" ]; then
adb -e install -r "$APK" ADB_FLAGS=(-e)
else else
adb -d install -r "$APK" ADB_FLAGS=(-d)
fi
# adb natif s'il fonctionne (PATH + binaire exécutable sur cet OS)...
if command -v adb >/dev/null 2>&1 && adb version >/dev/null 2>&1; then
adb "${ADB_FLAGS[@]}" install -r "$APK"
# ...sinon repli NixOS : l'adb du SDK est un binaire FHS dynamiquement
# lié, on l'exécute via steam-run (cf. local.properties pour sdk.dir).
elif command -v steam-run >/dev/null 2>&1; then
SDK_DIR="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-}}"
if [ -z "$SDK_DIR" ] && [ -f local.properties ]; then
SDK_DIR="$(sed -n 's/^sdk\.dir=//p' local.properties | head -n 1)"
fi
if [ -z "$SDK_DIR" ] && [ -d "$HOME/Android/Sdk" ]; then
SDK_DIR="$HOME/Android/Sdk"
fi
if [ -z "$SDK_DIR" ] || [ ! -x "$SDK_DIR/platform-tools/adb" ]; then
echo "adb introuvable : définissez ANDROID_HOME ou sdk.dir dans local.properties." >&2
exit 1
fi
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-}:$HOME/.nix-profile/lib:/run/opengl-driver/lib"
steam-run "$SDK_DIR/platform-tools/adb" "${ADB_FLAGS[@]}" install -r "$APK"
else
echo "adb ne fonctionne pas sur cet OS et steam-run est absent (NixOS)." >&2
exit 1
fi fi
''' '''
+5
View File
@@ -84,6 +84,11 @@ android {
} }
} }
// m19 : export du schéma Room (`app/schemas/`) pour détecter les dérives en CI.
ksp {
arg("room.schemaLocation", "$projectDir/schemas")
}
dependencies { dependencies {
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.lifecycle.runtime.ktx)
@@ -0,0 +1,730 @@
{
"formatVersion": 1,
"database": {
"version": 16,
"identityHash": "ec10fdb23d5da3a76a73222e9c404561",
"entities": [
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `exists` INTEGER, `parent_resource_id` TEXT, `owner_id` TEXT, `sync_status` TEXT NOT NULL, `created_in_app` INTEGER NOT NULL DEFAULT 0, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdInApp",
"columnName": "created_in_app",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_folders_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_folders_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "user_preferences",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`key`))",
"fields": [
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"key"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "files",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `folder_resource_id` TEXT NOT NULL, `extension` TEXT, `size` INTEGER NOT NULL, `mime_type` TEXT, `exists` INTEGER, `last_modified` INTEGER, `owner_id` TEXT, `category` TEXT, `sync_status` TEXT NOT NULL, `content` TEXT, `processed` INTEGER NOT NULL, `ocr_text` TEXT, `ocr_attempts` INTEGER NOT NULL, `ocr_queued_at` INTEGER, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderResourceId",
"columnName": "folder_resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "extension",
"columnName": "extension",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "size",
"columnName": "size",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mimeType",
"columnName": "mime_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "category",
"columnName": "category",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "content",
"columnName": "content",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "processed",
"columnName": "processed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrText",
"columnName": "ocr_text",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ocrAttempts",
"columnName": "ocr_attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrQueuedAt",
"columnName": "ocr_queued_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_files_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_files_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_files_folder_resource_id",
"unique": false,
"columnNames": [
"folder_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_folder_resource_id` ON `${TABLE_NAME}` (`folder_resource_id`)"
},
{
"name": "index_files_category",
"unique": false,
"columnNames": [
"category"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_category` ON `${TABLE_NAME}` (`category`)"
},
{
"name": "index_files_exists_processed_sync_status",
"unique": false,
"columnNames": [
"exists",
"processed",
"sync_status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` ON `${TABLE_NAME}` (`exists`, `processed`, `sync_status`)"
}
],
"foreignKeys": []
},
{
"tableName": "pending_operations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_id` TEXT, `operation_id` TEXT NOT NULL, `ref_type` TEXT, `ref_id` INTEGER, `resource_id` TEXT, `resource_type` TEXT, `operation` TEXT NOT NULL, `payload` TEXT NOT NULL, `parent_resource_id` TEXT, `status` TEXT NOT NULL, `attempts` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "deviceId",
"columnName": "device_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operationId",
"columnName": "operation_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "refType",
"columnName": "ref_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "refId",
"columnName": "ref_id",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operation",
"columnName": "operation",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "payload",
"columnName": "payload",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "attempts",
"columnName": "attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_pending_operations_device_id_operation_id",
"unique": true,
"columnNames": [
"device_id",
"operation_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_pending_operations_device_id_operation_id` ON `${TABLE_NAME}` (`device_id`, `operation_id`)"
},
{
"name": "index_pending_operations_status",
"unique": false,
"columnNames": [
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_status` ON `${TABLE_NAME}` (`status`)"
},
{
"name": "index_pending_operations_resource_id",
"unique": false,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_pending_operations_resource_id_operation_status",
"unique": false,
"columnNames": [
"resource_id",
"operation",
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` ON `${TABLE_NAME}` (`resource_id`, `operation`, `status`)"
},
{
"name": "index_pending_operations_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_sessions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `root_folder_id` TEXT, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "rootFolderId",
"columnName": "root_folder_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_sessions_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_sessions_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_pages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `session_id` INTEGER NOT NULL, `temp_uri` TEXT NOT NULL, `corners_json` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, FOREIGN KEY(`session_id`) REFERENCES `scan_sessions`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sessionId",
"columnName": "session_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "tempUri",
"columnName": "temp_uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cornersJson",
"columnName": "corners_json",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "width",
"columnName": "width",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "height",
"columnName": "height",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_pages_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_pages_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_scan_pages_session_id",
"unique": false,
"columnNames": [
"session_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_session_id` ON `${TABLE_NAME}` (`session_id`)"
},
{
"name": "index_scan_pages_sort_order",
"unique": false,
"columnNames": [
"sort_order"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_sort_order` ON `${TABLE_NAME}` (`sort_order`)"
}
],
"foreignKeys": [
{
"table": "scan_sessions",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"session_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "resource_permissions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resource_id` TEXT NOT NULL, `resource_type` TEXT NOT NULL, `effective_access` TEXT NOT NULL, `owner_id` TEXT, `shared_by_id` TEXT, `expires_at` INTEGER, `cached_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`resource_id`))",
"fields": [
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "effectiveAccess",
"columnName": "effective_access",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "sharedById",
"columnName": "shared_by_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "expiresAt",
"columnName": "expires_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "cachedAt",
"columnName": "cached_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"resource_id"
]
},
"indices": [
{
"name": "index_resource_permissions_expires_at",
"unique": false,
"columnNames": [
"expires_at"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` ON `${TABLE_NAME}` (`expires_at`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ec10fdb23d5da3a76a73222e9c404561')"
]
}
}
@@ -0,0 +1,742 @@
{
"formatVersion": 1,
"database": {
"version": 17,
"identityHash": "97790c7bc08828c46cc63c36d628a327",
"entities": [
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `exists` INTEGER, `parent_resource_id` TEXT, `owner_id` TEXT, `sync_status` TEXT NOT NULL, `created_in_app` INTEGER NOT NULL DEFAULT 0, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdInApp",
"columnName": "created_in_app",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_folders_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_folders_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "user_preferences",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`key`))",
"fields": [
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"key"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "files",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `folder_resource_id` TEXT NOT NULL, `extension` TEXT, `size` INTEGER NOT NULL, `mime_type` TEXT, `exists` INTEGER, `last_modified` INTEGER, `owner_id` TEXT, `category` TEXT, `sync_status` TEXT NOT NULL, `content` TEXT, `processed` INTEGER NOT NULL, `ocr_text` TEXT, `ocr_attempts` INTEGER NOT NULL, `ocr_queued_at` INTEGER, `bytes_uploaded` INTEGER NOT NULL, `bytes_upload_attempts` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderResourceId",
"columnName": "folder_resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "extension",
"columnName": "extension",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "size",
"columnName": "size",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mimeType",
"columnName": "mime_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "category",
"columnName": "category",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "content",
"columnName": "content",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "processed",
"columnName": "processed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrText",
"columnName": "ocr_text",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ocrAttempts",
"columnName": "ocr_attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrQueuedAt",
"columnName": "ocr_queued_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "bytesUploaded",
"columnName": "bytes_uploaded",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "bytesUploadAttempts",
"columnName": "bytes_upload_attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_files_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_files_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_files_folder_resource_id",
"unique": false,
"columnNames": [
"folder_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_folder_resource_id` ON `${TABLE_NAME}` (`folder_resource_id`)"
},
{
"name": "index_files_category",
"unique": false,
"columnNames": [
"category"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_category` ON `${TABLE_NAME}` (`category`)"
},
{
"name": "index_files_exists_processed_sync_status",
"unique": false,
"columnNames": [
"exists",
"processed",
"sync_status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` ON `${TABLE_NAME}` (`exists`, `processed`, `sync_status`)"
}
],
"foreignKeys": []
},
{
"tableName": "pending_operations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_id` TEXT, `operation_id` TEXT NOT NULL, `ref_type` TEXT, `ref_id` INTEGER, `resource_id` TEXT, `resource_type` TEXT, `operation` TEXT NOT NULL, `payload` TEXT NOT NULL, `parent_resource_id` TEXT, `status` TEXT NOT NULL, `attempts` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "deviceId",
"columnName": "device_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operationId",
"columnName": "operation_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "refType",
"columnName": "ref_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "refId",
"columnName": "ref_id",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operation",
"columnName": "operation",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "payload",
"columnName": "payload",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "attempts",
"columnName": "attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_pending_operations_device_id_operation_id",
"unique": true,
"columnNames": [
"device_id",
"operation_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_pending_operations_device_id_operation_id` ON `${TABLE_NAME}` (`device_id`, `operation_id`)"
},
{
"name": "index_pending_operations_status",
"unique": false,
"columnNames": [
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_status` ON `${TABLE_NAME}` (`status`)"
},
{
"name": "index_pending_operations_resource_id",
"unique": false,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_pending_operations_resource_id_operation_status",
"unique": false,
"columnNames": [
"resource_id",
"operation",
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` ON `${TABLE_NAME}` (`resource_id`, `operation`, `status`)"
},
{
"name": "index_pending_operations_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_sessions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `root_folder_id` TEXT, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "rootFolderId",
"columnName": "root_folder_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_sessions_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_sessions_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_pages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `session_id` INTEGER NOT NULL, `temp_uri` TEXT NOT NULL, `corners_json` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, FOREIGN KEY(`session_id`) REFERENCES `scan_sessions`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sessionId",
"columnName": "session_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "tempUri",
"columnName": "temp_uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cornersJson",
"columnName": "corners_json",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "width",
"columnName": "width",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "height",
"columnName": "height",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_pages_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_pages_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_scan_pages_session_id",
"unique": false,
"columnNames": [
"session_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_session_id` ON `${TABLE_NAME}` (`session_id`)"
},
{
"name": "index_scan_pages_sort_order",
"unique": false,
"columnNames": [
"sort_order"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_sort_order` ON `${TABLE_NAME}` (`sort_order`)"
}
],
"foreignKeys": [
{
"table": "scan_sessions",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"session_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "resource_permissions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resource_id` TEXT NOT NULL, `resource_type` TEXT NOT NULL, `effective_access` TEXT NOT NULL, `owner_id` TEXT, `shared_by_id` TEXT, `expires_at` INTEGER, `cached_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`resource_id`))",
"fields": [
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "effectiveAccess",
"columnName": "effective_access",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "sharedById",
"columnName": "shared_by_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "expiresAt",
"columnName": "expires_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "cachedAt",
"columnName": "cached_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"resource_id"
]
},
"indices": [
{
"name": "index_resource_permissions_expires_at",
"unique": false,
"columnNames": [
"expires_at"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` ON `${TABLE_NAME}` (`expires_at`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '97790c7bc08828c46cc63c36d628a327')"
]
}
}
@@ -0,0 +1,754 @@
{
"formatVersion": 1,
"database": {
"version": 18,
"identityHash": "443cfaf8d993f1ce6f39b9b8ad67dd23",
"entities": [
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `exists` INTEGER, `parent_resource_id` TEXT, `owner_id` TEXT, `sync_status` TEXT NOT NULL, `created_in_app` INTEGER NOT NULL DEFAULT 0, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdInApp",
"columnName": "created_in_app",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_folders_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_folders_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "user_preferences",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`key`))",
"fields": [
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"key"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "files",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `folder_resource_id` TEXT NOT NULL, `extension` TEXT, `size` INTEGER NOT NULL, `mime_type` TEXT, `exists` INTEGER, `last_modified` INTEGER, `owner_id` TEXT, `category` TEXT, `sync_status` TEXT NOT NULL, `content` TEXT, `processed` INTEGER NOT NULL, `ocr_text` TEXT, `ocr_attempts` INTEGER NOT NULL, `ocr_queued_at` INTEGER, `bytes_uploaded` INTEGER NOT NULL, `bytes_upload_attempts` INTEGER NOT NULL, `has_content_server` INTEGER NOT NULL, `wanted_offline` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderResourceId",
"columnName": "folder_resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "extension",
"columnName": "extension",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "size",
"columnName": "size",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mimeType",
"columnName": "mime_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "category",
"columnName": "category",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "content",
"columnName": "content",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "processed",
"columnName": "processed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrText",
"columnName": "ocr_text",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ocrAttempts",
"columnName": "ocr_attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrQueuedAt",
"columnName": "ocr_queued_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "bytesUploaded",
"columnName": "bytes_uploaded",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "bytesUploadAttempts",
"columnName": "bytes_upload_attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasContentServer",
"columnName": "has_content_server",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "wantedOffline",
"columnName": "wanted_offline",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_files_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_files_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_files_folder_resource_id",
"unique": false,
"columnNames": [
"folder_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_folder_resource_id` ON `${TABLE_NAME}` (`folder_resource_id`)"
},
{
"name": "index_files_category",
"unique": false,
"columnNames": [
"category"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_category` ON `${TABLE_NAME}` (`category`)"
},
{
"name": "index_files_exists_processed_sync_status",
"unique": false,
"columnNames": [
"exists",
"processed",
"sync_status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` ON `${TABLE_NAME}` (`exists`, `processed`, `sync_status`)"
}
],
"foreignKeys": []
},
{
"tableName": "pending_operations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_id` TEXT, `operation_id` TEXT NOT NULL, `ref_type` TEXT, `ref_id` INTEGER, `resource_id` TEXT, `resource_type` TEXT, `operation` TEXT NOT NULL, `payload` TEXT NOT NULL, `parent_resource_id` TEXT, `status` TEXT NOT NULL, `attempts` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "deviceId",
"columnName": "device_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operationId",
"columnName": "operation_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "refType",
"columnName": "ref_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "refId",
"columnName": "ref_id",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operation",
"columnName": "operation",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "payload",
"columnName": "payload",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "attempts",
"columnName": "attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_pending_operations_device_id_operation_id",
"unique": true,
"columnNames": [
"device_id",
"operation_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_pending_operations_device_id_operation_id` ON `${TABLE_NAME}` (`device_id`, `operation_id`)"
},
{
"name": "index_pending_operations_status",
"unique": false,
"columnNames": [
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_status` ON `${TABLE_NAME}` (`status`)"
},
{
"name": "index_pending_operations_resource_id",
"unique": false,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_pending_operations_resource_id_operation_status",
"unique": false,
"columnNames": [
"resource_id",
"operation",
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` ON `${TABLE_NAME}` (`resource_id`, `operation`, `status`)"
},
{
"name": "index_pending_operations_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_sessions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `root_folder_id` TEXT, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "rootFolderId",
"columnName": "root_folder_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_sessions_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_sessions_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_pages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `session_id` INTEGER NOT NULL, `temp_uri` TEXT NOT NULL, `corners_json` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, FOREIGN KEY(`session_id`) REFERENCES `scan_sessions`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sessionId",
"columnName": "session_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "tempUri",
"columnName": "temp_uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cornersJson",
"columnName": "corners_json",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "width",
"columnName": "width",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "height",
"columnName": "height",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_pages_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_pages_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_scan_pages_session_id",
"unique": false,
"columnNames": [
"session_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_session_id` ON `${TABLE_NAME}` (`session_id`)"
},
{
"name": "index_scan_pages_sort_order",
"unique": false,
"columnNames": [
"sort_order"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_sort_order` ON `${TABLE_NAME}` (`sort_order`)"
}
],
"foreignKeys": [
{
"table": "scan_sessions",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"session_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "resource_permissions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resource_id` TEXT NOT NULL, `resource_type` TEXT NOT NULL, `effective_access` TEXT NOT NULL, `owner_id` TEXT, `shared_by_id` TEXT, `expires_at` INTEGER, `cached_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`resource_id`))",
"fields": [
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "effectiveAccess",
"columnName": "effective_access",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "sharedById",
"columnName": "shared_by_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "expiresAt",
"columnName": "expires_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "cachedAt",
"columnName": "cached_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"resource_id"
]
},
"indices": [
{
"name": "index_resource_permissions_expires_at",
"unique": false,
"columnNames": [
"expires_at"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` ON `${TABLE_NAME}` (`expires_at`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '443cfaf8d993f1ce6f39b9b8ad67dd23')"
]
}
}
@@ -41,6 +41,16 @@
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
<!-- Liens de partage `kazier://share/<token>` (32-hex) : ouverture
dans l'écran de résolution (route publique, sans auth). -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="kazier"
android:host="share" />
</intent-filter>
</activity> </activity>
</application> </application>
@@ -51,6 +51,20 @@ class SecureTokenStore @Inject constructor(
override fun getExpiresAt(): Long? = override fun getExpiresAt(): Long? =
prefs.getLong(KEY_EXPIRES_AT, -1L).takeIf { it >= 0L } prefs.getLong(KEY_EXPIRES_AT, -1L).takeIf { it >= 0L }
override fun getCredentials(): Credentials? {
val username = prefs.getString(KEY_USERNAME, null)?.takeIf { it.isNotBlank() } ?: return null
val password = prefs.getString(KEY_PASSWORD, null)?.takeIf { it.isNotEmpty() } ?: return null
return Credentials(username, password)
}
override fun saveCredentials(username: String, password: String) {
prefs.edit().putString(KEY_USERNAME, username).putString(KEY_PASSWORD, password).apply()
}
override fun clearCredentials() {
prefs.edit().remove(KEY_USERNAME).remove(KEY_PASSWORD).apply()
}
override fun save(token: String, user: UserDto, expiresAt: Long?) { override fun save(token: String, user: UserDto, expiresAt: Long?) {
prefs.edit() prefs.edit()
.putString(KEY_TOKEN, token) .putString(KEY_TOKEN, token)
@@ -70,5 +84,7 @@ class SecureTokenStore @Inject constructor(
private const val KEY_TOKEN = "kazier.auth_token" private const val KEY_TOKEN = "kazier.auth_token"
private const val KEY_ACCOUNT = "kazier.account" private const val KEY_ACCOUNT = "kazier.account"
private const val KEY_EXPIRES_AT = "kazier.expires_at" private const val KEY_EXPIRES_AT = "kazier.expires_at"
private const val KEY_USERNAME = "kazier.auth_username"
private const val KEY_PASSWORD = "kazier.auth_password"
} }
} }
@@ -2,7 +2,9 @@ package com.kazier.mobile.auth
import com.kazier.mobile.data.local.dao.PendingOperationDao import com.kazier.mobile.data.local.dao.PendingOperationDao
import com.kazier.mobile.data.remote.ApiClient import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.remote.dto.UserDto import com.kazier.mobile.data.remote.dto.UserDto
import com.kazier.mobile.data.repository.AuthRepository
import com.kazier.mobile.domain.ActiveUserStore import com.kazier.mobile.domain.ActiveUserStore
import com.kazier.mobile.domain.LocalModeStore import com.kazier.mobile.domain.LocalModeStore
import javax.inject.Inject import javax.inject.Inject
@@ -10,8 +12,23 @@ import javax.inject.Singleton
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import timber.log.Timber
/** Événements de session vers l'UI (re-login silencieux, lot 3). */
sealed interface AuthEvent {
/** Le token a été renouvelé sans action utilisateur — rester connecté. */
data class Reauthenticated(val user: UserDto) : AuthEvent
/** Plus de session récupérable — afficher le login (pré-rempli si possible). */
data class SessionExpired(val username: String?) : AuthEvent
}
/** /**
* Orchestration de la session (restauration/sauvegarde/purge) : relie le store * Orchestration de la session (restauration/sauvegarde/purge) : relie le store
@@ -20,8 +37,15 @@ import kotlinx.coroutines.withContext
* ([LocalModeStore]) pour survivre aux redémarrages. * ([LocalModeStore]) pour survivre aux redémarrages.
* *
* Le callback 401 est possédé ici (singleton, M25) — jamais par un ViewModel : * Le callback 401 est possédé ici (singleton, M25) — jamais par un ViewModel :
* après `onCleared`, un token expiré/révoqué continue de purger la session * après `onCleared`, un token expiré/révoqué continue d'être traité (le worker
* (le worker cesse alors de rejouer l'outbox sous un token mort). * cesse alors de rejouer l'outbox sous un token mort).
*
* Re-login silencieux (lot 3) : les identifiants saisis au login sont
* persistés chiffrés ; sur 401 (ou token expiré détecté en proactif), une
* seule tentative de `POST /auth/login` est jouée (single-flight). Succès →
* [AuthEvent.Reauthenticated] (file conservée si même compte) ; identifiants
* rejetés → purge complète + [AuthEvent.SessionExpired]. La requête en vol
* ayant subi le 401 n'est PAS rejouée — l'appelant la relance (pull, retry).
*/ */
@Singleton @Singleton
class SessionManager @Inject constructor( class SessionManager @Inject constructor(
@@ -31,14 +55,22 @@ class SessionManager @Inject constructor(
private val localModeStore: LocalModeStore, private val localModeStore: LocalModeStore,
private val pendingOperationDao: PendingOperationDao, private val pendingOperationDao: PendingOperationDao,
private val apiClient: ApiClient, private val apiClient: ApiClient,
private val authRepository: AuthRepository,
) { ) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
/** Single-flight du re-login : N 401 concurrents → 1 seul `POST /auth/login`. */
private val reloginMutex = Mutex()
private val _events = MutableSharedFlow<AuthEvent>(extraBufferCapacity = 4)
val events: SharedFlow<AuthEvent> = _events.asSharedFlow()
init { init {
// 401 sur un endpoint protégé (token expiré/révoqué, compte supprimé) // 401 sur un endpoint protégé (token expiré/révoqué, compte supprimé)
// → purge de la session. Le 401 du login et des routes publiques est // → re-login silencieux puis purge si irrécupérable. Le 401 du login
// exonéré côté ApiClient (skipUnauthorizedHandling). // et des routes publiques est exonéré côté ApiClient
// (skipUnauthorizedHandling).
apiClient.onUnauthorized = { handleUnauthorized() } apiClient.onUnauthorized = { handleUnauthorized() }
} }
@@ -50,10 +82,18 @@ class SessionManager @Inject constructor(
AuthSession(token = token, user = user, expiresAt = tokenStore.getExpiresAt()) AuthSession(token = token, user = user, expiresAt = tokenStore.getExpiresAt())
} }
suspend fun save(token: String, user: UserDto, expiresAt: Long? = null) = suspend fun save(
withContext(Dispatchers.IO) { token: String,
user: UserDto,
expiresAt: Long? = null,
username: String? = null,
password: String? = null,
) = withContext(Dispatchers.IO) {
val previousUserId = activeUserStore.get() val previousUserId = activeUserStore.get()
tokenStore.save(token, user, expiresAt) tokenStore.save(token, user, expiresAt)
if (username != null && password != null) {
tokenStore.saveCredentials(username, password)
}
activeUserStore.set(user.id) activeUserStore.set(user.id)
localModeStore.clear() localModeStore.clear()
tokenProvider.current = token tokenProvider.current = token
@@ -69,6 +109,7 @@ class SessionManager @Inject constructor(
suspend fun clear() = withContext(Dispatchers.IO) { suspend fun clear() = withContext(Dispatchers.IO) {
tokenStore.clear() tokenStore.clear()
tokenStore.clearCredentials()
activeUserStore.clear() activeUserStore.clear()
tokenProvider.current = null tokenProvider.current = null
// Sign-out explicite : la file non poussée est abandonnée (C5, voir // Sign-out explicite : la file non poussée est abandonnée (C5, voir
@@ -77,16 +118,82 @@ class SessionManager @Inject constructor(
} }
/** /**
* Purge fire-and-forget sur 401 (appelée depuis le thread OkHttp via * 401 sur endpoint protégé (appelée depuis le thread OkHttp via
* `ApiClient`) : le token en mémoire tombe synchronement pour ne plus * `ApiClient`) : le token en mémoire tombe synchronement pour ne plus
* émettre de requêtes authentifiées, la persistance suit en IO. * émettre de requêtes authentifiées, puis le re-login silencieux est tenté
* en IO (single-flight).
*
* Garde : sans session persistée (mode local, jamais connecté), un 401
* (token absent → `Bearer` omis → 401 serveur) ne signifie PAS une
* session morte — ignorer, sans purge ni événement. Sinon un appel
* égaré éjecte l'utilisateur local vers l'écran de login.
*/ */
fun handleUnauthorized() { fun handleUnauthorized() {
tokenProvider.current = null tokenProvider.current = null
scope.launch { scope.launch {
val hadSession = runCatching {
tokenStore.getToken() != null || tokenStore.getUser() != null
}.getOrDefault(false)
if (!hadSession) return@launch
reloginMutex.withLock { silentReloginLocked() }
}
}
/**
* Re-login proactif (démarrage, retour foreground) : si le token en
* mémoire est absent ou expiré et que des identifiants sont sauvés, tente
* un renouvellement. Vrai si un token frais est disponible au retour.
*/
suspend fun trySilentRelogin(nowMs: Long = System.currentTimeMillis()): Boolean =
withContext(Dispatchers.IO) {
if (tokenProvider.current != null && !isTokenExpired(nowMs)) return@withContext true
reloginMutex.withLock { silentReloginLocked() }
}
/**
* Corps du re-login, sous [reloginMutex]. Vrai si la session est (à
* nouveau) valide. Émet [AuthEvent.Reauthenticated] en cas de succès et
* [AuthEvent.SessionExpired] quand rien n'est récupérable.
*/
private suspend fun silentReloginLocked(): Boolean {
// Re-vérification sous mutex : un re-login concurrent vient peut-être
// de rafraîchir le token pendant l'attente du verrou (N 401 → 1 login).
if (tokenProvider.current != null && !isTokenExpired()) return true
val creds = runCatching { tokenStore.getCredentials() }.getOrNull()
if (creds == null) {
purgeToExpired(username = null)
return false
}
return try {
val response = authRepository.login(creds.username, creds.password)
save(response.token, response.user, response.expiresAt)
Timber.d("auth: re-login silencieux OK pour %s", creds.username)
_events.tryEmit(AuthEvent.Reauthenticated(response.user))
true
} catch (e: Exception) {
if (e is ApiException && e.code == "UNAUTHORIZED") {
// Identifiants rejetés (mot de passe changé ailleurs, compte
// supprimé) : ne plus jamais les rejouer.
Timber.w("auth: re-login rejeté, purge des identifiants")
runCatching { tokenStore.clearCredentials() }
purgeToExpired(username = creds.username)
} else {
// Transitoire (réseau/5xx) : token mort, identifiants conservés
// pour une tentative ultérieure (prochain démarrage/login).
Timber.w(e, "auth: re-login transitoire, session expirée")
purgeToExpired(username = creds.username)
}
false
}
}
/** Purge token + compte actif (file intacte, cf. C5) + événement UI. */
private suspend fun purgeToExpired(username: String?) {
val knownUsername = username ?: runCatching { tokenStore.getUser()?.username }.getOrNull()
tokenProvider.current = null
runCatching { tokenStore.clear() } runCatching { tokenStore.clear() }
runCatching { activeUserStore.clear() } runCatching { activeUserStore.clear() }
} _events.tryEmit(AuthEvent.SessionExpired(knownUsername))
} }
/** /**
@@ -6,6 +6,11 @@ import com.kazier.mobile.data.remote.dto.UserDto
* Persistance du token paseto, du profil compte et de l'expiration du token * Persistance du token paseto, du profil compte et de l'expiration du token
* (claim `expires_at` du login, TTL 7 j). Implémentation : [SecureTokenStore] * (claim `expires_at` du login, TTL 7 j). Implémentation : [SecureTokenStore]
* (Keystore + AES, jamais en clair dans SQLite). * (Keystore + AES, jamais en clair dans SQLite).
*
* Les identifiants (username + password) sont persistés à part pour le
* re-login silencieux sur 401 (lot 3) : ils survivent à la purge du token
* ([clear] ne les touche pas) et ne tombent qu'au sign-out explicite
* ([clearCredentials]) ou quand le serveur les rejette (401 au re-login).
*/ */
interface TokenStore { interface TokenStore {
@@ -18,5 +23,19 @@ interface TokenStore {
fun save(token: String, user: UserDto, expiresAt: Long?) fun save(token: String, user: UserDto, expiresAt: Long?)
/** Purge token + compte + expiration — jamais les identifiants. */
fun clear() fun clear()
/** Identifiants du re-login silencieux — null si jamais connectés. */
fun getCredentials(): Credentials?
fun saveCredentials(username: String, password: String)
fun clearCredentials()
} }
/** Identifiants persistés (chiffrés) pour le re-login silencieux. */
data class Credentials(
val username: String,
val password: String,
)
@@ -5,11 +5,13 @@ import androidx.room.RoomDatabase
import com.kazier.mobile.data.local.dao.FileDao import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.dao.FolderDao import com.kazier.mobile.data.local.dao.FolderDao
import com.kazier.mobile.data.local.dao.PendingOperationDao import com.kazier.mobile.data.local.dao.PendingOperationDao
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
import com.kazier.mobile.data.local.dao.ScanDao import com.kazier.mobile.data.local.dao.ScanDao
import com.kazier.mobile.data.local.dao.UserPreferenceDao import com.kazier.mobile.data.local.dao.UserPreferenceDao
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FolderEntity import com.kazier.mobile.data.local.entity.FolderEntity
import com.kazier.mobile.data.local.entity.PendingOperationEntity import com.kazier.mobile.data.local.entity.PendingOperationEntity
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
import com.kazier.mobile.data.local.entity.ScanPageEntity import com.kazier.mobile.data.local.entity.ScanPageEntity
import com.kazier.mobile.data.local.entity.ScanSessionEntity import com.kazier.mobile.data.local.entity.ScanSessionEntity
import com.kazier.mobile.data.local.entity.UserPreferenceEntity import com.kazier.mobile.data.local.entity.UserPreferenceEntity
@@ -27,14 +29,22 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity
* operation_id) (contrat outbox docs/api-v1.md §6.1). * operation_id) (contrat outbox docs/api-v1.md §6.1).
* v13: index composites files(exists, processed, sync_status) et * v13: index composites files(exists, processed, sync_status) et
* pending_operations(resource_id, operation, status) (requêtes review/OCR/gates). * pending_operations(resource_id, operation, status) (requêtes review/OCR/gates).
* v14: parent_resource_id sur pending_operations (cascade P8).
* v15: backfill exists NULL→1 sur folders/files (M13).
* v16: table resource_permissions (cache snapshot, M27).
* v17: bytes_uploaded + bytes_upload_attempts sur files (upload V2).
* v18: has_content_server + wanted_offline sur files (download V2).
*/ */
@Database( @Database(
entities = [ entities = [
FolderEntity::class, UserPreferenceEntity::class, FileEntity::class, FolderEntity::class, UserPreferenceEntity::class, FileEntity::class,
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class, PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
ResourcePermissionEntity::class,
], ],
version = 14, version = 18,
exportSchema = false, // m19 : schéma exporté (`app/schemas/`) — toute dérive non migrée casse
// la compilation au lieu de briqueter les utilisateurs au démarrage.
exportSchema = true,
) )
abstract class AppDatabase : RoomDatabase() { abstract class AppDatabase : RoomDatabase() {
@@ -43,4 +53,5 @@ abstract class AppDatabase : RoomDatabase() {
abstract fun fileDao(): FileDao abstract fun fileDao(): FileDao
abstract fun pendingOperationDao(): PendingOperationDao abstract fun pendingOperationDao(): PendingOperationDao
abstract fun scanDao(): ScanDao abstract fun scanDao(): ScanDao
abstract fun resourcePermissionDao(): ResourcePermissionDao
} }
@@ -0,0 +1,27 @@
package com.kazier.mobile.data.local
import java.text.Normalizer
import java.util.Locale
/**
* Échappe les jokers `LIKE` (`%`, `_`) et l'échappement lui-même (`\`) dans
* un fragment destiné à une requête `... LIKE ... ESCAPE '\'` (m5, m7).
* Sans ça, un `%`/`_` saisi (recherche) ou présent (uris SAF encodées
* `%3A…`) agit comme joker : match-all en recherche, sur-sélection au walk.
*/
internal fun String.escapeLike(): String =
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
/**
* Normalise une saisie de recherche pour le matching insensible aux accents
* (suivi m7) : minuscules (ROOT, pas de surprise turque), décomposition NFD,
* suppression des diacritiques, ligatures `œ`/`æ` explicites (non décomposées
* par NFD). À appliquer AVANT [escapeLike] ; le SQL compare contre
* `name` normalisé de la même façon (chaîne de `REPLACE`, voir `FileDao`).
*/
internal fun String.normalizeSearch(): String =
lowercase(Locale.ROOT)
.let { Normalizer.normalize(it, Normalizer.Form.NFD) }
.replace(Regex("\\p{Mn}+"), "")
.replace("œ", "oe")
.replace("æ", "ae")
@@ -15,6 +15,12 @@ interface FileDao {
@Query("SELECT * FROM files ORDER BY name ASC") @Query("SELECT * FROM files ORDER BY name ASC")
suspend fun getAll(): List<FileEntity> suspend fun getAll(): List<FileEntity>
/**
* Lignes sous une racine SAF (m5) — voir `FolderDao.getUnderRoot`.
*/
@Query("SELECT * FROM files WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FileEntity>
/** /**
* Repasse C4 : lignes déjà journalisées (`exists = 0`) dont les octets * Repasse C4 : lignes déjà journalisées (`exists = 0`) dont les octets
* sont peut-être encore sur le disque (journal-first, crash ou refus SAF * sont peut-être encore sur le disque (journal-first, crash ou refus SAF
@@ -39,14 +45,29 @@ interface FileDao {
@Query("SELECT * FROM files WHERE uri = :uri LIMIT 1") @Query("SELECT * FROM files WHERE uri = :uri LIMIT 1")
suspend fun getByUri(uri: String): FileEntity? suspend fun getByUri(uri: String): FileEntity?
/**
* Recherche par nom (m7 + suivi accents) : `:query` arrive déjà échappé
* (`escapeLike`, `%`/`_` littéraux, pas des jokers) avec `ESCAPE '\'`.
* `COLLATE NOCASE` couvre la casse ASCII ; la deuxième branche compare
* `lower(name)` débarrassé de ses accents (chaîne de `REPLACE` FR — pas de
* colonne normalisée ni de migration) contre `:normQuery` (saisie passée
* par `normalizeSearch` + `escapeLike`). « ete » trouve « ÉTÉ ».
*/
@Query(""" @Query("""
SELECT * FROM files SELECT * FROM files
WHERE "exists" = 1 WHERE "exists" = 1
AND (:query IS NULL OR name LIKE '%' || :query || '%') AND (:query IS NULL OR name COLLATE NOCASE LIKE '%' || :query || '%' ESCAPE '\'
OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
lower(name),
'œ','oe'),'æ','ae'),'ç','c'),'à','a'),'â','a'),'ä','a'),
'é','e'),'è','e'),'ê','e'),'ë','e'),'î','i'),'ï','i'),
'ô','o'),'ö','o'),'ù','u'),'û','u'),'ü','u'),'ÿ','y')
LIKE '%' || :normQuery || '%' ESCAPE '\')
AND (:category IS NULL OR category = :category) AND (:category IS NULL OR category = :category)
ORDER BY name ASC ORDER BY name ASC
""") """)
fun searchWithFilters(query: String?, category: String?): Flow<List<FileEntity>> fun searchWithFilters(query: String?, normQuery: String?, category: String?): Flow<List<FileEntity>>
@Query(""" @Query("""
SELECT * FROM files SELECT * FROM files
@@ -194,4 +215,121 @@ interface FileDao {
/** Échec terminal : +1 tentative, marqueur levé (ne rejoue pas à l'infini). */ /** Échec terminal : +1 tentative, marqueur levé (ne rejoue pas à l'infini). */
@Query("UPDATE files SET ocr_attempts = ocr_attempts + 1, ocr_queued_at = NULL, updated_at = :now WHERE resource_id = :resourceId") @Query("UPDATE files SET ocr_attempts = ocr_attempts + 1, ocr_queued_at = NULL, updated_at = :now WHERE resource_id = :resourceId")
suspend fun markOcrFailure(resourceId: String, now: Long) suspend fun markOcrFailure(resourceId: String, now: Long)
/**
* Candidats upload V2 : copie physique locale, métadonnées déjà connues
* du serveur (`local-cloud` = `create_resource` synced), octets jamais
* poussés, pas épuisés (< 3 échecs terminaux). Le serveur overwrite en
* aveugle sur re-upload ciblé : l'idempotence est au `resource_id`.
*/
@Query("""
SELECT * FROM files
WHERE "exists" = 1
AND processed = 1
AND sync_status = 'local-cloud'
AND uri IS NOT NULL
AND bytes_uploaded = 0
AND bytes_upload_attempts < 3
ORDER BY COALESCE(last_modified, added_at) DESC, name ASC
""")
suspend fun getBytesUploadCandidates(): List<FileEntity>
/** Octets confirmés serveur (upload ciblé réussi). */
@Query("UPDATE files SET bytes_uploaded = 1, updated_at = :now WHERE resource_id = :resourceId")
suspend fun markBytesUploaded(resourceId: String, now: Long)
/** Échec terminal d'upload (4xx : trop gros, inconnu, rejeté). */
@Query("UPDATE files SET bytes_upload_attempts = bytes_upload_attempts + 1, updated_at = :now WHERE resource_id = :resourceId")
suspend fun markBytesUploadFailure(resourceId: String, now: Long)
/**
* Candidats download V2 : cloud-only (`uri` NULL) encore visibles, avec
* octets constatés serveur, dont le rapatriement a été demandé
* (`wanted_offline`, survit au reboot). Le worker efface `wanted_offline`
* au succès (ligne rattachée) ou sur 404 (+ `has_content_server = 0`).
*/
@Query("""
SELECT * FROM files
WHERE "exists" = 1
AND uri IS NULL
AND has_content_server = 1
AND wanted_offline = 1
ORDER BY updated_at ASC
""")
suspend fun getOfflineWantedCandidates(): List<FileEntity>
/** Demande (`wanted_offline = 1`) ou annule le rapatriement d'un fichier. */
@Query("UPDATE files SET wanted_offline = :wanted, updated_at = :now WHERE resource_id = :resourceId")
suspend fun setWantedOffline(resourceId: String, wanted: Boolean, now: Long)
/** Miroir serveur de `FileDto.hasContent` (convergé par refresh). */
@Query("UPDATE files SET has_content_server = :hasContent, updated_at = :now WHERE resource_id = :resourceId")
suspend fun setHasContentServer(resourceId: String, hasContent: Boolean, now: Long)
/**
* Rattachement post-download : la copie SAF devient la localisation de la
* ligne (même `resource_id`, pas de doublon). Le walk converge par `uri`
* (index unique) vers ce même dossier — pas de réimport. Demande soldée.
*/
@Query("""
UPDATE files
SET uri = :uri,
folder_resource_id = :folderId,
sync_status = 'local-cloud',
processed = 1,
"exists" = 1,
wanted_offline = 0,
size = :size,
updated_at = :now
WHERE resource_id = :resourceId
""")
suspend fun attachDownloaded(
resourceId: String,
uri: String,
folderId: String,
size: Long,
now: Long,
)
/**
* Détachement V2-3 (« libérer de l'espace ») : supprime la localisation
* SAF, la ligne redevient cloud-only (`uri` NULL) mais reste visible
* (`exists = 1`). Aucune op outbox — le serveur est inchangé (il garde
* les octets, d'où le gate `isReleasable` côté repository). Demande
* hors-ligne éventuelle soldée.
*/
@Query("""
UPDATE files
SET uri = NULL,
sync_status = 'cloud',
wanted_offline = 0,
updated_at = :now
WHERE resource_id = :resourceId
""")
suspend fun detachLocalCopy(resourceId: String, now: Long)
/**
* Candidats rétention V2-5 : copies locales purgeables
* (`isReleasable` en SQL) plus anciennes que `cutoffMs`
* (`COALESCE(last_modified, added_at)`), les plus anciennes d'abord.
*/
@Query("""
SELECT * FROM files
WHERE "exists" = 1
AND uri IS NOT NULL
AND (has_content_server = 1 OR bytes_uploaded = 1)
AND COALESCE(last_modified, added_at) < :cutoffMs
ORDER BY COALESCE(last_modified, added_at) ASC
""")
suspend fun releasableOlderThan(cutoffMs: Long): List<FileEntity>
/** Octets récupérables par la rétention (stats UI, même filtre). */
@Query("""
SELECT COALESCE(SUM(size), 0) FROM files
WHERE "exists" = 1
AND uri IS NOT NULL
AND (has_content_server = 1 OR bytes_uploaded = 1)
AND COALESCE(last_modified, added_at) < :cutoffMs
""")
suspend fun sumReleasableBytes(cutoffMs: Long): Long
} }
@@ -18,6 +18,14 @@ interface FolderDao {
@Query("SELECT * FROM folders ORDER BY name ASC") @Query("SELECT * FROM folders ORDER BY name ASC")
suspend fun getAll(): List<FolderEntity> suspend fun getAll(): List<FolderEntity>
/**
* Lignes sous une racine SAF (m5) : le walk et sa réconciliation ne
* scannent plus toute la table par racine. `:escapedRoot` est la racine
* avec `%`, `_`, `\` échappés côté appelant (`ESCAPE '\'`).
*/
@Query("SELECT * FROM folders WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FolderEntity>
/** /**
* Repasse C4 (dossiers) : voir `FileDao.getMissingWithUri`. Un dossier * Repasse C4 (dossiers) : voir `FileDao.getMissingWithUri`. Un dossier
* n'est re-supprimé physiquement que si toute sa descendance Room est * n'est re-supprimé physiquement que si toute sa descendance Room est
@@ -198,4 +198,19 @@ interface PendingOperationDao {
AND status IN ('pending', 'synced') AND status IN ('pending', 'synced')
""") """)
suspend fun countMoveOperations(resourceId: String): Int suspend fun countMoveOperations(resourceId: String): Int
/**
* Ops de partage encore en attente de push pour cette ressource
* (`share`, `update_share`, `revoke_share`, `create_link`, `revoke_link`).
* Le sheet de partage les affiche comme « en attente d'envoi » : la liste
* serveur ne les reflète qu'après le drain du worker.
*/
@Query("""
SELECT * FROM pending_operations
WHERE resource_id = :resourceId
AND operation IN ('share', 'update_share', 'revoke_share', 'create_link', 'revoke_link')
AND status = 'pending'
ORDER BY id ASC
""")
suspend fun pendingShareOps(resourceId: String): List<PendingOperationEntity>
} }
@@ -0,0 +1,30 @@
package com.kazier.mobile.data.local.dao
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
@Dao
interface ResourcePermissionDao {
@Upsert
suspend fun upsertAll(perms: List<ResourcePermissionEntity>)
@Query("SELECT * FROM resource_permissions WHERE resource_id = :resourceId LIMIT 1")
suspend fun getByResourceId(resourceId: String): ResourcePermissionEntity?
/** Grants périmés à masquer localement (`expires_at` passé). */
@Query("SELECT * FROM resource_permissions WHERE expires_at IS NOT NULL AND expires_at <= :now")
suspend fun getExpired(now: Long): List<ResourcePermissionEntity>
/**
* Convergence du pull complet : oublie les grants absents du snapshot
* (révocation/expiration côté serveur).
*/
@Query("DELETE FROM resource_permissions WHERE resource_id NOT IN (:snapshotIds)")
suspend fun deleteNotIn(snapshotIds: List<String>)
@Query("DELETE FROM resource_permissions")
suspend fun clear()
}
@@ -42,8 +42,9 @@ data class FileEntity(
val size: Long, val size: Long,
@ColumnInfo(name = "mime_type") @ColumnInfo(name = "mime_type")
val mimeType: String? = null, val mimeType: String? = null,
// M13 : voir `FolderEntity.exists` — défaut 1, backfill en migration 14→15.
@ColumnInfo(name = "exists") @ColumnInfo(name = "exists")
val exists: Int? = null, val exists: Int? = 1,
@ColumnInfo(name = "last_modified") @ColumnInfo(name = "last_modified")
val lastModified: Long? = null, val lastModified: Long? = null,
@ColumnInfo(name = "owner_id") @ColumnInfo(name = "owner_id")
@@ -62,6 +63,30 @@ data class FileEntity(
val ocrAttempts: Int = 0, val ocrAttempts: Int = 0,
@ColumnInfo(name = "ocr_queued_at") @ColumnInfo(name = "ocr_queued_at")
val ocrQueuedAt: Long? = null, val ocrQueuedAt: Long? = null,
/**
* V2 : octets poussés vers le serveur (`POST /files/upload` ciblé) —
* 0 = en attente, 1 = présents serveur. Distinct de `sync_status`
* (métadonnées connues : `local-cloud`) qui ne dit rien des octets.
*/
@ColumnInfo(name = "bytes_uploaded")
val bytesUploaded: Int = 0,
/** Tentatives d'upload définitives (4xx) — cap 3, comme `ocr_attempts`. */
@ColumnInfo(name = "bytes_upload_attempts")
val bytesUploadAttempts: Int = 0,
/**
* V2-2 : miroir de `FileDto.hasContent` (octets vus présents serveur).
* Renseigné par `refreshFromServer` ; `FALSE` = jamais constatés, pas
* « certifié absent » (lazy healing côté serveur).
*/
@ColumnInfo(name = "has_content_server")
val hasContentServer: Boolean = false,
/**
* V2-2 : download demandé mais pas encore accompli (file du
* `DownloadWorker`, reprise après reboot). Le worker l'efface au succès
* (ligne rattachée) ou sur 404 (avec `has_content_server = 0`).
*/
@ColumnInfo(name = "wanted_offline")
val wantedOffline: Boolean = false,
@ColumnInfo(name = "added_at") @ColumnInfo(name = "added_at")
val addedAt: Long, val addedAt: Long,
@ColumnInfo(name = "updated_at") @ColumnInfo(name = "updated_at")
@@ -74,3 +99,12 @@ object FileStatus {
const val CLOUD = "cloud" const val CLOUD = "cloud"
const val LOCAL_CLOUD = "local-cloud" const val LOCAL_CLOUD = "local-cloud"
} }
/**
* Purge sûre V2-3 : vrai si les octets locaux peuvent être supprimés sans
* risque de perte — une autre copie durable existe côté serveur
* (`has_content_server`, miroir) ou a été poussée par ce device
* (`bytes_uploaded`, vérité locale). Pure (testée sans Robolectric).
*/
fun FileEntity.isReleasable(): Boolean =
uri != null && exists != 0 && (hasContentServer || bytesUploaded == 1)
@@ -32,8 +32,11 @@ data class FolderEntity(
val uri: String? = null, val uri: String? = null,
@ColumnInfo(name = "name") @ColumnInfo(name = "name")
val name: String, val name: String,
// M13 : défaut 1 — une ligne sans `exists` explicite restait invisible
// des requêtes `WHERE exists = 1`. La colonne reste nullable côté schéma
// (pas de rewrite), le backfill NULL→1 est fait en migration 14→15.
@ColumnInfo(name = "exists") @ColumnInfo(name = "exists")
val exists: Int? = null, val exists: Int? = 1,
@ColumnInfo(name = "parent_resource_id") @ColumnInfo(name = "parent_resource_id")
val parentResourceId: String? = null, val parentResourceId: String? = null,
@ColumnInfo(name = "owner_id") @ColumnInfo(name = "owner_id")
@@ -83,4 +83,11 @@ object PendingOperationType {
const val UPDATE_SHARE = "update_share" const val UPDATE_SHARE = "update_share"
const val CREATE_LINK = "create_link" const val CREATE_LINK = "create_link"
const val REVOKE_LINK = "revoke_link" const val REVOKE_LINK = "revoke_link"
/**
* V2 placements : signalement de présence d'octets (`{ hasBytes }`).
* Hint, jamais bloquant : un échec est dead-letter + suite du batch
* (voir `OutboxSyncWorker`), et chaque changement d'état exige un nouvel
* `operation_id` (garde anti-rejeu serveur A9).
*/
const val REPORT_BYTES = "report_bytes"
} }
@@ -0,0 +1,59 @@
package com.kazier.mobile.data.local.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
/**
* Cache local du snapshot `GET /sync/permissions` (M27, docs/api-v1.md §6.2).
*
* Une ligne = la permission effective connue pour une ressource NON possédée
* (les ressources `owner` ne sont pas stockées : l'ownership se résout depuis
* les lignes `files`/`folders`). Fondement de [canAccess][com.kazier.mobile.data.repository.ShareRepository.canAccess]
* sans réseau : rang effectif, expiration du grant et fraîcheur du snapshot
* (TTL 24h → downgrade lecture seule).
*/
@Entity(
tableName = "resource_permissions",
indices = [
Index(value = ["expires_at"]),
],
)
data class ResourcePermissionEntity(
@PrimaryKey
@ColumnInfo(name = "resource_id")
val resourceId: String,
@ColumnInfo(name = "resource_type")
val resourceType: String,
@ColumnInfo(name = "effective_access")
val effectiveAccess: String,
@ColumnInfo(name = "owner_id")
val ownerId: String? = null,
@ColumnInfo(name = "shared_by_id")
val sharedById: String? = null,
/** Fin du grant, ms epoch ; null = jamais. */
@ColumnInfo(name = "expires_at")
val expiresAt: Long? = null,
/** Horodatage du snapshot serveur, ms epoch (TTL 24h). */
@ColumnInfo(name = "cached_at")
val cachedAt: Long,
@ColumnInfo(name = "updated_at")
val updatedAt: Long,
)
/** Rangs d'accès effectif — `viewer < commenter < editor < owner`. */
object AccessRank {
const val VIEWER = "viewer"
const val COMMENTER = "commenter"
const val EDITOR = "editor"
const val OWNER = "owner"
fun rank(access: String?): Int = when (access) {
OWNER -> 4
EDITOR -> 3
COMMENTER -> 2
VIEWER -> 1
else -> 0
}
}
@@ -33,6 +33,9 @@ import androidx.sqlite.db.SupportSQLiteDatabase
* v13 : index composites `files(exists, processed, sync_status)` (review + * v13 : index composites `files(exists, processed, sync_status)` (review +
* candidats OCR auto) et `pending_operations(resource_id, operation, status)` * candidats OCR auto) et `pending_operations(resource_id, operation, status)`
* (gates outbox create/move) — requêtes à chaud sans full-table scan. * (gates outbox create/move) — requêtes à chaud sans full-table scan.
* v14 : colonne `parent_resource_id` sur `pending_operations` (cascade P8).
* v15 : backfill `exists` NULL→1 sur `folders`/`files` (M13) + défaut Kotlin 1.
* v16 : table `resource_permissions` (cache snapshot, M27) + index `expires_at`.
*/ */
object Migrations { object Migrations {
@@ -246,7 +249,74 @@ object Migrations {
} }
} }
/**
* M13 : backfill `exists` NULL→1 sur `folders` et `files`. Les lignes
* insérées sans `exists` explicite (défaut Kotlin `null` avant ce fix)
* étaient invisibles des requêtes `WHERE exists = 1` — elles
* réapparaissent comme présentes, état le plus sûr (le walk les
* re-marque `exists = 0` si elles ont vraiment disparu).
*/
private val MIGRATION_14_15 = object : Migration(14, 15) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("UPDATE `folders` SET `exists` = 1 WHERE `exists` IS NULL")
db.execSQL("UPDATE `files` SET `exists` = 1 WHERE `exists` IS NULL")
}
}
/**
* M27 : cache du snapshot permissions — table `resource_permissions`
* (rang effectif + expiration + fraîcheur, fondement de `canAccess`).
*/
private val MIGRATION_15_16 = object : Migration(15, 16) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS `resource_permissions` (
`resource_id` TEXT NOT NULL,
`resource_type` TEXT NOT NULL,
`effective_access` TEXT NOT NULL,
`owner_id` TEXT,
`shared_by_id` TEXT,
`expires_at` INTEGER,
`cached_at` INTEGER NOT NULL,
`updated_at` INTEGER NOT NULL,
PRIMARY KEY(`resource_id`)
)
""".trimIndent(),
)
db.execSQL(
"CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` " +
"ON `resource_permissions` (`expires_at`)",
)
}
}
/**
* V2 : upload générique des octets — `bytes_uploaded` (0 = en attente,
* 1 = présents serveur) + `bytes_upload_attempts` (cap 3, comme
* `ocr_attempts`). Zéro backfill : tout fichier existant est
* ré-uploadé une fois (idempotent côté serveur, overwrite ciblé).
*/
private val MIGRATION_16_17 = object : Migration(16, 17) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `files` ADD COLUMN `bytes_uploaded` INTEGER NOT NULL DEFAULT 0")
db.execSQL("ALTER TABLE `files` ADD COLUMN `bytes_upload_attempts` INTEGER NOT NULL DEFAULT 0")
}
}
/**
* V2-2 : download persistant — `has_content_server` (miroir serveur) +
* `wanted_offline` (download demandé, reprise après reboot). Défauts
* FALSE : rien n'est présumé rapatriable ni demandé.
*/
private val MIGRATION_17_18 = object : Migration(17, 18) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `files` ADD COLUMN `has_content_server` INTEGER NOT NULL DEFAULT 0")
db.execSQL("ALTER TABLE `files` ADD COLUMN `wanted_offline` INTEGER NOT NULL DEFAULT 0")
}
}
val ALL: Array<Migration> = arrayOf( val ALL: Array<Migration> = arrayOf(
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18,
) )
} }
@@ -7,7 +7,11 @@ import com.squareup.moshi.Moshi
import com.kazier.mobile.data.remote.dto.ApiEnvelope import com.kazier.mobile.data.remote.dto.ApiEnvelope
import com.kazier.mobile.data.remote.dto.ApiErrorEnvelope import com.kazier.mobile.data.remote.dto.ApiErrorEnvelope
import com.kazier.mobile.data.remote.dto.ApiMeta import com.kazier.mobile.data.remote.dto.ApiMeta
import com.kazier.mobile.data.remote.dto.AddGroupMemberDto
import com.kazier.mobile.data.remote.dto.ChangePasswordDto import com.kazier.mobile.data.remote.dto.ChangePasswordDto
import com.kazier.mobile.data.remote.dto.CreateGroupDto
import com.kazier.mobile.data.remote.dto.GroupDto
import com.kazier.mobile.data.remote.dto.GroupMemberDto
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
import com.kazier.mobile.data.remote.dto.FileDto import com.kazier.mobile.data.remote.dto.FileDto
import com.kazier.mobile.data.remote.dto.FileOcrDto import com.kazier.mobile.data.remote.dto.FileOcrDto
@@ -17,8 +21,10 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
import com.kazier.mobile.data.remote.dto.LoginResponseDto import com.kazier.mobile.data.remote.dto.LoginResponseDto
import com.kazier.mobile.data.remote.dto.OcrJobDto import com.kazier.mobile.data.remote.dto.OcrJobDto
import com.kazier.mobile.data.remote.dto.OcrSubmitDto import com.kazier.mobile.data.remote.dto.OcrSubmitDto
import com.kazier.mobile.data.remote.dto.PlacementDto
import com.kazier.mobile.data.remote.dto.ResolvedUserDto import com.kazier.mobile.data.remote.dto.ResolvedUserDto
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
import com.kazier.mobile.data.remote.dto.ShareGrantDto
import com.kazier.mobile.data.remote.dto.ShareLinkDto import com.kazier.mobile.data.remote.dto.ShareLinkDto
import com.kazier.mobile.data.remote.dto.SyncOpDto import com.kazier.mobile.data.remote.dto.SyncOpDto
import com.kazier.mobile.data.remote.dto.SyncOpsRequest import com.kazier.mobile.data.remote.dto.SyncOpsRequest
@@ -161,6 +167,127 @@ class ApiClient @Inject constructor(
suspend fun getShareLink(token: String): ShareLinkDto = suspend fun getShareLink(token: String): ShareLinkDto =
unwrap({ apiService.getShareLink(token) }, skipUnauthorizedHandling = true) unwrap({ apiService.getShareLink(token) }, skipUnauthorizedHandling = true)
/**
* Grants actifs d'une ressource possédée — `GET /files/:id/shares`
* (owner uniquement, 404 sinon).
*/
suspend fun listShares(fileId: String): List<ShareGrantDto> =
unwrap({ apiService.listShares(fileId) })
/**
* Liens publics actifs d'une ressource possédée — `GET /files/:id/links`
* (owner uniquement, 404 sinon).
*/
suspend fun listLinks(fileId: String): List<ShareLinkDto> =
unwrap({ apiService.listLinks(fileId) })
/**
* Présence des octets d'une ressource possédée —
* `GET /files/:id/placements` (owner uniquement, 404 sinon, V2).
*/
suspend fun listPlacements(fileId: String): List<PlacementDto> =
unwrap({ apiService.listPlacements(fileId) })
/** Crée un groupe possédé (`POST /groups`). */
suspend fun createGroup(name: String): GroupDto =
unwrap({ apiService.createGroup(CreateGroupDto(name.trim())) })
/** Groupes possédés + rejoints (`GET /groups`). */
suspend fun listGroups(): List<GroupDto> =
unwrap({ apiService.listGroups() })
/** Ajoute un membre résolu (`POST /groups/:id/members`). */
suspend fun addGroupMember(groupId: String, userId: String): String =
unwrap({ apiService.addGroupMember(groupId, AddGroupMemberDto(userId)) }).id
/** Membres d'un groupe possédé (`GET /groups/:id/members`). */
suspend fun listGroupMembers(groupId: String): List<GroupMemberDto> =
unwrap({ apiService.listGroupMembers(groupId) })
/** Retire un membre (`DELETE /groups/:id/members/:userId`). */
suspend fun removeGroupMember(groupId: String, userId: String): String =
unwrap({ apiService.removeGroupMember(groupId, userId) }).id
/** Supprime un groupe possédé (`DELETE /groups/:id`). */
suspend fun deleteGroup(groupId: String): String =
unwrap({ apiService.deleteGroup(groupId) }).id
/**
* Octets physiques d'un fichier visible — `GET /files/:id/content`
* (binaire brut, hors enveloppe). Streaming sans cache : lecture bornée
* à [maxBytes] (+1 pour détecter le dépassement → `FILE_TOO_LARGE`),
* jamais persistée. 404 = invisible ou metadata-only sans octets.
*/
suspend fun downloadContentBytes(
fileId: String,
maxBytes: Long = MAX_CONTENT_BYTES,
): ByteArray {
val response = try {
apiService.downloadContent(fileId)
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
Timber.d(e, "api: transport error (content)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} catch (e: Exception) {
if (e is CancellationException) throw e
Timber.d(e, "api: unexpected error (content)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
}
if (!response.isSuccessful) {
val status = response.code()
if (status == 401) {
onUnauthorized?.invoke()
}
val error = response.errorBody()?.use { body ->
body.string().let { raw ->
runCatching { errorEnvelopeAdapter.fromJson(raw)?.error }.getOrNull()
}
}
throw ApiException(
code = error?.code ?: if (status == 404) "NOT_FOUND" else "HTTP_$status",
message = error?.message ?: "HTTP $status",
httpCode = status,
)
}
val body = response.body()
?: throw ApiException("INVALID_RESPONSE", "Réponse serveur invalide (corps vide)", response.code())
if (body.contentLength() > maxBytes) {
body.close()
throw ApiException("FILE_TOO_LARGE", "Fichier trop volumineux pour le streaming", response.code())
}
try {
body.byteStream().use { input ->
val out = java.io.ByteArrayOutputStream()
val buf = ByteArray(32 * 1024)
var total = 0L
while (true) {
val read = input.read(buf)
if (read < 0) break
total += read
if (total > maxBytes) {
throw ApiException("FILE_TOO_LARGE", "Fichier trop volumineux pour le streaming", response.code())
}
out.write(buf, 0, read)
}
return out.toByteArray()
}
} catch (e: ApiException) {
throw e
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} finally {
body.close()
}
}
companion object {
/** Borne streaming sans cache : 12 Mo (jamais en RAM au-delà). */
const val MAX_CONTENT_BYTES = 12 * 1024 * 1024L
}
private suspend fun <T> unwrap( private suspend fun <T> unwrap(
call: suspend () -> Response<ApiEnvelope<T>>, call: suspend () -> Response<ApiEnvelope<T>>,
skipUnauthorizedHandling: Boolean = false, skipUnauthorizedHandling: Boolean = false,
@@ -6,18 +6,25 @@ import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
import com.kazier.mobile.data.remote.dto.FileDto import com.kazier.mobile.data.remote.dto.FileDto
import com.kazier.mobile.data.remote.dto.FileOcrDto import com.kazier.mobile.data.remote.dto.FileOcrDto
import com.kazier.mobile.data.remote.dto.FolderDto import com.kazier.mobile.data.remote.dto.FolderDto
import com.kazier.mobile.data.remote.dto.AddGroupMemberDto
import com.kazier.mobile.data.remote.dto.CreateGroupDto
import com.kazier.mobile.data.remote.dto.GroupDto
import com.kazier.mobile.data.remote.dto.GroupMemberDto
import com.kazier.mobile.data.remote.dto.IdResultDto import com.kazier.mobile.data.remote.dto.IdResultDto
import com.kazier.mobile.data.remote.dto.LoginRequestDto import com.kazier.mobile.data.remote.dto.LoginRequestDto
import com.kazier.mobile.data.remote.dto.LoginResponseDto import com.kazier.mobile.data.remote.dto.LoginResponseDto
import com.kazier.mobile.data.remote.dto.OcrJobDto import com.kazier.mobile.data.remote.dto.OcrJobDto
import com.kazier.mobile.data.remote.dto.OcrSubmitDto import com.kazier.mobile.data.remote.dto.OcrSubmitDto
import com.kazier.mobile.data.remote.dto.PlacementDto
import com.kazier.mobile.data.remote.dto.ResolvedUserDto import com.kazier.mobile.data.remote.dto.ResolvedUserDto
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
import com.kazier.mobile.data.remote.dto.ShareGrantDto
import com.kazier.mobile.data.remote.dto.ShareLinkDto import com.kazier.mobile.data.remote.dto.ShareLinkDto
import com.kazier.mobile.data.remote.dto.SyncOpsRequest import com.kazier.mobile.data.remote.dto.SyncOpsRequest
import com.kazier.mobile.data.remote.dto.SyncOpsResult import com.kazier.mobile.data.remote.dto.SyncOpsResult
import okhttp3.MultipartBody import okhttp3.MultipartBody
import okhttp3.RequestBody import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Response import retrofit2.Response
import retrofit2.http.Body import retrofit2.http.Body
import retrofit2.http.DELETE import retrofit2.http.DELETE
@@ -28,6 +35,7 @@ import retrofit2.http.POST
import retrofit2.http.Part import retrofit2.http.Part
import retrofit2.http.Path import retrofit2.http.Path
import retrofit2.http.Query import retrofit2.http.Query
import retrofit2.http.Streaming
/** /**
* Contrat HTTP V1 — copie de `mobile/api/client.ts` (le client mobile est la * Contrat HTTP V1 — copie de `mobile/api/client.ts` (le client mobile est la
@@ -119,6 +127,18 @@ interface ApiService {
@Path("id") fileId: String, @Path("id") fileId: String,
): Response<ApiEnvelope<FileDto>> ): Response<ApiEnvelope<FileDto>>
/**
* Octets physiques d'un fichier visible (viewer+, own ou shared) —
* `GET /files/:id/content` (binaire brut, hors enveloppe `{data}`).
* Streaming lecture seule : le client ne persiste rien (V1 streaming).
* 404 = invisible OU metadata-only jamais uploadé (indistinguables).
*/
@Streaming
@GET("files/{id}/content")
suspend fun downloadContent(
@Path("id") fileId: String,
): Response<ResponseBody>
/** Suppression serveur d'un fichier possédé — `DELETE /files/:id`. */ /** Suppression serveur d'un fichier possédé — `DELETE /files/:id`. */
@DELETE("files/{id}") @DELETE("files/{id}")
suspend fun deleteFile( suspend fun deleteFile(
@@ -154,4 +174,68 @@ interface ApiService {
suspend fun getShareLink( suspend fun getShareLink(
@Path("token") token: String, @Path("token") token: String,
): Response<ApiEnvelope<ShareLinkDto>> ): Response<ApiEnvelope<ShareLinkDto>>
/**
* Grants actifs d'une ressource possédée (`GET /files/:id/shares`,
* owner uniquement — 404 sinon, pas d'énumération).
*/
@GET("files/{id}/shares")
suspend fun listShares(
@Path("id") fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>>
/**
* Liens publics actifs d'une ressource possédée (`GET /files/:id/links`,
* owner uniquement — même forme que `getShareLink`).
*/
@GET("files/{id}/links")
suspend fun listLinks(
@Path("id") fileId: String,
): Response<ApiEnvelope<List<ShareLinkDto>>>
/**
* Présence des octets d'une ressource possédée
* (`GET /files/:id/placements`, owner uniquement — entrée `server`
* implicite + reports devices, V2).
*/
@GET("files/{id}/placements")
suspend fun listPlacements(
@Path("id") fileId: String,
): Response<ApiEnvelope<List<PlacementDto>>>
/** Crée un groupe possédé (`POST /groups`). */
@POST("groups")
suspend fun createGroup(
@Body body: CreateGroupDto,
): Response<ApiEnvelope<GroupDto>>
/** Groupes possédés + rejoints (`GET /groups`). */
@GET("groups")
suspend fun listGroups(): Response<ApiEnvelope<List<GroupDto>>>
/** Ajoute un membre (owner du groupe, `POST /groups/:id/members`). */
@POST("groups/{id}/members")
suspend fun addGroupMember(
@Path("id") groupId: String,
@Body body: AddGroupMemberDto,
): Response<ApiEnvelope<IdResultDto>>
/** Membres d'un groupe possédé (`GET /groups/:id/members`). */
@GET("groups/{id}/members")
suspend fun listGroupMembers(
@Path("id") groupId: String,
): Response<ApiEnvelope<List<GroupMemberDto>>>
/** Retire un membre (`DELETE /groups/:id/members/:userId`). */
@DELETE("groups/{id}/members/{userId}")
suspend fun removeGroupMember(
@Path("id") groupId: String,
@Path("userId") userId: String,
): Response<ApiEnvelope<IdResultDto>>
/** Supprime un groupe possédé (`DELETE /groups/:id`). */
@DELETE("groups/{id}")
suspend fun deleteGroup(
@Path("id") groupId: String,
): Response<ApiEnvelope<IdResultDto>>
} }
@@ -0,0 +1,45 @@
package com.kazier.mobile.data.remote
import android.content.ContentResolver
import androidx.core.net.toUri
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okio.BufferedSink
import okio.source
/**
* Corps multipart paresseux lisant un flux SAF à l'écriture (jamais chargé
* en RAM) — partagé par l'upload OCR ciblé (`OcrRepository`) et l'upload
* générique V2 (`RemoteContentRepository`).
*/
internal class SafFileRequestBody(
private val contentResolver: ContentResolver,
private val uri: String,
private val length: Long,
private val mediaType: MediaType?,
) : RequestBody() {
override fun contentType(): MediaType? = mediaType
override fun contentLength(): Long = length
override fun writeTo(sink: BufferedSink) {
contentResolver.openInputStream(uri.toUri())?.use { stream ->
sink.writeAll(stream.source())
}
}
}
/** Construit la partie `file` multipart depuis une URI SAF + métadonnées. */
internal fun ContentResolver.safFilePart(
uri: String,
name: String,
size: Long,
mediaType: MediaType?,
): MultipartBody.Part =
MultipartBody.Part.createFormData(
"file",
name,
SafFileRequestBody(this, uri, size, mediaType),
)
@@ -45,6 +45,12 @@ data class FileDto(
@Json(name = "mimeType") val mimeType: String? = null, @Json(name = "mimeType") val mimeType: String? = null,
@Json(name = "folderId") val folderId: String? = null, @Json(name = "folderId") val folderId: String? = null,
@Json(name = "tags") val tags: List<String>? = null, @Json(name = "tags") val tags: List<String>? = null,
/**
* V2 : octets vus présents côté serveur (lazy healing — `FALSE` =
* jamais constatés, pas « certifié absent »). Persistance Room prévue
* en V2-2 (avec `wanted_offline`).
*/
@Json(name = "hasContent") val hasContent: Boolean = false,
@Json(name = "createdAt") val createdAt: String? = null, @Json(name = "createdAt") val createdAt: String? = null,
@Json(name = "updatedAt") val updatedAt: String? = null, @Json(name = "updatedAt") val updatedAt: String? = null,
) )
@@ -112,6 +118,60 @@ data class ShareLinkDto(
@Json(name = "expiresAt") val expiresAt: String? = null, @Json(name = "expiresAt") val expiresAt: String? = null,
) )
/**
* Entrée de présence `GET /files/:id/placements` (owner uniquement, V2) —
* miroir de `PlacementDTO` Go. L'entrée `server` est implicite (dérivée de
* `has_content`) ; les entrées devices viennent des reports `report_bytes`.
*/
data class PlacementDto(
@Json(name = "locationType") val locationType: String,
@Json(name = "deviceId") val deviceId: String? = null,
@Json(name = "hasBytes") val hasBytes: Boolean,
@Json(name = "updatedAt") val updatedAt: String? = null,
)
/**
* Grant actif `GET /files/:id/shares` (owner uniquement) — miroir de
* `ShareGrantDTO` Go. `expiresAt` en ms epoch (null = jamais), même
* convention que le snapshot `ResourcePermissionDto` pour les comparaisons
* locales (`System.currentTimeMillis()`). `granteeKind` = "user" | "group"
* (V2-6) ; `granteeUserId` porte l'id du principal, `username` son nom.
*/
data class ShareGrantDto(
@Json(name = "granteeUserId") val granteeUserId: String,
@Json(name = "granteeKind") val granteeKind: String = "user",
@Json(name = "username") val username: String,
@Json(name = "access") val access: String,
@Json(name = "inherit") val inherit: Boolean,
@Json(name = "expiresAt") val expiresAt: Long? = null,
@Json(name = "updatedAt") val updatedAt: Long = 0L,
)
/**
* Groupe V2-6 (`GET /groups`) — possédé ou rejoint (`role`).
*/
data class GroupDto(
@Json(name = "id") val id: String,
@Json(name = "name") val name: String,
@Json(name = "role") val role: String,
)
/** Membre d'un groupe (`GET /groups/:id/members`, owner). */
data class GroupMemberDto(
@Json(name = "id") val id: String,
@Json(name = "username") val username: String,
)
/** Création de groupe (`POST /groups`). */
data class CreateGroupDto(
@Json(name = "name") val name: String,
)
/** Ajout d'un membre (`POST /groups/:id/members`). */
data class AddGroupMemberDto(
@Json(name = "userId") val userId: String,
)
/** Outbox — une op du batch `POST /sync/ops` (docs/api-v1.md §6.1). */ /** Outbox — une op du batch `POST /sync/ops` (docs/api-v1.md §6.1). */
data class SyncOpDto( data class SyncOpDto(
@Json(name = "operation_id") val operationId: String, @Json(name = "operation_id") val operationId: String,
@@ -140,15 +200,19 @@ data class SyncFailedDto(
@Json(name = "message") val message: String, @Json(name = "message") val message: String,
) )
/** Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2). */ /**
* Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2, miroir de
* `ResourcePermission` Go : `sharedById *string`, `expiresAt *int64` ms epoch).
* M27 : typés (fini les `Any?` jamais lus) — lus par le cache et `canAccess`.
*/
data class ResourcePermissionDto( data class ResourcePermissionDto(
@Json(name = "resource_id") val resourceId: String, @Json(name = "resource_id") val resourceId: String,
@Json(name = "resourceType") val resourceType: String, @Json(name = "resourceType") val resourceType: String,
@Json(name = "effectiveAccess") val effectiveAccess: String, @Json(name = "effectiveAccess") val effectiveAccess: String,
@Json(name = "inherit") val inherit: Boolean, @Json(name = "inherit") val inherit: Boolean,
@Json(name = "ownerId") val ownerId: String? = null, @Json(name = "ownerId") val ownerId: String? = null,
@Json(name = "sharedById") val sharedById: Any? = null, @Json(name = "sharedById") val sharedById: String? = null,
@Json(name = "expiresAt") val expiresAt: Any? = null, @Json(name = "expiresAt") val expiresAt: Long? = null,
@Json(name = "cachedAt") val cachedAt: Long, @Json(name = "cachedAt") val cachedAt: Long,
@Json(name = "updatedAt") val updatedAt: Long, @Json(name = "updatedAt") val updatedAt: Long,
@Json(name = "name") val name: String = "", @Json(name = "name") val name: String = "",
@@ -2,6 +2,8 @@ package com.kazier.mobile.data.repository
import androidx.room.withTransaction import androidx.room.withTransaction
import com.kazier.mobile.data.local.AppDatabase import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.escapeLike
import com.kazier.mobile.data.local.normalizeSearch
import com.kazier.mobile.data.local.dao.FileDao import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.dao.FolderDao import com.kazier.mobile.data.local.dao.FolderDao
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
@@ -46,12 +48,20 @@ class FileRepository @Inject constructor(
/** Fichiers visibles de toute l'arborescence — écran d'accueil (grille par date). */ /** Fichiers visibles de toute l'arborescence — écran d'accueil (grille par date). */
fun observeAllVisible(): Flow<List<FileEntity>> = fileDao.observeAllVisible() fun observeAllVisible(): Flow<List<FileEntity>> = fileDao.observeAllVisible()
/** Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel). */ /**
fun searchFiles(query: String?, category: String?): Flow<List<FileEntity>> = * Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel).
fileDao.searchWithFilters( * m7 : la saisie est échappée (`%`/`_` littéraux, pas des jokers) ;
query = query?.trim()?.takeIf { it.isNotEmpty() }, * suivi accents : la saisie normalisée (`normalizeSearch`) matche
* « ÉTÉ » depuis « ete » (branche SQL dédiée, sans migration).
*/
fun searchFiles(query: String?, category: String?): Flow<List<FileEntity>> {
val trimmed = query?.trim()?.takeIf { it.isNotEmpty() }
return fileDao.searchWithFilters(
query = trimmed?.escapeLike(),
normQuery = trimmed?.normalizeSearch()?.escapeLike(),
category = category, category = category,
) )
}
/** Les `limit` fichiers les plus récents (date de référence), filtrés par catégorie. */ /** Les `limit` fichiers les plus récents (date de référence), filtrés par catégorie. */
fun recentFiles(category: String?, limit: Int = RECENT_LIMIT): Flow<List<FileEntity>> = fun recentFiles(category: String?, limit: Int = RECENT_LIMIT): Flow<List<FileEntity>> =
@@ -171,6 +181,10 @@ class FileRepository @Inject constructor(
suspend fun getAll(): List<FileEntity> = fileDao.getAll() suspend fun getAll(): List<FileEntity> = fileDao.getAll()
/** Lignes sous une racine SAF (m5) — voir `FolderRepository.getUnderRoot`. */
suspend fun getUnderRoot(rootUri: String): List<FileEntity> =
fileDao.getUnderRoot(rootUri, rootUri.escapeLike())
/** /**
* Upsert local d'un fichier SAF — miroir de `saveFile()` JS : déduplication * Upsert local d'un fichier SAF — miroir de `saveFile()` JS : déduplication
* par `resource_id` ou `uri`, conservation de l'identité/sync_status/owner. * par `resource_id` ou `uri`, conservation de l'identité/sync_status/owner.
@@ -359,11 +373,32 @@ class FileRepository @Inject constructor(
// de l'uri / de régression du placement). // de l'uri / de régression du placement).
syncStatus = SyncPlacement.confirmed(existing?.uri != null), syncStatus = SyncPlacement.confirmed(existing?.uri != null),
processed = existing?.processed ?: false, processed = existing?.processed ?: false,
// V2-2 : miroir serveur (converge vers la vérité lue) ; intention
// locale préservée (le serveur ne la connaît pas).
hasContentServer = dto.hasContent,
wantedOffline = existing?.wantedOffline ?: false,
addedAt = existing?.addedAt ?: now, addedAt = existing?.addedAt ?: now,
updatedAt = now, updatedAt = now,
) )
} }
/**
* Demande le rapatriement hors-ligne d'un fichier cloud-only (V2-2) :
* pose `wanted_offline`, drainé par `DownloadWorker` (reprise reboot).
* Faux si la ligne est absente, déjà locale ou déjà demandée.
*/
suspend fun requestOffline(resourceId: String): Boolean {
val file = fileDao.getByResourceId(resourceId) ?: return false
if (file.uri != null || file.exists == 0 || file.wantedOffline) return false
fileDao.setWantedOffline(resourceId, true, System.currentTimeMillis())
return true
}
/** Détache la copie locale (Room seul — le SAF est supprimé par l'appelant). */
suspend fun detachLocalCopy(resourceId: String) {
fileDao.detachLocalCopy(resourceId, System.currentTimeMillis())
}
companion object { companion object {
private const val PAGE_SIZE = 50 private const val PAGE_SIZE = 50
private const val RECENT_LIMIT = 5 private const val RECENT_LIMIT = 5
@@ -2,6 +2,7 @@ package com.kazier.mobile.data.repository
import androidx.room.withTransaction import androidx.room.withTransaction
import com.kazier.mobile.data.local.AppDatabase import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.escapeLike
import com.kazier.mobile.data.local.dao.FolderDao import com.kazier.mobile.data.local.dao.FolderDao
import com.kazier.mobile.data.local.entity.FolderEntity import com.kazier.mobile.data.local.entity.FolderEntity
import com.kazier.mobile.data.local.entity.FolderStatus import com.kazier.mobile.data.local.entity.FolderStatus
@@ -44,6 +45,13 @@ class FolderRepository @Inject constructor(
suspend fun getAll(): List<FolderEntity> = folderDao.getAll() suspend fun getAll(): List<FolderEntity> = folderDao.getAll()
/**
* Lignes sous une racine SAF (m5) : la racine est échappée pour le `LIKE`
* (les uris SAF contiennent des `%` d'encodage et parfois des `_`).
*/
suspend fun getUnderRoot(rootUri: String): List<FolderEntity> =
folderDao.getUnderRoot(rootUri, rootUri.escapeLike())
/** Snapshot des sous-dossiers visibles d'un dossier (opérations batch hors UI). */ /** Snapshot des sous-dossiers visibles d'un dossier (opérations batch hors UI). */
suspend fun getChildren(parentResourceId: String): List<FolderEntity> = suspend fun getChildren(parentResourceId: String): List<FolderEntity> =
folderDao.getByParentOnce(parentResourceId) folderDao.getByParentOnce(parentResourceId)
@@ -83,7 +91,8 @@ class FolderRepository @Inject constructor(
resourceId = dto.id, resourceId = dto.id,
uri = existing?.uri, uri = existing?.uri,
name = dto.name, name = dto.name,
exists = existing?.exists, // M13 : une ligne serveur nouvelle n'a pas d'`exists` local — 1 par défaut.
exists = existing?.exists ?: 1,
parentResourceId = dto.parentId, parentResourceId = dto.parentId,
ownerId = existing?.ownerId, ownerId = existing?.ownerId,
// Le snapshot serveur confirme la présence cloud : si une copie // Le snapshot serveur confirme la présence cloud : si une copie
@@ -144,7 +153,9 @@ class FolderRepository @Inject constructor(
resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(), resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(),
uri = input.uri, uri = input.uri,
name = input.name, name = input.name,
exists = input.exists?.let { if (it) 1 else 0 }, // M13 : `null` (défaut de `SaveFolderInput`) = présent, jamais NULL
// en base — sinon la ligne disparaît des requêtes `exists = 1`.
exists = if (input.exists != false) 1 else 0,
parentResourceId = effectiveParent, parentResourceId = effectiveParent,
// `owner_id` Room = user_id du compte actif, jamais l'identité device. // `owner_id` Room = user_id du compte actif, jamais l'identité device.
ownerId = ownerId ?: existing?.ownerId ?: activeUserStore.get(), ownerId = ownerId ?: existing?.ownerId ?: activeUserStore.get(),
@@ -1,23 +1,16 @@
package com.kazier.mobile.data.repository package com.kazier.mobile.data.repository
import android.content.ContentResolver
import android.content.Context import android.content.Context
import android.net.Uri
import androidx.core.net.toUri
import com.kazier.mobile.data.local.dao.FileDao import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.remote.ApiClient import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiException import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.remote.dto.OcrJobDto import com.kazier.mobile.data.remote.dto.OcrJobDto
import com.kazier.mobile.data.remote.dto.OcrJobStatus import com.kazier.mobile.data.remote.dto.OcrJobStatus
import com.kazier.mobile.data.remote.safFilePart
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okio.BufferedSink
import okio.source
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@@ -48,9 +41,9 @@ class OcrRepository @Inject constructor(
suspend fun ensurePhysical(file: FileEntity) { suspend fun ensurePhysical(file: FileEntity) {
val uri = file.uri ?: return val uri = file.uri ?: return
val mediaType = file.mimeType?.toMediaTypeOrNull() val mediaType = file.mimeType?.toMediaTypeOrNull()
val body = SafFileRequestBody(context.contentResolver, uri, file.size, mediaType) val part = context.contentResolver.safFilePart(uri, file.name, file.size, mediaType)
apiClient.uploadFile( apiClient.uploadFile(
file = MultipartBody.Part.createFormData("file", file.name, body), file = part,
resourceId = file.resourceId, resourceId = file.resourceId,
) )
} }
@@ -62,12 +55,27 @@ class OcrRepository @Inject constructor(
/** /**
* Poll toutes les 3 s (docs §5) jusqu'à l'état terminal. [onProgress] est * Poll toutes les 3 s (docs §5) jusqu'à l'état terminal. [onProgress] est
* appelé à chaque réponse du serveur (état courant exposé à l'UI). * appelé à chaque réponse du serveur (état courant exposé à l'UI).
*
* m20 : borné (deadline + nombre max de polls) — un job resté `processing`
* (stale claim serveur) levait sinon une coroutine tenue indéfiniment.
* Le timeout remonte en `ApiException("OCR_TIMEOUT")`, géré comme échec
* par les appelants (`processAuto` → `Failed`, viewer → message d'erreur).
*/ */
suspend fun poll(jobId: String, onProgress: (OcrJobDto) -> Unit = {}): OcrJobDto { suspend fun poll(
jobId: String,
timeoutMs: Long = POLL_TIMEOUT_MS,
onProgress: (OcrJobDto) -> Unit = {},
): OcrJobDto {
val deadline = System.currentTimeMillis() + timeoutMs
var polls = 0
while (true) { while (true) {
val job = apiClient.getOcrJob(jobId) val job = apiClient.getOcrJob(jobId)
onProgress(job) onProgress(job)
if (job.status in OcrJobStatus.TERMINAL) return job if (job.status in OcrJobStatus.TERMINAL) return job
polls++
if (polls >= POLL_MAX_ATTEMPTS || System.currentTimeMillis() >= deadline) {
throw ApiException("OCR_TIMEOUT", "OCR sans réponse (job $jobId)", 0)
}
delay(POLL_INTERVAL_MS) delay(POLL_INTERVAL_MS)
} }
} }
@@ -144,6 +152,9 @@ class OcrRepository @Inject constructor(
companion object { companion object {
const val POLL_INTERVAL_MS = 3_000L const val POLL_INTERVAL_MS = 3_000L
/** Timeout du poll (m20) : 10 min ≈ 200 polls × 3 s. */
const val POLL_TIMEOUT_MS = 10 * 60 * 1_000L
const val POLL_MAX_ATTEMPTS = 200
} }
} }
@@ -161,26 +172,3 @@ sealed interface OcrAutoOutcome {
/** Token expiré/révoqué : le re-login passera par l'UI. */ /** Token expiré/révoqué : le re-login passera par l'UI. */
data object Unauthorized : OcrAutoOutcome data object Unauthorized : OcrAutoOutcome
} }
/**
* `RequestBody` paresseux : le flux SAF est ouvert à l'écriture (multipart),
* jamais chargé en mémoire — les fichiers jusqu'à `MAX_FILE_SIZE_MB` restent
* gérables.
*/
private class SafFileRequestBody(
private val contentResolver: ContentResolver,
private val uri: String,
private val length: Long,
private val mediaType: MediaType?,
) : RequestBody() {
override fun contentType(): MediaType? = mediaType
override fun contentLength(): Long = length
override fun writeTo(sink: BufferedSink) {
contentResolver.openInputStream(uri.toUri())?.use { stream ->
sink.writeAll(stream.source())
}
}
}
@@ -112,13 +112,15 @@ class OutboxRepository @Inject constructor(
) )
/** /**
* Raccourci `share` — payload `{ granteeUserId, access }` (voir * Raccourci `share` — payload `{ granteeUserId|granteeGroupId, access }`
* docs/api-v1.md §6.1). `access`: viewer | commenter | editor. * (voir docs/api-v1.md §6.1). `access`: viewer | commenter | editor.
* Exactement un principal (le serveur rejette sinon).
*/ */
suspend fun enqueueShare( suspend fun enqueueShare(
resourceId: String, resourceId: String,
resourceType: String, resourceType: String,
granteeUserId: String, granteeUserId: String? = null,
granteeGroupId: String? = null,
access: String, access: String,
inherit: Boolean = true, inherit: Boolean = true,
expiresAt: Long? = null, expiresAt: Long? = null,
@@ -127,7 +129,8 @@ class OutboxRepository @Inject constructor(
resourceId = resourceId, resourceId = resourceId,
resourceType = resourceType, resourceType = resourceType,
payload = buildMap { payload = buildMap {
put("granteeUserId", granteeUserId) granteeUserId?.let { put("granteeUserId", it) }
granteeGroupId?.let { put("granteeGroupId", it) }
put("access", access) put("access", access)
put("inherit", inherit) put("inherit", inherit)
expiresAt?.let { put("expiresAt", it) } expiresAt?.let { put("expiresAt", it) }
@@ -146,9 +149,108 @@ class OutboxRepository @Inject constructor(
payload = mapOf("granteeUserId" to granteeUserId), payload = mapOf("granteeUserId" to granteeUserId),
) )
/**
* Raccourci `update_metadata` — payload `{ name }` (rename d'une ressource
* partagée, `editor+`, docs/api-v1.md §6.1). m21 : rend le rename partagé
* émissible — l'op n'avait aucun écrivain côté client.
*/
suspend fun enqueueUpdateMetadata(
resourceId: String,
resourceType: String,
name: String,
): String = enqueue(
operation = PendingOperationType.UPDATE_METADATA,
resourceId = resourceId,
resourceType = resourceType,
payload = mapOf("name" to name),
)
/**
* Raccourci `update_share` — même payload que `share` (m21 : update d'un
* partage existant inopérant sans écrivain). Principal user ou groupe.
*/
suspend fun enqueueUpdateShare(
resourceId: String,
resourceType: String,
granteeUserId: String? = null,
granteeGroupId: String? = null,
access: String,
inherit: Boolean = true,
expiresAt: Long? = null,
): String = enqueue(
operation = PendingOperationType.UPDATE_SHARE,
resourceId = resourceId,
resourceType = resourceType,
payload = buildMap {
granteeUserId?.let { put("granteeUserId", it) }
granteeGroupId?.let { put("granteeGroupId", it) }
put("access", access)
put("inherit", inherit)
expiresAt?.let { put("expiresAt", it) }
},
)
/**
* Raccourci `create_link` — payload `{ token, access, expiresAt? }`
* (m21 : liens publics inopérants sans écrivain). Le `token` 32-hex est
* généré côté client (`GenerateId`) : c'est l'identifiant du lien.
*/
suspend fun enqueueCreateLink(
resourceId: String,
resourceType: String,
token: String,
access: String,
expiresAt: Long? = null,
): String = enqueue(
operation = PendingOperationType.CREATE_LINK,
resourceId = resourceId,
resourceType = resourceType,
payload = buildMap {
put("token", token)
put("access", access)
expiresAt?.let { put("expiresAt", it) }
},
)
/** Raccourci `revoke_link` — payload `{ token }` (m21). */
suspend fun enqueueRevokeLink(
resourceId: String,
resourceType: String,
token: String,
): String = enqueue(
operation = PendingOperationType.REVOKE_LINK,
resourceId = resourceId,
resourceType = resourceType,
payload = mapOf("token" to token),
)
/**
* Raccourci `report_bytes` — payload `{ hasBytes }` (V2 placements).
* Uniquement sur changement d'état réel (upload/download/release/delete
* locale) : le serveur exige un `operation_id` frais par état (A9) et
* l'échec est dead-letter sans bloquer la file.
*/
suspend fun enqueueReportBytes(
resourceId: String,
resourceType: String,
hasBytes: Boolean,
): String = enqueue(
operation = PendingOperationType.REPORT_BYTES,
resourceId = resourceId,
resourceType = resourceType,
payload = mapOf("hasBytes" to hasBytes),
)
/** Nombre d'ops en attente de push (stats UI optionnelles). */ /** Nombre d'ops en attente de push (stats UI optionnelles). */
suspend fun countPending(): Int = pendingOperationDao.countPending() suspend fun countPending(): Int = pendingOperationDao.countPending()
/**
* Ops de partage en attente pour une ressource (sheet de partage :
* « en attente d'envoi », pas encore reflétées par les listes serveur).
*/
suspend fun pendingShareOps(resourceId: String): List<PendingOperationEntity> =
pendingOperationDao.pendingShareOps(resourceId)
/** /**
* Un `create_resource` (pending ou synced) existe-t-il déjà pour ce fichier ? * Un `create_resource` (pending ou synced) existe-t-il déjà pour ce fichier ?
* Utilisé par le gate « processed » : seuls les fichiers traités déclenchent * Utilisé par le gate « processed » : seuls les fichiers traités déclenchent
@@ -0,0 +1,212 @@
package com.kazier.mobile.data.repository
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.dao.FolderDao
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.preferences.DefaultRootStore
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.remote.safFilePart
import com.kazier.mobile.features.saf.SafUris
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
/**
* Contenu distant en streaming (V1 finitions, lot download).
*
* Lit les octets physiques d'un fichier visible via
* `GET /files/:id/content` (binaire brut, hors enveloppe) sans jamais les
* persister : ni Room, ni SAF, ni fichier durable. Seul le rendu PDF exige
* un fichier temporaire du `cacheDir`, créé à la volée par le viewer et
* supprimé à sa sortie (éphémère, pas un cache).
*
* Upload générique V2 ([upload]) : pousse les octets SAF vers le
* `resource_id` serveur déjà connu (métadonnées synced) via l'upload ciblé
* `POST /files/upload` — même pipeline que l'OCR, hors outbox.
*/
@Singleton
class RemoteContentRepository @Inject constructor(
private val apiClient: ApiClient,
private val fileDao: FileDao,
private val folderDao: FolderDao,
private val defaultRootStore: DefaultRootStore,
private val outboxRepository: OutboxRepository,
@ApplicationContext private val context: Context,
) {
/** Octets du fichier, bornés ([ApiClient.MAX_CONTENT_BYTES]). */
suspend fun fetch(fileId: String): ByteArray =
apiClient.downloadContentBytes(fileId)
/**
* Pousse les octets locaux vers le serveur (overwrite ciblé idempotent).
* Succès → `bytes_uploaded = 1` + report `hasBytes = true` (V2
* placements, état frais) ; 4xx (trop gros, rejeté) → +1 tentative
* (cap 3, le worker passe au suivant) ; réseau/5xx → `Retryable` sans
* toucher au compteur ; 401 → `Unauthorized` (re-login via l'UI).
*/
suspend fun upload(file: FileEntity): BytesUploadOutcome {
val uri = file.uri ?: return BytesUploadOutcome.Failed.also {
fileDao.markBytesUploadFailure(file.resourceId, System.currentTimeMillis())
}
return try {
val part = context.contentResolver.safFilePart(
uri, file.name, file.size, file.mimeType?.toMediaTypeOrNull(),
)
apiClient.uploadFile(file = part, resourceId = file.resourceId)
fileDao.markBytesUploaded(file.resourceId, System.currentTimeMillis())
outboxRepository.enqueueReportBytes(file.resourceId, "file", true)
BytesUploadOutcome.Done
} catch (e: ApiException) {
when {
e.code == "NETWORK_ERROR" || e.httpCode >= 500 -> BytesUploadOutcome.Retryable
e.httpCode == 401 -> BytesUploadOutcome.Unauthorized
else -> {
fileDao.markBytesUploadFailure(file.resourceId, System.currentTimeMillis())
BytesUploadOutcome.Failed
}
}
} catch (e: Exception) {
fileDao.markBytesUploadFailure(file.resourceId, System.currentTimeMillis())
BytesUploadOutcome.Failed
}
}
suspend fun download(
file: FileEntity,
write: (suspend (folderUri: String, name: String, mime: String, bytes: ByteArray) -> String?)? = null,
): DownloadOutcome {
val now = System.currentTimeMillis()
// Cible : dossier propre s'il a une URI SAF, sinon racine par défaut.
// Aucun des deux → demande soldée (l'utilisateur retentera plus tard).
val target = resolveDownloadTarget(file)
if (target == null) {
fileDao.setWantedOffline(file.resourceId, false, now)
return DownloadOutcome.NoLocalFolder
}
val bytes = try {
apiClient.downloadContentBytes(file.resourceId)
} catch (e: ApiException) {
return when {
e.code == "NOT_FOUND" -> {
// Pas d'octets serveur : solder + converger le miroir.
fileDao.setWantedOffline(file.resourceId, false, now)
fileDao.setHasContentServer(file.resourceId, false, now)
DownloadOutcome.NoContent
}
e.code == "NETWORK_ERROR" || e.httpCode >= 500 -> DownloadOutcome.Retryable
e.httpCode == 401 -> DownloadOutcome.Unauthorized
else -> {
fileDao.setWantedOffline(file.resourceId, false, now)
DownloadOutcome.Failed
}
}
} catch (e: Exception) {
Timber.w(e, "download: unexpected fetch failure for %s", file.resourceId)
return DownloadOutcome.Retryable
}
val mime = file.mimeType?.takeIf { it.isNotBlank() } ?: "application/octet-stream"
val createdUri = try {
write?.invoke(target.uri, file.name, mime, bytes)
?: writeDownloadedBytes(target.uri, file.name, mime, bytes)
} catch (e: Exception) {
Timber.w(e, "download: write failed for %s", file.resourceId)
null
}
if (createdUri == null) return DownloadOutcome.Retryable
fileDao.attachDownloaded(file.resourceId, createdUri, target.folderId, bytes.size.toLong(), now)
outboxRepository.enqueueReportBytes(file.resourceId, "file", true)
return DownloadOutcome.Done
}
/** Dossier d'accueil SAF : dossier propre, sinon racine par défaut. */
private suspend fun resolveDownloadTarget(file: FileEntity): DownloadTarget? {
folderDao.getByResourceId(file.folderResourceId)?.uri?.let {
return DownloadTarget(it, file.folderResourceId)
}
val rootId = defaultRootStore.get() ?: return null
val rootUri = folderDao.getByResourceId(rootId)?.uri ?: return null
return DownloadTarget(rootUri, rootId)
}
/** Écriture SAF réelle : createDocument + copie + permission persistante. */
private suspend fun writeDownloadedBytes(
folderUri: String,
name: String,
mime: String,
bytes: ByteArray,
): String? = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val parent = SafUris.toDocumentUri(folderUri) ?: error("bad folder uri")
val created = DocumentsContract.createDocument(resolver, parent, mime, name)
?: error("cannot create document")
resolver.openOutputStream(created)?.use { it.write(bytes) }
?: error("cannot open output stream")
runCatching {
resolver.takePersistableUriPermission(
created,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
)
}
created.toString()
}.getOrNull()
}
private data class DownloadTarget(val uri: String, val folderId: String)
}
/** Résultat d'une passe de download V2 (un fichier max). */
sealed interface DownloadOutcome {
/** Rattaché : `uri` posée, `local-cloud`, demande soldée. */
data object Done : DownloadOutcome
/** Pas d'octets serveur : demande soldée, miroir convergé à 0. */
data object NoContent : DownloadOutcome
/** Aucun dossier SAF local (ni propre ni racine) : demande soldée. */
data object NoLocalFolder : DownloadOutcome
/** Erreur permanente (autre 4xx) : demande soldée. */
data object Failed : DownloadOutcome
/** Erreur transitoire : demande conservée, à retenter via backoff. */
data object Retryable : DownloadOutcome
/** Token expiré/révoqué : le re-login passera par l'UI. */
data object Unauthorized : DownloadOutcome
}
/** Résultat d'une passe d'upload V2 (un fichier max). */
sealed interface BytesUploadOutcome {
/** Octets confirmés serveur : `bytes_uploaded = 1`. */
data object Done : BytesUploadOutcome
/** Erreur permanente : `bytes_upload_attempts` incrémenté. */
data object Failed : BytesUploadOutcome
/** Erreur transitoire : à retenter via backoff WorkManager. */
data object Retryable : BytesUploadOutcome
/** Token expiré/révoqué : le re-login passera par l'UI. */
data object Unauthorized : BytesUploadOutcome
}
/**
* Rapatrie durablement un fichier cloud-only vers SAF (V2-2) : octets
* téléchargés puis écrits comme nouveau document dans son dossier s'il a
* une URI SAF, sinon dans la racine par défaut. La ligne est rattachée
* (même `resource_id`, `local-cloud`, `processed`) — le walk converge par
* `uri` (index unique), pas de doublon ni de review.
*
* `write` est un seam de test : écrit les octets et retourne l'URI créée,
* ou null si l'écriture échoue. Null (défaut) = vraie écriture SAF.
*/
@@ -4,11 +4,15 @@ import androidx.room.withTransaction
import com.kazier.mobile.data.local.AppDatabase import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.dao.FileDao import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.dao.FolderDao import com.kazier.mobile.data.local.dao.FolderDao
import com.kazier.mobile.data.local.entity.AccessRank
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FolderEntity import com.kazier.mobile.data.local.entity.FolderEntity
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
import com.kazier.mobile.data.remote.ApiClient import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
import com.kazier.mobile.domain.ActiveUserStore import com.kazier.mobile.domain.ActiveUserStore
import com.kazier.mobile.domain.PrefKeys
import com.kazier.mobile.domain.SyncPlacement import com.kazier.mobile.domain.SyncPlacement
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@@ -21,8 +25,17 @@ import javax.inject.Singleton
* de l'utilisateur. Les ressources non possédées (viewer/commenter/editor) * de l'utilisateur. Les ressources non possédées (viewer/commenter/editor)
* sont importées en tant que lignes cloud-only (`uri = NULL`, `sync_status = "cloud"`). * sont importées en tant que lignes cloud-only (`uri = NULL`, `sync_status = "cloud"`).
* *
* Un pull complet (`after=0`) est effectué au login et à la restauration de * M27 — delta, expiration et `canAccess` :
* session pour garantir la convergence (révocations = disparition du snapshot). * - le `cachedAt` du dernier pull est persisté (`user_preferences`) : pull
* complet (`after = null`) au premier appel, au login/restauration
* (`forceFull = true`) et quand le cache dépasse le TTL 24h ; delta
* (`after = cachedAt`) sinon — la convergence (lignes absentes = révoquées)
* ne tourne que sur pull complet ;
* - chaque grant non-owner est persisté en `resource_permissions` (rang,
* expiration, fraîcheur) : un grant expiré (`expiresAt` passé) masque la
* ligne locale au lieu de rester visible jusqu'au prochain login ;
* - [canAccess] répond offline (ownership local, puis rang persisté, avec
* downgrade lecture seule après TTL sans reseed).
*/ */
@Singleton @Singleton
class ShareRepository @Inject constructor( class ShareRepository @Inject constructor(
@@ -32,31 +45,60 @@ class ShareRepository @Inject constructor(
) { ) {
/** /**
* Récupère le snapshot complet des permissions et hydrate Room. * Récupère le snapshot des permissions et hydrate Room + le cache.
* *
* Pour chaque permission non-owner : * Pour chaque permission non-owner non expirée :
* - Folders : upsert cloud-only (uri=null, name, parentId, ownerId) * - Folders : upsert cloud-only (uri=null, name, parentId, ownerId)
* - Files : upsert cloud-only (uri=null, name, folderResourceId, ownerId, processed=true) * - Files : upsert cloud-only (uri=null, name, folderResourceId, ownerId, processed=true)
* *
* Convergence : les lignes cloud-only absentes du snapshot complet sont * Convergence (pull complet uniquement) : les lignes cloud-only absentes
* marquées `exists = 0`. * du snapshot complet sont marquées `exists = 0`, et les grants du cache
* absents sont oubliés.
*/ */
suspend fun syncSnapshot() { suspend fun syncSnapshot(forceFull: Boolean = false) {
// `ownerId` serveur = user_id : comparer au compte actif, jamais au device. // `ownerId` serveur = user_id : comparer au compte actif, jamais au device.
val currentUserId = activeUserStore.get() val currentUserId = activeUserStore.get()
val permissions = apiClient.syncPermissions() val prefs = appDatabase.userPreferenceDao()
val permDao = appDatabase.resourcePermissionDao()
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val cachedAt = prefs.getValue(PrefKeys.PERMISSIONS_CACHED_AT)?.toLongOrNull()
val full = forceFull || cachedAt == null || now - cachedAt > PERMISSION_TTL_MS
val permissions = apiClient.syncPermissions(if (full) null else cachedAt)
val folderDao = appDatabase.folderDao() val folderDao = appDatabase.folderDao()
val fileDao = appDatabase.fileDao() val fileDao = appDatabase.fileDao()
val snapshotFolderIds = mutableSetOf<String>() val snapshotFolderIds = mutableSetOf<String>()
val snapshotFileIds = mutableSetOf<String>() val snapshotFileIds = mutableSetOf<String>()
val snapshotPermIds = mutableSetOf<String>()
appDatabase.withTransaction { appDatabase.withTransaction {
for (perm in permissions) { for (perm in permissions) {
if (perm.effectiveAccess == "owner") continue
snapshotPermIds += perm.resourceId
permDao.upsertAll(
listOf(
ResourcePermissionEntity(
resourceId = perm.resourceId,
resourceType = perm.resourceType,
effectiveAccess = perm.effectiveAccess,
ownerId = perm.ownerId,
sharedById = perm.sharedById,
expiresAt = perm.expiresAt,
// Fraîcheur = heure locale du pull (M27) : le TTL
// mesure « 24h sans reseed », pas l'horloge serveur
// (skew). `perm.cachedAt` sert au delta `after`.
cachedAt = now,
updatedAt = perm.updatedAt,
),
),
)
if (isExpired(perm.expiresAt, now)) {
// Grant expiré : masquer la ligne locale au lieu d'hydrater.
markSharedMissing(perm.resourceId, perm.resourceType, currentUserId, now, folderDao, fileDao)
continue
}
when { when {
perm.effectiveAccess == "owner" -> Unit
perm.resourceType == "folder" -> { perm.resourceType == "folder" -> {
snapshotFolderIds += perm.resourceId snapshotFolderIds += perm.resourceId
upsertSharedFolder(perm, now, folderDao) upsertSharedFolder(perm, now, folderDao)
@@ -68,6 +110,7 @@ class ShareRepository @Inject constructor(
} }
} }
if (full) {
// Convergence : marquer les lignes cloud-only d'autrui absentes du // Convergence : marquer les lignes cloud-only d'autrui absentes du
// snapshot comme disparues (révocation / expiration côté serveur). // snapshot comme disparues (révocation / expiration côté serveur).
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le // Sans compte actif, impossible d'attribuer : ne rien masquer. Le
@@ -89,15 +132,96 @@ class ShareRepository @Inject constructor(
fileDao.markMissing(file.resourceId, now) fileDao.markMissing(file.resourceId, now)
} }
} }
// Oublie les grants du cache absents du snapshot complet.
if (snapshotPermIds.isEmpty()) {
permDao.clear()
} else {
permDao.deleteNotIn(snapshotPermIds.toList())
}
}
// Grants périmés connus du cache (delta ou TTL) : masquer localement.
for (expired in permDao.getExpired(now)) {
markSharedMissing(expired.resourceId, expired.resourceType, currentUserId, now, folderDao, fileDao)
}
prefs.upsert(
UserPreferenceEntity(
PrefKeys.PERMISSIONS_CACHED_AT,
now.toString(),
now,
),
)
} }
Timber.d( Timber.d(
"syncSnapshot: hydrated %d folders, %d files", "syncSnapshot: hydrated %d folders, %d files (full=%s)",
snapshotFolderIds.size, snapshotFolderIds.size,
snapshotFileIds.size, snapshotFileIds.size,
full,
) )
} }
/**
* Droit offline sur une ressource (docs/api-v1.md §6.2) : ownership local
* d'abord (`owner` implique tout), sinon rang persisté du snapshot.
* Grant expiré → refusé ; snapshot périmé (TTL 24h sans reseed) →
* downgrade lecture seule (`viewer` exigé au plus).
*/
suspend fun canAccess(resourceId: String, required: String = AccessRank.VIEWER): Boolean {
val requiredRank = AccessRank.rank(required)
if (requiredRank <= 0) return false
val currentUserId = activeUserStore.get()
val now = System.currentTimeMillis()
if (currentUserId != null) {
val folderOwner = appDatabase.folderDao().getByResourceId(resourceId)?.ownerId
val fileOwner = if (folderOwner == null) {
appDatabase.fileDao().getByResourceId(resourceId)?.ownerId
} else {
null
}
if (folderOwner == currentUserId || fileOwner == currentUserId) return true
}
val perm = appDatabase.resourcePermissionDao().getByResourceId(resourceId) ?: return false
if (isExpired(perm.expiresAt, now)) return false
val effective = if (now - perm.cachedAt > PERMISSION_TTL_MS) {
// Stale : downgrade lecture seule.
minOf(AccessRank.rank(perm.effectiveAccess), AccessRank.rank(AccessRank.VIEWER))
} else {
AccessRank.rank(perm.effectiveAccess)
}
return effective >= requiredRank
}
private fun isExpired(expiresAt: Long?, now: Long): Boolean =
expiresAt != null && expiresAt <= now
/**
* Masque une ligne partagée cloud-only d'autrui (`exists = 0`) — jamais
* une copie physique locale ni une ressource possédée.
*/
private suspend fun markSharedMissing(
resourceId: String,
resourceType: String,
currentUserId: String?,
now: Long,
folderDao: FolderDao,
fileDao: FileDao,
) {
if (currentUserId == null) return
if (resourceType == "folder") {
val folder = folderDao.getByResourceId(resourceId) ?: return
if (isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists)) {
folderDao.markMissing(resourceId, now)
}
} else {
val file = fileDao.getByResourceId(resourceId) ?: return
if (isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists)) {
fileDao.markMissing(resourceId, now)
}
}
}
/** /**
* Ligne hébergée cloud (uri NULL), non possédée localement, encore visible. * Ligne hébergée cloud (uri NULL), non possédée localement, encore visible.
* Absente du snapshot → ressource partagée révoquée/expirée → marquer disparue. * Absente du snapshot → ressource partagée révoquée/expirée → marquer disparue.
@@ -159,9 +283,18 @@ class ShareRepository @Inject constructor(
ownerId = perm.ownerId ?: existing?.ownerId, ownerId = perm.ownerId ?: existing?.ownerId,
syncStatus = SyncPlacement.confirmed(false), syncStatus = SyncPlacement.confirmed(false),
processed = true, processed = true,
// V2-2 : le snapshot ne dit rien des octets ni de l'intention
// locale — préserver, jamais écraser.
hasContentServer = existing?.hasContentServer ?: false,
wantedOffline = existing?.wantedOffline ?: false,
addedAt = existing?.addedAt ?: now, addedAt = existing?.addedAt ?: now,
updatedAt = now, updatedAt = now,
) )
fileDao.upsert(entity) fileDao.upsert(entity)
} }
companion object {
/** TTL du snapshot permissions (docs/api-v1.md §6.2) : 24h. */
const val PERMISSION_TTL_MS = 24 * 60 * 60 * 1000L
}
} }
@@ -6,6 +6,7 @@ import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.dao.FileDao import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.dao.FolderDao import com.kazier.mobile.data.local.dao.FolderDao
import com.kazier.mobile.data.local.dao.PendingOperationDao import com.kazier.mobile.data.local.dao.PendingOperationDao
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
import com.kazier.mobile.data.local.dao.ScanDao import com.kazier.mobile.data.local.dao.ScanDao
import com.kazier.mobile.data.local.dao.UserPreferenceDao import com.kazier.mobile.data.local.dao.UserPreferenceDao
import com.kazier.mobile.data.local.migration.Migrations import com.kazier.mobile.data.local.migration.Migrations
@@ -25,6 +26,13 @@ object DatabaseModule {
fun provideDatabase(@ApplicationContext context: Context): AppDatabase = fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
Room.databaseBuilder(context, AppDatabase::class.java, "dot.db") Room.databaseBuilder(context, AppDatabase::class.java, "dot.db")
.addMigrations(*Migrations.ALL) .addMigrations(*Migrations.ALL)
// m15 : un APK plus ancien que la DB (downgrade) ne doit plus
// crasher en `IllegalStateException` brut — reconstruction
// destructive documentée : le miroir SAF se reconstruit au walk
// suivant, les données serveur restent la source de vérité.
// Perte acceptée : l'outbox non poussée (mutations locales) —
// cas rare (rollback d'APK), préféré au crash au démarrage.
.fallbackToDestructiveMigrationOnDowngrade()
.build() .build()
@Provides @Provides
@@ -41,4 +49,7 @@ object DatabaseModule {
@Provides @Provides
fun provideScanDao(db: AppDatabase): ScanDao = db.scanDao() fun provideScanDao(db: AppDatabase): ScanDao = db.scanDao()
@Provides
fun provideResourcePermissionDao(db: AppDatabase): ResourcePermissionDao = db.resourcePermissionDao()
} }
@@ -8,4 +8,8 @@ object PrefKeys {
const val SYNC_MODE = "sync_mode" const val SYNC_MODE = "sync_mode"
const val THEME = "theme" const val THEME = "theme"
const val SERVER_URL = "server_url" const val SERVER_URL = "server_url"
/** Dernier pull `GET /sync/permissions` réussi, ms epoch (M27 : delta + TTL 24h). */
const val PERMISSIONS_CACHED_AT = "permissions_cached_at"
/** Règle de rétention locale V2-5 : `all` | `last_months:N`. */
const val RETENTION_RULE = "retention_rule"
} }
@@ -0,0 +1,33 @@
package com.kazier.mobile.domain
/**
* Règle de rétention locale V2-5 (libération auto d'espace) — syntaxe
* `retention_rule` du modèle V2 (`V2.md` §3.6), sous-ensemble implémenté :
* tout garder, ou N derniers mois. Appliquée par `RetentionWorker`
* (purge sûre : seuls les fichiers dont le serveur a les octets partent).
*/
sealed interface RetentionRule {
data object KeepAll : RetentionRule
data class LastMonths(val months: Int) : RetentionRule
/** Forme stockée (`user_preferences`) : `all` | `last_months:N`. */
val stored: String
get() = when (this) {
is KeepAll -> "all"
is LastMonths -> "last_months:$months"
}
companion object {
val OPTIONS = listOf(KeepAll, LastMonths(3), LastMonths(6), LastMonths(12))
fun parse(stored: String?): RetentionRule {
if (stored == null) return KeepAll
if (stored == "all") return KeepAll
val months = stored.removePrefix("last_months:").toIntOrNull()
if (stored.startsWith("last_months:") && months != null && months > 0) {
return LastMonths(months)
}
return KeepAll
}
}
}
@@ -0,0 +1,43 @@
package com.kazier.mobile.domain
import com.kazier.mobile.data.local.dao.UserPreferenceDao
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* Règle de rétention locale (V2-5) : `all` par défaut, chargée une fois
* depuis `user_preferences` puis exposée en [StateFlow] (même discipline
* que [ThemePreferenceStore]).
*/
@Singleton
class RetentionStore @Inject constructor(
private val userPreferenceDao: UserPreferenceDao,
) {
private val loaded = AtomicBoolean(false)
private val _rule = MutableStateFlow<RetentionRule>(RetentionRule.KeepAll)
val rule: StateFlow<RetentionRule> = _rule.asStateFlow()
/** Charge la valeur persistée au boot (idempotent). */
suspend fun load() {
if (!loaded.compareAndSet(false, true)) return
_rule.value = RetentionRule.parse(userPreferenceDao.getValue(PrefKeys.RETENTION_RULE))
}
/** Lecture directe (workers hors UI, sans passer par le flow). */
suspend fun current(): RetentionRule =
RetentionRule.parse(userPreferenceDao.getValue(PrefKeys.RETENTION_RULE))
suspend fun set(rule: RetentionRule) {
userPreferenceDao.upsert(
UserPreferenceEntity(PrefKeys.RETENTION_RULE, rule.stored, System.currentTimeMillis()),
)
_rule.value = rule
}
}
@@ -8,6 +8,7 @@ import androidx.room.withTransaction
import com.kazier.mobile.data.local.AppDatabase import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus import com.kazier.mobile.data.local.entity.FileStatus
import com.kazier.mobile.data.local.entity.isReleasable
import com.kazier.mobile.data.repository.FileRepository import com.kazier.mobile.data.repository.FileRepository
import com.kazier.mobile.data.repository.OutboxRepository import com.kazier.mobile.data.repository.OutboxRepository
import com.kazier.mobile.features.thumbnails.ThumbnailStore import com.kazier.mobile.features.thumbnails.ThumbnailStore
@@ -71,6 +72,8 @@ class FileDeleter @Inject constructor(
if (deleted) { if (deleted) {
fileRepository.markMissing(file.resourceId, System.currentTimeMillis()) fileRepository.markMissing(file.resourceId, System.currentTimeMillis())
thumbnailStore.delete(file.resourceId) thumbnailStore.delete(file.resourceId)
// Octets partis : le serveur doit l'apprendre (V2 placements).
outboxRepository.enqueueReportBytes(file.resourceId, "file", false)
Timber.d("deleted locally %s", uri) Timber.d("deleted locally %s", uri)
} else { } else {
Timber.w("deleteDocument returned false for %s", uri) Timber.w("deleteDocument returned false for %s", uri)
@@ -81,13 +84,18 @@ class FileDeleter @Inject constructor(
} }
/** /**
* Suppression cloud uniquement (outbox `delete_resource`). * Suppression cloud uniquement (outbox `delete_resource` + tombstone locale).
* Le fichier local n\'est pas touché. N\'a de sens que si la ressource a * Le fichier physique local n'est pas touché, mais la ligne Room passe
* déjà été poussée (gate « processed » : un fichier jamais envoyé est no-op). * `exists = 0` dans la MÊME transaction (M5) : sans ça la ressource restait
* affichée, le walk la revoyait et `refreshFromServer` ne supprime jamais
* de lignes → fantôme local vs serveur supprimé. N'a de sens que si la
* ressource a déjà été poussée (gate « processed »).
*/ */
private suspend fun deleteInCloud(file: FileEntity): Boolean { private suspend fun deleteInCloud(file: FileEntity): Boolean {
var ok = false var ok = false
runCatching { runCatching {
val now = System.currentTimeMillis()
appDatabase.withTransaction {
// Jamais poussé (create encore pending) : annulation (M19), pas // Jamais poussé (create encore pending) : annulation (M19), pas
// de delete — le serveur n'a rien à oublier. Poussé (synced) : // de delete — le serveur n'a rien à oublier. Poussé (synced) :
// `delete_resource`, le serveur connaît la ressource. // `delete_resource`, le serveur connaît la ressource.
@@ -95,6 +103,8 @@ class FileDeleter @Inject constructor(
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) { if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
outboxRepository.enqueueDeleteResource(file.resourceId, "file") outboxRepository.enqueueDeleteResource(file.resourceId, "file")
} }
fileRepository.markMissing(file.resourceId, now)
}
ok = true ok = true
Timber.d("enqueued cloud delete for %s", file.resourceId) Timber.d("enqueued cloud delete for %s", file.resourceId)
}.onFailure { e -> }.onFailure { e ->
@@ -166,13 +176,65 @@ class FileDeleter @Inject constructor(
}.getOrDefault(false) }.getOrDefault(false)
if (deleted) { if (deleted) {
thumbnailStore.delete(file.resourceId) thumbnailStore.delete(file.resourceId)
// Rattrapage : ces octets n'avaient jamais été signalés partis.
outboxRepository.enqueueReportBytes(file.resourceId, "file", false)
swept++ swept++
} }
} }
return swept return swept
} }
/**
* Purge sûre V2-3 (« libérer de l'espace ») : supprime les octets SAF des
* fichiers dont une copie durable existe côté serveur (gate
* [FileRepository.isReleasable]), puis détache la ligne (cloud-only,
* toujours visible — contrairement à LOCALLY qui la fait disparaître).
* Aucune op outbox : le serveur est inchangé. `deleteDoc` est un seam de
* test (défaut = vrai `deleteDocument`).
*/
suspend fun releaseLocalCopies(
files: List<FileEntity>,
deleteDoc: (suspend (uri: String) -> Boolean)? = null,
): ReleaseReport {
var released = 0
var skipped = 0
var failed = 0
withContext(Dispatchers.IO) {
for (file in files) {
val uri = file.uri
if (!file.isReleasable() || uri == null) {
skipped++
} else {
val deleted = runCatching {
deleteDoc?.invoke(uri)
?: DocumentsContract.deleteDocument(resolver, Uri.parse(uri))
}.onFailure { e ->
Timber.w(e, "release: deleteDocument failed for %s", uri)
}.getOrDefault(false)
if (!deleted) {
failed++
} else {
fileRepository.detachLocalCopy(file.resourceId)
thumbnailStore.delete(file.resourceId)
// Octets partis : le serveur doit l'apprendre (V2).
outboxRepository.enqueueReportBytes(file.resourceId, "file", false)
released++
Timber.d("released local copy %s", uri)
}
}
}
}
return ReleaseReport(released, skipped, failed)
}
companion object { companion object {
private const val SWEEP_LIMIT = 50 private const val SWEEP_LIMIT = 50
} }
} }
/** Bilan d'une purge « libérer de l'espace » (fichiers). */
data class ReleaseReport(
val released: Int,
val skipped: Int,
val failed: Int,
)
@@ -87,13 +87,19 @@ class FolderDeleter @Inject constructor(
return false return false
} }
/** Suppression cloud uniquement (outbox `delete_resource`), physique intact. */ /**
* Suppression cloud uniquement (outbox `delete_resource` + tombstone locale,
* M5) : le dossier et toute sa descendance Room passent `exists = 0` dans
* la MÊME transaction — le physique reste intact mais l'arbre disparaît de
* l'UI et le walk ne le ressuscite plus (garde `hasPendingDeleteOperation`).
*/
private suspend fun deleteInCloud(folder: FolderEntity): Boolean { private suspend fun deleteInCloud(folder: FolderEntity): Boolean {
var ok = false var ok = false
runCatching { runCatching {
outboxRepository.cancelPendingCreates(folder.resourceId) val tree = collectDescendants(folder.resourceId)
if (outboxRepository.hasSyncedCreateOperationAnyType(folder.resourceId)) { val now = System.currentTimeMillis()
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder") appDatabase.withTransaction {
treeMarkMissing(folder, tree, now)
} }
ok = true ok = true
Timber.d("enqueued cloud delete for folder %s", folder.resourceId) Timber.d("enqueued cloud delete for folder %s", folder.resourceId)
@@ -29,6 +29,12 @@ import javax.inject.Singleton
* *
* L'ordre outbox est garanti par l'insertion séquentielle : `create_resource` * L'ordre outbox est garanti par l'insertion séquentielle : `create_resource`
* du dossier fusionné avant les `move_resource`, avant les `delete_resource`. * du dossier fusionné avant les `move_resource`, avant les `delete_resource`.
*
* M9 — reprise après crash : chaque étape est transactionnelle et idempotente
* (dossier réutilisé, contenus déjà déplacés naturellement ignorés), et une
* source n'est supprimée que si elle est réellement vide après déplacement
* (gate de vidage) — jamais de suppression d'un dossier dont le contenu n'a
* pas pu être déplacé, jamais de doublon serveur à la relance.
*/ */
@Singleton @Singleton
class FolderMerger @Inject constructor( class FolderMerger @Inject constructor(
@@ -68,7 +74,10 @@ class FolderMerger @Inject constructor(
val files = fileRepository.getFilesInFolder(src.resourceId) val files = fileRepository.getFilesInFolder(src.resourceId)
if (files.isNotEmpty()) { if (files.isNotEmpty()) {
fileMover.moveFiles(files.map { it.resourceId }, merged.resourceId) fileMover.moveFiles(files.map { it.resourceId }, merged.resourceId)
movedFiles += files.size // Ne compte que les fichiers réellement partis (relecture :
// `moveFiles` ignore silencieusement les refus SAF, et une
// relance après crash ne doit pas recompter les déjà-déplacés).
movedFiles += files.size - fileRepository.getFilesInFolder(src.resourceId).size
} }
val subFolders = folderRepository.getChildren(src.resourceId) val subFolders = folderRepository.getChildren(src.resourceId)
if (subFolders.isNotEmpty()) { if (subFolders.isNotEmpty()) {
@@ -80,6 +89,14 @@ class FolderMerger @Inject constructor(
folderRepository.reparentSubFolders(movable.map { it.resourceId }, merged.resourceId) folderRepository.reparentSubFolders(movable.map { it.resourceId }, merged.resourceId)
} }
} }
// Gate de vidage (M9) : ne supprimer que les sources
// réellement vidées — un refus SAF silencieux ne doit jamais
// mener à la suppression d'un contenu non déplacé.
val filesLeft = fileRepository.getFilesInFolder(src.resourceId).size
val foldersLeft = folderRepository.getChildren(src.resourceId).size
if (filesLeft > 0 || foldersLeft > 0) {
error("source non vidée : $filesLeft fichier(s), $foldersLeft dossier(s) restants")
}
}.isSuccess }.isSuccess
if (ok) { if (ok) {
readyToDelete += src readyToDelete += src
@@ -0,0 +1,97 @@
package com.kazier.mobile.features.sync
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.kazier.mobile.auth.TokenProvider
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.repository.BytesUploadOutcome
import com.kazier.mobile.data.repository.RemoteContentRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.util.concurrent.TimeUnit
import timber.log.Timber
/**
* Upload générique V2, fichier par fichier : à chaque exécution, un seul
* candidat (copie SAF locale, métadonnées synced `local-cloud`, octets jamais
* poussés, `< 3` échecs) est envoyé via l'upload ciblé `POST /files/upload`
* (`resourceId` = overwrite idempotent). Un seul run à la fois via
* `enqueueUniqueWork(KEEP)`, self-chain tant qu'il reste des candidats
* *distincts* (même discipline que `OcrAutoWorker`).
*
* Erreurs :
* - **réseau / 5xx** → `Result.retry()` (backoff 30 s), compteur intact ;
* - **4xx** (trop gros, rejeté) → +1 tentative, pas de re-enchaine ;
* - **token expiré (401)** → `Result.success()` (re-login passera par l'UI).
*/
@HiltWorker
class BytesUploadWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val remoteContentRepository: RemoteContentRepository,
private val fileDao: FileDao,
private val tokenProvider: TokenProvider,
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
if (tokenProvider.current == null) return Result.success()
val file = fileDao.getBytesUploadCandidates().firstOrNull()
?: return Result.success()
Timber.d("bytes-upload: candidate %s (%s)", file.name, file.resourceId)
val outcome = try {
remoteContentRepository.upload(file)
} catch (e: ApiException) {
when {
e.code == "NETWORK_ERROR" || e.httpCode >= 500 -> BytesUploadOutcome.Retryable
e.httpCode == 401 -> BytesUploadOutcome.Unauthorized
else -> BytesUploadOutcome.Failed
}
} catch (e: Exception) {
Timber.w(e, "bytes-upload: unexpected failure for %s", file.resourceId)
BytesUploadOutcome.Failed
}
when (outcome) {
is BytesUploadOutcome.Done ->
Timber.d("bytes-upload: done %s", file.resourceId)
is BytesUploadOutcome.Failed ->
Timber.w("bytes-upload: failed %s", file.resourceId)
is BytesUploadOutcome.Retryable -> return Result.retry()
is BytesUploadOutcome.Unauthorized -> return Result.success()
}
// Self-chain : un autre candidat *distinct* du dernier attend ?
val more = fileDao.getBytesUploadCandidates().any { it.resourceId != file.resourceId }
if (more) {
enqueue(applicationContext)
}
return Result.success()
}
companion object {
const val NAME = "bytes_upload"
fun enqueue(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<BytesUploadWorker>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(NAME, ExistingWorkPolicy.KEEP, request)
}
}
}
@@ -72,13 +72,18 @@ class DeviceSync @Inject constructor(
// Phase 1 — listing SAF (I/O disque, HORS transaction). // Phase 1 — listing SAF (I/O disque, HORS transaction).
val folders = scanner.scanTree(Uri.parse(rootUri)) val folders = scanner.scanTree(Uri.parse(rootUri))
// Phase 2 — écritures Room (transaction courte, SQL pur). // Phase 2 — écritures Room par lots (m5) : chaque lot est sa propre
return appDatabase.withTransaction { // transaction courte au lieu d'une transaction géante (N upserts +
// full-table scans sous verrou écriture → lecteurs Room bloqués,
// jank/ANR). L'ordre parent-avant-enfant est préservé (itération
// séquentielle, seules les frontières de commit changent).
val seen = HashSet<String>() val seen = HashSet<String>()
val resourceIdByUri = HashMap<String, String>() val resourceIdByUri = HashMap<String, String>()
var fileCount = 0 var fileCount = 0
for (folder in folders) { for (chunk in folders.chunked(SYNC_BATCH)) {
appDatabase.withTransaction {
for (folder in chunk) {
seen += folder.uri seen += folder.uri
val parentResourceId = if (folder.parentUri == null) { val parentResourceId = if (folder.parentUri == null) {
null null
@@ -103,12 +108,18 @@ class DeviceSync @Inject constructor(
) )
resourceIdByUri[folder.uri] = saved.resourceId resourceIdByUri[folder.uri] = saved.resourceId
} }
}
}
for (folder in folders) { val fileWrites = folders.flatMap { folder ->
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne // Dossier ignoré plus haut (parent manquant) : ses fichiers ne
// sont pas rattachés à la racine, ils attendent le walk suivant. // sont pas rattachés à la racine, ils attendent le walk suivant.
val folderResourceId = resourceIdByUri[folder.uri] ?: continue val folderResourceId = resourceIdByUri[folder.uri] ?: return@flatMap emptyList()
for (file in folder.files) { folder.files.map { file -> folderResourceId to file }
}
for (chunk in fileWrites.chunked(SYNC_BATCH)) {
appDatabase.withTransaction {
for ((folderResourceId, file) in chunk) {
seen += file.uri seen += file.uri
fileRepository.saveLocalFile( fileRepository.saveLocalFile(
input = SaveFileInput( input = SaveFileInput(
@@ -125,12 +136,15 @@ class DeviceSync @Inject constructor(
fileCount++ fileCount++
} }
} }
}
var missing = 0 var missing = 0
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
for (folder in folderRepository.getAll()) { // Réconciliation scopée à la racine (m5) : fini les `getAll()`
// O(racines×DB) — le SQL filtre par préfixe d'uri (échappé).
for (folder in folderRepository.getUnderRoot(rootUri)) {
val folderUri = folder.uri val folderUri = folder.uri
if (folder.exists != 0 && folderUri != null && isChildOf(folderUri, rootUri) && folderUri !in seen && if (folder.exists != 0 && folderUri != null && folderUri !in seen &&
!outboxRepository.hasPendingMoveOperation(folder.resourceId) !outboxRepository.hasPendingMoveOperation(folder.resourceId)
) { ) {
folderRepository.markMissing(folder.resourceId, now) folderRepository.markMissing(folder.resourceId, now)
@@ -140,7 +154,7 @@ class DeviceSync @Inject constructor(
missing++ missing++
} }
} }
for (file in fileRepository.getAll()) { for (file in fileRepository.getUnderRoot(rootUri)) {
val fileUri = file.uri val fileUri = file.uri
// Un `move_resource` encore `pending` fait de l'outbox la // Un `move_resource` encore `pending` fait de l'outbox la
// source de vérité du placement : on ne masque jamais une ligne // source de vérité du placement : on ne masque jamais une ligne
@@ -149,7 +163,7 @@ class DeviceSync @Inject constructor(
// Un move déjà `synced` ne protège plus : si le fichier a // Un move déjà `synced` ne protège plus : si le fichier a
// ensuite disparu du disque, c'est une vraie suppression // ensuite disparu du disque, c'est une vraie suppression
// (sinon fantôme `exists = 1` éternel, M4). // (sinon fantôme `exists = 1` éternel, M4).
if (file.exists != 0 && fileUri != null && isChildOf(fileUri, rootUri) && fileUri !in seen && if (file.exists != 0 && fileUri != null && fileUri !in seen &&
!outboxRepository.hasPendingMoveOperation(file.resourceId) !outboxRepository.hasPendingMoveOperation(file.resourceId)
) { ) {
fileRepository.markMissing(file.resourceId, now) fileRepository.markMissing(file.resourceId, now)
@@ -158,12 +172,13 @@ class DeviceSync @Inject constructor(
} }
} }
SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing) return SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing)
}
} }
private fun isChildOf(uri: String, rootUri: String): Boolean = companion object {
uri == rootUri || uri.startsWith("$rootUri/") /** Taille des lots d'upserts Room du walk (m5 : transactions courtes). */
private const val SYNC_BATCH = 200
}
} }
private fun String.extensionOrNull(): String? { private fun String.extensionOrNull(): String? {
@@ -0,0 +1,101 @@
package com.kazier.mobile.features.sync
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.kazier.mobile.auth.TokenProvider
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.repository.DownloadOutcome
import com.kazier.mobile.data.repository.RemoteContentRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.util.concurrent.TimeUnit
import timber.log.Timber
/**
* Download persistant V2, fichier par fichier : à chaque exécution, un seul
* fichier cloud-only demandé (`wanted_offline`, octets constatés serveur)
* est téléchargé puis écrit en SAF (dossier propre, sinon racine par
* défaut) et rattaché (même `resource_id`, `local-cloud`). Un seul run à la
* fois via `enqueueUniqueWork(KEEP)`, self-chain tant qu'il reste des
* candidats (même discipline que `BytesUploadWorker`).
*
* Erreurs :
* - **réseau / 5xx / écriture** → `Result.retry()` (backoff 30 s), demande
* conservée (reprise après reboot via `wanted_offline`) ;
* - **404** → demande soldée + miroir `has_content_server = 0` ;
* - **sans dossier SAF / autre 4xx** → demande soldée ;
* - **token expiré (401)** → `Result.success()` (re-login passera par l'UI).
*/
@HiltWorker
class DownloadWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val remoteContentRepository: RemoteContentRepository,
private val fileDao: FileDao,
private val tokenProvider: TokenProvider,
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
if (tokenProvider.current == null) return Result.success()
val file = fileDao.getOfflineWantedCandidates().firstOrNull()
?: return Result.success()
Timber.d("download: candidate %s (%s)", file.name, file.resourceId)
val outcome = try {
remoteContentRepository.download(file)
} catch (e: ApiException) {
when {
e.code == "NETWORK_ERROR" || e.httpCode >= 500 -> DownloadOutcome.Retryable
e.httpCode == 401 -> DownloadOutcome.Unauthorized
else -> DownloadOutcome.Failed
}
} catch (e: Exception) {
Timber.w(e, "download: unexpected failure for %s", file.resourceId)
DownloadOutcome.Retryable
}
when (outcome) {
is DownloadOutcome.Done ->
Timber.d("download: done %s", file.resourceId)
is DownloadOutcome.NoContent,
is DownloadOutcome.NoLocalFolder,
is DownloadOutcome.Failed ->
Timber.w("download: settled %s (%s)", file.resourceId, outcome)
is DownloadOutcome.Retryable -> return Result.retry()
is DownloadOutcome.Unauthorized -> return Result.success()
}
// Self-chain : une autre demande attend ?
val more = fileDao.getOfflineWantedCandidates().any { it.resourceId != file.resourceId }
if (more) {
enqueue(applicationContext)
}
return Result.success()
}
companion object {
const val NAME = "offline_download"
fun enqueue(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<DownloadWorker>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(NAME, ExistingWorkPolicy.KEEP, request)
}
}
}
@@ -103,7 +103,7 @@ class OutboxSyncWorker @AssistedInject constructor(
Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java), Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java),
) )
/** Set à true si un fichier a été promu pendant ce run → enchaîne OcrAutoWorker. */ /** Set à true si un fichier a été promu pendant ce run → enchaîne OCR + upload octets. */
private var filePromoted = false private var filePromoted = false
override suspend fun doWork(): Result { override suspend fun doWork(): Result {
@@ -121,7 +121,10 @@ class OutboxSyncWorker @AssistedInject constructor(
val pending = pendingOperationDao.selectPending(BATCH_SIZE) val pending = pendingOperationDao.selectPending(BATCH_SIZE)
if (pending.isEmpty()) { if (pending.isEmpty()) {
pendingOperationDao.purgeSynced(System.currentTimeMillis() - PURGE_AGE_MS) pendingOperationDao.purgeSynced(System.currentTimeMillis() - PURGE_AGE_MS)
if (filePromoted) OcrAutoWorker.enqueue(applicationContext) if (filePromoted) {
OcrAutoWorker.enqueue(applicationContext)
BytesUploadWorker.enqueue(applicationContext)
}
return Result.success() return Result.success()
} }
@@ -165,7 +168,10 @@ class OutboxSyncWorker @AssistedInject constructor(
} }
// Première erreur non-idempotente → dead-letter + cascade éventuelle. // Première erreur non-idempotente → dead-letter + cascade éventuelle.
result.failed?.let { fail -> // (if explicite plutôt que `?.let` : le `continue` V2 ci-dessous
// est interdit dans un lambda inline.)
val fail = result.failed
if (fail != null) {
val failedIndex = pending.indexOfFirst { it.operationId == fail.operationId } val failedIndex = pending.indexOfFirst { it.operationId == fail.operationId }
if (failedIndex < 0) { if (failedIndex < 0) {
// Garde C7 : `operation_id` inconnu → stop, pas de boucle // Garde C7 : `operation_id` inconnu → stop, pas de boucle
@@ -176,6 +182,13 @@ class OutboxSyncWorker @AssistedInject constructor(
val failedOp = pending[failedIndex] val failedOp = pending[failedIndex]
pendingOperationDao.markFailed(failedOp.id, now) pendingOperationDao.markFailed(failedOp.id, now)
Timber.w("outbox failed %s (%s: %s)", fail.operationId, fail.code, fail.message) Timber.w("outbox failed %s (%s: %s)", fail.operationId, fail.code, fail.message)
if (failedOp.operation == PendingOperationType.REPORT_BYTES) {
// V2 placements : un hint périmé (partage révoqué,
// ressource supprimée côté serveur) ne doit jamais
// bloquer la file — dead-letter et suite du batch
// (re-sélection du pending restant).
continue
}
if (failedOp.operation == PendingOperationType.CREATE_RESOURCE) { if (failedOp.operation == PendingOperationType.CREATE_RESOURCE) {
failedOp.resourceId?.let { resourceId -> failedOp.resourceId?.let { resourceId ->
pendingOperationDao.failDescendants(resourceId, now) pendingOperationDao.failDescendants(resourceId, now)
@@ -184,7 +197,7 @@ class OutboxSyncWorker @AssistedInject constructor(
} }
// C6 : stop au 1er échec — le serveur s'est arrêté là, tout ce // C6 : stop au 1er échec — le serveur s'est arrêté là, tout ce
// qui suit reste pending pour le prochain run (jamais de // qui suit reste pending pour le prochain run (jamais de
// `continue` vers le batch suivant). // `continue` vers le batch suivant, sauf hint V2 ci-dessus).
return Result.success() return Result.success()
} }
@@ -0,0 +1,72 @@
package com.kazier.mobile.features.sync
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.domain.RetentionRule
import com.kazier.mobile.domain.RetentionStore
import com.kazier.mobile.features.saf.FileDeleter
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.util.concurrent.TimeUnit
import timber.log.Timber
/**
* Rétention auto V2-5 (1×/jour) : purge sûre des copies locales plus
* anciennes que la règle ([RetentionStore]) via [FileDeleter.releaseLocalCopies]
* (gate `isReleasable` : seuls les fichiers dont le serveur a les octets
* partent — jamais de perte). Opération purement locale : aucune contrainte
* réseau, batterie faible exclue.
*/
@HiltWorker
class RetentionWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val retentionStore: RetentionStore,
private val fileDeleter: FileDeleter,
private val fileDao: FileDao,
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
val rule = retentionStore.current()
if (rule is RetentionRule.KeepAll) return Result.success()
val months = (rule as RetentionRule.LastMonths).months
val cutoff = System.currentTimeMillis() - months * MONTH_MS
val candidates = fileDao.releasableOlderThan(cutoff)
if (candidates.isEmpty()) return Result.success()
val report = fileDeleter.releaseLocalCopies(candidates)
Timber.d(
"retention: released=%d skipped=%d failed=%d (rule=%s)",
report.released, report.skipped, report.failed, rule.stored,
)
return Result.success()
}
companion object {
const val NAME = "retention_daily"
private const val MONTH_MS = 30L * 24 * 60 * 60 * 1000
fun cutoffMs(nowMs: Long, months: Int): Long = nowMs - months * MONTH_MS
fun enqueuePeriodic(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.setRequiresBatteryNotLow(true)
.build()
val request = PeriodicWorkRequestBuilder<RetentionWorker>(24, TimeUnit.HOURS)
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(NAME, ExistingPeriodicWorkPolicy.KEEP, request)
}
}
}
@@ -100,37 +100,61 @@ class SyncViewModel @Inject constructor(
/** Démarre la boucle une seule fois (idempotent). */ /** Démarre la boucle une seule fois (idempotent). */
fun ensureStarted() { fun ensureStarted() {
if (loopJob?.isActive == true) return if (loopJob?.isActive == true) return
// Rétention auto V2-5 : passe quotidienne périodique (KEEP).
RetentionWorker.enqueuePeriodic(appContext)
loopJob = viewModelScope.launch { loopJob = viewModelScope.launch {
// Premier cycle différé : laisser le boot et le premier écran // Premier cycle différé : laisser le boot et le premier écran
// répondre avant de lancer un walk potentiellement long. // répondre avant de lancer un walk potentiellement long.
delay(FIRST_DELAY_MS) delay(FIRST_DELAY_MS)
while (isActive) { while (isActive) {
_walkInProgress.value = true _walkInProgress.value = true
try {
var changed = false
runCatching { deviceSync.syncAll() } runCatching { deviceSync.syncAll() }
.onSuccess { results -> .onSuccess { results ->
if (results.isNotEmpty()) Timber.d("syncAll: %s", results) if (results.isNotEmpty()) Timber.d("syncAll: %s", results)
// Les nouvelles ressources découvertes sont dans l'outbox changed = results.any { it.folders > 0 || it.files > 0 || it.missing > 0 }
// → drainer vers POST /sync/ops (single-flight via KEEP).
OutboxSyncWorker.enqueue(appContext)
// OCR auto : uploader les octets des fichiers récemment promus (local-cloud).
OcrAutoWorker.enqueue(appContext)
// Repasse C4 : les suppressions journalisées dont les // Repasse C4 : les suppressions journalisées dont les
// octets ont survécu (crash entre journal et SAF). // octets ont survécu (crash entre journal et SAF).
runCatching { runCatching {
fileDeleter.sweepPendingPhysicalDeletes() + fileDeleter.sweepPendingPhysicalDeletes() +
folderDeleter.sweepPendingPhysicalDeletes() folderDeleter.sweepPendingPhysicalDeletes()
}.onSuccess { swept -> }.onSuccess { swept ->
if (swept > 0) Timber.d("sweep: %d suppressions physiques rattrapées", swept) if (swept > 0) {
Timber.d("sweep: %d suppressions physiques rattrapées", swept)
changed = true
}
}.onFailure { e -> }.onFailure { e ->
Timber.w(e, "sweep failed, retrying later") Timber.w(e, "sweep failed, retrying later")
} }
} }
.onFailure { e -> Timber.w(e, "syncAll failed, retrying later") } .onFailure { e ->
if (e is CancellationException) throw e
Timber.w(e, "syncAll failed, retrying later")
}
// Hydrate les ressources partagées depuis le snapshot serveur. // Hydrate les ressources partagées depuis le snapshot serveur.
// Échec réseau toléré : le prochain tick réessaiera. // Échec réseau toléré : le prochain tick réessaiera.
runCatching { shareRepository.syncSnapshot() } runCatching { shareRepository.syncSnapshot() }
.onFailure { e -> Timber.d("syncSnapshot failed, retrying later: %s", e.message) } .onFailure { e ->
if (e is CancellationException) throw e
Timber.d("syncSnapshot failed, retrying later: %s", e.message)
}
// m2 : ne réveiller WorkManager que si le tick a produit
// quelque chose (walk/sweep) ou si l'outbox attend un drain
// (op partagée depuis l'UI, drain précédent interrompu…).
// Les nouvelles ressources découvertes sont dans l'outbox
// → drainer vers POST /sync/ops (single-flight via KEEP) ;
// OCR auto : octets des fichiers récemment promus.
if (changed || pendingOperationDao.countPending() > 0) {
OutboxSyncWorker.enqueue(appContext)
OcrAutoWorker.enqueue(appContext)
BytesUploadWorker.enqueue(appContext)
}
} finally {
// m1 : le badge « syncing » retombe même si le scope est
// annulé ou si le snapshot réseau a échoué.
_walkInProgress.value = false _walkInProgress.value = false
}
delay(INTERVAL_MS) delay(INTERVAL_MS)
} }
} }
@@ -161,6 +185,7 @@ class SyncViewModel @Inject constructor(
// la racine ne doit pas dormir jusqu'au prochain tick. // la racine ne doit pas dormir jusqu'au prochain tick.
OutboxSyncWorker.enqueue(appContext) OutboxSyncWorker.enqueue(appContext)
OcrAutoWorker.enqueue(appContext) OcrAutoWorker.enqueue(appContext)
BytesUploadWorker.enqueue(appContext)
runCatching { runCatching {
fileDeleter.sweepPendingPhysicalDeletes() + fileDeleter.sweepPendingPhysicalDeletes() +
folderDeleter.sweepPendingPhysicalDeletes() folderDeleter.sweepPendingPhysicalDeletes()
@@ -6,7 +6,17 @@ import com.kazier.mobile.data.remote.dto.UserDto
/** État global de connexion — équivalent de `AuthStatus` JS. */ /** État global de connexion — équivalent de `AuthStatus` JS. */
sealed interface AuthState { sealed interface AuthState {
data object Loading : AuthState data object Loading : AuthState
data object SignedOut : AuthState
/**
* Déconnecté. `expired` = la session précédente est tombée (401 / token
* expiré) plutôt qu'un sign-out volontaire — le login affiche un avis et
* pré-remplit `username` quand il est connu.
*/
data class SignedOut(
val expired: Boolean = false,
val username: String? = null,
) : AuthState
data object Local : AuthState data object Local : AuthState
data class SignedIn(val user: UserDto) : AuthState data class SignedIn(val user: UserDto) : AuthState
} }
@@ -3,11 +3,13 @@ package com.kazier.mobile.ui.auth
import android.content.Context import android.content.Context
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.kazier.mobile.auth.AuthEvent
import com.kazier.mobile.auth.SessionManager import com.kazier.mobile.auth.SessionManager
import com.kazier.mobile.data.remote.ApiException import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.repository.AuthRepository import com.kazier.mobile.data.repository.AuthRepository
import com.kazier.mobile.data.repository.ShareRepository import com.kazier.mobile.data.repository.ShareRepository
import com.kazier.mobile.features.sync.OutboxSyncWorker import com.kazier.mobile.features.sync.OutboxSyncWorker
import com.kazier.mobile.features.sync.BytesUploadWorker
import com.kazier.mobile.features.ocr.OcrAutoWorker import com.kazier.mobile.features.ocr.OcrAutoWorker
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
@@ -37,21 +39,41 @@ class AuthViewModel @Inject constructor(
init { init {
// Le 401 est géré par SessionManager (singleton) — jamais ici (M25) : // Le 401 est géré par SessionManager (singleton) — jamais ici (M25) :
// ce callback survivrait sinon à onCleared et figerait l'outbox. // ce callback survivrait sinon à onCleared et figerait l'outbox. On ne
// consomme que ses événements (re-login silencieux / expiration).
viewModelScope.launch {
sessionManager.events.collect { event ->
when (event) {
is AuthEvent.Reauthenticated -> enterSignedIn(event.user, reseed = true)
is AuthEvent.SessionExpired ->
_authState.value = AuthState.SignedOut(expired = true, username = event.username)
}
}
}
viewModelScope.launch { viewModelScope.launch {
val session = sessionManager.restore() val session = sessionManager.restore()
_authState.value = when { _authState.value = when {
session != null -> AuthState.SignedIn(session.user) session == null && sessionManager.isLocalMode() -> AuthState.Local
sessionManager.isLocalMode() -> AuthState.Local session == null -> AuthState.SignedOut()
else -> AuthState.SignedOut sessionManager.isTokenExpired() -> {
// Token périmé connu : re-login proactif avant tout 401.
// Échec → login avec avis d'expiration (username pré-rempli).
if (sessionManager.trySilentRelogin()) {
AuthState.SignedIn(session.user)
} else {
AuthState.SignedOut(expired = true, username = session.user.username)
}
}
else -> AuthState.SignedIn(session.user)
} }
authRepository.registerDevice() authRepository.registerDevice()
// Session restaurée → drainer l'outbox laissée en attente. // Session restaurée → drainer l'outbox laissée en attente.
OutboxSyncWorker.enqueue(appContext) OutboxSyncWorker.enqueue(appContext)
OcrAutoWorker.enqueue(appContext) OcrAutoWorker.enqueue(appContext)
if (session != null) { BytesUploadWorker.enqueue(appContext)
// Snapshot complet des permissions partagées (convergence). if (session != null && _authState.value is AuthState.SignedIn) {
runCatching { shareRepository.syncSnapshot() } // Snapshot complet des permissions partagées (convergence, M27).
runCatching { shareRepository.syncSnapshot(forceFull = true) }
.onFailure { e -> Timber.d("syncSnapshot on restore failed: %s", e.message) } .onFailure { e -> Timber.d("syncSnapshot on restore failed: %s", e.message) }
} }
} }
@@ -66,15 +88,9 @@ class AuthViewModel @Inject constructor(
_loginUiState.update { LoginUiState(isSubmitting = true) } _loginUiState.update { LoginUiState(isSubmitting = true) }
runCatching { authRepository.login(username, password) } runCatching { authRepository.login(username, password) }
.onSuccess { response -> .onSuccess { response ->
sessionManager.save(response.token, response.user, response.expiresAt) sessionManager.save(response.token, response.user, response.expiresAt, username.trim(), password)
_loginUiState.value = LoginUiState() _loginUiState.value = LoginUiState()
_authState.value = AuthState.SignedIn(response.user) enterSignedIn(response.user, reseed = true)
// Connexion réussie → pousser les mutations locales en attente.
OutboxSyncWorker.enqueue(appContext)
OcrAutoWorker.enqueue(appContext)
// Snapshot complet des permissions partagées (convergence).
runCatching { shareRepository.syncSnapshot() }
.onFailure { e -> Timber.d("syncSnapshot on login failed: %s", e.message) }
} }
.onFailure { e -> .onFailure { e ->
val error = when (e) { val error = when (e) {
@@ -86,6 +102,20 @@ class AuthViewModel @Inject constructor(
} }
} }
/** Session (re)connectée : état + drain + snapshot permissions. */
private fun enterSignedIn(user: com.kazier.mobile.data.remote.dto.UserDto, reseed: Boolean) {
_authState.value = AuthState.SignedIn(user)
if (reseed) {
OutboxSyncWorker.enqueue(appContext)
OcrAutoWorker.enqueue(appContext)
BytesUploadWorker.enqueue(appContext)
viewModelScope.launch {
runCatching { shareRepository.syncSnapshot(forceFull = true) }
.onFailure { e -> Timber.d("syncSnapshot on login failed: %s", e.message) }
}
}
}
fun continueWithoutAccount() { fun continueWithoutAccount() {
viewModelScope.launch { viewModelScope.launch {
sessionManager.setLocalMode() sessionManager.setLocalMode()
@@ -112,7 +142,7 @@ class AuthViewModel @Inject constructor(
sessionManager.clear() sessionManager.clear()
sessionManager.clearLocalMode() sessionManager.clearLocalMode()
} }
_authState.value = AuthState.SignedOut _authState.value = AuthState.SignedOut()
} }
} }
} }
@@ -0,0 +1,133 @@
package com.kazier.mobile.ui.auth
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.kazier.mobile.R
/**
* Formulaire d'authentification partagé (Login + Réglages) : validation
* inline (champs non vides), touche Done = submit, œil voir/masquer le mot
* de passe, erreur centrée sous le bouton.
*/
@Composable
fun LoginForm(
username: String,
onUsernameChange: (String) -> Unit,
password: String,
onPasswordChange: (String) -> Unit,
submitting: Boolean,
errorRes: Int?,
submitLabel: String,
onSubmit: () -> Unit,
modifier: Modifier = Modifier,
) {
var passwordVisible by rememberSaveable { mutableStateOf(false) }
// Pas d'appel réseau pour des champs vides — validation pure UI.
val canSubmit = !submitting && username.isNotBlank() && password.isNotBlank()
val submitIfValid = { if (canSubmit) onSubmit() }
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
OutlinedTextField(
value = username,
onValueChange = onUsernameChange,
label = { Text(stringResource(R.string.login_username)) },
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Next,
),
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = password,
onValueChange = onPasswordChange,
label = { Text(stringResource(R.string.login_password)) },
singleLine = true,
visualTransformation = if (passwordVisible) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
},
trailingIcon = {
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(
imageVector = if (passwordVisible) {
Icons.Filled.VisibilityOff
} else {
Icons.Filled.Visibility
},
contentDescription = stringResource(
if (passwordVisible) {
R.string.login_hide_password
} else {
R.string.login_show_password
},
),
)
}
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(onDone = { submitIfValid() }),
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(4.dp))
Button(
onClick = submitIfValid,
enabled = canSubmit,
modifier = Modifier.fillMaxWidth(),
) {
if (submitting) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
strokeWidth = 2.dp,
)
} else {
Text(submitLabel)
}
}
if (errorRes != null) {
Text(
text = stringResource(errorRes),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
@@ -8,42 +8,47 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.kazier.mobile.R import com.kazier.mobile.R
/**
* Premier écran : choix explicite entre compte serveur et mode local, puis
* formulaire de connexion. Le mode local est expliqué avant d'être choisi
* (pas un petit lien d'esquive sous le formulaire).
*
* Après expiration de session (`expired`), le formulaire s'ouvre directement
* avec le username pré-rempli et un avis explicite — pas de repassage par
* l'écran de choix.
*/
@Composable @Composable
fun LoginScreen( fun LoginScreen(
viewModel: AuthViewModel = hiltViewModel(), viewModel: AuthViewModel = hiltViewModel(),
expired: Boolean = false,
initialUsername: String? = null,
) { ) {
val loginUi by viewModel.loginUiState.collectAsStateWithLifecycle() val loginUi by viewModel.loginUiState.collectAsStateWithLifecycle()
var username by rememberSaveable { mutableStateOf("") } var username by rememberSaveable { mutableStateOf(initialUsername.orEmpty()) }
var password by rememberSaveable { mutableStateOf("") } var password by rememberSaveable { mutableStateOf("") }
var showForm by rememberSaveable { mutableStateOf(expired) }
Column( Column(
modifier = Modifier modifier = Modifier
@@ -60,70 +65,68 @@ fun LoginScreen(
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
) )
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(8.dp))
if (!showForm) {
Text( Text(
text = stringResource(R.string.login_subtitle), text = stringResource(R.string.login_choice_subtitle),
style = MaterialTheme.typography.bodyLarge, style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(32.dp))
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text(stringResource(R.string.login_username)) },
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(12.dp))
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text(stringResource(R.string.login_password)) },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
),
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(24.dp))
Button(
onClick = { viewModel.signIn(username, password) },
enabled = !loginUi.isSubmitting,
modifier = Modifier.fillMaxWidth(),
) {
if (loginUi.isSubmitting) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
strokeWidth = 2.dp,
)
} else {
Text(stringResource(R.string.login_submit))
}
}
loginUi.error?.let { error ->
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(authErrorResFor(error)),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
Spacer(Modifier.height(32.dp))
Button(
onClick = { showForm = true },
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(R.string.login_submit))
} }
Spacer(Modifier.height(12.dp))
Spacer(Modifier.height(16.dp)) OutlinedButton(
TextButton(onClick = viewModel::continueWithoutAccount) { onClick = viewModel::continueWithoutAccount,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(R.string.login_skip)) Text(stringResource(R.string.login_skip))
} }
Spacer(Modifier.height(16.dp))
Text( Text(
text = stringResource(R.string.skip_message), text = stringResource(R.string.skip_message),
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
} else {
Text(
text = stringResource(R.string.login_subtitle),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (expired) {
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.login_session_expired),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
textAlign = TextAlign.Center,
)
}
Spacer(Modifier.height(32.dp))
LoginForm(
username = username,
onUsernameChange = { username = it },
password = password,
onPasswordChange = { password = it },
submitting = loginUi.isSubmitting,
errorRes = loginUi.error?.let(::authErrorResFor),
submitLabel = stringResource(R.string.login_submit),
onSubmit = { viewModel.signIn(username, password) },
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(16.dp))
TextButton(onClick = { showForm = false }) {
Text(stringResource(R.string.back))
}
}
} }
} }
@@ -17,25 +17,27 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.kazier.mobile.R import com.kazier.mobile.R
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus import com.kazier.mobile.data.local.entity.FileStatus
import com.kazier.mobile.features.saf.FileDeleter import com.kazier.mobile.features.saf.FileDeleter
import com.kazier.mobile.ui.theme.NavItemShape
import java.io.Serializable
/** Résultat de l\'analyse de compatibilité entre les fichiers et le mode choisi. */ /** Résultat de l'analyse de compatibilité entre les fichiers et le mode choisi. */
data class DeleteReview( data class DeleteReview(
val mode: FileDeleter.DeleteMode, val mode: FileDeleter.DeleteMode,
val total: Int, val total: Int,
val incompatibleCount: Int, val incompatibleCount: Int,
) { ) : Serializable {
val hasWarning: Boolean get() = incompatibleCount > 0 val hasWarning: Boolean get() = incompatibleCount > 0
} }
@@ -61,15 +63,16 @@ fun DeleteDropdownButton(
onModeSelected: (FileDeleter.DeleteMode) -> Unit, onModeSelected: (FileDeleter.DeleteMode) -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
var expanded by remember { mutableStateOf(false) } var expanded by rememberSaveable { mutableStateOf(false) }
val tint = if (enabled) MaterialTheme.colorScheme.error val tint = if (enabled) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurfaceVariant
val deleteLabel = stringResource(R.string.delete)
Box(modifier = modifier) { Box(modifier = modifier) {
Surface( Surface(
onClick = { if (enabled) expanded = true }, onClick = { if (enabled) expanded = true },
enabled = enabled, enabled = enabled,
shape = androidx.compose.foundation.shape.RoundedCornerShape(20.dp), shape = NavItemShape,
color = if (enabled) MaterialTheme.colorScheme.errorContainer color = if (enabled) MaterialTheme.colorScheme.errorContainer
else MaterialTheme.colorScheme.surfaceVariant, else MaterialTheme.colorScheme.surfaceVariant,
modifier = modifier, modifier = modifier,
@@ -84,15 +87,16 @@ fun DeleteDropdownButton(
) { ) {
Icon( Icon(
imageVector = Icons.Filled.Delete, imageVector = Icons.Filled.Delete,
contentDescription = null, contentDescription = deleteLabel,
tint = tint, tint = tint,
modifier = Modifier.size(20.dp), modifier = Modifier.size(20.dp),
) )
Text( Text(
text = stringResource(R.string.delete), text = deleteLabel,
color = tint, color = tint,
fontSize = 11.sp, style = MaterialTheme.typography.labelSmall,
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
) )
Icon( Icon(
@@ -9,12 +9,15 @@ import androidx.compose.material.icons.filled.Movie
import androidx.compose.material.icons.filled.MusicNote import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material.icons.filled.PictureAsPdf import androidx.compose.material.icons.filled.PictureAsPdf
import androidx.compose.material.icons.filled.TextSnippet import androidx.compose.material.icons.filled.TextSnippet
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import com.kazier.mobile.R
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.domain.FileCategory import com.kazier.mobile.domain.FileCategory
import com.kazier.mobile.domain.computeCategory import com.kazier.mobile.domain.computeCategory
@@ -31,17 +34,32 @@ val FileCategory.icon: ImageVector
FileCategory.OTHER -> Icons.Filled.InsertDriveFile FileCategory.OTHER -> Icons.Filled.InsertDriveFile
} }
/** Teinte dédiée à chaque catégorie de document. */ /** Teinte dédiée à chaque catégorie — déclinaison light/dark lisible sur les deux thèmes. */
val FileCategory.color: Color @Composable
get() = when (this) { fun FileCategory.color(): androidx.compose.ui.graphics.Color {
FileCategory.PDF -> Color(0xFFD32F2F) val dark = isSystemInDarkTheme()
FileCategory.OFFICE -> Color(0xFF1565C0) return when (this) {
FileCategory.IMAGE -> Color(0xFF2E7D32) FileCategory.PDF -> if (dark) androidx.compose.ui.graphics.Color(0xFFE57373) else androidx.compose.ui.graphics.Color(0xFFD32F2F)
FileCategory.TEXT -> Color(0xFF546E7A) FileCategory.OFFICE -> if (dark) androidx.compose.ui.graphics.Color(0xFF90CAF9) else androidx.compose.ui.graphics.Color(0xFF1565C0)
FileCategory.VIDEO -> Color(0xFF6A1B9A) FileCategory.IMAGE -> if (dark) androidx.compose.ui.graphics.Color(0xFF81C784) else androidx.compose.ui.graphics.Color(0xFF2E7D32)
FileCategory.AUDIO -> Color(0xFFAD1457) FileCategory.TEXT -> if (dark) androidx.compose.ui.graphics.Color(0xFFB0BEC5) else androidx.compose.ui.graphics.Color(0xFF546E7A)
FileCategory.OTHER -> Color(0xFF757575) FileCategory.VIDEO -> if (dark) androidx.compose.ui.graphics.Color(0xFFCE93D8) else androidx.compose.ui.graphics.Color(0xFF6A1B9A)
FileCategory.AUDIO -> if (dark) androidx.compose.ui.graphics.Color(0xFFF48FB1) else androidx.compose.ui.graphics.Color(0xFFAD1457)
FileCategory.OTHER -> if (dark) androidx.compose.ui.graphics.Color(0xFFBDBDBD) else androidx.compose.ui.graphics.Color(0xFF757575)
} }
}
/** Libellé i18n de la catégorie — utilisé comme contentDescription. */
@Composable
fun FileCategory.label(): String = when (this) {
FileCategory.PDF -> stringResource(R.string.category_pdf)
FileCategory.OFFICE -> stringResource(R.string.category_office)
FileCategory.IMAGE -> stringResource(R.string.category_image)
FileCategory.TEXT -> stringResource(R.string.category_text)
FileCategory.VIDEO -> stringResource(R.string.category_video)
FileCategory.AUDIO -> stringResource(R.string.category_audio)
FileCategory.OTHER -> stringResource(R.string.category_other)
}
/** /**
* Catégorie d'un fichier : valeur stockée (`category`, colonne ajoutée en v4) * Catégorie d'un fichier : valeur stockée (`category`, colonne ajoutée en v4)
@@ -63,8 +81,8 @@ fun FileCategoryIcon(
val category = file.categoryValue() val category = file.categoryValue()
Icon( Icon(
imageVector = category.icon, imageVector = category.icon,
contentDescription = null, contentDescription = category.label(),
tint = category.color, tint = category.color(),
modifier = modifier.size(size), modifier = modifier.size(size),
) )
} }
@@ -7,7 +7,6 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -19,6 +18,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.kazier.mobile.R import com.kazier.mobile.R
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.ui.theme.ThumbShape
/** /**
* Un fichier est « à traiter » s'il est présent physiquement et jamais encore * Un fichier est « à traiter » s'il est présent physiquement et jamais encore
@@ -41,7 +41,7 @@ fun FilePendingReviewBadge(
) { ) {
if (!file.isPendingReview()) return if (!file.isPendingReview()) return
Surface( Surface(
shape = RoundedCornerShape(8.dp), shape = ThumbShape,
color = MaterialTheme.colorScheme.tertiaryContainer, color = MaterialTheme.colorScheme.tertiaryContainer,
modifier = modifier, modifier = modifier,
) { ) {
@@ -5,12 +5,14 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Cloud import androidx.compose.material.icons.filled.Cloud
import androidx.compose.material.icons.filled.CloudDone import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.CloudOff import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import com.kazier.mobile.R
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus import com.kazier.mobile.data.local.entity.FileStatus
@@ -35,13 +37,23 @@ private val FileSyncPlacement.icon: ImageVector
FileSyncPlacement.LOCAL_CLOUD -> Icons.Filled.CloudDone FileSyncPlacement.LOCAL_CLOUD -> Icons.Filled.CloudDone
} }
/** Teinte dédiée à chaque placement. */ /** Teinte dédiée à chaque placement — déclinaison light/dark. */
private val FileSyncPlacement.color: Color @Composable
get() = when (this) { private fun FileSyncPlacement.color(): androidx.compose.ui.graphics.Color {
FileSyncPlacement.LOCAL -> Color(0xFFF57F17) val dark = isSystemInDarkTheme()
FileSyncPlacement.CLOUD -> Color(0xFF1565C0) return when (this) {
FileSyncPlacement.LOCAL_CLOUD -> Color(0xFF2E7D32) FileSyncPlacement.LOCAL -> if (dark) androidx.compose.ui.graphics.Color(0xFFFFB74D) else androidx.compose.ui.graphics.Color(0xFFB26A00)
FileSyncPlacement.CLOUD -> if (dark) androidx.compose.ui.graphics.Color(0xFF90CAF9) else androidx.compose.ui.graphics.Color(0xFF1565C0)
FileSyncPlacement.LOCAL_CLOUD -> if (dark) androidx.compose.ui.graphics.Color(0xFF81C784) else androidx.compose.ui.graphics.Color(0xFF2E7D32)
} }
}
@Composable
private fun FileSyncPlacement.label(): String = when (this) {
FileSyncPlacement.LOCAL -> stringResource(R.string.sync_placement_local)
FileSyncPlacement.CLOUD -> stringResource(R.string.sync_placement_cloud)
FileSyncPlacement.LOCAL_CLOUD -> stringResource(R.string.sync_placement_local_cloud)
}
/** Statut de sync d'un fichier — présence device / serveur distant. */ /** Statut de sync d'un fichier — présence device / serveur distant. */
@Composable @Composable
@@ -53,8 +65,8 @@ fun FileSyncStatusIcon(
val placement = file.syncPlacement() val placement = file.syncPlacement()
Icon( Icon(
imageVector = placement.icon, imageVector = placement.icon,
contentDescription = null, contentDescription = placement.label(),
tint = placement.color, tint = placement.color(),
modifier = modifier.size(size), modifier = modifier.size(size),
) )
} }
@@ -2,7 +2,6 @@ package com.kazier.mobile.ui.components
import android.content.Context import android.content.Context
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState import androidx.compose.runtime.produceState
@@ -13,12 +12,12 @@ import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage import coil.compose.AsyncImage
import coil.request.ImageRequest import coil.request.ImageRequest
import com.kazier.mobile.data.local.entity.FileEntity import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.domain.FileCategory import com.kazier.mobile.domain.FileCategory
import com.kazier.mobile.features.thumbnails.ThumbnailStore import com.kazier.mobile.features.thumbnails.ThumbnailStore
import com.kazier.mobile.ui.theme.ThumbShape
import dagger.hilt.EntryPoint import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors import dagger.hilt.android.EntryPointAccessors
@@ -41,7 +40,7 @@ fun FileThumbnail(
file: FileEntity, file: FileEntity,
size: Dp, size: Dp,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
shape: Shape = RoundedCornerShape(8.dp), shape: Shape = ThumbShape,
) { ) {
val category = file.categoryValue() val category = file.categoryValue()
if (category != FileCategory.IMAGE && category != FileCategory.PDF) { if (category != FileCategory.IMAGE && category != FileCategory.PDF) {
@@ -8,7 +8,7 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
@@ -20,7 +20,7 @@ fun FolderNameDialog(
onDismiss: () -> Unit, onDismiss: () -> Unit,
onConfirm: (String) -> Unit, onConfirm: (String) -> Unit,
) { ) {
var name by remember { mutableStateOf("") } var name by rememberSaveable { mutableStateOf("") }
AlertDialog( AlertDialog(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.new_folder_name_title)) }, title = { Text(stringResource(R.string.new_folder_name_title)) },
@@ -0,0 +1,36 @@
package com.kazier.mobile.ui.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.kazier.mobile.R
import java.util.Locale
/**
* Formattage de taille centralisé (Phase 0) : remplace les 5 copies
* (`FolderList`, `FolderDetail`, `Search`, `Document`, `SwipeCardDeck`,
* `PdfBuilder`) dont 2 en français en dur (`o/ko/Mo`).
* Utilise les strings i18n `unit_bytes / unit_kilobytes / unit_megabytes`.
*/
@Composable
fun formatFileSize(bytes: Long): String {
val safe = bytes.coerceAtLeast(0)
if (safe < 1_024) {
return "$safe ${stringResource(R.string.unit_bytes)}"
}
if (safe < 1_024 * 1_024) {
val kb = safe / 1_024f
return String.format(
Locale.getDefault(),
"%.1f %s",
kb,
stringResource(R.string.unit_kilobytes),
)
}
val mb = safe / (1_024f * 1_024f)
return String.format(
Locale.getDefault(),
"%.1f %s",
mb,
stringResource(R.string.unit_megabytes),
)
}
@@ -0,0 +1,331 @@
package com.kazier.mobile.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.kazier.mobile.R
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
import com.kazier.mobile.features.connection.ServerConnectionStatus
import com.kazier.mobile.features.sync.SyncViewModel
import com.kazier.mobile.ui.theme.PendingDark
import com.kazier.mobile.ui.theme.PendingLight
import com.kazier.mobile.ui.theme.PillShape
import com.kazier.mobile.ui.theme.SuccessDark
import com.kazier.mobile.ui.theme.SuccessLight
import com.kazier.mobile.ui.theme.SyncingDark
import com.kazier.mobile.ui.theme.SyncingLight
/**
* Pastille de statut unique du header : un point coloré (ou spinner pendant
* une synchro) + un libellé. Un appui ouvre le bottom-sheet « état » :
* statut serveur, bouton de test, résumé de la file d'envoi et accès à son
* détail.
*
* En mode local il n'y a rien à pousser : la pastille affiche « Mode local »
* et le sheet l'explique sans proposer de test (le tap-à-vérifier serait
* une impasse).
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HeaderStatusAction(
syncViewModel: SyncViewModel,
connectionStatusViewModel: ConnectionStatusViewModel,
modifier: Modifier = Modifier,
) {
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
val syncStatus by syncViewModel.syncStatus.collectAsStateWithLifecycle()
var showSheet by rememberSaveable { mutableStateOf(false) }
var showQueue by rememberSaveable { mutableStateOf(false) }
val isLocal = connectionStatus == ServerConnectionStatus.Local
val dark = isSystemInDarkTheme()
val onlineGreen = if (dark) SuccessDark else SuccessLight
val pendingAmber = if (dark) PendingDark else PendingLight
val syncingAccent = if (dark) SyncingDark else SyncingLight
val (dotColor, label, showSpinner) = when {
isLocal -> Triple(
MaterialTheme.colorScheme.onSurfaceVariant,
stringResource(R.string.status_local),
false,
)
connectionStatus == ServerConnectionStatus.Checking -> Triple(
pendingAmber,
stringResource(R.string.status_checking),
false,
)
syncStatus.syncing -> Triple(
syncingAccent,
stringResource(R.string.sync_syncing),
true,
)
syncStatus.pending > 0 -> {
val text = if (syncStatus.pending == 1) {
stringResource(R.string.sync_pending_count_one)
} else {
stringResource(R.string.sync_pending_count, syncStatus.pending)
}
val color = if (connectionStatus == ServerConnectionStatus.Offline) {
MaterialTheme.colorScheme.error
} else {
pendingAmber
}
Triple(color, text, false)
}
syncStatus.failed > 0 -> Triple(
MaterialTheme.colorScheme.error,
stringResource(R.string.sync_summary_failed, syncStatus.failed),
false,
)
connectionStatus == ServerConnectionStatus.Offline -> Triple(
MaterialTheme.colorScheme.error,
stringResource(R.string.status_offline),
false,
)
else -> Triple(
onlineGreen,
stringResource(R.string.status_online),
false,
)
}
val tapLabel = stringResource(R.string.sync_tap_to_view)
Row(
modifier = modifier
.clip(PillShape)
.clickable(
role = Role.Button,
onClickLabel = tapLabel,
onClick = { showSheet = true },
)
.padding(horizontal = 10.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
if (showSpinner) {
CircularProgressIndicator(
modifier = Modifier.size(12.dp),
strokeWidth = 2.dp,
color = dotColor,
)
} else {
Box(
modifier = Modifier
.size(8.dp)
.background(dotColor, CircleShape),
)
}
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (showSheet) {
ModalBottomSheet(
onDismissRequest = { showSheet = false },
sheetState = rememberModalBottomSheetState(),
) {
StatusSheetContent(
connectionStatus = connectionStatus,
syncStatus = syncStatus,
onTest = connectionStatusViewModel::checkNow,
onViewQueue = {
showSheet = false
showQueue = true
},
onDismiss = { showSheet = false },
)
}
}
if (showQueue) {
SyncOperationsDialog(
status = syncStatus,
onDismiss = { showQueue = false },
)
}
}
@Composable
private fun StatusSheetContent(
connectionStatus: ServerConnectionStatus,
syncStatus: SyncViewModel.SyncStatus,
onTest: () -> Unit,
onViewQueue: () -> Unit,
onDismiss: () -> Unit,
) {
val isLocal = connectionStatus == ServerConnectionStatus.Local
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp)
.padding(bottom = 32.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
text = stringResource(R.string.status_sheet_title),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.SemiBold,
)
StatusServerRow(
status = connectionStatus,
onTest = onTest,
)
if (isLocal) {
Text(
text = stringResource(R.string.skip_message),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
HorizontalDivider()
StatusSyncSection(
status = syncStatus,
onViewQueue = onViewQueue,
)
}
TextButton(
onClick = onDismiss,
modifier = Modifier.align(Alignment.End),
) {
Text(stringResource(R.string.settings_close))
}
}
}
@Composable
private fun StatusServerRow(
status: ServerConnectionStatus,
onTest: () -> Unit,
) {
val dark = isSystemInDarkTheme()
val dotColor = when (status) {
ServerConnectionStatus.Checking -> if (dark) PendingDark else PendingLight
ServerConnectionStatus.Online -> if (dark) SuccessDark else SuccessLight
ServerConnectionStatus.Offline -> MaterialTheme.colorScheme.error
ServerConnectionStatus.Local -> MaterialTheme.colorScheme.onSurfaceVariant
}
val label = stringResource(
when (status) {
ServerConnectionStatus.Checking -> R.string.status_checking
ServerConnectionStatus.Online -> R.string.status_online
ServerConnectionStatus.Offline -> R.string.status_offline
ServerConnectionStatus.Local -> R.string.status_local
},
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Box(
modifier = Modifier
.size(12.dp)
.background(dotColor, CircleShape),
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.settings_server),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
text = label,
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.Medium,
)
}
if (status != ServerConnectionStatus.Local) {
OutlinedButton(
onClick = onTest,
enabled = status != ServerConnectionStatus.Checking,
) {
Text(stringResource(R.string.settings_test_connection))
}
}
}
}
@Composable
private fun StatusSyncSection(
status: SyncViewModel.SyncStatus,
onViewQueue: () -> Unit,
) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(R.string.dashboard_sync_title),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
when {
status.syncing -> {
Text(
text = stringResource(R.string.sync_syncing),
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.Medium,
)
}
status.pending > 0 -> {
Text(
text = if (status.pending == 1) {
stringResource(R.string.sync_pending_count_one)
} else {
stringResource(R.string.sync_pending_count, status.pending)
},
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.Medium,
)
}
status.failed > 0 -> {
Text(
text = stringResource(R.string.sync_summary_failed, status.failed),
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.error,
)
}
else -> {
Text(
text = stringResource(R.string.sync_idle),
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.Medium,
)
}
}
OutlinedButton(onClick = onViewQueue) {
Text(stringResource(R.string.status_sheet_view_queue))
}
}
}
@@ -0,0 +1,39 @@
package com.kazier.mobile.ui.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.kazier.mobile.ui.theme.KazierDimens
import com.kazier.mobile.ui.theme.ListCardShape
/**
* Carte de liste unifiée (Phase 0) : remplace les 3 recettes dispersées
* (`surfaceVariant+elev 1dp`, `surface+elev 1dp`, `#F7F8FA + border #EAEAEA`).
* Couleurs 100% thème → lisible en dark mode.
*
* Le clic (simple ou combiné long) se gère via `modifier` pour préserver
* les `combinedClickable` de sélection — pas de `onClick` M3 ici.
*/
@Composable
fun KazierCard(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Card(
modifier = modifier,
shape = ListCardShape,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
),
border = BorderStroke(
KazierDimens.CardBorderWidth,
MaterialTheme.colorScheme.outlineVariant,
),
elevation = CardDefaults.cardElevation(defaultElevation = KazierDimens.CardElevation),
content = { content() },
)
}
@@ -0,0 +1,63 @@
package com.kazier.mobile.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import com.kazier.mobile.R
/**
* CTA « documents à traiter » partagé (dashboard + écran Fichiers) : la
* file review reste joignable même sans passer par le dashboard.
*/
@Composable
fun ReviewCtaCard(
count: Int,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val label = stringResource(R.string.dashboard_review_title, count)
KazierCard(
modifier = modifier.clickable(
role = Role.Button,
onClickLabel = label,
onClick = onClick,
),
) {
Row(
modifier = Modifier.padding(20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = label,
style = MaterialTheme.typography.titleMedium,
)
Text(
text = stringResource(R.string.dashboard_review_hint),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 4.dp),
)
}
Icon(
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
}
}
}
@@ -13,7 +13,11 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.kazier.mobile.R
/** /**
* État du mode multi-sélection (long-press pour entrer, tap pour cocher). * État du mode multi-sélection (long-press pour entrer, tap pour cocher).
@@ -50,12 +54,16 @@ fun rememberSelectionState(): SelectionState = remember { SelectionState() }
fun SelectionStatusIcon(selected: Boolean, modifier: Modifier = Modifier) { fun SelectionStatusIcon(selected: Boolean, modifier: Modifier = Modifier) {
Icon( Icon(
imageVector = if (selected) Icons.Filled.CheckCircle else Icons.Filled.RadioButtonUnchecked, imageVector = if (selected) Icons.Filled.CheckCircle else Icons.Filled.RadioButtonUnchecked,
contentDescription = null, contentDescription = stringResource(
if (selected) R.string.selection_selected else R.string.selection_unselected,
),
tint = if (selected) { tint = if (selected) {
MaterialTheme.colorScheme.primary MaterialTheme.colorScheme.primary
} else { } else {
MaterialTheme.colorScheme.onSurfaceVariant MaterialTheme.colorScheme.onSurfaceVariant
}, },
modifier = modifier.size(24.dp), modifier = modifier
.size(24.dp)
.semantics { this.selected = selected },
) )
} }
@@ -1,74 +0,0 @@
package com.kazier.mobile.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.kazier.mobile.R
import com.kazier.mobile.features.connection.ServerConnectionStatus
import com.kazier.mobile.ui.theme.InactiveGray
private val OnlineGreen = Color(0xFF2E7D32)
private val CheckingAmber = Color(0xFFF9A825)
/**
* Pilule de statut serveur affichée dans le header : cercle coloré + libellé.
* Un appui relance une vérification immédiate du serveur.
*/
@Composable
fun ServerStatusBadge(
status: ServerConnectionStatus,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val (dotColor, labelRes) = when (status) {
ServerConnectionStatus.Checking -> CheckingAmber to R.string.status_checking
ServerConnectionStatus.Online -> OnlineGreen to R.string.status_online
ServerConnectionStatus.Offline -> MaterialTheme.colorScheme.error to R.string.status_offline
ServerConnectionStatus.Local -> InactiveGray to R.string.status_local
}
val label = stringResource(labelRes)
val tapLabel = stringResource(R.string.status_tap_to_recheck)
val shape = RoundedCornerShape(percent = 50)
Row(
modifier = modifier
.clip(shape)
.clickable(
role = Role.Button,
onClickLabel = tapLabel,
onClick = onClick,
)
.padding(horizontal = 10.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Box(
modifier = Modifier
.size(8.dp)
.background(dotColor, CircleShape),
)
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@@ -2,6 +2,7 @@ package com.kazier.mobile.ui.components
import android.text.format.DateUtils import android.text.format.DateUtils
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -20,7 +21,6 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -28,10 +28,13 @@ import com.kazier.mobile.R
import com.kazier.mobile.data.local.entity.PendingOpStatus import com.kazier.mobile.data.local.entity.PendingOpStatus
import com.kazier.mobile.data.local.entity.PendingOperationEntity import com.kazier.mobile.data.local.entity.PendingOperationEntity
import com.kazier.mobile.features.sync.SyncViewModel import com.kazier.mobile.features.sync.SyncViewModel
import com.kazier.mobile.ui.theme.ErrorDark
private val StatusPending = Color(0xFF1E88E5) import com.kazier.mobile.ui.theme.ErrorLight
private val StatusSynced = Color(0xFF2E7D32) import com.kazier.mobile.ui.theme.KazierDimens
private val StatusFailed = Color(0xFFC62828) import com.kazier.mobile.ui.theme.SuccessDark
import com.kazier.mobile.ui.theme.SuccessLight
import com.kazier.mobile.ui.theme.SyncingDark
import com.kazier.mobile.ui.theme.SyncingLight
/** /**
* Dialogue « liste des sync » : dernières opérations de l'outbox (tous statuts), * Dialogue « liste des sync » : dernières opérations de l'outbox (tous statuts),
@@ -58,7 +61,7 @@ internal fun SyncOperationsDialog(
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.heightIn(max = 360.dp), .heightIn(max = KazierDimens.DialogListMaxHeight),
verticalArrangement = Arrangement.spacedBy(2.dp), verticalArrangement = Arrangement.spacedBy(2.dp),
) { ) {
items(status.operations, key = { it.id }) { op -> items(status.operations, key = { it.id }) { op ->
@@ -99,10 +102,11 @@ private fun SyncListSummary(status: SyncViewModel.SyncStatus) {
@Composable @Composable
private fun SyncOperationRow(op: PendingOperationEntity) { private fun SyncOperationRow(op: PendingOperationEntity) {
val dark = isSystemInDarkTheme()
val (dotColor, statusLabel) = when (op.status) { val (dotColor, statusLabel) = when (op.status) {
PendingOpStatus.PENDING -> StatusPending to stringResource(R.string.sync_status_pending) PendingOpStatus.PENDING -> (if (dark) SyncingDark else SyncingLight) to stringResource(R.string.sync_status_pending)
PendingOpStatus.SYNCED -> StatusSynced to stringResource(R.string.sync_status_synced) PendingOpStatus.SYNCED -> (if (dark) SuccessDark else SuccessLight) to stringResource(R.string.sync_status_synced)
else -> StatusFailed to stringResource(R.string.sync_status_failed) else -> (if (dark) ErrorDark else ErrorLight) to stringResource(R.string.sync_status_failed)
} }
val opLabel = operationLabel(op.operation) val opLabel = operationLabel(op.operation)
val time = DateUtils.getRelativeTimeSpanString(op.createdAt).toString() val time = DateUtils.getRelativeTimeSpanString(op.createdAt).toString()
@@ -1,143 +0,0 @@
package com.kazier.mobile.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.kazier.mobile.R
import com.kazier.mobile.features.sync.SyncViewModel
private val SyncingAccent = Color(0xFF1E88E5)
private val PendingAmber = Color(0xFFF9A825)
/**
* Pilule de statut de synchro affichée dans le header : spinner quand une marche
* SAF ou un drain outbox est en cours, compteur d'ops en attente sinon, coche
* quand tout est poussé. Un appui ouvre la « liste des sync » (dernières ops).
*/
@Composable
fun SyncStatusBadge(
status: SyncViewModel.SyncStatus,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val (accent, label, showSpinner) = when {
status.syncing -> {
Triple(SyncingAccent, stringResource(R.string.sync_syncing), true)
}
status.pending > 0 -> {
val label = if (status.pending == 1) {
stringResource(R.string.sync_pending_count_one)
} else {
stringResource(R.string.sync_pending_count, status.pending)
}
Triple(PendingAmber, label, false)
}
else -> Triple(
MaterialTheme.colorScheme.primary,
stringResource(R.string.sync_idle),
false,
)
}
val shape = RoundedCornerShape(percent = 50)
val tapLabel = stringResource(R.string.sync_tap_to_view)
Row(
modifier = modifier
.clip(shape)
.clickable(
role = Role.Button,
onClickLabel = tapLabel,
onClick = onClick,
)
.padding(horizontal = 10.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
if (showSpinner) {
CircularProgressIndicator(
modifier = Modifier.size(12.dp),
strokeWidth = 2.dp,
color = accent,
)
} else if (status.pending > 0) {
Box(
modifier = Modifier
.size(14.dp)
.background(accent, CircleShape),
contentAlignment = Alignment.Center,
) {
Text(
text = status.pending.coerceAtMost(99).toString(),
style = MaterialTheme.typography.labelSmall,
color = Color.White,
fontWeight = FontWeight.Bold,
)
}
} else {
Icon(
imageVector = Icons.Filled.Check,
contentDescription = null,
modifier = Modifier.size(12.dp),
tint = accent,
)
}
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
/**
* Composable prêt-à-poser dans un header : badge + dialogue « liste des sync ».
* Le dialogue est géré localement (état `showList`), aucun wiring externe.
*/
@Composable
fun SyncStatusAction(
syncViewModel: SyncViewModel,
modifier: Modifier = Modifier,
) {
val status by syncViewModel.syncStatus.collectAsStateWithLifecycle()
var showList by rememberSaveable { mutableStateOf(false) }
SyncStatusBadge(
status = status,
onClick = { showList = true },
modifier = modifier,
)
if (showList) {
SyncOperationsDialog(
status = status,
onDismiss = { showList = false },
)
}
}
@@ -0,0 +1,63 @@
package com.kazier.mobile.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.kazier.mobile.ui.theme.KazierDimens
/**
* Bouton d'action vertical (icône + libellé `labelSmall` ellipsé) : tient
* sur 360dp là où des boutons horizontaux icône+texte seraient tronqués
* (exports du scan, ajouts du PdfBuilder).
*/
@Composable
fun VerticalActionButton(
icon: ImageVector,
label: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
outlined: Boolean = true,
) {
val content: @Composable () -> Unit = {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier.size(20.dp),
)
Text(
text = label,
style = MaterialTheme.typography.labelSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
if (outlined) {
OutlinedButton(
onClick = onClick,
enabled = enabled,
modifier = modifier.heightIn(min = KazierDimens.MinTouchTarget),
content = { content() },
)
} else {
Button(
onClick = onClick,
enabled = enabled,
modifier = modifier.heightIn(min = KazierDimens.MinTouchTarget),
content = { content() },
)
}
}
@@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -23,6 +22,7 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.kazier.mobile.R import com.kazier.mobile.R
import com.kazier.mobile.ui.theme.PillShape
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersViewModel import com.kazier.mobile.ui.watchedfolders.WatchedFoldersViewModel
/** Seuil au-delà duquel le badge affiche « 99+ » au lieu du compte exact. */ /** Seuil au-delà duquel le badge affiche « 99+ » au lieu du compte exact. */
@@ -47,7 +47,7 @@ fun WatchedFoldersBadge(
Row( Row(
modifier = Modifier modifier = Modifier
.clip(RoundedCornerShape(percent = 50)) .clip(PillShape)
.clickable( .clickable(
role = Role.Button, role = Role.Button,
onClickLabel = contentDescription, onClickLabel = contentDescription,
@@ -9,20 +9,27 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.DocumentScanner import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material3.Card import androidx.compose.material.icons.filled.Sync
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SmallFloatingActionButton import androidx.compose.material3.SmallFloatingActionButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
import androidx.compose.material3.pulltorefresh.pullToRefresh
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
@@ -32,9 +39,11 @@ import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.kazier.mobile.R import com.kazier.mobile.R
import com.kazier.mobile.features.connection.ConnectionStatusViewModel import com.kazier.mobile.features.connection.ConnectionStatusViewModel
import com.kazier.mobile.features.connection.ServerConnectionStatus
import com.kazier.mobile.features.sync.SyncViewModel import com.kazier.mobile.features.sync.SyncViewModel
import com.kazier.mobile.ui.components.ServerStatusBadge import com.kazier.mobile.ui.components.HeaderStatusAction
import com.kazier.mobile.ui.components.SyncStatusAction import com.kazier.mobile.ui.components.KazierCard
import com.kazier.mobile.ui.components.ReviewCtaCard
import com.kazier.mobile.ui.navigation.FloatingNavBar import com.kazier.mobile.ui.navigation.FloatingNavBar
import com.kazier.mobile.ui.navigation.NavTab import com.kazier.mobile.ui.navigation.NavTab
@@ -51,16 +60,27 @@ fun DashboardScreen(
) { ) {
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle() val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle() val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle()
val syncStatus by syncViewModel.syncStatus.collectAsStateWithLifecycle()
// Mode local : rien n'est poussé vers le serveur, la carte sync est inutile.
val isLocal = connectionStatus == ServerConnectionStatus.Local
val showSyncCard = !isLocal && (syncStatus.syncing || syncStatus.pending > 0 || syncStatus.failed > 0)
// Tirer-pour-actualiser = revérifier le serveur (review + file sont déjà
// temps réel via les flows, il n'y a rien d'autre à recharger ici).
var userRefresh by rememberSaveable { mutableStateOf(false) }
val isRefreshing = userRefresh && connectionStatus == ServerConnectionStatus.Checking
LaunchedEffect(connectionStatus) {
if (connectionStatus != ServerConnectionStatus.Checking) userRefresh = false
}
Scaffold( Scaffold(
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text(stringResource(R.string.dashboard)) }, title = { Text(stringResource(R.string.dashboard)) },
actions = { actions = {
SyncStatusAction(syncViewModel = syncViewModel) HeaderStatusAction(
ServerStatusBadge( syncViewModel = syncViewModel,
status = connectionStatus, connectionStatusViewModel = connectionStatusViewModel,
onClick = connectionStatusViewModel::checkNow,
) )
}, },
) )
@@ -81,20 +101,43 @@ fun DashboardScreen(
} }
}, },
) { padding -> ) { padding ->
Column( val pullState = rememberPullToRefreshState()
Box(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding) .padding(padding)
.pullToRefresh(
state = pullState,
// Mode local : rien à revérifier — geste désactivé, sinon
// l'indicateur resterait coincé (jamais de cycle vrai→faux).
enabled = !isLocal,
isRefreshing = isRefreshing,
onRefresh = {
userRefresh = true
connectionStatusViewModel.checkNow()
},
),
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp), .padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp),
) { ) {
if (unprocessed > 0) { if (unprocessed > 0) {
ReviewCard( ReviewCtaCard(
count = unprocessed, count = unprocessed,
onClick = onOpenReview, onClick = onOpenReview,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) )
} else { }
if (showSyncCard) {
SyncSummaryCard(
status = syncStatus,
modifier = Modifier.fillMaxWidth(),
)
}
if (unprocessed == 0 && !showSyncCard) {
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@@ -119,38 +162,70 @@ fun DashboardScreen(
} }
} }
} }
PullToRefreshDefaults.Indicator(
state = pullState,
isRefreshing = isRefreshing,
modifier = Modifier.align(Alignment.TopCenter),
)
}
} }
} }
/**
* Résumé de la file de synchro (état déjà exposé par [SyncViewModel]) :
* marche en cours, opérations en attente, échecs — sans nouveau ViewModel.
*/
@Composable @Composable
private fun ReviewCard( private fun SyncSummaryCard(
count: Int, status: SyncViewModel.SyncStatus,
onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
Card(onClick = onClick, modifier = modifier) { KazierCard(modifier = modifier) {
Row( Row(
modifier = Modifier.padding(20.dp), modifier = Modifier.padding(20.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp),
) { ) {
if (status.syncing) {
CircularProgressIndicator(modifier = Modifier.size(28.dp))
} else {
Icon(
imageVector = Icons.Filled.Sync,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(28.dp),
)
}
Column(modifier = Modifier.weight(1f)) { Column(modifier = Modifier.weight(1f)) {
Text( Text(
text = stringResource(R.string.dashboard_review_title, count), text = stringResource(R.string.dashboard_sync_title),
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
) )
if (status.syncing) {
Text( Text(
text = stringResource(R.string.dashboard_review_hint), text = stringResource(R.string.sync_syncing),
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 4.dp), modifier = Modifier.padding(top = 4.dp),
) )
} }
Icon( if (status.pending > 0) {
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, Text(
contentDescription = null, text = stringResource(R.string.sync_pending_count, status.pending),
tint = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 4.dp),
)
}
if (status.failed > 0) {
Text(
text = stringResource(R.string.sync_summary_failed, status.failed),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(top = 4.dp),
) )
} }
} }
}
}
} }
@@ -18,7 +18,6 @@ import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
@@ -26,15 +25,16 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DocumentScanner import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@@ -70,7 +70,6 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.view.WindowCompat import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat import androidx.core.view.WindowInsetsControllerCompat
@@ -86,14 +85,17 @@ import com.kazier.mobile.features.ocr.OcrViewModel
import com.kazier.mobile.features.saf.FileDeleter import com.kazier.mobile.features.saf.FileDeleter
import com.kazier.mobile.features.sync.SyncViewModel import com.kazier.mobile.features.sync.SyncViewModel
import com.kazier.mobile.ui.components.DeleteConfirmDialog import com.kazier.mobile.ui.components.DeleteConfirmDialog
import com.kazier.mobile.ui.components.ServerStatusBadge import com.kazier.mobile.ui.components.HeaderStatusAction
import com.kazier.mobile.ui.components.SyncStatusAction import com.kazier.mobile.ui.components.KazierCard
import com.kazier.mobile.ui.components.categoryValue import com.kazier.mobile.ui.components.categoryValue
import com.kazier.mobile.ui.components.formatFileSize
import com.kazier.mobile.ui.document.content.DocumentContentViewer import com.kazier.mobile.ui.document.content.DocumentContentViewer
import com.kazier.mobile.ui.document.content.ImageViewer import com.kazier.mobile.ui.document.content.ImageViewer
import com.kazier.mobile.ui.document.content.PdfFocusViewer import com.kazier.mobile.ui.document.content.PdfFocusViewer
import com.kazier.mobile.ui.document.content.TextFocusViewer import com.kazier.mobile.ui.document.content.TextFocusViewer
import com.kazier.mobile.ui.document.content.ZoomableContent import com.kazier.mobile.ui.document.content.ZoomableContent
import com.kazier.mobile.ui.theme.PillShape
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import java.time.Instant import java.time.Instant
import java.time.ZoneId import java.time.ZoneId
@@ -123,7 +125,6 @@ fun DocumentViewerScreen(
val documents by viewModel.documents.collectAsStateWithLifecycle() val documents by viewModel.documents.collectAsStateWithLifecycle()
val viewerState by viewModel.uiState.collectAsStateWithLifecycle() val viewerState by viewModel.uiState.collectAsStateWithLifecycle()
val ocrState by ocrViewModel.uiState.collectAsStateWithLifecycle() val ocrState by ocrViewModel.uiState.collectAsStateWithLifecycle()
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
val pagerState = rememberPagerState(pageCount = { documents.size }) val pagerState = rememberPagerState(pageCount = { documents.size })
// M30 : survit à la rotation (`rememberSaveable`) — `savedPage` mémorise // M30 : survit à la rotation (`rememberSaveable`) — `savedPage` mémorise
@@ -195,9 +196,15 @@ fun DocumentViewerScreen(
viewModel.clearKeepMessage() viewModel.clearKeepMessage()
} }
} }
LaunchedEffect(viewerState.releaseMessage) {
viewerState.releaseMessage?.let {
snackbarHostState.showSnackbar(it)
viewModel.clearReleaseMessage()
}
}
// Confirmation avant suppression d'un document déjà traité. // Confirmation avant suppression d'un document déjà traité.
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) } var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) } var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
var fullscreen by rememberSaveable { mutableStateOf(false) } var fullscreen by rememberSaveable { mutableStateOf(false) }
@@ -252,10 +259,9 @@ fun DocumentViewerScreen(
} }
}, },
actions = { actions = {
SyncStatusAction(syncViewModel = syncViewModel) HeaderStatusAction(
ServerStatusBadge( syncViewModel = syncViewModel,
status = connectionStatus, connectionStatusViewModel = connectionStatusViewModel,
onClick = connectionStatusViewModel::checkNow,
) )
}, },
) )
@@ -276,6 +282,17 @@ fun DocumentViewerScreen(
.fillMaxSize() .fillMaxSize()
.padding(padding), .padding(padding),
) { ) {
if (documents.isEmpty()) {
// Chargement initial : le pager serait vide sans repère.
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
} else {
HorizontalPager( HorizontalPager(
state = pagerState, state = pagerState,
modifier = Modifier modifier = Modifier
@@ -293,6 +310,7 @@ fun DocumentViewerScreen(
) )
} }
} }
}
// Barre d'action fixe pilotée par le document affiché : garder // Barre d'action fixe pilotée par le document affiché : garder
// ou supprimer un document en attente de review, ou supprimer // ou supprimer un document en attente de review, ou supprimer
// (local / cloud / les deux) un document déjà traité. // (local / cloud / les deux) un document déjà traité.
@@ -306,6 +324,8 @@ fun DocumentViewerScreen(
pendingDeleteMode = mode pendingDeleteMode = mode
showDeleteConfirm = true showDeleteConfirm = true
}, },
releasable = viewModel.isReleasable(current),
onRelease = { viewModel.release(current) },
onOcr = if (ocrCanRun || hasOcr) { onOcr = if (ocrCanRun || hasOcr) {
{ {
if (!hasOcr) ocrViewModel.run(current) if (!hasOcr) ocrViewModel.run(current)
@@ -356,6 +376,9 @@ fun DocumentViewerScreen(
* - IMAGE → document plein écran sur fond noir * - IMAGE → document plein écran sur fond noir
* - TEXT → lecture immersive (fond sombre, texte clair, sélectionnable) * - TEXT → lecture immersive (fond sombre, texte clair, sélectionnable)
* *
* Fichier cloud-only (`uri == null`) : le viewer streaming plein écran
* (même contenu que la page, en plus grand) — jamais persisté.
*
* Le retour (tap ou bouton système) est géré par le cadre commun [FocusScaffold]. * Le retour (tap ou bouton système) est géré par le cadre commun [FocusScaffold].
*/ */
@Composable @Composable
@@ -365,6 +388,20 @@ private fun FocusDocumentReader(
onExitFullscreen: () -> Unit, onExitFullscreen: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
if (file.uri == null) {
FocusScaffold(
file = file,
onExitFullscreen = onExitFullscreen,
modifier = modifier,
) {
DocumentContentViewer(
file = file,
onOpenExternalFailed = onOpenExternalFailed,
modifier = Modifier.fillMaxSize(),
)
}
return
}
when (file.categoryValue()) { when (file.categoryValue()) {
FileCategory.PDF -> PdfFullscreenReader( FileCategory.PDF -> PdfFullscreenReader(
file = file, file = file,
@@ -388,7 +425,8 @@ private fun FocusDocumentReader(
/** /**
* Cadre commun du mode focus : fond noir plein écran, un tap (l'indicatrice de * Cadre commun du mode focus : fond noir plein écran, un tap (l'indicatrice de
* position est optionnelle) quitte le mode. * position est optionnelle) quitte le mode. Un hint discret « toucher pour
* quitter » s'affiche 3 s à l'entrée pour lever l'ambiguïté tap / pinch.
*/ */
@Composable @Composable
private fun FocusScaffold( private fun FocusScaffold(
@@ -398,6 +436,11 @@ private fun FocusScaffold(
position: String? = null, position: String? = null,
content: @Composable () -> Unit, content: @Composable () -> Unit,
) { ) {
var showHint by remember(file.resourceId) { mutableStateOf(true) }
LaunchedEffect(file.resourceId) {
delay(3_000)
showHint = false
}
Box( Box(
modifier = modifier modifier = modifier
.fillMaxSize() .fillMaxSize()
@@ -407,12 +450,28 @@ private fun FocusScaffold(
}, },
) { ) {
content() content()
if (showHint) {
Surface(
modifier = Modifier
.align(Alignment.TopCenter)
.padding(top = 16.dp),
shape = PillShape,
color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f),
) {
Text(
text = stringResource(R.string.focus_tap_to_exit),
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.inverseOnSurface,
)
}
}
if (position != null) { if (position != null) {
Surface( Surface(
modifier = Modifier modifier = Modifier
.align(Alignment.BottomCenter) .align(Alignment.BottomCenter)
.padding(bottom = 16.dp), .padding(bottom = 16.dp),
shape = RoundedCornerShape(percent = 50), shape = PillShape,
color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f), color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f),
) { ) {
Text( Text(
@@ -549,14 +608,11 @@ private fun DocumentViewerPage(
Spacer(Modifier.height(16.dp)) Spacer(Modifier.height(16.dp))
Card( KazierCard(modifier = Modifier.fillMaxWidth()) {
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
) {
Column(modifier = Modifier Column(modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(16.dp)) { .padding(16.dp)) {
MetadataRow(stringResource(R.string.document_size), formatSize(file.size)) MetadataRow(stringResource(R.string.document_size), formatFileSize(file.size))
MetadataRow(stringResource(R.string.document_type), fileTypeLabel(file)) MetadataRow(stringResource(R.string.document_type), fileTypeLabel(file))
MetadataRow(stringResource(R.string.document_added_at), formatDateTime(file.addedAt)) MetadataRow(stringResource(R.string.document_added_at), formatDateTime(file.addedAt))
file.lastModified?.let { lastModified -> file.lastModified?.let { lastModified ->
@@ -583,6 +639,8 @@ private fun DocumentActionBar(
onKeep: () -> Unit, onKeep: () -> Unit,
onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit, onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit,
onOcr: (() -> Unit)? = null, onOcr: (() -> Unit)? = null,
releasable: Boolean = false,
onRelease: (() -> Unit)? = null,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val pendingReview = !file.processed && file.uri != null val pendingReview = !file.processed && file.uri != null
@@ -599,7 +657,7 @@ private fun DocumentActionBar(
) { ) {
if (pendingReview) { if (pendingReview) {
Surface( Surface(
shape = RoundedCornerShape(percent = 50), shape = PillShape,
color = MaterialTheme.colorScheme.secondaryContainer, color = MaterialTheme.colorScheme.secondaryContainer,
) { ) {
Text( Text(
@@ -610,7 +668,10 @@ private fun DocumentActionBar(
) )
} }
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(48.dp)) { Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterHorizontally),
) {
DocumentActionButton( DocumentActionButton(
icon = Icons.Filled.Close, icon = Icons.Filled.Close,
contentDescription = stringResource(R.string.review_delete), contentDescription = stringResource(R.string.review_delete),
@@ -635,6 +696,12 @@ private fun DocumentActionBar(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
) { ) {
if (onRelease != null && releasable) {
DocumentReleaseButton(
enabled = !busy,
onClick = onRelease,
)
}
if (onOcr != null) { if (onOcr != null) {
DocumentOcrButton( DocumentOcrButton(
label = if (file.ocrText != null) R.string.ocr_open else R.string.ocr_action, label = if (file.ocrText != null) R.string.ocr_open else R.string.ocr_action,
@@ -653,7 +720,32 @@ private fun DocumentActionBar(
} }
} }
/** Bouton « OCR » — même gabarit que le menu Supprimer (Surface 88×48). */ /** Bouton « Libérer » V2-3 — purge sûre (le serveur garde les octets). */
@Composable
private fun DocumentReleaseButton(
enabled: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
FilledTonalButton(
onClick = onClick,
enabled = enabled,
modifier = modifier,
) {
Icon(
imageVector = Icons.Filled.CloudOff,
contentDescription = null,
modifier = Modifier.size(20.dp),
)
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
Text(
text = stringResource(R.string.release_action),
maxLines = 1,
)
}
}
/** Bouton « OCR » M3 — gabarit adaptatif (plus de Surface 88×48 fixe). */
@Composable @Composable
private fun DocumentOcrButton( private fun DocumentOcrButton(
label: Int, label: Int,
@@ -661,38 +753,23 @@ private fun DocumentOcrButton(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val tint = if (enabled) MaterialTheme.colorScheme.primary val labelText = stringResource(label)
else MaterialTheme.colorScheme.onSurfaceVariant FilledTonalButton(
onClick = onClick,
Surface(
onClick = { if (enabled) onClick() },
enabled = enabled, enabled = enabled,
shape = RoundedCornerShape(20.dp),
color = if (enabled) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.surfaceVariant,
modifier = modifier, modifier = modifier,
) { ) {
Box(
modifier = Modifier.size(width = 88.dp, height = 48.dp),
contentAlignment = Alignment.Center,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon( Icon(
imageVector = Icons.Filled.DocumentScanner, imageVector = Icons.Filled.DocumentScanner,
contentDescription = null, contentDescription = null,
tint = tint,
modifier = Modifier.size(20.dp), modifier = Modifier.size(20.dp),
) )
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
Text( Text(
text = stringResource(label), text = labelText,
color = tint,
fontSize = 11.sp,
maxLines = 1, maxLines = 1,
fontWeight = FontWeight.Bold,
) )
} }
}
}
} }
/** /**
@@ -815,45 +892,34 @@ private fun DocumentDeleteMenu(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val modes = deleteModesFor(file) val modes = deleteModesFor(file)
var expanded by remember { mutableStateOf(false) } var expanded by rememberSaveable { mutableStateOf(false) }
val tint = if (enabled) MaterialTheme.colorScheme.error val deleteLabel = stringResource(R.string.delete)
else MaterialTheme.colorScheme.onSurfaceVariant
Box(modifier = modifier) { Box(modifier = modifier) {
Surface( FilledTonalButton(
onClick = { if (enabled) expanded = true }, onClick = { expanded = true },
enabled = enabled, enabled = enabled,
shape = RoundedCornerShape(20.dp), colors = ButtonDefaults.filledTonalButtonColors(
color = if (enabled) MaterialTheme.colorScheme.errorContainer containerColor = MaterialTheme.colorScheme.errorContainer,
else MaterialTheme.colorScheme.surfaceVariant, contentColor = MaterialTheme.colorScheme.onErrorContainer,
),
) { ) {
Box(
modifier = Modifier.size(width = 88.dp, height = 48.dp),
contentAlignment = Alignment.Center,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon( Icon(
imageVector = Icons.Filled.Delete, imageVector = Icons.Filled.Delete,
contentDescription = null, contentDescription = null,
tint = tint,
modifier = Modifier.size(20.dp), modifier = Modifier.size(20.dp),
) )
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
Text( Text(
text = stringResource(R.string.delete), text = deleteLabel,
color = tint,
fontSize = 11.sp,
maxLines = 1, maxLines = 1,
fontWeight = FontWeight.Bold,
) )
Icon( Icon(
imageVector = Icons.Filled.ArrowDropDown, imageVector = Icons.Filled.ArrowDropDown,
contentDescription = null, contentDescription = deleteLabel,
tint = tint,
modifier = Modifier.size(16.dp), modifier = Modifier.size(16.dp),
) )
} }
}
}
DropdownMenu( DropdownMenu(
expanded = expanded, expanded = expanded,
@@ -935,9 +1001,9 @@ internal fun resolveViewerPage(currentPage: Int, restoredPage: Int, itemCount: I
internal fun shouldExitViewer(jumpPending: Boolean, hadDocuments: Boolean, isEmpty: Boolean): Boolean = internal fun shouldExitViewer(jumpPending: Boolean, hadDocuments: Boolean, isEmpty: Boolean): Boolean =
!jumpPending && hadDocuments && isEmpty !jumpPending && hadDocuments && isEmpty
/** Vrai si le fichier est local et appartient à une catégorie consultable en mode focus. */ /** Vrai si le fichier appartient à une catégorie consultable en mode focus. */
private fun FileEntity.canFocus(): Boolean = private fun FileEntity.canFocus(): Boolean =
uri != null && categoryValue() in FOCUS_CATEGORIES categoryValue() in FOCUS_CATEGORIES
/** /**
* Vrai si le fichier est prêt pour l'OCR serveur : copie physique locale ET * Vrai si le fichier est prêt pour l'OCR serveur : copie physique locale ET
@@ -964,17 +1030,3 @@ private fun formatDateTime(millis: Long): String {
val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(dateTime) val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(dateTime)
return "$day $time" return "$day $time"
} }
/** Miroir de `formatSize` (app/index.tsx). */
@Composable
private fun formatSize(bytes: Long): String {
if (bytes < 1_024) {
return "$bytes ${stringResource(R.string.unit_bytes)}"
}
if (bytes < 1_024 * 1_024) {
val kb = bytes / 1_024f
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
}
val mb = bytes / (1_024f * 1_024f)
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
}

Some files were not shown because too many files have changed in this diff Show More