Compare commits
4
Commits
9e8b01b135
..
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0957e90d0 | ||
|
|
a50eb830f4 | ||
|
|
c642763035 | ||
|
|
b869f70922 |
@@ -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** — 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), `ListShares`/`ListLinks` (owner-only) ; `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/Revoke, CreateLink/RevokeLink, ListActiveForResource, ListActiveLinksForResource, snapshot `ListEffectivePermissions`) ; 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→000013) : `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 16**, `Migrations.kt` : tables `folders`, `files` (+ `category`, `processed`, `content`, `ocr_text`, `ocr_attempts`, `ocr_queued_at`), `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`)
|
||||||
- `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`, é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é)
|
||||||
- `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)
|
||||||
- `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) ; **schedulé** au login/restauration de session (`AuthViewModel`) et après chaque `syncAll()` (`SyncViewModel`)
|
||||||
- `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), `pdfbuilder` (multi-select → génération PDF), `auth` (login, mode local, avis d'expiration), `share` (`ShareBottomSheet` : grants + liens + ouverture de lien ; `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`, `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) — 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
|
||||||
|
|
||||||
|
|||||||
+7
-2
@@ -5,10 +5,12 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### Changé
|
## [1.0.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é
|
||||||
|
- 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 +19,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).
|
||||||
|
|||||||
@@ -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) |
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ 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",
|
||||||
"DELETE /api/v1/files/:id",
|
"DELETE /api/v1/files/:id",
|
||||||
"POST /api/v1/files/upload",
|
"POST /api/v1/files/upload",
|
||||||
|
|
||||||
|
|||||||
@@ -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")
|
||||||
|
|||||||
@@ -686,3 +686,147 @@ 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 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")
|
||||||
|
}
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ 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.DELETE("/files/:id", FilesDelete)
|
protected.DELETE("/files/:id", FilesDelete)
|
||||||
protected.POST("/files/upload", FilesUpload)
|
protected.POST("/files/upload", FilesUpload)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -455,5 +455,49 @@ func (s *Shares) ListActiveLinksForResource(resourceID string) ([]LinkInfo, erro
|
|||||||
return links, rows.Err()
|
return links, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ShareGrant is one active user-to-user grant on a resource (owner view).
|
||||||
|
type ShareGrant struct {
|
||||||
|
GranteeUserID string
|
||||||
|
Username string
|
||||||
|
Access string
|
||||||
|
Inherit bool
|
||||||
|
ExpiresAt *time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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, COALESCE(u.username, s.grantee_user_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
|
||||||
|
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
|
||||||
|
expiresAt sql.NullTime
|
||||||
|
)
|
||||||
|
if err := rows.Scan(&g.GranteeUserID, &g.Username, &g.Access, &g.Inherit, &expiresAt, &g.UpdatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
|||||||
@@ -146,6 +146,66 @@ 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"
|
||||||
|
}
|
||||||
|
return ContentInfo{Path: resolved, Name: row.Name, MimeType: mime, Size: fi.Size()}, nil
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
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.
|
||||||
|
type ShareGrantDTO struct {
|
||||||
|
GranteeUserID string `json:"granteeUserId"`
|
||||||
|
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
|
||||||
|
}
|
||||||
|
out = append(out, ShareGrantDTO{
|
||||||
|
GranteeUserID: g.GranteeUserID,
|
||||||
|
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
|
||||||
|
}
|
||||||
+4
-1
@@ -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,8 @@ 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, username, access, inherit, expiresAt (ms\|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) |
|
||||||
| 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[]` | — |
|
||||||
|
|
||||||
@@ -119,7 +122,7 @@ type FileOcr = { text: string; updatedAt?: string | null };
|
|||||||
- `revoke_link` : `payload = { "token": "…32-hex" }`. **Idempotent**.
|
- `revoke_link` : `payload = { "token": "…32-hex" }`. **Idempotent**.
|
||||||
- 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>`
|
||||||
|
|
||||||
|
|||||||
@@ -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,25 +82,34 @@ 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,
|
||||||
val previousUserId = activeUserStore.get()
|
user: UserDto,
|
||||||
tokenStore.save(token, user, expiresAt)
|
expiresAt: Long? = null,
|
||||||
activeUserStore.set(user.id)
|
username: String? = null,
|
||||||
localModeStore.clear()
|
password: String? = null,
|
||||||
tokenProvider.current = token
|
) = withContext(Dispatchers.IO) {
|
||||||
// Changement de compte sans sign-out explicite (login de B par
|
val previousUserId = activeUserStore.get()
|
||||||
// dessus la session de A) : même purge que `clear()` — la file de
|
tokenStore.save(token, user, expiresAt)
|
||||||
// A ne doit pas partir sous le token de B. Premier login
|
if (username != null && password != null) {
|
||||||
// (`previousUserId == null`, éventuel travail du mode local) et
|
tokenStore.saveCredentials(username, password)
|
||||||
// re-login du même compte : file conservée.
|
|
||||||
if (previousUserId != null && previousUserId != user.id) {
|
|
||||||
pendingOperationDao.deleteUnpushed()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
activeUserStore.set(user.id)
|
||||||
|
localModeStore.clear()
|
||||||
|
tokenProvider.current = token
|
||||||
|
// Changement de compte sans sign-out explicite (login de B par
|
||||||
|
// dessus la session de A) : même purge que `clear()` — la file de
|
||||||
|
// A ne doit pas partir sous le token de B. Premier login
|
||||||
|
// (`previousUserId == null`, éventuel travail du mode local) et
|
||||||
|
// re-login du même compte : file conservée.
|
||||||
|
if (previousUserId != null && previousUserId != user.id) {
|
||||||
|
pendingOperationDao.deleteUnpushed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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,18 +118,75 @@ 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).
|
||||||
*/
|
*/
|
||||||
fun handleUnauthorized() {
|
fun handleUnauthorized() {
|
||||||
tokenProvider.current = null
|
tokenProvider.current = null
|
||||||
scope.launch {
|
scope.launch {
|
||||||
runCatching { tokenStore.clear() }
|
reloginMutex.withLock { silentReloginLocked() }
|
||||||
runCatching { activeUserStore.clear() }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 { activeUserStore.clear() }
|
||||||
|
_events.tryEmit(AuthEvent.SessionExpired(knownUsername))
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pré-relogin : vrai si l'`expires_at` persistée du login est atteinte
|
* Pré-relogin : vrai si l'`expires_at` persistée du login est atteinte
|
||||||
* (marge anti-course d'1 min par défaut). L'appelant peut alors reloginer
|
* (marge anti-course d'1 min par défaut). L'appelant peut alors reloginer
|
||||||
|
|||||||
@@ -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,
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package com.kazier.mobile.data.local
|
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
|
* Échappe les jokers `LIKE` (`%`, `_`) et l'échappement lui-même (`\`) dans
|
||||||
* un fragment destiné à une requête `... LIKE ... ESCAPE '\'` (m5, m7).
|
* un fragment destiné à une requête `... LIKE ... ESCAPE '\'` (m5, m7).
|
||||||
@@ -8,3 +11,17 @@ package com.kazier.mobile.data.local
|
|||||||
*/
|
*/
|
||||||
internal fun String.escapeLike(): String =
|
internal fun String.escapeLike(): String =
|
||||||
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
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")
|
||||||
|
|||||||
@@ -46,20 +46,28 @@ interface FileDao {
|
|||||||
suspend fun getByUri(uri: String): FileEntity?
|
suspend fun getByUri(uri: String): FileEntity?
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recherche par nom (m7) : `:query` arrive déjà échappé (`escapeLike`,
|
* Recherche par nom (m7 + suivi accents) : `:query` arrive déjà échappé
|
||||||
* `%`/`_` littéraux, pas des jokers) avec `ESCAPE '\'`. `COLLATE NOCASE`
|
* (`escapeLike`, `%`/`_` littéraux, pas des jokers) avec `ESCAPE '\'`.
|
||||||
* sur l'opérande gauche pour une casse ASCII insensible explicite
|
* `COLLATE NOCASE` couvre la casse ASCII ; la deuxième branche compare
|
||||||
* (le repli Unicode « ete » → « ÉTÉ » demanderait une colonne normalisée,
|
* `lower(name)` débarrassé de ses accents (chaîne de `REPLACE` FR — pas de
|
||||||
* hors scope — voir FEEDBACK).
|
* 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 COLLATE NOCASE LIKE '%' || :query || '%' ESCAPE '\')
|
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
|
||||||
|
|||||||
+15
@@ -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>
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,7 @@ 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.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 +162,96 @@ 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) })
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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,
|
||||||
|
|||||||
@@ -13,11 +13,13 @@ 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.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 +30,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 +122,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 +169,22 @@ 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>>>
|
||||||
}
|
}
|
||||||
@@ -112,6 +112,21 @@ data class ShareLinkDto(
|
|||||||
@Json(name = "expiresAt") val expiresAt: String? = null,
|
@Json(name = "expiresAt") val expiresAt: 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()`).
|
||||||
|
*/
|
||||||
|
data class ShareGrantDto(
|
||||||
|
@Json(name = "granteeUserId") val granteeUserId: String,
|
||||||
|
@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,
|
||||||
|
)
|
||||||
|
|
||||||
/** 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,
|
||||||
|
|||||||
+10
-4
@@ -3,6 +3,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.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
|
||||||
@@ -49,13 +50,18 @@ class FileRepository @Inject constructor(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel).
|
* Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel).
|
||||||
* m7 : la saisie est échappée (`%`/`_` littéraux, pas des jokers).
|
* m7 : la saisie est échappée (`%`/`_` littéraux, pas des jokers) ;
|
||||||
|
* 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>> =
|
fun searchFiles(query: String?, category: String?): Flow<List<FileEntity>> {
|
||||||
fileDao.searchWithFilters(
|
val trimmed = query?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
query = query?.trim()?.takeIf { it.isNotEmpty() }?.escapeLike(),
|
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>> =
|
||||||
|
|||||||
@@ -222,6 +222,13 @@ class OutboxRepository @Inject constructor(
|
|||||||
/** 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
|
||||||
|
|||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package com.kazier.mobile.data.repository
|
||||||
|
|
||||||
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
|
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).
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class RemoteContentRepository @Inject constructor(
|
||||||
|
private val apiClient: ApiClient,
|
||||||
|
) {
|
||||||
|
/** Octets du fichier, bornés ([ApiClient.MAX_CONTENT_BYTES]). */
|
||||||
|
suspend fun fetch(fileId: String): ByteArray =
|
||||||
|
apiClient.downloadContentBytes(fileId)
|
||||||
|
}
|
||||||
@@ -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,6 +3,7 @@ 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
|
||||||
@@ -37,19 +38,38 @@ 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) {
|
if (session != null && _authState.value is AuthState.SignedIn) {
|
||||||
// Snapshot complet des permissions partagées (convergence, M27).
|
// Snapshot complet des permissions partagées (convergence, M27).
|
||||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
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 +86,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, M27).
|
|
||||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
|
||||||
.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 +100,19 @@ 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)
|
||||||
|
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 +139,7 @@ class AuthViewModel @Inject constructor(
|
|||||||
sessionManager.clear()
|
sessionManager.clear()
|
||||||
sessionManager.clearLocalMode()
|
sessionManager.clearLocalMode()
|
||||||
}
|
}
|
||||||
_authState.value = AuthState.SignedOut
|
_authState.value = AuthState.SignedOut()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,16 +33,22 @@ import com.kazier.mobile.R
|
|||||||
* Premier écran : choix explicite entre compte serveur et mode local, puis
|
* Premier écran : choix explicite entre compte serveur et mode local, puis
|
||||||
* formulaire de connexion. Le mode local est expliqué avant d'être choisi
|
* formulaire de connexion. Le mode local est expliqué avant d'être choisi
|
||||||
* (pas un petit lien d'esquive sous le formulaire).
|
* (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(false) }
|
var showForm by rememberSaveable { mutableStateOf(expired) }
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -94,6 +100,15 @@ fun LoginScreen(
|
|||||||
style = MaterialTheme.typography.bodyLarge,
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
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))
|
Spacer(Modifier.height(32.dp))
|
||||||
|
|
||||||
LoginForm(
|
LoginForm(
|
||||||
|
|||||||
+19
-2
@@ -367,6 +367,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
|
||||||
@@ -376,6 +379,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,
|
||||||
@@ -942,9 +959,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
|
||||||
|
|||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.kazier.mobile.ui.document
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import com.kazier.mobile.data.remote.ApiException
|
||||||
|
import com.kazier.mobile.data.repository.RemoteContentRepository
|
||||||
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chargement streaming d'un fichier cloud-only (V1 finitions).
|
||||||
|
*
|
||||||
|
* Stateless : [load] lit les octets via `GET /files/:id/content` sans les
|
||||||
|
* persister. Le composant appelant garde l'état (idle/loading/loaded/error).
|
||||||
|
*/
|
||||||
|
@HiltViewModel
|
||||||
|
class RemoteContentViewModel @Inject constructor(
|
||||||
|
private val repository: RemoteContentRepository,
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
suspend fun load(fileId: String): Result<ByteArray> =
|
||||||
|
runCatching { repository.fetch(fileId) }
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** Code quand le serveur n'a aucun octet (metadata-only jamais uploadé). */
|
||||||
|
fun isNoContent(e: Throwable): Boolean =
|
||||||
|
e is ApiException && e.code == "NOT_FOUND"
|
||||||
|
|
||||||
|
fun isTooLarge(e: Throwable): Boolean =
|
||||||
|
e is ApiException && e.code == "FILE_TOO_LARGE"
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -42,7 +42,7 @@ fun DocumentContentViewer(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (file.uri == null) {
|
if (file.uri == null) {
|
||||||
CloudOnlyPlaceholder(file, modifier)
|
RemoteDocumentViewer(file, onOpenExternalFailed, modifier)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-12
@@ -55,6 +55,10 @@ import kotlinx.coroutines.withContext
|
|||||||
* largeur cible borne les bitmaps et un cache LRU limite la mémoire. Le
|
* largeur cible borne les bitmaps et un cache LRU limite la mémoire. Le
|
||||||
* `PdfRenderer` n'est pas thread-safe : toutes les lectures passent par un
|
* `PdfRenderer` n'est pas thread-safe : toutes les lectures passent par un
|
||||||
* `Mutex` et un dispatcher IO.
|
* `Mutex` et un dispatcher IO.
|
||||||
|
*
|
||||||
|
* `openFd` (optionnel) remplace la lecture SAF : streaming distant (lot 1) —
|
||||||
|
* les octets sont écrits dans un fichier temporaire du `cacheDir` par
|
||||||
|
* l'appelant ([RemoteDocumentViewer]), supprimé à la sortie.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun PdfPageViewer(
|
fun PdfPageViewer(
|
||||||
@@ -62,16 +66,17 @@ fun PdfPageViewer(
|
|||||||
contentResolver: ContentResolver,
|
contentResolver: ContentResolver,
|
||||||
onOpenExternalFailed: () -> Unit,
|
onOpenExternalFailed: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
|
openFd: (() -> ParcelFileDescriptor?)? = null,
|
||||||
) {
|
) {
|
||||||
val uri = file.uri
|
val uri = file.uri
|
||||||
if (uri == null) {
|
if (uri == null && openFd == null) {
|
||||||
CloudOnlyPlaceholder(file, modifier)
|
CloudOnlyPlaceholder(file, modifier)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
val document = remember(uri) { PdfDocumentState(contentResolver, uri) }
|
val document = remember(file.resourceId, uri) { PdfDocumentState(contentResolver, uri, openFd) }
|
||||||
var pageCount by remember(uri) { mutableIntStateOf(0) }
|
var pageCount by remember(file.resourceId) { mutableIntStateOf(0) }
|
||||||
var loadFailed by remember(uri) { mutableStateOf(false) }
|
var loadFailed by remember(file.resourceId) { mutableStateOf(false) }
|
||||||
|
|
||||||
// Le state vit en mémoire (cache + dossier ouvert) tant que ce lecteur est
|
// Le state vit en mémoire (cache + dossier ouvert) tant que ce lecteur est
|
||||||
// affiché ; il est fermé à la sortie ou au changement de document.
|
// affiché ; il est fermé à la sortie ou au changement de document.
|
||||||
@@ -79,7 +84,7 @@ fun PdfPageViewer(
|
|||||||
onDispose { document.close() }
|
onDispose { document.close() }
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(uri) {
|
LaunchedEffect(document) {
|
||||||
pageCount = 0
|
pageCount = 0
|
||||||
loadFailed = false
|
loadFailed = false
|
||||||
if (document.load()) {
|
if (document.load()) {
|
||||||
@@ -136,22 +141,23 @@ fun PdfFocusViewer(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
onPageCountChanged: ((Int) -> Unit)? = null,
|
onPageCountChanged: ((Int) -> Unit)? = null,
|
||||||
renderScale: Float = 1f,
|
renderScale: Float = 1f,
|
||||||
|
openFd: (() -> ParcelFileDescriptor?)? = null,
|
||||||
) {
|
) {
|
||||||
val uri = file.uri
|
val uri = file.uri
|
||||||
if (uri == null) {
|
if (uri == null && openFd == null) {
|
||||||
CloudOnlyPlaceholder(file, modifier)
|
CloudOnlyPlaceholder(file, modifier)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
val document = remember(uri) { PdfDocumentState(contentResolver, uri) }
|
val document = remember(file.resourceId, uri) { PdfDocumentState(contentResolver, uri, openFd) }
|
||||||
var pageCount by remember(uri) { mutableIntStateOf(0) }
|
var pageCount by remember(file.resourceId) { mutableIntStateOf(0) }
|
||||||
var loadFailed by remember(uri) { mutableStateOf(false) }
|
var loadFailed by remember(file.resourceId) { mutableStateOf(false) }
|
||||||
|
|
||||||
DisposableEffect(document) {
|
DisposableEffect(document) {
|
||||||
onDispose { document.close() }
|
onDispose { document.close() }
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(uri) {
|
LaunchedEffect(document) {
|
||||||
pageCount = 0
|
pageCount = 0
|
||||||
loadFailed = false
|
loadFailed = false
|
||||||
if (document.load()) {
|
if (document.load()) {
|
||||||
@@ -303,10 +309,15 @@ private fun PdfPageItem(
|
|||||||
/**
|
/**
|
||||||
* État d'un document PDF : ouvre le `PdfRenderer` à la demande, rend chaque
|
* État d'un document PDF : ouvre le `PdfRenderer` à la demande, rend chaque
|
||||||
* page via le cache LRU et verrouille l'accès au renderer (non thread-safe).
|
* page via le cache LRU et verrouille l'accès au renderer (non thread-safe).
|
||||||
|
*
|
||||||
|
* Source des octets : SAF (`contentResolver` + `uri`) par défaut, ou
|
||||||
|
* `openFd` (streaming distant — l'appelant écrit les octets dans un fichier
|
||||||
|
* temporaire et fournit un descripteur frais à chaque appel).
|
||||||
*/
|
*/
|
||||||
private class PdfDocumentState(
|
private class PdfDocumentState(
|
||||||
private val contentResolver: ContentResolver,
|
private val contentResolver: ContentResolver,
|
||||||
private val uri: String,
|
private val uri: String?,
|
||||||
|
private val openFd: (() -> ParcelFileDescriptor?)? = null,
|
||||||
) {
|
) {
|
||||||
@Volatile
|
@Volatile
|
||||||
private var renderer: PdfRenderer? = null
|
private var renderer: PdfRenderer? = null
|
||||||
@@ -329,7 +340,8 @@ private class PdfDocumentState(
|
|||||||
if (closed) return@withLock false
|
if (closed) return@withLock false
|
||||||
if (renderer != null) return@withLock true
|
if (renderer != null) return@withLock true
|
||||||
val opened = runCatching {
|
val opened = runCatching {
|
||||||
val pfd: ParcelFileDescriptor? = DocumentContent.openFileDescriptor(contentResolver, uri)
|
val pfd: ParcelFileDescriptor? = openFd?.invoke()
|
||||||
|
?: uri?.let { DocumentContent.openFileDescriptor(contentResolver, it) }
|
||||||
if (pfd != null) PdfRenderer(pfd) else null
|
if (pfd != null) PdfRenderer(pfd) else null
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
if (opened != null) renderer = opened
|
if (opened != null) renderer = opened
|
||||||
|
|||||||
+337
@@ -0,0 +1,337 @@
|
|||||||
|
package com.kazier.mobile.ui.document.content
|
||||||
|
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.os.ParcelFileDescriptor
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
|
import com.kazier.mobile.domain.FileCategory
|
||||||
|
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||||
|
import com.kazier.mobile.ui.components.categoryValue
|
||||||
|
import com.kazier.mobile.ui.document.RemoteContentViewModel
|
||||||
|
import java.io.File
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lecteur streaming d'un fichier cloud-only (`uri == null`).
|
||||||
|
*
|
||||||
|
* V1 finitions, choix « streaming sans cache » : les octets sont lus via
|
||||||
|
* `GET /files/:id/content` sur demande (bouton, jamais d'auto-load au swipe),
|
||||||
|
* gardés en RAM le temps de l'affichage, jamais persistés (ni Room, ni SAF).
|
||||||
|
* Seul le PDF exige un fichier temporaire du `cacheDir` (le `PdfRenderer`
|
||||||
|
* système ne sait lire que depuis un descripteur) — éphémère, supprimé à la
|
||||||
|
* sortie du viewer. 404 = aucun octet serveur (metadata-only jamais uploadé).
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun RemoteDocumentViewer(
|
||||||
|
file: FileEntity,
|
||||||
|
onOpenExternalFailed: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
viewModel: RemoteContentViewModel = hiltViewModel(),
|
||||||
|
) {
|
||||||
|
var started by remember(file.resourceId) { mutableStateOf(false) }
|
||||||
|
var loading by remember(file.resourceId) { mutableStateOf(false) }
|
||||||
|
var bytes by remember(file.resourceId) { mutableStateOf<ByteArray?>(null) }
|
||||||
|
var error by remember(file.resourceId) { mutableStateOf<Throwable?>(null) }
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
|
fun reload() {
|
||||||
|
loading = true
|
||||||
|
error = null
|
||||||
|
scope.launch {
|
||||||
|
viewModel.load(file.resourceId)
|
||||||
|
.onSuccess {
|
||||||
|
bytes = it
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
.onFailure {
|
||||||
|
error = it
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val loaded = bytes
|
||||||
|
when {
|
||||||
|
loaded != null -> RemoteContentBody(
|
||||||
|
file = file,
|
||||||
|
bytes = loaded,
|
||||||
|
onOpenExternalFailed = onOpenExternalFailed,
|
||||||
|
modifier = modifier,
|
||||||
|
)
|
||||||
|
loading -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.document_stream_loading),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
error != null -> RemoteContentError(
|
||||||
|
error = error!!,
|
||||||
|
onRetry = ::reload,
|
||||||
|
modifier = modifier,
|
||||||
|
)
|
||||||
|
!started -> RemoteContentGate(
|
||||||
|
file = file,
|
||||||
|
onLoad = {
|
||||||
|
started = true
|
||||||
|
reload()
|
||||||
|
},
|
||||||
|
modifier = modifier,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** État initial : métadonnées + bouton de lecture à la demande (pas d'auto-load). */
|
||||||
|
@Composable
|
||||||
|
private fun RemoteContentGate(
|
||||||
|
file: FileEntity,
|
||||||
|
onLoad: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = modifier,
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
) {
|
||||||
|
FileCategoryIcon(file = file, size = 64.dp)
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.document_cloud_only),
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.document_cloud_only_hint),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
Button(onClick = onLoad) {
|
||||||
|
Text(stringResource(R.string.document_stream_load))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Échec de streaming : message + réessai (404 → aucun contenu serveur). */
|
||||||
|
@Composable
|
||||||
|
private fun RemoteContentError(
|
||||||
|
error: Throwable,
|
||||||
|
onRetry: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val message = when {
|
||||||
|
RemoteContentViewModel.isNoContent(error) ->
|
||||||
|
stringResource(R.string.document_stream_no_content)
|
||||||
|
RemoteContentViewModel.isTooLarge(error) ->
|
||||||
|
stringResource(R.string.document_stream_too_large)
|
||||||
|
else -> stringResource(R.string.document_stream_error)
|
||||||
|
}
|
||||||
|
Column(
|
||||||
|
modifier = modifier.padding(24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = message,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
TextButton(onClick = onRetry) {
|
||||||
|
Text(stringResource(R.string.document_stream_retry))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dispatch du contenu distant par catégorie (PDF / image / texte supportés). */
|
||||||
|
@Composable
|
||||||
|
private fun RemoteContentBody(
|
||||||
|
file: FileEntity,
|
||||||
|
bytes: ByteArray,
|
||||||
|
onOpenExternalFailed: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
when (file.categoryValue()) {
|
||||||
|
FileCategory.IMAGE -> RemoteImageViewer(bytes = bytes, description = file.name, modifier = modifier)
|
||||||
|
FileCategory.TEXT -> RemoteTextViewer(bytes = bytes, modifier = modifier)
|
||||||
|
FileCategory.PDF -> RemotePdfViewer(
|
||||||
|
file = file,
|
||||||
|
bytes = bytes,
|
||||||
|
onOpenExternalFailed = onOpenExternalFailed,
|
||||||
|
modifier = modifier,
|
||||||
|
)
|
||||||
|
else -> Column(
|
||||||
|
modifier = modifier.padding(24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.document_stream_unsupported),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
ExternalOpenButton(file = file, onOpenExternalFailed = onOpenExternalFailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RemoteImageViewer(bytes: ByteArray, description: String, modifier: Modifier = Modifier) {
|
||||||
|
val bitmap = remember(bytes) {
|
||||||
|
runCatching { BitmapFactory.decodeByteArray(bytes, 0, bytes.size) }.getOrNull()
|
||||||
|
}
|
||||||
|
if (bitmap != null) {
|
||||||
|
Image(
|
||||||
|
bitmap = bitmap.asImageBitmap(),
|
||||||
|
contentDescription = description,
|
||||||
|
modifier = modifier.fillMaxSize(),
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Repli : Coil décode depuis le ByteArray (mêmes bytes, autre décodeur).
|
||||||
|
AsyncImage(
|
||||||
|
model = bytes,
|
||||||
|
contentDescription = description,
|
||||||
|
modifier = modifier.fillMaxSize(),
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Texte distant : décodage UTF-8 borné, même présentation que le viewer local. */
|
||||||
|
@Composable
|
||||||
|
private fun RemoteTextViewer(bytes: ByteArray, modifier: Modifier = Modifier) {
|
||||||
|
val text = remember(bytes) {
|
||||||
|
val capped = bytes.size > REMOTE_TEXT_MAX
|
||||||
|
val length = minOf(bytes.size, REMOTE_TEXT_MAX)
|
||||||
|
String(bytes, 0, length, Charsets.UTF_8).removePrefix("") to capped
|
||||||
|
}
|
||||||
|
Column(modifier.fillMaxSize()) {
|
||||||
|
if (text.second) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.document_truncated_notice),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
SelectionContainer(Modifier.weight(1f)) {
|
||||||
|
LazyColumn(contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)) {
|
||||||
|
item {
|
||||||
|
Text(text = text.first, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PDF distant : les octets sont écrits dans un fichier temporaire du
|
||||||
|
* `cacheDir` (`stream-<resourceId>.pdf`), lu via le pager multi-pages
|
||||||
|
* partagé ([PdfPageViewer]), puis supprimé à la sortie. La fermeture du
|
||||||
|
* renderer (enfant) précède la suppression du fichier (parent).
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun RemotePdfViewer(
|
||||||
|
file: FileEntity,
|
||||||
|
bytes: ByteArray,
|
||||||
|
onOpenExternalFailed: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val contentResolver = context.contentResolver
|
||||||
|
var tmpFile by remember(file.resourceId) { mutableStateOf<File?>(null) }
|
||||||
|
var writeFailed by remember(file.resourceId) { mutableStateOf(false) }
|
||||||
|
|
||||||
|
LaunchedEffect(file.resourceId, bytes) {
|
||||||
|
writeFailed = false
|
||||||
|
tmpFile = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val tmp = File(context.cacheDir, "stream-${file.resourceId}.pdf")
|
||||||
|
tmp.writeBytes(bytes)
|
||||||
|
tmp
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
if (tmpFile == null) writeFailed = true
|
||||||
|
}
|
||||||
|
DisposableEffect(file.resourceId) {
|
||||||
|
onDispose {
|
||||||
|
val tmp = tmpFile
|
||||||
|
tmpFile = null
|
||||||
|
if (tmp != null) {
|
||||||
|
runCatching {
|
||||||
|
kotlinx.coroutines.runBlocking(Dispatchers.IO) { tmp.delete() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val tmp = tmpFile
|
||||||
|
when {
|
||||||
|
writeFailed -> Text(
|
||||||
|
text = stringResource(R.string.document_cannot_read),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
modifier = modifier,
|
||||||
|
)
|
||||||
|
tmp == null -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
}
|
||||||
|
else -> PdfPageViewer(
|
||||||
|
file = file,
|
||||||
|
contentResolver = contentResolver,
|
||||||
|
onOpenExternalFailed = onOpenExternalFailed,
|
||||||
|
modifier = modifier,
|
||||||
|
openFd = {
|
||||||
|
runCatching {
|
||||||
|
ParcelFileDescriptor.open(tmp, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||||
|
}.getOrNull()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val REMOTE_TEXT_MAX = 512 * 1024
|
||||||
+7
-6
@@ -328,18 +328,19 @@ fun FolderDetailScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (showShareSheet) {
|
if (showShareSheet) {
|
||||||
|
LaunchedEffect(folderResourceId) {
|
||||||
|
shareViewModel.load(folderResourceId, "folder")
|
||||||
|
}
|
||||||
ShareBottomSheet(
|
ShareBottomSheet(
|
||||||
|
resourceId = folderResourceId,
|
||||||
|
resourceType = "folder",
|
||||||
resourceName = uiState.folder?.name ?: stringResource(R.string.folder),
|
resourceName = uiState.folder?.name ?: stringResource(R.string.folder),
|
||||||
|
viewModel = shareViewModel,
|
||||||
|
state = shareState,
|
||||||
onDismiss = {
|
onDismiss = {
|
||||||
showShareSheet = false
|
showShareSheet = false
|
||||||
shareViewModel.reset()
|
shareViewModel.reset()
|
||||||
},
|
},
|
||||||
onShare = { username, access ->
|
|
||||||
shareViewModel.share(folderResourceId, "folder", username, access)
|
|
||||||
},
|
|
||||||
sharing = shareState.sharing,
|
|
||||||
error = shareState.error,
|
|
||||||
enqueued = shareState.enqueued,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -585,18 +585,19 @@ fun FolderListScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
shareTarget?.let { target ->
|
shareTarget?.let { target ->
|
||||||
|
LaunchedEffect(target.resourceId) {
|
||||||
|
shareViewModel.load(target.resourceId, "folder")
|
||||||
|
}
|
||||||
ShareBottomSheet(
|
ShareBottomSheet(
|
||||||
|
resourceId = target.resourceId,
|
||||||
|
resourceType = "folder",
|
||||||
resourceName = target.name,
|
resourceName = target.name,
|
||||||
|
viewModel = shareViewModel,
|
||||||
|
state = shareState,
|
||||||
onDismiss = {
|
onDismiss = {
|
||||||
shareTarget = null
|
shareTarget = null
|
||||||
shareViewModel.reset()
|
shareViewModel.reset()
|
||||||
},
|
},
|
||||||
onShare = { username, access ->
|
|
||||||
shareViewModel.share(target.resourceId, "folder", username, access)
|
|
||||||
},
|
|
||||||
sharing = shareState.sharing,
|
|
||||||
error = shareState.error,
|
|
||||||
enqueued = shareState.enqueued,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,7 +55,10 @@ fun KazierApp(
|
|||||||
|
|
||||||
when (authState) {
|
when (authState) {
|
||||||
AuthState.Loading -> SplashScreen()
|
AuthState.Loading -> SplashScreen()
|
||||||
AuthState.SignedOut -> LoginScreen()
|
is AuthState.SignedOut -> {
|
||||||
|
val signedOut = authState as AuthState.SignedOut
|
||||||
|
LoginScreen(expired = signedOut.expired, initialUsername = signedOut.username)
|
||||||
|
}
|
||||||
AuthState.Local -> NavGraph(
|
AuthState.Local -> NavGraph(
|
||||||
authViewModel = authViewModel,
|
authViewModel = authViewModel,
|
||||||
syncViewModel = syncViewModel,
|
syncViewModel = syncViewModel,
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import androidx.navigation.compose.composable
|
|||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.compose.rememberNavController
|
||||||
import androidx.navigation.navArgument
|
import androidx.navigation.navArgument
|
||||||
|
import androidx.navigation.navDeepLink
|
||||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||||
import com.kazier.mobile.features.sync.SyncViewModel
|
import com.kazier.mobile.features.sync.SyncViewModel
|
||||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||||
@@ -27,6 +28,7 @@ import com.kazier.mobile.ui.review.SwipeReviewScreen
|
|||||||
import com.kazier.mobile.ui.scan.ScanFlowScreen
|
import com.kazier.mobile.ui.scan.ScanFlowScreen
|
||||||
import com.kazier.mobile.ui.search.SearchScreen
|
import com.kazier.mobile.ui.search.SearchScreen
|
||||||
import com.kazier.mobile.ui.settings.SettingsScreen
|
import com.kazier.mobile.ui.settings.SettingsScreen
|
||||||
|
import com.kazier.mobile.ui.share.OpenLinkScreen
|
||||||
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersScreen
|
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersScreen
|
||||||
|
|
||||||
object Routes {
|
object Routes {
|
||||||
@@ -43,6 +45,10 @@ object Routes {
|
|||||||
const val PDF_BUILDER = "pdfbuilder/{ids}"
|
const val PDF_BUILDER = "pdfbuilder/{ids}"
|
||||||
const val ARG_BUILDER_IDS = "ids"
|
const val ARG_BUILDER_IDS = "ids"
|
||||||
const val SCAN = "scan"
|
const val SCAN = "scan"
|
||||||
|
const val OPEN_LINK = "openlink/{token}"
|
||||||
|
const val ARG_LINK_TOKEN = "token"
|
||||||
|
|
||||||
|
fun openLink(token: String): String = "openlink/$token"
|
||||||
|
|
||||||
fun folder(folderResourceId: String): String = "folder/$folderResourceId"
|
fun folder(folderResourceId: String): String = "folder/$folderResourceId"
|
||||||
fun document(documentResourceId: String): String = "document/$documentResourceId"
|
fun document(documentResourceId: String): String = "document/$documentResourceId"
|
||||||
@@ -233,6 +239,23 @@ fun NavGraph(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
composable(
|
||||||
|
route = Routes.OPEN_LINK,
|
||||||
|
arguments = listOf(
|
||||||
|
navArgument(Routes.ARG_LINK_TOKEN) { type = NavType.StringType },
|
||||||
|
),
|
||||||
|
deepLinks = listOf(
|
||||||
|
navDeepLink { uriPattern = "kazier://share/{token}" },
|
||||||
|
),
|
||||||
|
) { backStackEntry ->
|
||||||
|
val token = checkNotNull(
|
||||||
|
backStackEntry.arguments?.getString(Routes.ARG_LINK_TOKEN),
|
||||||
|
)
|
||||||
|
OpenLinkScreen(
|
||||||
|
token = token,
|
||||||
|
onBack = { navController.popBackStack() },
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package com.kazier.mobile.ui.share
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ouverture d'un lien de partage reçu (deep-link `kazier://share/<token>`).
|
||||||
|
*
|
||||||
|
* Résolution publique (`GET /shares/links/:token`, sans auth) : affiche les
|
||||||
|
* métadonnées du lien. Un lien seul ne crée aucun grant — le contenu
|
||||||
|
* n'apparaît dans l'app que via un partage direct du propriétaire (snapshot
|
||||||
|
* `GET /sync/permissions`), d'où le hint explicite.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun OpenLinkScreen(
|
||||||
|
token: String,
|
||||||
|
onBack: () -> Unit,
|
||||||
|
viewModel: ShareViewModel = hiltViewModel(),
|
||||||
|
) {
|
||||||
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
LaunchedEffect(token) {
|
||||||
|
viewModel.reset()
|
||||||
|
viewModel.resolveLink(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text(stringResource(R.string.share_section_open_link)) },
|
||||||
|
navigationIcon = {
|
||||||
|
IconButton(onClick = onBack) {
|
||||||
|
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
},
|
||||||
|
) { padding ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(padding)
|
||||||
|
.padding(24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
) {
|
||||||
|
when {
|
||||||
|
state.resolving -> {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.document_stream_loading),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
state.resolvedLink != null -> {
|
||||||
|
val link = state.resolvedLink!!
|
||||||
|
Text(
|
||||||
|
text = link.name,
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
text = "${link.resourceType} · ${link.access}",
|
||||||
|
style = MaterialTheme.typography.labelLarge,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_resolved_hint),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
Text(
|
||||||
|
text = stringResource(
|
||||||
|
when (state.resolveError) {
|
||||||
|
"LINK_INVALID" -> R.string.share_error_link_invalid
|
||||||
|
"LINK_NOT_FOUND" -> R.string.share_error_link_not_found
|
||||||
|
else -> R.string.share_error_link_failed
|
||||||
|
},
|
||||||
|
),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,29 +1,40 @@
|
|||||||
package com.kazier.mobile.ui.share
|
package com.kazier.mobile.ui.share
|
||||||
|
|
||||||
|
import android.widget.Toast
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
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.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Check
|
import androidx.compose.material.icons.filled.Check
|
||||||
|
import androidx.compose.material.icons.filled.ContentCopy
|
||||||
|
import androidx.compose.material.icons.filled.Delete
|
||||||
|
import androidx.compose.material.icons.filled.Link
|
||||||
import androidx.compose.material.icons.filled.Share
|
import androidx.compose.material.icons.filled.Share
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Card
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.MenuAnchorType
|
import androidx.compose.material3.MenuAnchorType
|
||||||
import androidx.compose.material3.ModalBottomSheet
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.rememberModalBottomSheetState
|
import androidx.compose.material3.rememberModalBottomSheetState
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
@@ -33,7 +44,10 @@ 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.platform.LocalClipboardManager
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
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
|
||||||
@@ -52,24 +66,29 @@ private val ACCESS_OPTIONS = listOf(
|
|||||||
AccessOption(R.string.share_access_editor, ShareAccessLevel.EDITOR),
|
AccessOption(R.string.share_access_editor, ShareAccessLevel.EDITOR),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gestion du partage d'une ressource possédée : grants actifs (accès
|
||||||
|
* modifiable, révocation), ajout par username, liens publics (création,
|
||||||
|
* copie, révocation) et ouverture d'un lien reçu. Les mutations sont
|
||||||
|
* enqueued dans l'outbox ([ShareViewModel]) — le badge « en attente »
|
||||||
|
* couvre le délai avant le drain.
|
||||||
|
*/
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun ShareBottomSheet(
|
fun ShareBottomSheet(
|
||||||
|
resourceId: String,
|
||||||
|
resourceType: String,
|
||||||
resourceName: String,
|
resourceName: String,
|
||||||
|
viewModel: ShareViewModel,
|
||||||
|
state: ShareUiState,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onShare: (username: String, access: String) -> Unit,
|
|
||||||
sharing: Boolean,
|
|
||||||
error: String?,
|
|
||||||
enqueued: Boolean,
|
|
||||||
) {
|
) {
|
||||||
var username by rememberSaveable { mutableStateOf("") }
|
|
||||||
var access by rememberSaveable { mutableStateOf(ShareAccessLevel.VIEWER) }
|
|
||||||
// Confirmation visible avant fermeture : fini l'auto-dismiss silencieux.
|
// Confirmation visible avant fermeture : fini l'auto-dismiss silencieux.
|
||||||
var justShared by rememberSaveable { mutableStateOf(false) }
|
var justShared by rememberSaveable { mutableStateOf(false) }
|
||||||
val sheetState = rememberModalBottomSheetState()
|
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||||
|
|
||||||
LaunchedEffect(enqueued) {
|
LaunchedEffect(state.enqueued) {
|
||||||
if (enqueued && !justShared) {
|
if (state.enqueued && !justShared) {
|
||||||
justShared = true
|
justShared = true
|
||||||
delay(1_200)
|
delay(1_200)
|
||||||
onDismiss()
|
onDismiss()
|
||||||
@@ -83,6 +102,7 @@ fun ShareBottomSheet(
|
|||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
.padding(horizontal = 16.dp)
|
.padding(horizontal = 16.dp)
|
||||||
.padding(bottom = 24.dp),
|
.padding(bottom = 24.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
@@ -99,30 +119,54 @@ fun ShareBottomSheet(
|
|||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
)
|
)
|
||||||
|
|
||||||
OutlinedTextField(
|
if (state.pendingCount > 0) {
|
||||||
value = username,
|
|
||||||
onValueChange = { username = it },
|
|
||||||
label = { Text(stringResource(R.string.share_username_hint)) },
|
|
||||||
singleLine = true,
|
|
||||||
enabled = !justShared,
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
)
|
|
||||||
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.share_access_label),
|
|
||||||
style = MaterialTheme.typography.labelLarge,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
AccessDropdown(
|
|
||||||
selected = access,
|
|
||||||
onSelect = { access = it },
|
|
||||||
enabled = !justShared,
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
)
|
|
||||||
|
|
||||||
error?.let { code ->
|
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(shareErrorResFor(code)),
|
text = stringResource(R.string.share_pending, state.pendingCount),
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
when {
|
||||||
|
state.loading -> Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.Center,
|
||||||
|
) {
|
||||||
|
CircularProgressIndicator(modifier = Modifier.size(28.dp))
|
||||||
|
}
|
||||||
|
state.loadError != null -> LoadErrorRow(
|
||||||
|
code = state.loadError,
|
||||||
|
onRetry = { viewModel.refresh() },
|
||||||
|
)
|
||||||
|
else -> {
|
||||||
|
GrantsSection(
|
||||||
|
grants = state.shares,
|
||||||
|
onChangeAccess = { grant, access ->
|
||||||
|
viewModel.changeAccess(resourceId, resourceType, grant, access)
|
||||||
|
},
|
||||||
|
onRevoke = { grant -> viewModel.revoke(resourceId, resourceType, grant) },
|
||||||
|
)
|
||||||
|
AddShareSection(
|
||||||
|
sharing = state.sharing,
|
||||||
|
error = state.error,
|
||||||
|
enqueued = state.enqueued,
|
||||||
|
justShared = justShared,
|
||||||
|
onShare = { username, access ->
|
||||||
|
viewModel.share(resourceId, resourceType, username, access)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
LinksSection(
|
||||||
|
links = state.links,
|
||||||
|
lastCreated = state.lastCreatedLink,
|
||||||
|
onCreate = { access -> viewModel.createLink(resourceId, resourceType, access) },
|
||||||
|
onRevoke = { link -> viewModel.revokeLink(resourceId, resourceType, link) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
state.actionError?.let {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_error_generic),
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.error,
|
color = MaterialTheme.colorScheme.error,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
@@ -130,45 +174,17 @@ fun ShareBottomSheet(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (justShared) {
|
OpenLinkSection(
|
||||||
Row(
|
resolving = state.resolving,
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
resolved = state.resolvedLink,
|
||||||
horizontalArrangement = Arrangement.Center,
|
resolveError = state.resolveError,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
onResolve = { viewModel.resolveLink(it) },
|
||||||
) {
|
onClear = { viewModel.clearResolved() },
|
||||||
Icon(
|
)
|
||||||
imageVector = Icons.Filled.Check,
|
|
||||||
contentDescription = null,
|
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
|
||||||
)
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.share_enqueued),
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.primary,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Button(
|
|
||||||
onClick = { onShare(username.trim(), access) },
|
|
||||||
enabled = username.isNotBlank() && !sharing && !justShared,
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
if (sharing) {
|
|
||||||
CircularProgressIndicator(
|
|
||||||
modifier = Modifier.size(20.dp),
|
|
||||||
strokeWidth = 2.dp,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Icon(Icons.Filled.Share, contentDescription = null)
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
Text(stringResource(R.string.share_submit))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onClick = onDismiss,
|
onClick = onDismiss,
|
||||||
enabled = !sharing && !justShared,
|
enabled = !state.sharing,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
Text(stringResource(R.string.share_cancel))
|
Text(stringResource(R.string.share_cancel))
|
||||||
@@ -177,6 +193,420 @@ fun ShareBottomSheet(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LoadErrorRow(code: String, onRetry: () -> Unit) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(
|
||||||
|
if (code == "FORBIDDEN") R.string.share_error_forbidden else R.string.share_error_load,
|
||||||
|
),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
TextButton(onClick = onRetry) {
|
||||||
|
Text(stringResource(R.string.share_retry))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SectionTitle(text: String) {
|
||||||
|
Text(
|
||||||
|
text = text,
|
||||||
|
style = MaterialTheme.typography.labelLarge,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GrantsSection(
|
||||||
|
grants: List<ShareGrantUi>,
|
||||||
|
onChangeAccess: (ShareGrantUi, String) -> Unit,
|
||||||
|
onRevoke: (ShareGrantUi) -> Unit,
|
||||||
|
) {
|
||||||
|
var pendingRevoke by rememberSaveable { mutableStateOf<ShareGrantUi?>(null) }
|
||||||
|
|
||||||
|
SectionTitle(stringResource(R.string.share_section_grants))
|
||||||
|
if (grants.isEmpty()) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_empty_grants),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
grants.forEach { grant ->
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = grant.username,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
if (grant.expired) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_expired),
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
GrantAccessPicker(
|
||||||
|
selected = grant.access,
|
||||||
|
onSelect = { onChangeAccess(grant, it) },
|
||||||
|
)
|
||||||
|
IconButton(onClick = { pendingRevoke = grant }) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Delete,
|
||||||
|
contentDescription = stringResource(R.string.share_revoke),
|
||||||
|
tint = MaterialTheme.colorScheme.error,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingRevoke?.let { grant ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { pendingRevoke = null },
|
||||||
|
text = { Text(stringResource(R.string.share_revoke_confirm, grant.username)) },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
onRevoke(grant)
|
||||||
|
pendingRevoke = null
|
||||||
|
}) {
|
||||||
|
Text(stringResource(R.string.share_confirm))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { pendingRevoke = null }) {
|
||||||
|
Text(stringResource(R.string.share_cancel))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sélecteur d'accès compact pour une ligne de grant existant. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
private fun GrantAccessPicker(selected: String, onSelect: (String) -> Unit) {
|
||||||
|
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||||
|
val label = ACCESS_OPTIONS.firstOrNull { it.value == selected }?.labelRes
|
||||||
|
?: ACCESS_OPTIONS.first().labelRes
|
||||||
|
ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = stringResource(label),
|
||||||
|
onValueChange = {},
|
||||||
|
readOnly = true,
|
||||||
|
singleLine = true,
|
||||||
|
textStyle = MaterialTheme.typography.labelLarge,
|
||||||
|
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||||
|
modifier = Modifier
|
||||||
|
.menuAnchor(MenuAnchorType.PrimaryNotEditable)
|
||||||
|
.width(150.dp),
|
||||||
|
)
|
||||||
|
ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||||
|
ACCESS_OPTIONS.forEach { option ->
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(stringResource(option.labelRes)) },
|
||||||
|
onClick = {
|
||||||
|
onSelect(option.value)
|
||||||
|
expanded = false
|
||||||
|
},
|
||||||
|
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun AddShareSection(
|
||||||
|
sharing: Boolean,
|
||||||
|
error: String?,
|
||||||
|
enqueued: Boolean,
|
||||||
|
justShared: Boolean,
|
||||||
|
onShare: (username: String, access: String) -> Unit,
|
||||||
|
) {
|
||||||
|
var username by rememberSaveable { mutableStateOf("") }
|
||||||
|
var access by rememberSaveable { mutableStateOf(ShareAccessLevel.VIEWER) }
|
||||||
|
|
||||||
|
SectionTitle(stringResource(R.string.share_section_add))
|
||||||
|
OutlinedTextField(
|
||||||
|
value = username,
|
||||||
|
onValueChange = { username = it },
|
||||||
|
label = { Text(stringResource(R.string.share_username_hint)) },
|
||||||
|
singleLine = true,
|
||||||
|
enabled = !justShared,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
AccessDropdown(
|
||||||
|
selected = access,
|
||||||
|
onSelect = { access = it },
|
||||||
|
enabled = !justShared,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
|
||||||
|
error?.let { code ->
|
||||||
|
Text(
|
||||||
|
text = stringResource(shareErrorResFor(code)),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (justShared && enqueued) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.Center,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Filled.Check,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_enqueued),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = { onShare(username.trim(), access) },
|
||||||
|
enabled = username.isNotBlank() && !sharing && !justShared,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
if (sharing) {
|
||||||
|
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||||
|
} else {
|
||||||
|
Icon(Icons.Filled.Share, contentDescription = null)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text(stringResource(R.string.share_submit))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LinksSection(
|
||||||
|
links: List<ShareLinkUi>,
|
||||||
|
lastCreated: ShareLinkUi?,
|
||||||
|
onCreate: (String) -> Unit,
|
||||||
|
onRevoke: (ShareLinkUi) -> Unit,
|
||||||
|
) {
|
||||||
|
var access by rememberSaveable { mutableStateOf(ShareAccessLevel.VIEWER) }
|
||||||
|
var pendingRevoke by rememberSaveable { mutableStateOf<ShareLinkUi?>(null) }
|
||||||
|
val clipboard = LocalClipboardManager.current
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
SectionTitle(stringResource(R.string.share_section_links))
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
AccessDropdown(
|
||||||
|
selected = access,
|
||||||
|
onSelect = { access = it },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
Button(onClick = { onCreate(access) }) {
|
||||||
|
Icon(Icons.Filled.Link, contentDescription = null)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text(stringResource(R.string.share_link_create))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lastCreated?.let { link ->
|
||||||
|
// Le token n'existe que côté client jusqu'au drain : la carte reste
|
||||||
|
// affichée pour copie avant fermeture.
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_link_created),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = link.url,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
maxLines = 2,
|
||||||
|
)
|
||||||
|
OutlinedButton(onClick = {
|
||||||
|
clipboard.setText(AnnotatedString(link.url))
|
||||||
|
Toast.makeText(context, context.getString(R.string.share_link_copied), Toast.LENGTH_SHORT).show()
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Filled.ContentCopy, contentDescription = null)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text(stringResource(R.string.share_link_copy))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (links.isEmpty()) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_empty_links),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
links.forEach { link ->
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = link.url,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = accessLabel(link.access),
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = {
|
||||||
|
clipboard.setText(AnnotatedString(link.url))
|
||||||
|
Toast.makeText(context, context.getString(R.string.share_link_copied), Toast.LENGTH_SHORT).show()
|
||||||
|
}) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.ContentCopy,
|
||||||
|
contentDescription = stringResource(R.string.share_link_copy),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = { pendingRevoke = link }) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Delete,
|
||||||
|
contentDescription = stringResource(R.string.share_revoke),
|
||||||
|
tint = MaterialTheme.colorScheme.error,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingRevoke?.let { link ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { pendingRevoke = null },
|
||||||
|
text = { Text(stringResource(R.string.share_link_revoke_confirm)) },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
onRevoke(link)
|
||||||
|
pendingRevoke = null
|
||||||
|
}) {
|
||||||
|
Text(stringResource(R.string.share_confirm))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { pendingRevoke = null }) {
|
||||||
|
Text(stringResource(R.string.share_cancel))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun accessLabel(access: String): String = stringResource(
|
||||||
|
when (access) {
|
||||||
|
ShareAccessLevel.COMMENTER -> R.string.share_access_commenter
|
||||||
|
ShareAccessLevel.EDITOR -> R.string.share_access_editor
|
||||||
|
else -> R.string.share_access_viewer
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun OpenLinkSection(
|
||||||
|
resolving: Boolean,
|
||||||
|
resolved: ResolvedLinkUi?,
|
||||||
|
resolveError: String?,
|
||||||
|
onResolve: (String) -> Unit,
|
||||||
|
onClear: () -> Unit,
|
||||||
|
) {
|
||||||
|
var input by rememberSaveable { mutableStateOf("") }
|
||||||
|
|
||||||
|
SectionTitle(stringResource(R.string.share_section_open_link))
|
||||||
|
OutlinedTextField(
|
||||||
|
value = input,
|
||||||
|
onValueChange = {
|
||||||
|
input = it
|
||||||
|
if (resolved != null || resolveError != null) onClear()
|
||||||
|
},
|
||||||
|
label = { Text(stringResource(R.string.share_open_link_hint)) },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = { onResolve(input) },
|
||||||
|
enabled = input.isNotBlank() && !resolving,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
if (resolving) {
|
||||||
|
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||||
|
} else {
|
||||||
|
Text(stringResource(R.string.share_open_link_button))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resolveError?.let { code ->
|
||||||
|
Text(
|
||||||
|
text = stringResource(
|
||||||
|
when (code) {
|
||||||
|
"LINK_INVALID" -> R.string.share_error_link_invalid
|
||||||
|
"LINK_NOT_FOUND" -> R.string.share_error_link_not_found
|
||||||
|
else -> R.string.share_error_link_failed
|
||||||
|
},
|
||||||
|
),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
resolved?.let { link ->
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Text(
|
||||||
|
text = link.name,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "${link.resourceType} · ${link.access}",
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.share_resolved_hint),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
private fun AccessDropdown(
|
private fun AccessDropdown(
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.kazier.mobile.ui.share
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extraction d'un token de lien de partage depuis une saisie utilisateur.
|
||||||
|
*
|
||||||
|
* Formats acceptés : 32-hex brut, deep-link `kazier://share/<token>`,
|
||||||
|
* URL API `…/shares/links/<token>`, ou page courte `…/s/<token>`.
|
||||||
|
* Retourne le token normalisé (lowercase) ou null si rien d'exploitable.
|
||||||
|
*
|
||||||
|
* Le format partagé est TOUJOURS le deep-link `kazier://share/<token>`
|
||||||
|
* (voir [shareUrl]) : indépendant du domaine du serveur, donc compatible
|
||||||
|
* self-hosting (pas d'App Links https vérifiés, qui exigeraient un domaine
|
||||||
|
* unique). Les formes https ne servent qu'à tolérer un lien collé.
|
||||||
|
*/
|
||||||
|
object ShareLinkParser {
|
||||||
|
private val HEX32 = Regex("^[0-9a-f]{32}$")
|
||||||
|
private val HEX32_LOOSE = Regex("^[0-9a-fA-F]{32}$")
|
||||||
|
private val IN_URL = Regex("(?:shares/links|/share|/s)[:/]([0-9a-fA-F]{32})(?![0-9a-fA-F])")
|
||||||
|
|
||||||
|
fun extractToken(input: String): String? {
|
||||||
|
val trimmed = input.trim()
|
||||||
|
if (trimmed.isEmpty()) return null
|
||||||
|
val lowered = trimmed.lowercase()
|
||||||
|
if (HEX32.matches(lowered)) return lowered
|
||||||
|
if (HEX32_LOOSE.matches(trimmed)) return lowered
|
||||||
|
return IN_URL.find(trimmed)?.groupValues?.get(1)?.lowercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Texte à copier/partager pour un lien : deep-link ouvrable par l'app. */
|
||||||
|
fun shareUrl(token: String): String = "kazier://share/$token"
|
||||||
|
}
|
||||||
@@ -6,8 +6,8 @@ import androidx.lifecycle.viewModelScope
|
|||||||
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.repository.OutboxRepository
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
import com.kazier.mobile.features.sync.OutboxSyncWorker
|
import com.kazier.mobile.features.sync.OutboxSyncWorker
|
||||||
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
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -18,14 +18,6 @@ import kotlinx.coroutines.launch
|
|||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
data class ShareUiState(
|
|
||||||
val sharing: Boolean = false,
|
|
||||||
/** Code d'erreur contractuel (`USER_NOT_FOUND`, `SHARE_FAILED`) ou null. */
|
|
||||||
val error: String? = null,
|
|
||||||
/** L'op `share` a été enqueued avec succès (prête pour le drain). */
|
|
||||||
val enqueued: Boolean = false,
|
|
||||||
)
|
|
||||||
|
|
||||||
/** Accès partage — valeur du payload `access` (docs/api-v1.md §6.1). */
|
/** Accès partage — valeur du payload `access` (docs/api-v1.md §6.1). */
|
||||||
object ShareAccessLevel {
|
object ShareAccessLevel {
|
||||||
const val VIEWER = "viewer"
|
const val VIEWER = "viewer"
|
||||||
@@ -33,27 +25,145 @@ object ShareAccessLevel {
|
|||||||
const val EDITOR = "editor"
|
const val EDITOR = "editor"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Grant actif affiché dans le sheet (miroir `ShareGrantDto`). */
|
||||||
|
data class ShareGrantUi(
|
||||||
|
val granteeUserId: String,
|
||||||
|
val username: String,
|
||||||
|
val access: String,
|
||||||
|
val inherit: Boolean,
|
||||||
|
val expiresAt: Long?,
|
||||||
|
val expired: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Lien public actif affiché dans le sheet (miroir `ShareLinkDto`). */
|
||||||
|
data class ShareLinkUi(
|
||||||
|
val token: String,
|
||||||
|
val access: String,
|
||||||
|
val expiresAt: String?,
|
||||||
|
/** Texte à copier : deep-link `kazier://share/<token>`. */
|
||||||
|
val url: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Lien résolu via `GET /shares/links/:token` (ouverture d'un lien reçu). */
|
||||||
|
data class ResolvedLinkUi(
|
||||||
|
val token: String,
|
||||||
|
val resourceId: String,
|
||||||
|
val resourceType: String,
|
||||||
|
val name: String,
|
||||||
|
val access: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ShareUiState(
|
||||||
|
val loading: Boolean = false,
|
||||||
|
/** Cible courante du sheet (resource partagée). */
|
||||||
|
val resourceId: String? = null,
|
||||||
|
val resourceType: String? = null,
|
||||||
|
val shares: List<ShareGrantUi> = emptyList(),
|
||||||
|
val links: List<ShareLinkUi> = emptyList(),
|
||||||
|
/** Ops de partage en attente d'envoi (pas encore reflétées serveur). */
|
||||||
|
val pendingCount: Int = 0,
|
||||||
|
/** Erreur de chargement des listes (`LOAD_FAILED`, `FORBIDDEN`). */
|
||||||
|
val loadError: String? = null,
|
||||||
|
/** Ajout d'un partage en cours. */
|
||||||
|
val sharing: Boolean = false,
|
||||||
|
/** Code d'erreur du formulaire d'ajout (`USER_NOT_FOUND`, `SHARE_FAILED`). */
|
||||||
|
val error: String? = null,
|
||||||
|
/** Succès transitoire d'ajout (affiché puis effacé). */
|
||||||
|
val enqueued: Boolean = false,
|
||||||
|
/** Erreur transitoire d'une action ligne (update/revoke/link). */
|
||||||
|
val actionError: String? = null,
|
||||||
|
/** Dernier lien créé — à copier (consommé puis effacé). */
|
||||||
|
val lastCreatedLink: ShareLinkUi? = null,
|
||||||
|
/** Résolution d'un lien reçu en cours. */
|
||||||
|
val resolving: Boolean = false,
|
||||||
|
val resolvedLink: ResolvedLinkUi? = null,
|
||||||
|
/** Erreur de résolution (`LINK_INVALID`, `LINK_NOT_FOUND`). */
|
||||||
|
val resolveError: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Partage d'une ressource locale avec un autre utilisateur : résout le
|
* Gestion complète du partage d'une ressource possédée :
|
||||||
* destinataire par username (exact), puis enqueue l'op `share` dans l'outbox
|
*
|
||||||
* (drainée par [OutboxSyncWorker]).
|
* - listes serveur (`GET /files/:id/shares`, `GET /files/:id/links`,
|
||||||
|
* owner uniquement) + compteur d'ops en attente (outbox locale) ;
|
||||||
|
* - ajout (`share`), changement d'accès (`update_share`), révocation
|
||||||
|
* (`revoke_share`) — enqueued dans l'outbox, drainés par
|
||||||
|
* [OutboxSyncWorker] ;
|
||||||
|
* - liens publics (`create_link` avec token [GenerateId], `revoke_link`) +
|
||||||
|
* copie du deep-link `kazier://share/<token>` ;
|
||||||
|
* - ouverture d'un lien reçu (collé ou deep-link) via `getShareLink`.
|
||||||
*/
|
*/
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class ShareViewModel @Inject constructor(
|
class ShareViewModel @Inject constructor(
|
||||||
private val apiClient: ApiClient,
|
private val apiClient: ApiClient,
|
||||||
private val outboxRepository: OutboxRepository,
|
private val outboxRepository: OutboxRepository,
|
||||||
|
private val generateId: GenerateId,
|
||||||
@ApplicationContext private val appContext: Context,
|
@ApplicationContext private val appContext: Context,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val _uiState = MutableStateFlow(ShareUiState())
|
private val _uiState = MutableStateFlow(ShareUiState())
|
||||||
val uiState: StateFlow<ShareUiState> = _uiState.asStateFlow()
|
val uiState: StateFlow<ShareUiState> = _uiState.asStateFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Charge les listes d'une ressource (appelé à l'ouverture du sheet).
|
||||||
|
* 404 serveur → la ressource n'est pas possédée (`FORBIDDEN`) : le sheet
|
||||||
|
* n'affiche que l'erreur, sans listes.
|
||||||
|
*/
|
||||||
|
fun load(resourceId: String, resourceType: String) {
|
||||||
|
val current = _uiState.value
|
||||||
|
if (current.resourceId == resourceId && current.loading) return
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(
|
||||||
|
loading = true, loadError = null, resourceId = resourceId,
|
||||||
|
resourceType = resourceType, actionError = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
viewModelScope.launch {
|
||||||
|
runCatching {
|
||||||
|
val shares = apiClient.listShares(resourceId)
|
||||||
|
val links = apiClient.listLinks(resourceId)
|
||||||
|
val pending = outboxRepository.pendingShareOps(resourceId).size
|
||||||
|
Triple(shares, links, pending)
|
||||||
|
}.onSuccess { (shares, links, pending) ->
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(
|
||||||
|
loading = false,
|
||||||
|
shares = shares.map { dto ->
|
||||||
|
ShareGrantUi(
|
||||||
|
granteeUserId = dto.granteeUserId,
|
||||||
|
username = dto.username,
|
||||||
|
access = dto.access,
|
||||||
|
inherit = dto.inherit,
|
||||||
|
expiresAt = dto.expiresAt,
|
||||||
|
expired = dto.expiresAt != null && dto.expiresAt <= now,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
links = links.map { dto ->
|
||||||
|
ShareLinkUi(
|
||||||
|
token = dto.token,
|
||||||
|
access = dto.access,
|
||||||
|
expiresAt = dto.expiresAt,
|
||||||
|
url = ShareLinkParser.shareUrl(dto.token),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
pendingCount = pending,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.onFailure { e ->
|
||||||
|
val code = if (e is ApiException && e.code == "NOT_FOUND") "FORBIDDEN" else "LOAD_FAILED"
|
||||||
|
Timber.w(e, "share: load failed for %s", resourceId)
|
||||||
|
_uiState.update { it.copy(loading = false, loadError = code) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Partage [resourceId] avec l'utilisateur [username] au niveau [access].
|
* Partage [resourceId] avec l'utilisateur [username] au niveau [access].
|
||||||
*
|
*
|
||||||
* 1. `GET /users/resolve` (username exact) → user id ;
|
* 1. `GET /users/resolve` (username exact) → user id ;
|
||||||
* 2. enqueue `share` dans l'outbox ;
|
* 2. enqueue `share` dans l'outbox ;
|
||||||
* 3. déclenche le drain du worker.
|
* 3. déclenche le drain du worker + recharge le compteur pending.
|
||||||
*/
|
*/
|
||||||
fun share(resourceId: String, resourceType: String, username: String, access: String) {
|
fun share(resourceId: String, resourceType: String, username: String, access: String) {
|
||||||
if (_uiState.value.sharing) return
|
if (_uiState.value.sharing) return
|
||||||
@@ -69,9 +179,9 @@ class ShareViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
}.onSuccess {
|
}.onSuccess {
|
||||||
OutboxSyncWorker.enqueue(appContext)
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
OcrAutoWorker.enqueue(appContext)
|
|
||||||
Timber.d("share: op enqueued for %s", resourceId)
|
Timber.d("share: op enqueued for %s", resourceId)
|
||||||
_uiState.update { it.copy(sharing = false, enqueued = true) }
|
_uiState.update { it.copy(sharing = false, enqueued = true) }
|
||||||
|
refreshPending(resourceId)
|
||||||
}.onFailure { e ->
|
}.onFailure { e ->
|
||||||
val error = when {
|
val error = when {
|
||||||
e is ApiException && e.code == "NOT_FOUND" -> "USER_NOT_FOUND"
|
e is ApiException && e.code == "NOT_FOUND" -> "USER_NOT_FOUND"
|
||||||
@@ -83,12 +193,174 @@ class ShareViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Consomme l'état clone (succès/erreur affiché) avant de rouvrir le sheet. */
|
/** Change l'accès d'un grant existant (`update_share`, upsert serveur). */
|
||||||
|
fun changeAccess(resourceId: String, resourceType: String, grant: ShareGrantUi, access: String) {
|
||||||
|
if (grant.access == access) return
|
||||||
|
viewModelScope.launch {
|
||||||
|
_uiState.update { it.copy(actionError = null) }
|
||||||
|
runCatching {
|
||||||
|
outboxRepository.enqueueUpdateShare(
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
granteeUserId = grant.granteeUserId,
|
||||||
|
access = access,
|
||||||
|
)
|
||||||
|
}.onSuccess {
|
||||||
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
|
_uiState.update { state ->
|
||||||
|
state.copy(
|
||||||
|
shares = state.shares.map {
|
||||||
|
if (it.granteeUserId == grant.granteeUserId) it.copy(access = access) else it
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
refreshPending(resourceId)
|
||||||
|
}.onFailure { e ->
|
||||||
|
Timber.w(e, "share: update failed")
|
||||||
|
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Révoque un grant (`revoke_share`, idempotent serveur). */
|
||||||
|
fun revoke(resourceId: String, resourceType: String, grant: ShareGrantUi) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_uiState.update { it.copy(actionError = null) }
|
||||||
|
runCatching {
|
||||||
|
outboxRepository.enqueueRevokeShare(
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
granteeUserId = grant.granteeUserId,
|
||||||
|
)
|
||||||
|
}.onSuccess {
|
||||||
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
|
_uiState.update { state ->
|
||||||
|
state.copy(shares = state.shares.filter { it.granteeUserId != grant.granteeUserId })
|
||||||
|
}
|
||||||
|
refreshPending(resourceId)
|
||||||
|
}.onFailure { e ->
|
||||||
|
Timber.w(e, "share: revoke failed")
|
||||||
|
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crée un lien public (`create_link`, token 32-hex généré localement).
|
||||||
|
* Le lien est exposé en [ShareUiState.lastCreatedLink] pour copie.
|
||||||
|
*/
|
||||||
|
fun createLink(resourceId: String, resourceType: String, access: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_uiState.update { it.copy(actionError = null, lastCreatedLink = null) }
|
||||||
|
val token = generateId.newResourceId()
|
||||||
|
runCatching {
|
||||||
|
outboxRepository.enqueueCreateLink(
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
token = token,
|
||||||
|
access = access,
|
||||||
|
)
|
||||||
|
}.onSuccess {
|
||||||
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(lastCreatedLink = ShareLinkUi(token, access, null, ShareLinkParser.shareUrl(token)))
|
||||||
|
}
|
||||||
|
refreshPending(resourceId)
|
||||||
|
}.onFailure { e ->
|
||||||
|
Timber.w(e, "share: create link failed")
|
||||||
|
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Révoque un lien public (`revoke_link`, idempotent serveur). */
|
||||||
|
fun revokeLink(resourceId: String, resourceType: String, link: ShareLinkUi) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_uiState.update { it.copy(actionError = null) }
|
||||||
|
runCatching {
|
||||||
|
outboxRepository.enqueueRevokeLink(
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
token = link.token,
|
||||||
|
)
|
||||||
|
}.onSuccess {
|
||||||
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
|
_uiState.update { state ->
|
||||||
|
state.copy(links = state.links.filter { it.token != link.token })
|
||||||
|
}
|
||||||
|
refreshPending(resourceId)
|
||||||
|
}.onFailure { e ->
|
||||||
|
Timber.w(e, "share: revoke link failed")
|
||||||
|
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout un lien reçu (token brut, deep-link `kazier://share/…` ou URL
|
||||||
|
* `…/shares/links/…` collé) via la route publique `getShareLink`.
|
||||||
|
*/
|
||||||
|
fun resolveLink(input: String) {
|
||||||
|
val token = ShareLinkParser.extractToken(input)
|
||||||
|
if (token == null) {
|
||||||
|
_uiState.update { it.copy(resolvedLink = null, resolveError = "LINK_INVALID") }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (_uiState.value.resolving) return
|
||||||
|
viewModelScope.launch {
|
||||||
|
_uiState.update { it.copy(resolving = true, resolvedLink = null, resolveError = null) }
|
||||||
|
runCatching { apiClient.getShareLink(token) }
|
||||||
|
.onSuccess { dto ->
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(
|
||||||
|
resolving = false,
|
||||||
|
resolvedLink = ResolvedLinkUi(
|
||||||
|
token = dto.token,
|
||||||
|
resourceId = dto.resourceId,
|
||||||
|
resourceType = dto.resourceType,
|
||||||
|
name = dto.name,
|
||||||
|
access = dto.access,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onFailure { e ->
|
||||||
|
val code = if (e is ApiException && e.code == "NOT_FOUND") "LINK_NOT_FOUND" else "LINK_FAILED"
|
||||||
|
Timber.w(e, "share: resolve link failed")
|
||||||
|
_uiState.update { it.copy(resolving = false, resolveError = code) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recharge les listes serveur (bouton réessayer / après drain). */
|
||||||
|
fun refresh() {
|
||||||
|
val state = _uiState.value
|
||||||
|
val id = state.resourceId ?: return
|
||||||
|
val type = state.resourceType ?: return
|
||||||
|
load(id, type)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun refreshPending(resourceId: String) {
|
||||||
|
val pending = runCatching { outboxRepository.pendingShareOps(resourceId).size }.getOrDefault(0)
|
||||||
|
_uiState.update { it.copy(pendingCount = pending) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Consomme l'état transitoire avant de rouvrir le sheet. */
|
||||||
fun reset() {
|
fun reset() {
|
||||||
_uiState.value = ShareUiState()
|
_uiState.value = ShareUiState()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Consomme le lien à copier après affichage. */
|
||||||
|
fun clearLastCreatedLink() {
|
||||||
|
_uiState.update { it.copy(lastCreatedLink = null) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Consomme le lien résolu après affichage. */
|
||||||
|
fun clearResolved() {
|
||||||
|
_uiState.update { it.copy(resolvedLink = null, resolveError = null) }
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCleared() {
|
override fun onCleared() {
|
||||||
super.onCleared()
|
super.onCleared()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,6 +84,13 @@
|
|||||||
<string name="document_truncated_notice">Preview truncated — the full file is not displayed.</string>
|
<string name="document_truncated_notice">Preview truncated — the full file is not displayed.</string>
|
||||||
<string name="document_loading">Reading document…</string>
|
<string name="document_loading">Reading document…</string>
|
||||||
<string name="document_cannot_read">Could not read this document.</string>
|
<string name="document_cannot_read">Could not read this document.</string>
|
||||||
|
<string name="document_stream_load">Stream</string>
|
||||||
|
<string name="document_stream_loading">Loading from the server…</string>
|
||||||
|
<string name="document_stream_retry">Retry</string>
|
||||||
|
<string name="document_stream_error">Streaming failed. Check your connection and retry.</string>
|
||||||
|
<string name="document_stream_no_content">No server content for this file.</string>
|
||||||
|
<string name="document_stream_too_large">File too large for streaming (max 12 MB).</string>
|
||||||
|
<string name="document_stream_unsupported">Streaming preview not supported for this file type.</string>
|
||||||
<string name="document_page_unreadable">Unreadable page</string>
|
<string name="document_page_unreadable">Unreadable page</string>
|
||||||
<string name="focus_tap_to_exit">Tap to exit</string>
|
<string name="focus_tap_to_exit">Tap to exit</string>
|
||||||
<string name="login_show_password">Show password</string>
|
<string name="login_show_password">Show password</string>
|
||||||
@@ -170,6 +177,7 @@
|
|||||||
<string name="login_error_required">Username and password are required</string>
|
<string name="login_error_required">Username and password are required</string>
|
||||||
<string name="login_error_generic">Could not sign in right now</string>
|
<string name="login_error_generic">Could not sign in right now</string>
|
||||||
<string name="login_error_unauthorized">Incorrect username or password</string>
|
<string name="login_error_unauthorized">Incorrect username or password</string>
|
||||||
|
<string name="login_session_expired">Session expired — sign in again to continue.</string>
|
||||||
<string name="login_skip">Continue without account</string>
|
<string name="login_skip">Continue without account</string>
|
||||||
<string name="login_choice_subtitle">Choose how to use Kazier</string>
|
<string name="login_choice_subtitle">Choose how to use Kazier</string>
|
||||||
<string name="skip_message">Local mode — your folders stay on this device and are not synced.</string>
|
<string name="skip_message">Local mode — your folders stay on this device and are not synced.</string>
|
||||||
@@ -309,6 +317,31 @@
|
|||||||
<string name="share_error_not_found">No user found with this username.</string>
|
<string name="share_error_not_found">No user found with this username.</string>
|
||||||
<string name="share_error_generic">Could not share right now.</string>
|
<string name="share_error_generic">Could not share right now.</string>
|
||||||
<string name="share_enqueued">Share saved — syncing.</string>
|
<string name="share_enqueued">Share saved — syncing.</string>
|
||||||
|
<string name="share_pending">%1$d change(s) pending upload.</string>
|
||||||
|
<string name="share_section_grants">People with access</string>
|
||||||
|
<string name="share_section_add">Add access</string>
|
||||||
|
<string name="share_section_links">Public links</string>
|
||||||
|
<string name="share_section_open_link">Open a received link</string>
|
||||||
|
<string name="share_empty_grants">Nobody yet — add access below.</string>
|
||||||
|
<string name="share_empty_links">No links — create one to share without a recipient account.</string>
|
||||||
|
<string name="share_expired">expired</string>
|
||||||
|
<string name="share_revoke">Revoke</string>
|
||||||
|
<string name="share_revoke_confirm">Revoke access for %1$s?</string>
|
||||||
|
<string name="share_link_create">Create link</string>
|
||||||
|
<string name="share_link_created">Link created — copy it before closing.</string>
|
||||||
|
<string name="share_link_copy">Copy</string>
|
||||||
|
<string name="share_link_copied">Link copied.</string>
|
||||||
|
<string name="share_link_revoke_confirm">Revoke this link? It will stop working.</string>
|
||||||
|
<string name="share_open_link_hint">Paste a received link or token</string>
|
||||||
|
<string name="share_open_link_button">Open</string>
|
||||||
|
<string name="share_resolved_hint">Valid link — ask the owner for a direct share to see the content in the app.</string>
|
||||||
|
<string name="share_error_link_invalid">Unreadable link — paste the full link or token.</string>
|
||||||
|
<string name="share_error_link_not_found">Unknown, revoked or expired link.</string>
|
||||||
|
<string name="share_error_link_failed">Could not open this link right now.</string>
|
||||||
|
<string name="share_error_load">Could not load shares.</string>
|
||||||
|
<string name="share_error_forbidden">You do not own this resource.</string>
|
||||||
|
<string name="share_retry">Retry</string>
|
||||||
|
<string name="share_confirm">Confirm</string>
|
||||||
<string name="share_content_description">Share this folder</string>
|
<string name="share_content_description">Share this folder</string>
|
||||||
<string name="share_action">Share</string>
|
<string name="share_action">Share</string>
|
||||||
<string name="more_actions">More actions</string>
|
<string name="more_actions">More actions</string>
|
||||||
|
|||||||
@@ -84,6 +84,13 @@
|
|||||||
<string name="document_truncated_notice">Aperçu tronqué — le fichier complet n\'est pas affiché.</string>
|
<string name="document_truncated_notice">Aperçu tronqué — le fichier complet n\'est pas affiché.</string>
|
||||||
<string name="document_loading">Lecture du document…</string>
|
<string name="document_loading">Lecture du document…</string>
|
||||||
<string name="document_cannot_read">Impossible de lire ce document.</string>
|
<string name="document_cannot_read">Impossible de lire ce document.</string>
|
||||||
|
<string name="document_stream_load">Lire en streaming</string>
|
||||||
|
<string name="document_stream_loading">Chargement depuis le serveur…</string>
|
||||||
|
<string name="document_stream_retry">Réessayer</string>
|
||||||
|
<string name="document_stream_error">Échec du streaming. Vérifie ta connexion puis réessaie.</string>
|
||||||
|
<string name="document_stream_no_content">Aucun contenu sur le serveur pour ce fichier.</string>
|
||||||
|
<string name="document_stream_too_large">Fichier trop volumineux pour le streaming (max 12 Mo).</string>
|
||||||
|
<string name="document_stream_unsupported">Aperçu en streaming non supporté pour ce type de fichier.</string>
|
||||||
<string name="document_page_unreadable">Page illisible</string>
|
<string name="document_page_unreadable">Page illisible</string>
|
||||||
<string name="focus_tap_to_exit">Toucher pour quitter</string>
|
<string name="focus_tap_to_exit">Toucher pour quitter</string>
|
||||||
<string name="login_show_password">Afficher le mot de passe</string>
|
<string name="login_show_password">Afficher le mot de passe</string>
|
||||||
@@ -170,6 +177,7 @@
|
|||||||
<string name="login_error_required">Nom d\'utilisateur et mot de passe requis</string>
|
<string name="login_error_required">Nom d\'utilisateur et mot de passe requis</string>
|
||||||
<string name="login_error_generic">Impossible de se connecter pour le moment</string>
|
<string name="login_error_generic">Impossible de se connecter pour le moment</string>
|
||||||
<string name="login_error_unauthorized">Nom d\'utilisateur ou mot de passe incorrect</string>
|
<string name="login_error_unauthorized">Nom d\'utilisateur ou mot de passe incorrect</string>
|
||||||
|
<string name="login_session_expired">Session expirée — reconnecte-toi pour continuer.</string>
|
||||||
<string name="login_skip">Continuer sans compte</string>
|
<string name="login_skip">Continuer sans compte</string>
|
||||||
<string name="login_choice_subtitle">Choisis comment utiliser Kazier</string>
|
<string name="login_choice_subtitle">Choisis comment utiliser Kazier</string>
|
||||||
<string name="skip_message">Mode local — tes dossiers restent sur cet appareil et ne sont pas synchronisés.</string>
|
<string name="skip_message">Mode local — tes dossiers restent sur cet appareil et ne sont pas synchronisés.</string>
|
||||||
@@ -309,6 +317,31 @@
|
|||||||
<string name="share_error_not_found">Aucun utilisateur connu sous ce nom.</string>
|
<string name="share_error_not_found">Aucun utilisateur connu sous ce nom.</string>
|
||||||
<string name="share_error_generic">Impossible de partager pour le moment.</string>
|
<string name="share_error_generic">Impossible de partager pour le moment.</string>
|
||||||
<string name="share_enqueued">Partage enregistré — synchronisation en cours.</string>
|
<string name="share_enqueued">Partage enregistré — synchronisation en cours.</string>
|
||||||
|
<string name="share_pending">%1$d modification(s) en attente d\'envoi.</string>
|
||||||
|
<string name="share_section_grants">Personnes avec accès</string>
|
||||||
|
<string name="share_section_add">Ajouter un accès</string>
|
||||||
|
<string name="share_section_links">Liens publics</string>
|
||||||
|
<string name="share_section_open_link">Ouvrir un lien reçu</string>
|
||||||
|
<string name="share_empty_grants">Personne pour l\'instant — ajoutez un accès ci-dessous.</string>
|
||||||
|
<string name="share_empty_links">Aucun lien — créez-en un pour partager sans compte destinataire.</string>
|
||||||
|
<string name="share_expired">expiré</string>
|
||||||
|
<string name="share_revoke">Révoquer</string>
|
||||||
|
<string name="share_revoke_confirm">Révoquer l\'accès de %1$s ?</string>
|
||||||
|
<string name="share_link_create">Créer un lien</string>
|
||||||
|
<string name="share_link_created">Lien créé — copiez-le avant de fermer.</string>
|
||||||
|
<string name="share_link_copy">Copier</string>
|
||||||
|
<string name="share_link_copied">Lien copié.</string>
|
||||||
|
<string name="share_link_revoke_confirm">Révoquer ce lien ? Il ne fonctionnera plus.</string>
|
||||||
|
<string name="share_open_link_hint">Collez un lien ou un token reçu</string>
|
||||||
|
<string name="share_open_link_button">Ouvrir</string>
|
||||||
|
<string name="share_resolved_hint">Lien valide — demandez au propriétaire un partage direct pour voir le contenu dans l\'app.</string>
|
||||||
|
<string name="share_error_link_invalid">Lien illisible — collez le lien complet ou le token.</string>
|
||||||
|
<string name="share_error_link_not_found">Lien inconnu, révoqué ou expiré.</string>
|
||||||
|
<string name="share_error_link_failed">Impossible d\'ouvrir ce lien pour le moment.</string>
|
||||||
|
<string name="share_error_load">Impossible de charger les partages.</string>
|
||||||
|
<string name="share_error_forbidden">Vous ne possédez pas cette ressource.</string>
|
||||||
|
<string name="share_retry">Réessayer</string>
|
||||||
|
<string name="share_confirm">Confirmer</string>
|
||||||
<string name="share_content_description">Partager ce dossier</string>
|
<string name="share_content_description">Partager ce dossier</string>
|
||||||
<string name="share_action">Partager</string>
|
<string name="share_action">Partager</string>
|
||||||
<string name="more_actions">Plus d\'actions</string>
|
<string name="more_actions">Plus d\'actions</string>
|
||||||
|
|||||||
+56
-4
@@ -18,7 +18,9 @@ import org.robolectric.annotation.Config
|
|||||||
/**
|
/**
|
||||||
* m7 : la recherche `LIKE` échappe `%`/`_` (littéraux, pas des jokers) —
|
* m7 : la recherche `LIKE` échappe `%`/`_` (littéraux, pas des jokers) —
|
||||||
* « 100% » ne matchait pas tout avant le fix. La casse ASCII reste
|
* « 100% » ne matchait pas tout avant le fix. La casse ASCII reste
|
||||||
* insensible (`COLLATE NOCASE`).
|
* insensible (`COLLATE NOCASE`), et le suivi accents rend la recherche
|
||||||
|
* insensible aux diacritiques (« ete » → « ÉTÉ », branche SQL `REPLACE`,
|
||||||
|
* sans migration).
|
||||||
*/
|
*/
|
||||||
@RunWith(RobolectricTestRunner::class)
|
@RunWith(RobolectricTestRunner::class)
|
||||||
@Config(sdk = [34])
|
@Config(sdk = [34])
|
||||||
@@ -50,7 +52,7 @@ class SearchEscapeTest {
|
|||||||
// Le repository échappe avant d'appeler le DAO — on rejoue ici le
|
// Le repository échappe avant d'appeler le DAO — on rejoue ici le
|
||||||
// contrat (`escapeLike`) pour verrouiller le comportement SQL.
|
// contrat (`escapeLike`) pour verrouiller le comportement SQL.
|
||||||
val escaped = "100%".escapeLikeForTest()
|
val escaped = "100%".escapeLikeForTest()
|
||||||
val rows = fileDao.searchWithFilters(escaped, null).first()
|
val rows = fileDao.searchWithFilters(escaped, escaped.normalizeForTest(), null).first()
|
||||||
|
|
||||||
assertEquals(listOf("100%.txt"), rows.map { it.name })
|
assertEquals(listOf("100%.txt"), rows.map { it.name })
|
||||||
}
|
}
|
||||||
@@ -61,7 +63,7 @@ class SearchEscapeTest {
|
|||||||
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
||||||
fileDao.upsert(file("c".repeat(32), "axb.txt"))
|
fileDao.upsert(file("c".repeat(32), "axb.txt"))
|
||||||
|
|
||||||
val rows = fileDao.searchWithFilters("a\\_b", null).first()
|
val rows = fileDao.searchWithFilters("a\\_b", "a\\_b", null).first()
|
||||||
|
|
||||||
assertEquals(listOf("a_b.txt"), rows.map { it.name })
|
assertEquals(listOf("a_b.txt"), rows.map { it.name })
|
||||||
}
|
}
|
||||||
@@ -70,11 +72,53 @@ class SearchEscapeTest {
|
|||||||
fun recherche_insensible_a_la_casse_ascii() = runTest {
|
fun recherche_insensible_a_la_casse_ascii() = runTest {
|
||||||
fileDao.upsert(file("a".repeat(32), "Rapport.TXT"))
|
fileDao.upsert(file("a".repeat(32), "Rapport.TXT"))
|
||||||
|
|
||||||
val rows = fileDao.searchWithFilters("rapport", null).first()
|
val rows = fileDao.searchWithFilters("rapport", "rapport", null).first()
|
||||||
|
|
||||||
assertEquals(listOf("Rapport.TXT"), rows.map { it.name })
|
assertEquals(listOf("Rapport.TXT"), rows.map { it.name })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun recherche_insensible_aux_accents() = runTest {
|
||||||
|
fileDao.upsert(file("a".repeat(32), "Été à la plage.txt"))
|
||||||
|
fileDao.upsert(file("b".repeat(32), "ÉCOLE.pdf"))
|
||||||
|
fileDao.upsert(file("c".repeat(32), "chœur final.mp3"))
|
||||||
|
fileDao.upsert(file("d".repeat(32), "façade naïve.doc"))
|
||||||
|
fileDao.upsert(file("e".repeat(32), "rien à voir.txt"))
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
listOf("Été à la plage.txt"),
|
||||||
|
fileDao.searchWithFilters("ete", "ete", null).first().map { it.name },
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf("ÉCOLE.pdf"),
|
||||||
|
fileDao.searchWithFilters("ecole", "ecole", null).first().map { it.name },
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf("chœur final.mp3"),
|
||||||
|
fileDao.searchWithFilters("choeur", "choeur", null).first().map { it.name },
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf("façade naïve.doc"),
|
||||||
|
fileDao.searchWithFilters("facade naive", "facade naive", null).first().map { it.name },
|
||||||
|
)
|
||||||
|
// La saisie accentuée trouve aussi (normalisée des deux côtés).
|
||||||
|
assertEquals(
|
||||||
|
listOf("Été à la plage.txt"),
|
||||||
|
fileDao.searchWithFilters("été", "ete", null).first().map { it.name },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun normalize_miroir_kotlin() {
|
||||||
|
// Miroir de `normalizeSearch` (interne au main) — verrouille le
|
||||||
|
// contrat repository → DAO.
|
||||||
|
assertEquals("ete", "Été".normalizeForTest())
|
||||||
|
assertEquals("choeur", "chœur".normalizeForTest())
|
||||||
|
assertEquals("facade", "façade".normalizeForTest())
|
||||||
|
assertEquals("aether", "Æther".normalizeForTest())
|
||||||
|
assertEquals("noel", "Noël".normalizeForTest())
|
||||||
|
}
|
||||||
|
|
||||||
private fun file(resourceId: String, name: String) = FileEntity(
|
private fun file(resourceId: String, name: String) = FileEntity(
|
||||||
resourceId = resourceId,
|
resourceId = resourceId,
|
||||||
name = name,
|
name = name,
|
||||||
@@ -89,6 +133,14 @@ class SearchEscapeTest {
|
|||||||
private fun String.escapeLikeForTest(): String =
|
private fun String.escapeLikeForTest(): String =
|
||||||
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
|
||||||
|
/** Miroir de `normalizeSearch` (interne au main) : minuscules + sans accents. */
|
||||||
|
private fun String.normalizeForTest(): String =
|
||||||
|
lowercase(java.util.Locale.ROOT)
|
||||||
|
.let { java.text.Normalizer.normalize(it, java.text.Normalizer.Form.NFD) }
|
||||||
|
.replace(Regex("\\p{Mn}+"), "")
|
||||||
|
.replace("œ", "oe")
|
||||||
|
.replace("æ", "ae")
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val NOW = 1_700_000_000_000L
|
const val NOW = 1_700_000_000_000L
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,10 +25,14 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
|||||||
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.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
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 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.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
import com.kazier.mobile.domain.LocalModeStore
|
import com.kazier.mobile.domain.LocalModeStore
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
@@ -36,6 +40,7 @@ import kotlinx.coroutines.withTimeout
|
|||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
import org.junit.After
|
import org.junit.After
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
@@ -82,6 +87,7 @@ class Auth401Test {
|
|||||||
LocalModeStore(db.userPreferenceDao()),
|
LocalModeStore(db.userPreferenceDao()),
|
||||||
db.pendingOperationDao(),
|
db.pendingOperationDao(),
|
||||||
apiClient,
|
apiClient,
|
||||||
|
AuthRepository(apiClient, DeviceIdentity(db.userPreferenceDao(), GenerateId())),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,6 +214,7 @@ class Auth401Test {
|
|||||||
private var token: String? = null
|
private var token: String? = null
|
||||||
private var user: UserDto? = null
|
private var user: UserDto? = null
|
||||||
private var expiresAt: Long? = null
|
private var expiresAt: Long? = null
|
||||||
|
private var credentials: com.kazier.mobile.auth.Credentials? = null
|
||||||
|
|
||||||
override fun getToken(): String? = token
|
override fun getToken(): String? = token
|
||||||
override fun getUser(): UserDto? = user
|
override fun getUser(): UserDto? = user
|
||||||
@@ -224,6 +231,16 @@ class Auth401Test {
|
|||||||
user = null
|
user = null
|
||||||
expiresAt = null
|
expiresAt = null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun getCredentials(): com.kazier.mobile.auth.Credentials? = credentials
|
||||||
|
|
||||||
|
override fun saveCredentials(username: String, password: String) {
|
||||||
|
credentials = com.kazier.mobile.auth.Credentials(username, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun clearCredentials() {
|
||||||
|
credentials = null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `listFolders` et `login` répondent 401 ; le reste est inutilisé. */
|
/** `listFolders` et `login` répondent 401 ; le reste est inutilisé. */
|
||||||
@@ -303,5 +320,17 @@ class Auth401Test {
|
|||||||
override suspend fun getShareLink(
|
override suspend fun getShareLink(
|
||||||
token: String,
|
token: String,
|
||||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
|||||||
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.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
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 com.kazier.mobile.data.repository.FileRepository
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
@@ -30,6 +31,7 @@ import com.kazier.mobile.domain.GenerateId
|
|||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
import org.junit.After
|
import org.junit.After
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Before
|
import org.junit.Before
|
||||||
@@ -192,5 +194,17 @@ class PaginationTest {
|
|||||||
override suspend fun getShareLink(
|
override suspend fun getShareLink(
|
||||||
token: String,
|
token: String,
|
||||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import retrofit2.Response
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Streaming `GET /files/:id/content` (V1 finitions) : octets bruts bornés,
|
||||||
|
* jamais persistés ; 404 = invisible ou metadata-only sans octets.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class RemoteContentTest {
|
||||||
|
|
||||||
|
private fun client(fake: ContentFake): ApiClient {
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
return ApiClient(fake, moshi)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `downloadContentBytes_retourne_les_octets_bruts`() = runTest {
|
||||||
|
val fake = ContentFake { Response.success("hello".toResponseBody("text/plain".toMediaType())) }
|
||||||
|
val bytes = client(fake).downloadContentBytes("aabbccddeeff11223344556677889900")
|
||||||
|
assertArrayEquals("hello".toByteArray(), bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `downloadContentBytes_404_mappe_NOT_FOUND`() = runTest {
|
||||||
|
val fake = ContentFake {
|
||||||
|
Response.error(404, "{\"error\":{\"code\":\"NOT_FOUND\",\"message\":\"file not found\"}}".toResponseBody("application/json".toMediaType()))
|
||||||
|
}
|
||||||
|
val ex = runCatching { client(fake).downloadContentBytes("aabbccddeeff11223344556677889900") }.exceptionOrNull()
|
||||||
|
assertTrue(ex is ApiException)
|
||||||
|
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `downloadContentBytes_borne_maxBytes_FILE_TOO_LARGE`() = runTest {
|
||||||
|
val fake = ContentFake { Response.success("0123456789ABCDEF".toResponseBody("text/plain".toMediaType())) }
|
||||||
|
val ex = runCatching { client(fake).downloadContentBytes("aabbccddeeff11223344556677889900", maxBytes = 4) }.exceptionOrNull()
|
||||||
|
assertTrue(ex is ApiException)
|
||||||
|
assertEquals("FILE_TOO_LARGE", (ex as ApiException).code)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `downloadContentBytes_401_declenche_onUnauthorized`() = runTest {
|
||||||
|
var unauthorized = 0
|
||||||
|
val fake = ContentFake {
|
||||||
|
Response.error(401, "{\"error\":{\"code\":\"UNAUTHORIZED\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType()))
|
||||||
|
}
|
||||||
|
val c = client(fake)
|
||||||
|
c.onUnauthorized = { unauthorized++ }
|
||||||
|
val ex = runCatching { c.downloadContentBytes("aabbccddeeff11223344556677889900") }.exceptionOrNull()
|
||||||
|
assertTrue(ex is ApiException)
|
||||||
|
assertEquals(1, unauthorized)
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ContentFake(
|
||||||
|
private val content: () -> Response<ResponseBody>,
|
||||||
|
) : ApiService {
|
||||||
|
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||||
|
Response.success(ApiEnvelope(data = body))
|
||||||
|
|
||||||
|
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||||
|
|
||||||
|
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = content()
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.auth.AuthEvent
|
||||||
|
import com.kazier.mobile.auth.Credentials
|
||||||
|
import com.kazier.mobile.auth.SessionManager
|
||||||
|
import com.kazier.mobile.auth.TokenProvider
|
||||||
|
import com.kazier.mobile.auth.TokenStore
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
|
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.SyncOpsRequest
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
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.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import com.kazier.mobile.domain.LocalModeStore
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.awaitAll
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import retrofit2.Response
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-login silencieux (lot 3) : sur 401, `SessionManager` rejoue
|
||||||
|
* `POST /auth/login` avec les identifiants chiffrés persistés au login
|
||||||
|
* (single-flight), sans purger la file du même compte. Identifiants rejetés
|
||||||
|
* → purge complète + `SessionExpired`.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class SessionReloginTest {
|
||||||
|
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
|
||||||
|
private lateinit var tokenStore: FakeTokenStore
|
||||||
|
private lateinit var tokenProvider: TokenProvider
|
||||||
|
private lateinit var fake: ReloginFake
|
||||||
|
private lateinit var apiClient: ApiClient
|
||||||
|
private lateinit var sessionManager: SessionManager
|
||||||
|
private val events = CopyOnWriteArrayList<AuthEvent>()
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
tokenStore = FakeTokenStore()
|
||||||
|
tokenProvider = TokenProvider()
|
||||||
|
fake = ReloginFake()
|
||||||
|
apiClient = ApiClient(fake, moshi)
|
||||||
|
sessionManager = SessionManager(
|
||||||
|
tokenStore,
|
||||||
|
ActiveUserStore(db.userPreferenceDao()),
|
||||||
|
tokenProvider,
|
||||||
|
LocalModeStore(db.userPreferenceDao()),
|
||||||
|
db.pendingOperationDao(),
|
||||||
|
apiClient,
|
||||||
|
AuthRepository(apiClient, DeviceIdentity(db.userPreferenceDao(), GenerateId())),
|
||||||
|
)
|
||||||
|
CoroutineScope(Dispatchers.Unconfined).launch {
|
||||||
|
sessionManager.events.collect { events += it }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun seed(token: String = "tok-old", withCreds: Boolean = true) {
|
||||||
|
tokenStore.save(token, UserDto(id = "u1", username = "alice"), expiresAt = 9_999_999_999_999L)
|
||||||
|
if (withCreds) tokenStore.saveCredentials("alice", "secret")
|
||||||
|
tokenProvider.current = token
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun awaitToken(value: String?) = withTimeout(5_000L) {
|
||||||
|
while (tokenProvider.current != value) delay(10L)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun awaitEvent(count: Int) = withTimeout(5_000L) {
|
||||||
|
while (events.size < count) delay(10L)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `401_relogine_silencieusement_et_conserve_la_file`() = runBlocking {
|
||||||
|
seed()
|
||||||
|
db.pendingOperationDao().insert(op("create-1"))
|
||||||
|
|
||||||
|
runCatching { apiClient.listFolders() }
|
||||||
|
awaitToken("tok-fresh")
|
||||||
|
awaitEvent(1)
|
||||||
|
|
||||||
|
assertEquals("tok-fresh", tokenStore.getToken())
|
||||||
|
assertEquals("alice", tokenStore.getUser()?.username)
|
||||||
|
assertEquals(1, db.pendingOperationDao().countPending())
|
||||||
|
assertTrue(events.single() is AuthEvent.Reauthenticated)
|
||||||
|
// Identifiants conservés pour le prochain renouvellement.
|
||||||
|
assertEquals(Credentials("alice", "secret"), tokenStore.getCredentials())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `401_login_rejete_purge_tout_et_emet_expired`() = runBlocking {
|
||||||
|
seed()
|
||||||
|
fake.loginMode = ReloginFake.LoginMode.REJECT
|
||||||
|
db.pendingOperationDao().insert(op("create-1"))
|
||||||
|
|
||||||
|
runCatching { apiClient.listFolders() }
|
||||||
|
awaitToken(null)
|
||||||
|
awaitEvent(1)
|
||||||
|
|
||||||
|
withTimeout(5_000L) { while (tokenStore.getToken() != null) delay(10L) }
|
||||||
|
assertNull(tokenStore.getCredentials())
|
||||||
|
val expired = events.single() as AuthEvent.SessionExpired
|
||||||
|
assertEquals("alice", expired.username)
|
||||||
|
// La file n'est pas purgée par le 401 (C5) — seul un changement de
|
||||||
|
// compte la purge.
|
||||||
|
assertEquals(1, db.pendingOperationDao().countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `401_sans_identifiants_purge_et_emet_expired`() = runBlocking {
|
||||||
|
seed(withCreds = false)
|
||||||
|
|
||||||
|
runCatching { apiClient.listFolders() }
|
||||||
|
awaitToken(null)
|
||||||
|
awaitEvent(1)
|
||||||
|
|
||||||
|
assertEquals(0, fake.loginCalls.get())
|
||||||
|
val expired = events.single() as AuthEvent.SessionExpired
|
||||||
|
assertEquals("alice", expired.username)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `401_concurrents_un_seul_login`() = runBlocking {
|
||||||
|
seed()
|
||||||
|
|
||||||
|
(1..5).map { async { runCatching { apiClient.listFolders() } } }.awaitAll()
|
||||||
|
awaitToken("tok-fresh")
|
||||||
|
awaitEvent(1)
|
||||||
|
|
||||||
|
assertEquals("un seul POST /auth/login malgré 5 401", 1, fake.loginCalls.get())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `relogin_proactif_sur_token_expire`() = runBlocking {
|
||||||
|
seed(token = "tok-old")
|
||||||
|
tokenProvider.current = null
|
||||||
|
|
||||||
|
assertTrue(sessionManager.trySilentRelogin())
|
||||||
|
assertEquals("tok-fresh", tokenProvider.current)
|
||||||
|
assertEquals("tok-fresh", tokenStore.getToken())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `relogin_proactif_sans_identifiants_echoue`() = runBlocking {
|
||||||
|
seed(withCreds = false)
|
||||||
|
tokenProvider.current = null
|
||||||
|
|
||||||
|
assertEquals(false, sessionManager.trySilentRelogin())
|
||||||
|
assertEquals(0, fake.loginCalls.get())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `signOut_purge_aussi_les_identifiants`() = runBlocking {
|
||||||
|
seed()
|
||||||
|
sessionManager.clear()
|
||||||
|
assertNull(tokenStore.getCredentials())
|
||||||
|
assertNull(tokenProvider.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun op(operationId: String) = PendingOperationEntity(
|
||||||
|
operationId = operationId,
|
||||||
|
resourceId = "r".repeat(32),
|
||||||
|
resourceType = "file",
|
||||||
|
operation = PendingOperationType.CREATE_RESOURCE,
|
||||||
|
payload = "{}",
|
||||||
|
status = PendingOpStatus.PENDING,
|
||||||
|
createdAt = 1L,
|
||||||
|
updatedAt = 1L,
|
||||||
|
)
|
||||||
|
|
||||||
|
private class FakeTokenStore : TokenStore {
|
||||||
|
private var token: String? = null
|
||||||
|
private var user: UserDto? = null
|
||||||
|
private var expiresAt: Long? = null
|
||||||
|
private var credentials: Credentials? = null
|
||||||
|
|
||||||
|
override fun getToken(): String? = token
|
||||||
|
override fun getUser(): UserDto? = user
|
||||||
|
override fun getExpiresAt(): Long? = expiresAt
|
||||||
|
override fun save(token: String, user: UserDto, expiresAt: Long?) {
|
||||||
|
this.token = token
|
||||||
|
this.user = user
|
||||||
|
this.expiresAt = expiresAt
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun clear() {
|
||||||
|
token = null
|
||||||
|
user = null
|
||||||
|
expiresAt = null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getCredentials(): Credentials? = credentials
|
||||||
|
override fun saveCredentials(username: String, password: String) {
|
||||||
|
credentials = Credentials(username, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun clearCredentials() {
|
||||||
|
credentials = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `listFolders` → 401 ; `login` rejoue un token frais (ou 401 si REJECT). */
|
||||||
|
private class ReloginFake : ApiService {
|
||||||
|
enum class LoginMode { SUCCESS, REJECT }
|
||||||
|
|
||||||
|
var loginMode = LoginMode.SUCCESS
|
||||||
|
val loginCalls = AtomicInteger(0)
|
||||||
|
|
||||||
|
private fun envelopeError(code: String): ResponseBody =
|
||||||
|
"{\"error\":{\"code\":\"$code\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType())
|
||||||
|
|
||||||
|
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||||
|
Response.error(401, envelopeError("UNAUTHORIZED"))
|
||||||
|
|
||||||
|
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> {
|
||||||
|
loginCalls.incrementAndGet()
|
||||||
|
delay(20L)
|
||||||
|
return when (loginMode) {
|
||||||
|
LoginMode.REJECT -> Response.error(401, envelopeError("UNAUTHORIZED"))
|
||||||
|
LoginMode.SUCCESS -> Response.success(
|
||||||
|
ApiEnvelope(
|
||||||
|
data = LoginResponseDto(
|
||||||
|
token = "tok-fresh",
|
||||||
|
expiresAt = 9_999_999_999_999L,
|
||||||
|
user = UserDto(id = "u1", username = body.username),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||||
|
Response.success(ApiEnvelope(data = body))
|
||||||
|
|
||||||
|
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||||
|
|
||||||
|
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
|
||||||
|
Response.success(ByteArray(0).toResponseBody(null))
|
||||||
|
|
||||||
|
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
|
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.SyncOpsRequest
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import retrofit2.Response
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listes de partage (lot 2) : `GET /files/:id/shares` et `/links`
|
||||||
|
* (owner uniquement) — mapping DTO et 404 non-owner.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class ShareManagementTest {
|
||||||
|
|
||||||
|
private fun client(fake: SharesFake): ApiClient {
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
return ApiClient(fake, moshi)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `listShares_retourne_les_grants`() = runTest {
|
||||||
|
val grants = listOf(
|
||||||
|
ShareGrantDto("aa01", "alice", "editor", true, null, 1_700_000_000_000L),
|
||||||
|
ShareGrantDto("bb02", "bob", "viewer", false, 1_800_000_000_000L, 1_700_000_000_001L),
|
||||||
|
)
|
||||||
|
val fake = SharesFake(shares = grants)
|
||||||
|
val got = client(fake).listShares("f".repeat(32))
|
||||||
|
assertEquals(2, got.size)
|
||||||
|
assertEquals("alice", got[0].username)
|
||||||
|
assertEquals("editor", got[0].access)
|
||||||
|
assertEquals(1_800_000_000_000L, got[1].expiresAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `listLinks_retourne_les_liens`() = runTest {
|
||||||
|
val links = listOf(
|
||||||
|
ShareLinkDto("t".repeat(32), "f".repeat(32), "folder", "Docs", "viewer", null),
|
||||||
|
)
|
||||||
|
val fake = SharesFake(links = links)
|
||||||
|
val got = client(fake).listLinks("f".repeat(32))
|
||||||
|
assertEquals(1, got.size)
|
||||||
|
assertEquals("t".repeat(32), got[0].token)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `listShares_404_non_owner_mappe_NOT_FOUND`() = runTest {
|
||||||
|
val fake = SharesFake(failShares = true)
|
||||||
|
val ex = runCatching { client(fake).listShares("f".repeat(32)) }.exceptionOrNull()
|
||||||
|
assertTrue(ex is ApiException)
|
||||||
|
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `getShareLink_invalide_mappe_LINK`() = runTest {
|
||||||
|
val fake = SharesFake(failLink = true)
|
||||||
|
val ex = runCatching { client(fake).getShareLink("t".repeat(32)) }.exceptionOrNull()
|
||||||
|
assertTrue(ex is ApiException)
|
||||||
|
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||||
|
}
|
||||||
|
|
||||||
|
private class SharesFake(
|
||||||
|
private val shares: List<ShareGrantDto> = emptyList(),
|
||||||
|
private val links: List<ShareLinkDto> = emptyList(),
|
||||||
|
private val failShares: Boolean = false,
|
||||||
|
private val failLink: Boolean = false,
|
||||||
|
) : ApiService {
|
||||||
|
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||||
|
Response.success(ApiEnvelope(data = body))
|
||||||
|
|
||||||
|
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||||
|
|
||||||
|
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
|
||||||
|
Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||||
|
if (failLink) {
|
||||||
|
Response.error(404, errBody("NOT_FOUND"))
|
||||||
|
} else {
|
||||||
|
Response.success(ApiEnvelope(data = ShareLinkDto(token, "f".repeat(32), "folder", "Docs", "viewer", null)))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
|
||||||
|
Response.success(ByteArray(0).toResponseBody(null))
|
||||||
|
|
||||||
|
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
|
||||||
|
if (failShares) {
|
||||||
|
Response.error(404, errBody("NOT_FOUND"))
|
||||||
|
} else {
|
||||||
|
Response.success(ApiEnvelope(data = shares))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = links))
|
||||||
|
|
||||||
|
private fun errBody(code: String) =
|
||||||
|
"{\"error\":{\"code\":\"$code\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType())
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -20,6 +20,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
|||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
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
|
||||||
@@ -52,6 +53,7 @@ import org.junit.runner.RunWith
|
|||||||
import org.robolectric.RobolectricTestRunner
|
import org.robolectric.RobolectricTestRunner
|
||||||
import org.robolectric.annotation.Config
|
import org.robolectric.annotation.Config
|
||||||
import retrofit2.Response
|
import retrofit2.Response
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Garde-fous data-layer de la fusion de dossiers : le re-parentage repositionne
|
* Garde-fous data-layer de la fusion de dossiers : le re-parentage repositionne
|
||||||
@@ -378,4 +380,16 @@ private class FolderMergeApiService : ApiService {
|
|||||||
override suspend fun getShareLink(
|
override suspend fun getShareLink(
|
||||||
token: String,
|
token: String,
|
||||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
+14
@@ -26,6 +26,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
|||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
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
|
||||||
@@ -54,6 +55,7 @@ import org.robolectric.RobolectricTestRunner
|
|||||||
import org.robolectric.annotation.Config
|
import org.robolectric.annotation.Config
|
||||||
import org.robolectric.shadows.ShadowContentResolver
|
import org.robolectric.shadows.ShadowContentResolver
|
||||||
import retrofit2.Response
|
import retrofit2.Response
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Garde-fous outbox du déplacement local : tant qu'un `move_resource` est en
|
* Garde-fous outbox du déplacement local : tant qu'un `move_resource` est en
|
||||||
@@ -467,4 +469,16 @@ private class MoveProtectionApiService : ApiService {
|
|||||||
override suspend fun getShareLink(
|
override suspend fun getShareLink(
|
||||||
token: String,
|
token: String,
|
||||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
+14
@@ -18,6 +18,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
|||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
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
|
||||||
@@ -46,6 +47,7 @@ import org.robolectric.annotation.Config
|
|||||||
import retrofit2.Response
|
import retrofit2.Response
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.ByteArrayInputStream
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pipeline OCR local : l'upload multipart ciblé envoie les octets du flux SAF
|
* Pipeline OCR local : l'upload multipart ciblé envoie les octets du flux SAF
|
||||||
@@ -385,4 +387,16 @@ private class OcrApiServiceFake : ApiService {
|
|||||||
body.writeTo(buffer)
|
body.writeTo(buffer)
|
||||||
return buffer.readUtf8()
|
return buffer.readUtf8()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
+14
@@ -28,6 +28,7 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
|||||||
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.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
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 com.kazier.mobile.domain.ActiveUserStore
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
@@ -44,6 +45,7 @@ import org.junit.runner.RunWith
|
|||||||
import org.robolectric.RobolectricTestRunner
|
import org.robolectric.RobolectricTestRunner
|
||||||
import org.robolectric.annotation.Config
|
import org.robolectric.annotation.Config
|
||||||
import retrofit2.Response
|
import retrofit2.Response
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Garde-fou refresh serveur vs reparent local (miroir dossiers du
|
* Garde-fou refresh serveur vs reparent local (miroir dossiers du
|
||||||
@@ -234,4 +236,16 @@ private class RefreshVsMoveApiService : ApiService {
|
|||||||
override suspend fun getShareLink(
|
override suspend fun getShareLink(
|
||||||
token: String,
|
token: String,
|
||||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
|
|||||||
+14
@@ -19,6 +19,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
|||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
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
|
||||||
@@ -45,6 +46,7 @@ import org.junit.runner.RunWith
|
|||||||
import org.robolectric.RobolectricTestRunner
|
import org.robolectric.RobolectricTestRunner
|
||||||
import org.robolectric.annotation.Config
|
import org.robolectric.annotation.Config
|
||||||
import retrofit2.Response
|
import retrofit2.Response
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Contrat de l'hydratation du snapshot `GET /sync/permissions` :
|
* Contrat de l'hydratation du snapshot `GET /sync/permissions` :
|
||||||
@@ -488,4 +490,16 @@ private class FakeApiService : ApiService {
|
|||||||
override suspend fun getShareLink(
|
override suspend fun getShareLink(
|
||||||
token: String,
|
token: String,
|
||||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
+14
@@ -40,6 +40,7 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
|||||||
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.ShareLinkDto
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||||
import com.kazier.mobile.data.remote.dto.SyncFailedDto
|
import com.kazier.mobile.data.remote.dto.SyncFailedDto
|
||||||
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
|
||||||
@@ -54,6 +55,7 @@ import kotlinx.coroutines.test.runTest
|
|||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
import org.junit.After
|
import org.junit.After
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
@@ -448,5 +450,17 @@ class OutboxSyncWorkerTest {
|
|||||||
|
|
||||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||||
throw UnsupportedOperationException()
|
throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun downloadContent(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||||
|
|
||||||
|
override suspend fun listShares(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listLinks(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.kazier.mobile.ui.share
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parsing des liens de partage (lot 2) : token brut, deep-link
|
||||||
|
* `kazier://share/…`, URL API `…/shares/links/…`.
|
||||||
|
*/
|
||||||
|
class ShareLinkParserTest {
|
||||||
|
|
||||||
|
private val token = "aabbccddeeff11223344556677889900"
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `extractToken_accepte_le_32_hex_brut`() {
|
||||||
|
assertEquals(token, ShareLinkParser.extractToken(token))
|
||||||
|
assertEquals(token, ShareLinkParser.extractToken(" $token\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `extractToken_normalise_la_casse`() {
|
||||||
|
assertEquals(token, ShareLinkParser.extractToken(token.uppercase()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `extractToken_extrait_du_deep_link`() {
|
||||||
|
assertEquals(token, ShareLinkParser.extractToken("kazier://share/$token"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `extractToken_extrait_de_l_url_api`() {
|
||||||
|
assertEquals(
|
||||||
|
token,
|
||||||
|
ShareLinkParser.extractToken("http://10.0.2.2:8080/api/v1/shares/links/$token"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `extractToken_extrait_de_la_page_courte`() {
|
||||||
|
assertEquals(
|
||||||
|
token,
|
||||||
|
ShareLinkParser.extractToken("https://mon-serveur.fr/s/$token"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `extractToken_rejette_l_illisible`() {
|
||||||
|
assertNull(ShareLinkParser.extractToken(""))
|
||||||
|
assertNull(ShareLinkParser.extractToken(" "))
|
||||||
|
assertNull(ShareLinkParser.extractToken("not-a-token"))
|
||||||
|
assertNull(ShareLinkParser.extractToken("kazier://share/zzz"))
|
||||||
|
assertNull(ShareLinkParser.extractToken("kazier://share/${token}00"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `shareUrl_produit_le_deep_link`() {
|
||||||
|
assertEquals("kazier://share/$token", ShareLinkParser.shareUrl(token))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user