Compare commits
8
Commits
v0.1.0
...
c642763035
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c642763035 | ||
|
|
b869f70922 | ||
|
|
9e8b01b135 | ||
|
|
456579880e | ||
|
|
25aedb431e | ||
|
|
25bab43b21 | ||
|
|
cbc94c8722 | ||
|
|
d1b0807d38 |
+120
-164
@@ -1,190 +1,146 @@
|
|||||||
# FEEDBACK — Audit bugs mobile-kotlin (local-first)
|
# FEEDBACK — Audit bugs mobile-kotlin (local-first)
|
||||||
|
|
||||||
> Généré le 2026-09-22 par 5 agents d'exploration parallèles (scopes : Room/DB, sync/outbox/SAF, réseau/auth/repos, UI/navigation/VM, scan/pdf/review/thumbnails).
|
> Généré le 2026-09-22 par 5 agents d'exploration parallèles (scopes : Room/DB, sync/outbox/SAF, réseau/auth/repos, UI/navigation/VM, scan/pdf/review/thumbnails).
|
||||||
> Chaque finding est vérifié avec preuve `file:line`. Méthode : lecture intégrale des fichiers + croisement `docs/api-v1.md`, `AGENTS.md`, handlers Go.
|
> Mise à jour le 2026-09-24 : les items corrigés par `d89c0d0 (fix 1 to 6)` et `22286aa (fix mobile audit review)` ont été re-vérifiés code en main et retirés. Ce document ne liste que le **reliquat confirmé**.
|
||||||
> Scope : `mobile-kotlin/` uniquement. Pas de fix appliqué — diagnostic seul.
|
> Màj 2026-09-24 (soir) : tout le reliquat ci-dessous est **corrigé et testé** (`:app:testDebugUnitTest` : 162/162 verts, DB v16, schéma `app/schemas/16.json` exporté). Les sections 🟠/🟡/🛠️ sont conservées comme traçabilité.
|
||||||
> Légende : 🔴 Critique (data loss / crash / sync bloquée) · 🟠 Majeur (divergence silencieuse, contrat violé) · 🟡 Mineur (UX, perf, dette).
|
> Chaque finding restant est vérifié avec preuve `file:line`.
|
||||||
|
> Scope : `mobile-kotlin/` uniquement.
|
||||||
|
> Légende : 🟠 Majeur (divergence silencieuse, contrat violé) · 🟡 Mineur (UX, perf, dette).
|
||||||
|
|
||||||
Base paths : `mobile-kotlin/app/src/main/java/com/kazier/mobile/…`
|
Base paths : `mobile-kotlin/app/src/main/java/com/kazier/mobile/…`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔴 Critiques (à corriger en priorité)
|
## ✅ Corrigés et retirés (vérifiés le 2026-09-24)
|
||||||
|
|
||||||
### C1 — `domain/GenerateId.kt:19` — IDs 32-hex non conformes (sign-extension `Byte` → `%02x`)
|
### 🔴 Critiques : 9/9 corrigés
|
||||||
`bytes.joinToString("") { "%02x".format(it) }` promeut chaque `Byte` signé en `int` : tout octet négatif produit `ffffffxx` (8 chars). Longueur 32→128, P(32 exact) ≈ 1/65536.
|
- **C1** `domain/GenerateId.kt:19` — masque `and 0xFF` contre la sign-extension, 32-hex conforme.
|
||||||
Impact : `resource_id` / `operation_id` / `device_user_id` violent `^[0-9a-f]{32}$` (CHECK serveur) → `POST /sync/ops` rejetés, outbox bloquée, identités invalides.
|
- **C2** `features/sync/OutboxSyncWorker.kt:139-145` — erreurs non-attribuables (`INVALID_RESPONSE`, 429/408, 4xx batch-level) → `Result.retry()` sans toucher aux ops.
|
||||||
Repro : boucler `newResourceId()` et tester `length == 32 && matches([0-9a-f]{32})` → échec quasi systématique.
|
- **C3** `data/local/dao/PendingOperationDao.kt:66-72` — `purgeSynced` exclut les `create_resource` (tombstones), gates `countCreateOperations` préservés.
|
||||||
|
- **C4** `features/saf/FileDeleter.kt:122-128` + `FolderDeleter.kt:122-124` — journal-first (`withTransaction` avant suppression SAF) + `sweepPendingPhysicalDeletes`.
|
||||||
|
- **C5** `auth/SessionManager.kt:70-77` — `clear()` purge les ops non poussées (`pending`/`failed`), appelé par `AuthViewModel.signOut/signOutToLocal`.
|
||||||
|
- **C6** `OutboxSyncWorker.kt:185-188` — stop au 1er échec (`return success()`, jamais `continue`) + cascade transitive `cascadeCreateFailure` via `parent_resource_id`/payload.
|
||||||
|
- **C7** `OutboxSyncWorker.kt:152,170-174,193-196` — `applied.coerceIn`, `failedIndex < 0 → stop`, `applied == 0 → stop` (anti busy-loop/crash).
|
||||||
|
- **C8** Scan export — `ScanExport.pendingForExport` idempotent, `shouldFinishSession` gate `DONE`, `uniquePageFile()` UUID, `deletePage` DB-d'abord, `exportPdf` ne marque que les succès.
|
||||||
|
- **C9** `features/scan/ScanImageProcessor.kt:91-92` + `ScanViewModel.kt:213` — jamais de `recycle()` sur l'alias affiché (`!==` check).
|
||||||
|
|
||||||
### C2 — `features/sync/OutboxSyncWorker.kt:101-106` — dead-letter abusive sur erreurs non-attribuables
|
### 🟠 Majeurs corrigés (31)
|
||||||
Le `else` dead-letter `pending.first()` pour toute `ApiException` non-`NETWORK_ERROR`/5xx/401. `INVALID_RESPONSE` (200 sans enveloppe `{data}`) et `HTTP_429`/`408` (transitoires) tombent dedans. La faute est imputée à la 1re op du batch quelle que soit l'op rejetée.
|
M1 (garde pending-move dossiers), M2 (gate `create` avant `move`), M3 (`FileMover` sans repli mensonger), M4 (exclusion `exists=0` pending seul), M6 (parent inconnu → `continue`), M7 (`importRoot` schedule le drain), M8 (fichiers 0-octet acceptés), M10 (`DeviceIdentity` mutex + `insertIgnore`), M11 (décision assumée : pas de backfill `create_resource`), M12 (`upsertTolerant` sur `resource_id`/`uri`), M14 (colonne `device_id`, `UNIQUE(device_id, operation_id)` + migration 11→12), M15 (`failDescendants` élargi, cf. C6), M21 (boucle `listFilesPaged` + `meta.total`), M22 (`ApiClient` distingue `CancellationException`/`JsonDataException`/`IOException`), M23 (`activeUserStore` vs `ownerId`, plus de confusion device/user), M24 (`normalizePayloadNumbers` Double→Long), M25 (`SessionManager` possède `onUnauthorized`), M26 (`ServerUrlInterceptor` `runBlocking load()` anti-race), M28 (validation URL `toHttpUrl()`), M29 (`pendingDefaultPick` saveable), M30 (pager `rememberSaveable`), M31 (debounce sur résultats seuls), M32 (gate `canShare` FolderDetail), M33 (`refreshShareGate` au login/logout), M34 (`selection.clear()` + chips figés en sélection), M35 (`resolveViewerPage` clamp), M36 (sélecteur thème 3 états), M37 (flag `dirty` anti-écrasement saisie), M38 (`MAX(sortOrder)+1`), M42 (`processed=true` PDF builder), M43 (réinsertion optimiste review), M44 (`remember(existingIds)` stable).
|
||||||
Impact : op saine → `failed` à vie sur erreur batch-level ou transitoire ; inclut le cas `429 RATE_LIMITED` (login/devices/sync) qui devrait suivre le chemin `retry()`.
|
|
||||||
Repro : serveur 200 sans `data` ou 429 → 1re op dead-lettrée.
|
|
||||||
|
|
||||||
### C3 — `features/sync/OutboxSyncWorker.kt:83` + `data/local/dao/PendingOperationDao.kt:42-43` — purge >7j qui casse le gate `processed`/`hasCreateOperation`
|
### 🟡 Mineurs corrigés dans `d89c0d0` (voir `git show --stat d89c0d0`)
|
||||||
`purgeSynced` efface les lignes `synced`, or `countCreateOperations` (`IN ('pending','synced')`) fonde les gates delete/create dessus.
|
m4 (gardes cursor SAF), m6 (`deleteLocally` transactionnel), m8 (`FileOrdering` aligné SQL), m9 (commentaire `attempts` diagnostic), m10-m14 (`updateUri`, `LocalModeStore`, `load` réarmable, `StateFlow` après succès DB, clé `SYNC_MODE` retirée), m16-m18 (index, `defaultValue processed`, `swapOrder` contraint), m22 (`ApiService` endpoints contrat ajoutés), m23 (`registerDevice` erreurs visibles), m24 (garde mode local), m25 (logging sans PII), m26 (`Bearer` hors routes publiques), m27 (`expiresAt` persisté), m28 (`SecureTokenStore` lazy + Direct Boot), m29-m31 (nav `pdfbuilder/empty`, `launchSingleTop`, controller hoisté), m33-m39 (side-effects `buildPhase`, dialogs `rememberSaveable`, badge collectes, saisie serveur debouncée, flash thème, bandeau import, `FileStatus.LOCAL`), m40-m56 (scan/camera/thumbnails : résolution bornée, `toBitmap` throttlé, listener retiré, `else` rotation, garde `sourceRect`, arrondi crop, `combine` nettoyé, purge `ABANDONED`, unicité session active, `FileCategory` CSV cohérent, purge map `Mutex`, `.tmp` nettoyés, `isUpToDate` taille+mtime, `runCatching` close, commentaire `max`, `release()` sur exception, deck conservé sur erreur).
|
||||||
Impact : (a) fichier poussé puis purgé → `SafFileDeleter`/`FileDeleter`/`treeMarkMissing` omettent le `delete_resource` → fantôme serveur indélébile ; (b) `markProcessed` ré-enqueue un `create_resource` dupliqué.
|
|
||||||
Repro : pousser un fichier, attendre 7j, le supprimer → aucun `delete_resource`, serveur garde la ressource.
|
|
||||||
|
|
||||||
### C4 — `features/saf/FolderDeleter.kt:106-124` + `features/saf/FileDeleter.kt:109-119` — suppression physique avant transaction, delete perdu sur crash
|
|
||||||
`deleteTreePhysically` (SAF, irréversible) avant `withTransaction { treeMarkMissing }`.
|
|
||||||
Impact : kill/crash entre les deux → octets supprimés, aucun `delete_resource` journalisé, walk suivant marque `exists=0` sans outbox (aucun chemin walk→enqueue) → fantôme serveur + divergence définitive.
|
|
||||||
Repro : `deleteFull` puis kill avant commit Room → serveur jamais notifié.
|
|
||||||
|
|
||||||
### C5 — `ui/auth/AuthViewModel.kt:112-121` — pas de vidage outbox au sign-out, replay cross-account
|
|
||||||
`signOut`/`signOutToLocal` purgent session et mode local mais aucune suppression de `pending_operations`. Les ops du compte A survivent au login du compte B (même `device_id`, `UNIQUE(device_id, operation_id)` sans historique partagé).
|
|
||||||
Impact : ops de A appliquées dans le scope de B (`NOT_FOUND`/`NAME_CONFLICT`, voire créations croisées).
|
|
||||||
Repro : enqueue offline sous A → sign-out → login B → drain pousse les ops de A sous token B.
|
|
||||||
|
|
||||||
### C6 — `features/sync/OutboxSyncWorker.kt:118-133` — drain poursuivi après échec + cascade limitée au même `resource_id`
|
|
||||||
Après `markFailed`, `continue` envoie le batch suivant, et `failDescendants` (`PendingOperationDao.kt:38`) ne cible que `resource_id = :resourceId` alors que les enfants portent un autre `resource_id` (lien dans le payload).
|
|
||||||
Impact : viole « serveur stop à la 1re erreur, client reprend à cet index » — creates enfants poussés et rejetés `NOT_FOUND` un par un, head-of-line blocking + dead-letters en cascade.
|
|
||||||
Repro : `create` dossier-parent en échec → le run pousse quand même les creates enfants au tour suivant.
|
|
||||||
|
|
||||||
### C7 — `features/sync/OutboxSyncWorker.kt:112-131` — gardes absents sur réponse serveur (boucle infinie / crash)
|
|
||||||
(a) `result.failed.operationId` absent du batch (`indexOfFirst < 0`) → silence + re-sélection du même batch → boucle serrée sans backoff ; (b) `result.applied > pending.size` → `pending[i]` lève `IndexOutOfBoundsException` → crash worker.
|
|
||||||
Impact : (a) drain CPU/batterie ; (b) batch jamais acquitté. Complété par `data/remote` : `while(true)` sans garde `applied==0 && failed==null` → busy-loop si serveur renvoie `{applied:0, failed:null}`.
|
|
||||||
Repro : mocker `syncOps → applied=0, failed=null` ou `operation_id` inconnu → boucle infinie ; `applied` incohérent → crash.
|
|
||||||
|
|
||||||
### C8 — Scan : perte de données à l'export
|
|
||||||
- `ui/scan/ScanViewModel.kt:387-389` (`exportPdf`) — pages en échec seulement loggées (`failedIds`), puis **toutes** marquées `EXPORTED` + session `DONE` → PDF incomplet, sources abandonnées.
|
|
||||||
- `ui/scan/ScanViewModel.kt:259-298` (`export`) — retry non idempotent : `getPages` retourne aussi les `EXPORTED`, chaque retry crée un nouvel URI SAF → documents + lignes Room + ops outbox dupliqués.
|
|
||||||
- `ui/scan/ScanViewModel.kt:263` — fichier temp manquant → page sautée sans marquage mais `finishSession` ferme la session → page `PENDING` dans session `DONE`, jamais reprise ni nettoyée.
|
|
||||||
- `ui/scan/ScanViewModel.kt:186-201` — nom page `page_$order.jpg` avec `order = pageCount+1` → collision après suppression (A,B → del A → C écrase B) → deux entités même `tempUri`, `deletePage` orpheline B.
|
|
||||||
Repro : cf. chaque item (export partiel, retry après perte permission SAF, temp supprimé, capture-suppression-capture).
|
|
||||||
|
|
||||||
### C9 — `features/scan/ScanImageProcessor.kt:87-88` + `ui/scan/ScanViewModel.kt:192` — `recycle()` du bitmap encore affiché quand OpenCV indisponible
|
|
||||||
`process()` retourne l'instance d'entrée si `!isAvailable()` ; l'appelant `recycle()` le `processed` qui alias le draft dessiné par `CropStage` → crash `recycled bitmap`.
|
|
||||||
Repro : device sans lib OpenCV → valider un crop → crash au retour caméra.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🟠 Majeurs
|
## 🟠 Majeurs restants (4) — ✅ tous corrigés le 2026-09-24 (162/162 tests verts)
|
||||||
|
|
||||||
### Sync / Outbox / SAF
|
- **M5 — `features/saf/FileDeleter.kt:88-104` + `features/saf/FolderDeleter.kt:91-103`** : `deleteInCloud` sans tombstone locale (`exists` reste 1) → ressource toujours affichée, walk la revoit, `refreshFromServer` ne supprime jamais de lignes → fantôme local vs serveur supprimé.
|
||||||
- **M1 — `features/sync/DeviceSync.kt:85-91` + `data/repository/FolderRepository.kt:99-134`** : le walk écrase le parent des dossiers sans garde pending-move (`saveFolder` écrase toujours, `reparentSubFolders` métadonnée-seule sans déplacement SAF). Les fichiers ont `hasPendingMoveOperation` (`FileRepository.kt:190`), les dossiers rien → tout reparent/merge revert au tick 30s suivant, divergence disque/serveur permanente.
|
- **M9 — `features/saf/FolderMerger.kt:59,65-101`** : merge toujours multi-transactions (create, moves, deletes séparés) ; seule idempotence `findExistingMerged:154-161` ajoutée, pas d'atomicité → crash à mi-fusion = état partiel poussé.
|
||||||
- **M2 — `data/repository/FileRepository.kt:238-250`** : `applyMove` enqueue `move_resource` sans gate `create` (contrairement aux deletes) → move d'un fichier jamais poussé = `NOT_FOUND`/no-op serveur + ligne figée par `hasPendingMoveOperation`. Même cause `reparentSubFolders` (`FolderRepository.kt:144-157`) pour dossier au `create` purgé (>7j).
|
- **M13 — entités `exists: Int? = null` + filtres `= 1`** (`FolderEntity.kt:36`, `FileEntity.kt:46`, `FolderDao.kt:43,50`, `FileDao.kt:27,44`) : toute ligne sans `exists` explicite disparaît UI/recherche/review — perte fonctionnelle silencieuse.
|
||||||
- **M3 — `features/saf/FileMover.kt:47-53`** : repli métadonnée-seule incohérent (nouveau parent + ancienne uri quand `moveDocument` refusé) → Room ment durablement, walk bloqué par le garde pending-move, divergence serveur/disque.
|
- **M27 — `data/repository/ShareRepository.kt:47` + `data/remote/dto/Dtos.kt:150-151`** : snapshot permissions sans delta (`after` jamais passé), `sharedById`/`expiresAt` en `Any?` jamais lus, `cachedAt` jamais persisté, aucun downgrade 24h ni `canAccess` → grant révoqué/expiré reste visible et ouvrable (`404`) jusqu'au prochain login.
|
||||||
- **M4 — `features/sync/DeviceSync.kt:122-134`** : réconciliation `exists=0` asymétrique — fichiers exclus via `hasMoveOperation` (pending **ou** synced → à vie après un move syncé, fichier supprimé ensuite = fantôme `exists=1` éternel) ; dossiers sans exclusion (move en transition marqué `missing` à tort).
|
|
||||||
- **M5 — `features/saf/FileDeleter.kt:88-100` + `features/saf/FolderDeleter.kt:91-103`** : `deleteInCloud` sans tombstone locale (`exists` reste 1) → ressource toujours affichée, walk la revoit, `refreshFromServer` ne supprime jamais de lignes → fantôme local vs serveur supprimé.
|
|
||||||
- **M6 — `features/sync/DeviceSync.kt:84`** : `?: root.resourceId` masque toute violation parent-avant-enfant (parent absent de `resourceIdByUri` → enfant rattaché racine) → arbre serveur corrompu silencieusement.
|
|
||||||
- **M7 — `features/sync/SyncViewModel.kt:135-156`** : `importRoot` ne schedule jamais le drain (contraire `syncAll:110`, login `AuthViewModel:54,77`) → `create_resource` racine dort jusqu'au prochain tick, badge faussement à jour.
|
|
||||||
- **M8 — `features/sync/SafScanner.kt:146`** : `if (size == 0L) continue` → fichiers vides légitimes exclus du miroir, jamais reviewés ni poussés (perte silencieuse).
|
|
||||||
- **M9 — `features/saf/FolderMerger.kt:45-85`** : merge multi-transactions non-atomique, non-idempotent (`createMergedFolder` recrée un dossier à chaque appel) → crash à mi-fusion = état partiel poussé, relance = dossier dupliqué côté serveur.
|
|
||||||
|
|
||||||
### Room / DB / Domain
|
|
||||||
- **M10 — `domain/DeviceIdentity.kt:18-26`** : `getOrCreate()` non atomique (read/insert/re-read hors transaction) + fallback `newResourceId()` jamais persisté → deux identités concurrentes, `owner_id` incohérents, outbox sous identité fantôme (aggravé par C1).
|
|
||||||
- **M11 — `data/local/migration/Migrations.kt:90-96`** : `MIGRATION_5_6` fait `UPDATE files SET processed = 1` sans `create_resource` rétroactif → backlog jamais poussé, invisible de la review (`getUnprocessed`) et du serveur, à vie.
|
|
||||||
- **M12 — `data/local/dao/FolderDao.kt:50-54` + `data/local/dao/FileDao.kt:48-49`** : `@Upsert` résout sur PK (`id`) pas sur uniques `resource_id`/`uri` ; pattern read-then-upsert (`id=0`) → deux inserts concurrents même `uri` = `SQLiteConstraintException` (crash walk SAF / refresh serveur).
|
|
||||||
- **M13 — entités `exists: Int? = null` + filtres `= 1`** (`FolderEntity.kt:36`, `FileEntity.kt:45`, `FolderDao.kt:34,41`, `FileDao.kt:15,18,21,32,42,95,98,108,135`, `Migrations.kt:51-72` sans DEFAULT) : toute ligne sans `exists` explicite disparaît UI/recherche/review — perte fonctionnelle silencieuse.
|
|
||||||
- **M14 — `data/local/entity/PendingOperationEntity.kt:28-53` + `Migrations.kt:101-123`** : pas de colonne `device_id`, unicité locale sur `operation_id` seul vs contrat `UNIQUE(device_id, operation_id)` → après régénération `device_user_id`, rejeu = `create_resource` dupliqués serveur.
|
|
||||||
- **M15 — `data/local/dao/PendingOperationDao.kt:38`** : `failDescendants` ne cascade que sur le même `resource_id`, pas les enfants (cf. C6).
|
|
||||||
- **M16 — `data/local/dao/FileDao.kt:133-145` + `Migrations.kt:75-82`** : `category` ajoutée sans backfill, `getOcrAutoCandidates()` exige `category IN (…)` → tout PDF/image/texte pré-v4 exclu de l'OCR auto à vie.
|
|
||||||
- **M17 — `data/local/dao/FileDao.kt:151-152`** : `clearOcrQueued` reset `ocr_attempts = 0` inconditionnellement (contredit commentaire `:130-132`) → échec permanent rejoué indéfiniment.
|
|
||||||
- **M18 — pas de FK `files → folders`** (`FileEntity.kt:18-26`, `FolderEntity.kt:18-25`, `FolderDao.kt:95-96`, `FileDao.kt:92-93` deletes physiques) → `remove(dossier)` laisse orphelins, `moveToFolder` vers parent inexistant accepté, cycles possibles.
|
|
||||||
- **M19 — `FolderDao.kt:56-57` + `FileDao.kt:51-52`** : `markMissing` = `SET exists = 0` seul (ni `sync_status` ni annulation `create` pending) → ressource disparue quand même poussée (fantôme serveur), placement `local-cloud` mensonger.
|
|
||||||
- **M20 — `data/local/dao/ScanDao.kt:12-64` + `entity/ScanSessionEntity.kt:15-20`** : sessions `active` multiples possibles (aucun index unique/partiel), aucun `deleteSession` → doubles inserts concurrents = session orpheline + pages fuyantes.
|
|
||||||
|
|
||||||
### Réseau / Auth / Repos
|
|
||||||
- **M21 — `data/repository/FileRepository.kt:261-272` + `data/remote/ApiClient.kt:64-65`** : pagination jetée (`pageSize=50` sans `page`, `meta` ignoré) alors que le serveur pagine → dossiers > 50 fichiers ne convergent jamais, silencieusement.
|
|
||||||
- **M22 — `data/remote/ApiClient.kt:119-125`** : `catch (Exception) → NETWORK_ERROR` attrape aussi `JsonDataException` (Moshi) et `InterruptedIOException` (annulation) → parsing cassé = `retry()` infini, coroutine annulée = `ApiException` au lieu de `CancellationException` (scope/WorkManager corrompus).
|
|
||||||
- **M23 — `data/repository/ShareRepository.kt:45,99-104` + `FolderRepository.kt:115`** : confusion `device_id` vs `user_id` — `syncSnapshot` compare `deviceIdentity.getOrCreate()` (device) à `perm.ownerId` (user serveur), `saveFolder` stocke le device dans `ownerId`, `ActiveUserStore` ignoré. Le snapshot serveur **exclut les ressources possédées** → toute ligne cloud-only au vrai `ownerId=user` est `markMissing` à chaque login/restore (ex. note `createNote(ownerId=userId)` disparaît).
|
|
||||||
- **M24 — `features/sync/OutboxSyncWorker.kt:159-170` + `data/repository/OutboxRepository.kt:29-31`** : round-trip `expiresAt` Long→Double (Moshi `Map<String,Any?>`) → `enqueueShare(expiresAt: Long)` réémis `1.7E12` → serveur `*int64` refuse → `400 INVALID_REQUEST` → **tout partage avec expiration dead-lettered**.
|
|
||||||
- **M25 — `ui/auth/AuthViewModel.kt:43,123-125`** : callback 401 singleton possédé par un ViewModel (`apiClient.onUnauthorized`, `ApiClient` `@Singleton` survit au VM, annulé dans `onCleared`) → après destruction, 401 ne purge plus la session → token expiré réutilisé, worker `success()` sur 401 fige l'outbox, utilisateur jamais déconnecté.
|
|
||||||
- **M26 — `domain/ServerConfigStore.kt:32-43` + `data/remote/ServerUrlInterceptor.kt:25-38`** : race `load()` — interceptor lit `current` (défaut `10.0.2.2`) sur thread OkHttp pendant que `load()` restaure l'URL ; `registerDevice()` part avant `load()` → cold start avec URL custom = premières requêtes (y compris `Authorization: Bearer` restauré) vers l'hôte par défaut (**fuite du bearer**).
|
|
||||||
- **M27 — `data/repository/ShareRepository.kt:44-93` + `data/remote/dto/Dtos.kt:120-132`** : snapshot permissions sans delta (`after` jamais passé), `sharedById`/`expiresAt` en `Any?` jamais lus, `cachedAt` jamais persisté, aucun downgrade 24h ni `canAccess` → grant révoqué/expiré reste visible et ouvrable (`404`) jusqu'au prochain login.
|
|
||||||
- **M28 — `domain/ServerConfigStore.kt:46-59`** : `set()` persiste URL non validée (`"http://"` → `"http:"`, `"foo bar"` → `"http://foo bar"`) → app semi-brickée jusqu'à correction manuelle (recoupé par 2 agents).
|
|
||||||
|
|
||||||
### UI / Navigation / VM
|
|
||||||
- **M29 — `ui/folderlist/FolderListScreen.kt:202+220`** : onboarding racine bloqué après rotation — `pendingDefaultPick` en `remember` (non-saveable), `LaunchedEffect` polling annulé à la rotation, import SAF continu en fond mais `setDefaultRoot()` jamais rappelé → écran figé sur `DefaultRootOnboarding`, re-picker = doublon d'import.
|
|
||||||
- **M30 — `ui/document/DocumentViewerScreen.kt:130-137`** : position pager perdue à la rotation (`jumpPending = remember`), re-scroll vers `initialResourceId` → page N → retour page initiale. Fix : `rememberSaveable` / mémoriser index courant.
|
|
||||||
- **M31 — `ui/search/SearchScreen.kt:276-284` + `SearchViewModel.kt:55-72`** : `TextField` branché sur la valeur **debouncée** (300 ms) → frappe affichée par à-coups, IME/autocorrect écrasés. Correct : champ sur requête brute, debounce pour Room seule.
|
|
||||||
- **M32 — `ui/folderdetail/FolderDetailScreen.kt:196-202`** : Partager sans gate `isShareable` (contraire FolderList `canShare`, `:154-159`) → partage d'un dossier local-only/reçu = op `share` vouée au dead-letter `NOT_FOUND`.
|
|
||||||
- **M33 — `ui/folderlist/FolderListViewModel.kt:165-173`** : `canShare` stale au login/logout (combine `_defaultRootId`/`_browseFolderId` sans token/auth) → « Partager » reste désactivé jusqu'à navigation après connexion depuis Réglages.
|
|
||||||
- **M34 — `ui/folderlist/FolderListScreen.kt:333-375 vs 326-330`** : suppression multi-dossiers filtre les items **visibles** alors que `selection.ids` survit à `openBrowseFolder` (jamais clear) → sélection hors-vue abandonnée silencieusement avec snackbar succès. Même classe `ui/search/SearchScreen.kt:290-305` (chips actifs en mode sélection, delete par snapshot).
|
|
||||||
- **M35 — `ui/document/DocumentViewerScreen.kt:131-144`** : pas de clamp après suppression — supprimer le dernier doc (page 2/2) laisse `pagerState` hors bornes → viewer vide au lieu de retomber sur 1er ou `onBack`.
|
|
||||||
- **M36 — `ui/settings/SettingsScreen.kt:120-128`** : préférence `SYSTEM` inatteignable (Switch DARK/LIGHT depuis `darkNow`, store + thème supportent SYSTEM) → impossible de revenir à « suivre le système ».
|
|
||||||
- **M37 — `ui/settings/SettingsViewModel.kt:30-36`** : `load()` écrase une saisie serveur en cours (`_serverUrl` init défaut puis réassigné après `load()` en `init`).
|
|
||||||
|
|
||||||
### Scan / PDF / Review / Thumbnails
|
|
||||||
- **M38 — `data/repository/ScanRepository.kt:63-78`** : `addPage` avec `sortOrder = pageCount` → doublons après suppression (`ORDER BY sort_order` instable, `swapOrder` ambigu). Cause : compteur au lieu de `MAX+1`.
|
|
||||||
- **M39 — `ui/scan/ScanViewModel.kt:180/199`** : dimensions stockées (pré-scale) ≠ réelles (downscale 2400px dans `process()`) → fiche `W×H` fausse pour grands quads.
|
|
||||||
- **M40 — `ui/scan/ScanViewModel.kt:177-203`** : écriture JPEG hors transaction Room (orphelins si insert échoue) ; `deletePage` supprime le fichier **avant** la ligne DB (crash = ligne vers fichier absent → rejoint C8).
|
|
||||||
- **M41 — `data/repository/FileRepository.kt:206`** : `saveLocalFile` ne remonte jamais `cloud` → `local-cloud` (`existing?.syncStatus ?: …`) → fichier cloud-only réimporté en SAF reste badgé « cloud », ignoré vignette/OCR (`sync_status='local-cloud'` requis, `FileDao.kt:137`).
|
|
||||||
- **M42 — `ui/pdfbuilder/PdfBuilderViewModel.kt:227-237`** : PDF assemblé importé `processed=false` (défaut omis, contraire export scan `true`) → atterrit en review alors que l'utilisateur vient de le construire.
|
|
||||||
- **M43 — `ui/review/SwipeReviewViewModel.kt:68-74,94-100`** : retrait optimiste sans réinsertion sur échec (`keep`/`markAllProcessed`, contraire `delete` qui réinsère) → carte perdue jusqu'au prochain `load()` (init seule).
|
|
||||||
- **M44 — `ui/pdfbuilder/PdfBuilderScreen.kt:248`** : `remember(files)` réinitialise la sélection à chaque update Room → cases cochées effacées pendant un refresh serveur.
|
|
||||||
- **M45 — `ui/pdfbuilder/PdfBuilderEngine.kt:104-107`** : pages PDF sources plafonnées à 1200pt malgré commentaire « format conservé » (`min(1, 1200/max, 3000/max)`, le 1200 gagne toujours) → pixellisation A3/300dpi.
|
|
||||||
- **M46 — `features/scan/CornerGeometry.kt:19-26`** : `orderPoints` sans validation dégénérescence (doublons/quad aplati) → `outputSize = 0` → bitmap 1×1 validé (page blanche) au lieu d'erreur.
|
|
||||||
- **M47 — `ui/scan/CameraStage.kt:162-181`** : overlay calibré sur flux `ImageAnalysis` (hypothèse `FILL_CENTER`) alors que `PreviewView` affiche le flux `Preview` (ratio/crop différents) → quad décalé systématiquement quand les ratios diffèrent.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🟡 Mineurs (UX, perf, dette)
|
## 🟡 Mineurs restants (8) — ✅ tous corrigés le 2026-09-24 (162/162 tests verts)
|
||||||
|
|
||||||
### Sync / Worker / SAF
|
### Sync / Worker / SAF
|
||||||
- **m1 — `features/sync/SyncViewModel.kt:103-121`** : `_walkInProgress` sans `finally` (reste `true` si scope annulé) → badge « syncing » collé ; la fenêtre inclut l'appel réseau partage.
|
- **m1 — `features/sync/SyncViewModel.kt:108-133`** : `_walkInProgress` sans `finally` dans la boucle (reste `true` si scope annulé ; seul `importRoot:173` a un `finally`) → badge « syncing » collé ; la fenêtre inclut l'appel réseau partage.
|
||||||
- **m2 — `features/sync/SyncViewModel.kt:106-112`** : `OutboxSyncWorker.enqueue` + `OcrAutoWorker.enqueue` à chaque tick même sans changement → réveils WorkManager / 30s pour rien.
|
- **m2 — `features/sync/SyncViewModel.kt:110-116`** : `OutboxSyncWorker.enqueue` + `OcrAutoWorker.enqueue` à chaque tick même sans changement → réveils WorkManager / 30s pour rien.
|
||||||
- **m3 — `features/sync/OutboxSyncWorker.kt:97-100`** : 401 → `success()` sans re-signal, ops pendantes figées jusqu'au prochain tick/login (bénin, `AuthViewModel` ré-enqueue au re-login).
|
- **m5 — `features/sync/DeviceSync.kt:76-162`** : « transaction courte » en réalité géante (N upserts + `getAll()` dossiers **et** fichiers par racine sous verrou écriture) → lecteurs Room bloqués, jank/ANR sur grosses arborescences.
|
||||||
- **m4 — `features/sync/SafScanner.kt:132-139`** : `cursor.getString(iDoc)` sans garde `iDoc == -1`, `name` plateforme-nullable déréférencé → provider dégénéré = crash de tout `scanTree` à chaque tick.
|
|
||||||
- **m5 — `features/sync/DeviceSync.kt:75-137`** : « transaction courte » en réalité géante (N upserts + `getAll()` dossiers **et** fichiers par racine, O(racines×DB) sous verrou écriture) → lecteurs Room bloqués, jank/ANR sur grosses arborescences.
|
|
||||||
- **m6 — `features/saf/FolderDeleter.kt:74-88`** : `deleteLocally` multi-writes hors transaction (contraire `treeMarkMissing`) → kill à mi-chemin = `exists` partiel.
|
|
||||||
|
|
||||||
### Room / Domain / DI
|
### Room / Domain / DI
|
||||||
- **m7 — `data/local/dao/FileDao.kt:30-37`** : `searchWithFilters` `LIKE` brut sans `ESCAPE`, casse ASCII-only → `%`/`_` = jokers (match-all), « ete » ne trouve pas « ÉTÉ ».
|
- **m7 — `data/local/dao/FileDao.kt:45`** : `searchWithFilters` `LIKE` brut sans `ESCAPE`, casse ASCII-only → `%`/`_` = jokers (match-all), « ete » ne trouve pas « ÉTÉ ».
|
||||||
- **m8 — `data/local/FileOrdering.kt:5-11`** : tri mémoire (`referenceDate` seule) divergent du SQL (`name ASC` tiebreak, `FileDao.kt:21,43`) ; `lastModified = 0` SAF trié comme plus vieux → ordre incohérent + fichiers `0` enfouis.
|
- **m15 — `di/DatabaseModule.kt:25-28`** : aucune stratégie de downgrade → APK plus ancien sur DB v14 = crash `IllegalStateException` au lieu de dégradation contrôlée.
|
||||||
- **m9 — `data/local/dao/PendingOperationDao.kt:30-32`** : commentaire `MAX_PENDING_ATTEMPTS` contredit le code (`markFailed()` = dead-letter immédiate, `attempts` diagnostique) — trompeur pour futurs appelants (cohérent avec worker, seul le commentaire est faux).
|
- **m19 — `data/local/AppDatabase.kt:36-37`** : `version=14, exportSchema=false`, migrations non snapshotées → dérives indétectables en CI.
|
||||||
- **m10 — `data/local/dao/FileDao.kt:89`** : `updateUri` ne touche pas `updated_at` → ordre de convergence faussé après move.
|
|
||||||
- **m11 — `domain/LocalModeStore.kt:24`** : `get()` teste `!= null` au lieu de `== "1"` → toute valeur parasite (`"0"`, `""`) = mode local actif à tort.
|
|
||||||
- **m12 — `domain/ServerConfigStore.kt:40-44` + `domain/ThemePreferenceStore.kt:28-32`** : `load()` once-only (`AtomicBoolean`, sans réarmement) → après wipe/logout, URL/thème périmés en mémoire.
|
|
||||||
- **m13 — `domain/ThemePreferenceStore.kt:34-39`** : `set()` publie le `StateFlow` avant succès DB → divergence UI/DB si upsert échoue.
|
|
||||||
- **m14 — `domain/PrefKeys.kt:8`** : clé `SYNC_MODE` morte (0 usage, grep vérifié) → dérive spec/impl.
|
|
||||||
- **m15 — `di/DatabaseModule.kt:25-28`** : aucune stratégie de downgrade → APK plus ancien sur DB v11 = crash `IllegalStateException` au lieu de dégradation contrôlée.
|
|
||||||
- **m16 — index composites manquants** (`PendingOperationEntity.kt:20-27`, `FileEntity.kt:18-26`, `PendingOperationDao.kt:13`, `FileDao.kt:133-145`) : `selectPending` et `getOcrAutoCandidates` = full-table scan → jank/batterie à 10k lignes.
|
|
||||||
- **m17 — `data/local/entity/FileEntity.kt:56-57` vs `Migrations.kt:92`** : `processed` sans `defaultValue` Room alors que la migration met `DEFAULT 0` (contraire `createdInApp`, `FolderEntity.kt:43`) → fresh-install ≠ migré.
|
|
||||||
- **m18 — `data/local/dao/ScanDao.kt:48-57`** : `swapOrder` sans contrôle d'appartenance ni transaction → swap inter-sessions corrompt `sort_order`, concurrence = doublons.
|
|
||||||
- **m19 — `data/local/AppDatabase.kt:27-34`** : `exportSchema = false`, migrations non snapshotées → dérives indétectables en CI.
|
|
||||||
- **m20 — `data/repository/OcrRepository.kt:66-73`** : `poll()` infini (`while(true)` + 3s, sans timeout) alors qu'un job peut rester `processing` 15 min (stale claim serveur) → coroutine tenue indéfiniment.
|
|
||||||
- **m21 — `data/repository/OutboxRepository.kt`** : ops contrat non émissibles (`update_metadata`, `update_share`, `create_link`, `revoke_link` — §6.1 = 9 ops, 5 helpers) → rename partagé, update share, liens publics inopérants.
|
|
||||||
- **m22 — `data/remote/ApiService.kt`** : endpoints contrat absents (`PATCH /users/me/password`, `GET/DELETE /files/:id`, `GET /files/search`, `GET /shares/links/:token`) → changement mot de passe impossible avec tokens 7j non révoqués.
|
|
||||||
- **m23 — `data/repository/AuthRepository.kt:21-35`** : `registerDevice` best-effort avale tout (y compris 400/429) → `INVALID_DEVICE_ID`/`RATE_LIMITED` invisibles, 401 trompeur plus tard.
|
|
||||||
- **m24 — `ui/auth/AuthViewModel.kt:52-55`** : `registerDevice()` émis même en mode local (pas de garde contrairement à `syncSnapshot`).
|
|
||||||
- **m25 — `di/NetworkModule.kt:37-43`** : logging `BASIC` en DEBUG loggue les query PII (`GET /users/resolve?username=…`) dans logcat.
|
|
||||||
- **m26 — `data/remote/AuthInterceptor.kt:20-26`** : `Bearer` joint aux routes publiques (`POST /devices`, `POST /auth/login`) — serveur l'ignore mais hygiène + amplification de la fuite M26.
|
|
||||||
- **m27 — `auth/SessionManager.kt:33-38`** : `expiresAt` du login jeté (paseto TTL 7j) → expiration découverte par 401 brutal, impossible de pré-relancer.
|
|
||||||
- **m28 — `auth/SecureTokenStore.kt:27-36`** : init Keystore/`EncryptedSharedPreferences` au construct Hilt + I/O synchrone possiblement Main (`MasterKeys` déprécié) → ANR au restore, crash Direct Boot avant déverrouillage.
|
|
||||||
|
|
||||||
### UI
|
### Sync contrat / OCR
|
||||||
- **m29 — `ui/navigation/NavGraph.kt:50`** : `pdfBuilder(listOf())` → `"pdfbuilder/"` ne matche pas `"pdfbuilder/{ids}"` (protégé aujourd'hui par `enabled = ids.isNotEmpty()` — contrat implicite fragile).
|
- **m20 — `data/repository/OcrRepository.kt:66-73`** : `poll()` infini (`while(true)` + 3s, sans timeout) alors qu'un job peut rester `processing` longtemps (stale claim serveur) → coroutine tenue indéfiniment.
|
||||||
- **m30 — `ui/navigation/NavGraph.kt:53-59,165`** : `folder/…` sans `launchSingleTop` → double-tap = doublon de pile.
|
- **m21 — `data/repository/OutboxRepository.kt:72-147`** : ops contrat non émissibles (`update_metadata`, `update_share`, `create_link`, `revoke_link` — §6.1 = 9 ops, helpers partiels) → rename partagé, update share, liens publics inopérants.
|
||||||
- **m31 — `ui/navigation/KazierApp.kt:54-63`** : `rememberNavController()` par branche SignedIn↔Local → `signOutToLocal()` perd la position d'exploration (hoister le controller).
|
|
||||||
- **m32 — `ui/folderdetail/FolderDetailScreen.kt:395-429`** : dossiers non sélectionnables dans le détail (vs FolderList) — incohérence partage/multi-suppression inter-écrans.
|
|
||||||
- **m33 — `ui/pdfbuilder/PdfBuilderScreen.kt:104-114`** : `LaunchedEffect(buildPhase)` rejoue side-effects à la recomposition racine (rotation → `Failed` re-snackbar, `Saved` re-`onOpenDocument` = double navigation possible).
|
|
||||||
- **m34 — dialogs `remember` perdus à la rotation** (`SyncStatusBadge.kt:129`, `showDeleteWarning/Confirm`, `showMoveDialog`, `showShareSheet`, `showNameDialog`) — sûr mais UX ; `showOcrDialog` en `rememberSaveable` = bon exemple.
|
|
||||||
- **m35 — `ui/components/WatchedFoldersBadge.kt:36-40` + `WatchedFoldersViewModel.kt:25-27`** : double instance VM + `SharingStarted.Eagerly` collecte Room en continu même sur autres onglets.
|
|
||||||
- **m36 — `ui/settings/SettingsViewModel.kt:43-48`** : `onServerUrlChange` écrit en prefs à chaque frappe (churn IO) ; commentaire `testConnection` obsolète.
|
|
||||||
- **m37 — `MainActivity.kt:27-33`** : `themePreferenceStore.load()` fire-and-forget → flash de thème aux premières frames.
|
|
||||||
- **m38 — `ui/navigation/NavGraph.kt:213-219`** : bandeau import global chevauchant la FloatingNavBar, doublon des indicateurs par-écran.
|
|
||||||
- **m39 — `ui/pdfbuilder/PdfBuilderViewModel.kt:236`** : `syncStatus="local"` en littéral au lieu de `FileStatus.LOCAL` — fonctionne mais casse silencieusement à toute renommée.
|
|
||||||
|
|
||||||
### Scan / PDF / Thumbnails
|
---
|
||||||
- **m40 — `ui/scan/CameraStage.kt:86-91`** : `ImageCapture` forcé 1920×1080 paysage → sur portrait, bitmap pleine-rés + copie tournée (×2 mémoire ~16 Mo) → OOM petits devices.
|
|
||||||
- **m41 — `ui/scan/CameraStage.kt:165-181`** : `toBitmap()` pleine-rés à chaque frame d'analyse (~30fps) puis downscale interne → churn GC + batterie.
|
## 🛠️ Plans de correction (reliquat) — ✅ implémentés le 2026-09-24
|
||||||
- **m42 — `ui/scan/CameraStage.kt:99-101`** : `addOnLayoutChangeListener` jamais retiré → fuite mineure du listener.
|
|
||||||
- **m43 — `ui/scan/CameraStage.kt:200-211`** : `when` rotation sans `else` → angle inattendu = copie silencieuse au lieu d'erreur.
|
Ordre suivi : M13 → M5 → M27+m21 → M9 → mineurs par lot (m1+m2, m5, m7, m20, m15+m19).
|
||||||
- **m44 — `ui/scan/ScanGeometry.kt:42-69`** : division par zéro si `sourceRect` dégénérée (`Infinity/NaN` dans le quad ; inatteignable via `initialViewport` mais API publique exposée).
|
Écarts d'implémentation vs plan : M13 sans rewrite (colonne restée nullable, défaut Kotlin 1 + backfill — pas de bump de contrainte) ; m7 `COLLATE NOCASE` sans colonne normalisée (repli Unicode « ete » → « ÉTÉ » toujours ouvert, voir suivi) ; M27 `cachedAt` persisté = heure locale du pull (pas l'horloge serveur, skew).
|
||||||
- **m45 — `ui/scan/CropStage.kt:188-193`** : arrondi `roundToInt` viewport indépendant de l'offset → dépassement 1px en bordure (frange noire sur images impaires).
|
|
||||||
- **m46 — `ui/scan/ScanViewModel.kt:111-122`** : `combine(pages, pageCount)` avec count ignoré → réassignations `_pages` redondantes.
|
### M5 — `deleteInCloud` sans tombstone locale
|
||||||
- **m47 — `ui/scan/ScanViewModel.kt:409-418`** : `abandon()` laisse sessions vides `ABANDONED` jamais purgées + `sessionDir()` fait `mkdirs()` en getter (recrée ce qu'on supprime).
|
Fichiers : `features/saf/FileDeleter.kt:88-104`, `features/saf/FolderDeleter.kt:91-103` (+ descendants via `collectDescendants`).
|
||||||
- **m48 — `data/repository/ScanRepository.kt:27-40`** : race `getOrCreateActiveSession` (double `active` possible, aucune unicité partielle ; fenêtre étroite).
|
Constat : `deleteInCloud` enqueue `delete_resource` mais laisse `exists = 1` ; la ressource reste affichée et le walk la revoit.
|
||||||
- **m49 — `domain/FileCategory.kt:19-27`** : CSV classé `TEXT` (par MIME) ou `OFFICE` (par extension) selon le chemin → icône/filtres/OCR divergents pour le même fichier.
|
Plan :
|
||||||
- **m50 — `features/thumbnails/ThumbnailStore.kt:51`** : map de `Mutex` jamais purgée → fuite lente par `resourceId`.
|
1. Dans `FileDeleter.deleteInCloud`, après `enqueueDeleteResource`, appeler `fileRepository.markMissing(resourceId, now)` dans la même transaction Room (ou `appDatabase.withTransaction` comme `deleteFull`).
|
||||||
- **m51 — `features/thumbnails/ThumbnailStore.kt:104-112`** : `.tmp` orphelin si `renameTo` échoue → résidus `*.webp.tmp`.
|
2. Dans `FolderDeleter.deleteInCloud`, idem pour le dossier ET sa descendance Room (`treeMarkMissing`-léger : `markMissing` sur fichiers + sous-dossiers, sans `delete_resource` supplémentaire sauf si `hasSyncedCreateOperation`).
|
||||||
- **m52 — `features/thumbnails/ThumbnailStore.kt:83-87`** : `isUpToDate` sur `mtime` seule (granularité seconde SAF) → vignette périmée après édition rapide (pas de taille/hash).
|
3. Vérifier que le walk ne ressuscite pas : les lignes `exists = 0` + `delete_resource` pending doivent être ignorées par la réconciliation (garde `hasPendingDeleteOperation`, cf. `OutboxRepository.kt:204`).
|
||||||
- **m53 — `ui/pdfbuilder/PdfBuilderEngine.kt:121-124`** : `renderer?.close()` non protégé (si `close()` lève, `pfd.close()` sautée → fd leak ; `ThumbnailStore.renderPdfPage` fait `runCatching`).
|
4. UI : vérifier que les listes filtrent `exists = 1` (déjà le cas) → la ligne disparaît aussitôt.
|
||||||
- **m54 — `features/scan/CornerGeometry.kt:40-45`** : commentaire « moyenne » mais code `max` → warp légèrement étiré vs réel.
|
Tests : étendre `ProcessedGateTest` ou nouveau `DeleteInCloudTest` — `deleteInCloud` puis assert `exists == 0` + op `delete_resource` présente ; walk simulé ne ressuscite pas.
|
||||||
- **m55 — `features/scan/ScanImageProcessor.kt:126-181`** : mats de contours non libérés sur exception (`c.release()` chemin nominal seul) → fuite native OpenCV.
|
|
||||||
- **m56 — `ui/review/SwipeReviewViewModel.kt:52-64`** : échec de reload écrase le deck (`update{cards=files}` même sur `emptyList` d'erreur) → deck vidé à tort.
|
### M9 — `FolderMerger` multi-transactions non-atomique
|
||||||
|
Fichier : `features/saf/FolderMerger.kt:53-106`.
|
||||||
|
Constat : `createMergedFolder` (transaction 1), moves (N transactions via `FileMover`/`reparentSubFolders`), deletes (N transactions). Un crash à mi-fusion laisse un état partiel ; la relance est idempotente (dossier réutilisé) mais ne reprend pas les moves manquants proprement.
|
||||||
|
Plan :
|
||||||
|
1. Envelopper `mergeSelectedFolders` dans `appDatabase.withTransaction` pour la partie Room (create + reparent + `treeMarkMissing`) — nécessite d'injecter `AppDatabase` dans `FolderMerger` et de rendre `FileMover.moveFiles` / `reparentSubFolders` appelables dans une transaction existante (ou journaliser les `move_resource`/`delete_resource` dans la transaction et n'exécuter le SAF physique qu'avant/après selon le sens crash-safe : journal-first comme C4).
|
||||||
|
2. Ordre crash-safe : (a) transaction Room = create + moves logiques + deletes logiques (`exists = 0` + outbox), (b) exécution SAF physique (moves + deletes), (c) sweep au prochain tick pour les physiques manqués (réutiliser `sweepPendingPhysicalDeletes`).
|
||||||
|
3. Garder l'idempotence `findExistingMerged` pour les relances.
|
||||||
|
4. À défaut d'une transaction unique (SAF non transactionnel), a minima : rendre chaque étape reprise-safe (skip les sources déjà vides, skip les moves déjà journalisés via `hasPendingMoveOperation`).
|
||||||
|
Tests : nouveau `FolderMergerTest` — fusion 2 dossiers avec fichiers + sous-dossier, assert `movedFiles/deletedFolders`, relance idempotente (pas de doublon), crash simulé entre étape 2 et 3 → reprise sans perte.
|
||||||
|
|
||||||
|
### M13 — `exists: Int? = null` invisible
|
||||||
|
Fichiers : `data/local/entity/FolderEntity.kt:36`, `data/local/entity/FileEntity.kt:46`, DAO (`FolderDao`, `FileDao` filtres `= 1`), `Migrations.kt` (créations tables sans `DEFAULT 1` / `NOT NULL`).
|
||||||
|
Constat : toute ligne insérée sans `exists` explicite (défaut Kotlin `null`) est cachée par les requêtes `WHERE exists = 1`.
|
||||||
|
Plan :
|
||||||
|
1. Durcir les entités : `exists: Int = 1` (non-null, défaut 1) dans `FolderEntity` et `FileEntity`.
|
||||||
|
2. Migration v14→v15 : `UPDATE folders SET exists = 1 WHERE exists IS NULL`, idem `files`, puis recréation ou `NOT NULL DEFAULT 1` (Room : via `autoMigrations` ou SQL `ALTER` + table rewrite selon la version SQLite ; le plus simple : `UPDATE` + contrainte applicative + défaut entité, sans rewrite si Room accepte le changement nullable→non-null via migration manuelle avec recréation de table).
|
||||||
|
3. Auditer tous les `saveFolder`/`saveLocalFile`/`upsertShared*` pour passer `exists = 1` explicitement.
|
||||||
|
4. Option : ajouter un test `ExistsDefaultTest` — insert sans `exists`, assert visible dans `observeByFolder`/`searchWithFilters`.
|
||||||
|
Note : migration à tester via `Migration13To14Test`-style (nouveau `Migration14To15Test`) + `:app:testDebugUnitTest`.
|
||||||
|
|
||||||
|
### M27 — snapshot permissions sans delta ni `canAccess`
|
||||||
|
Fichiers : `data/repository/ShareRepository.kt:44-47`, `data/remote/dto/Dtos.kt:144-156` (`sharedById`/`expiresAt: Any?`), `data/remote/ApiService.kt:74-78`, `ApiClient.kt:106-108`.
|
||||||
|
Constat : `syncPermissions()` sans `after`, champs `sharedById`/`expiresAt` jamais lus, `cachedAt` jamais persisté, aucun downgrade TTL 24h ni `canAccess` → grants révoqués/expirés visibles jusqu'au prochain login.
|
||||||
|
Plan :
|
||||||
|
1. DTO : typer `sharedById: String?`, `expiresAt: Long?` (le serveur renvoie ms epoch ou null — vérifier `docs/api-v1.md §6.2` et adapter avec un adapter Moshi tolérant `Any?`→Long).
|
||||||
|
2. Persistance : stocker `cachedAt`/`expiresAt`/`sharedById`/`effectiveAccess` — soit colonnes sur `files`/`folders`, soit nouvelle table `resource_permissions` (préférable : ne pas polluer les entités). A minima `user_preferences` : `permissions_cached_at`.
|
||||||
|
3. Delta : `syncSnapshot(after: Long? = cachedAt)` → `apiClient.syncPermissions(after)` ; pull complet (`after = null`) au login/restauration + quand `now - cachedAt > 24h` (TTL).
|
||||||
|
4. Expiration locale : au tick, marquer `exists = 0` les lignes dont `expiresAt < now` ; downgrade lecture seule après TTL sans reseed (gate `canAccess` : à exposer via `ShareRepository.canAccess(resourceId, required)` utilisé par les VM avant open/share/rename).
|
||||||
|
5. `canAccess` : ranking viewer < commenter < editor < owner, `ownerId == currentUser` → owner.
|
||||||
|
Tests : étendre `ShareRepositoryTest` — delta `after`, révocation (absent du snapshot → `markMissing`), expiration (`expiresAt` passé → masqué), `canAccess` ranking.
|
||||||
|
|
||||||
|
### m1+m2 — badge sync et réveils WorkManager
|
||||||
|
Fichier : `features/sync/SyncViewModel.kt:100-137`.
|
||||||
|
Plan :
|
||||||
|
1. m1 : envelopper le corps de boucle dans `try { … } finally { _walkInProgress.value = false }` (comme `importRoot:173-176`), et sortir `syncSnapshot` de la fenêtre `_walkInProgress` (flag séparé ou `syncing` = walk || drain déjà calculé via WorkManager).
|
||||||
|
2. m2 : n'enqueuer `OutboxSyncWorker`/`OcrAutoWorker` que si le tick a produit quelque chose (`results.any { folders+files+missing > 0 }` ou `pendingOperationDao.countPending() > 0` / fichier promu). Éviter les réveils /30s à vide.
|
||||||
|
Tests : Robolectric `SyncViewModelTest` — annulation du scope → flag retombe ; tick sans changement → `WorkManager` non sollicité (mock/static ou extraction d'un `SyncScheduler` testable).
|
||||||
|
|
||||||
|
### m5 — walk : transaction géante + `getAll()` par racine
|
||||||
|
Fichier : `features/sync/DeviceSync.kt:67-163`.
|
||||||
|
Plan :
|
||||||
|
1. Découper la phase 2 : upserts dossiers/fichiers par batch (ex. 200) en transactions courtes successives au lieu d'une transaction unique ; la réconciliation `missing` en passe séparée.
|
||||||
|
2. Remplacer `folderRepository.getAll()` + `fileRepository.getAll()` (full-table scan par racine) par des requêtes scopées à la racine (`getByRootUri`/`getDescendants`) — à ajouter aux DAO avec index sur `uri` (déjà unique) ; filtrer en SQL plutôt qu'en mémoire (`isChildOf` en `LIKE rootUri || '/%'`).
|
||||||
|
3. Conserver le `Mutex` single-flight ; vérifier `ensureActive()` dans les boucles longues pour annulation propre.
|
||||||
|
Tests : `SafScannerTest`-style perf — 5k fichiers simulés, assert temps/absence d'ANR ; test de convergence identique avant/après.
|
||||||
|
|
||||||
|
### m7 — recherche `LIKE` sans `ESCAPE`
|
||||||
|
Fichier : `data/local/dao/FileDao.kt:42-49`.
|
||||||
|
Plan : échapper `%`, `_`, `\` dans `:query` côté repository (`searchFiles`) + `LIKE … ESCAPE '\'` dans la requête ; ajouter `COLLATE NOCASE` (ou normalisation) pour « ete » → « ÉTÉ ». Tester : `%`, `_`, `\`, accents, casse.
|
||||||
|
Tests : `SearchFieldTest` ou nouveau `SearchEscapeTest` — `%` littéral ne matche pas tout, `_` littéral, insensible à la casse.
|
||||||
|
|
||||||
|
### m20 — `OcrRepository.poll()` infini
|
||||||
|
Fichier : `data/repository/OcrRepository.kt:66-73`.
|
||||||
|
Plan : ajouter timeout (ex. 10 min) + nombre max de polls + backoff ; lever `OcrTimeoutException` ou retourner le dernier état ; coopérer avec l'annulation (`ensureActive`). Mettre à jour les appelants (viewer auto) pour afficher « OCR indisponible, réessayer ».
|
||||||
|
Tests : `OcrRepositoryTest` — job restant `processing` → timeout au bout de N polls (fake `ApiClient` + virtual time/delays courts).
|
||||||
|
|
||||||
|
### m15+m19 — robustesse DB (downgrade + `exportSchema`)
|
||||||
|
Fichiers : `di/DatabaseModule.kt:25-28`, `data/local/AppDatabase.kt:31-38`.
|
||||||
|
Plan :
|
||||||
|
1. m19 : `exportSchema = true` + `schemas/` commité ; ajouter un test `Migration13To14Test`-style qui échoue en cas de dérive (CI).
|
||||||
|
2. m15 : stratégie downgrade explicite et documentée — soit `fallbackToDestructiveMigrationOnDowngrade()` (avec avertissement perte de données locales, acceptable car miroir SAF + outbox non poussée à préserver → plutôt refuser le démarrage avec message), soit crash contrôlé avec écran « mettez à jour l'app ». Choisir et documenter ; ne jamais laisser `IllegalStateException` brut.
|
||||||
|
Tests : build avec `exportSchema=true` + `room.schemaLocation` ; test downgrade (ouverture v15 avec APK v14 → comportement attendu).
|
||||||
|
|
||||||
|
### m21 — ops contrat non émissibles
|
||||||
|
Fichiers : `data/repository/OutboxRepository.kt:72-147`, `data/local/entity/PendingOperationEntity.kt:76-86` (constantes déjà présentes : `UPDATE_METADATA`, `UPDATE_SHARE`, `CREATE_LINK`, `REVOKE_LINK`).
|
||||||
|
Plan : ajouter `enqueueUpdateMetadata(resourceId, resourceType, name?)`, `enqueueUpdateShare(...)`, `enqueueCreateLink(resourceId, resourceType, token, access, expiresAt?)`, `enqueueRevokeLink(...)` avec payloads §6.1 (`granteeUserId/access/inherit/expiresAt`, `token/access/expiresAt`) ; brancher les appelants (rename partagé, update share, liens publics) ; `GenerateId` pour `token` 32-hex côté client.
|
||||||
|
Tests : `OutboxSyncWorkerTest`-style — sérialisation payload, `normalizePayloadNumbers` (`expiresAt` Long exact, non `1.7E12`), round-trip `POST /sync/ops` mocké.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -195,7 +151,7 @@ Repro : device sans lib OpenCV → valider un crop → crash au retour caméra.
|
|||||||
- Ordre interceptors `serverUrl → auth → logging`, `BASIC` ne log ni headers ni bodies — OK.
|
- Ordre interceptors `serverUrl → auth → logging`, `BASIC` ne log ni headers ni bodies — OK.
|
||||||
- Contrat HTTP conforme sur endpoints déclarés (query `folderId/page/pageSize`, `deviceId` camel vs `device_id` login, multipart `file`/`resourceId`/`folderId`, enveloppes `{data,meta}`/`{error:{code,message}}`, codes) — OK.
|
- Contrat HTTP conforme sur endpoints déclarés (query `folderId/page/pageSize`, `deviceId` camel vs `device_id` login, multipart `file`/`resourceId`/`folderId`, enveloppes `{data,meta}`/`{error:{code,message}}`, codes) — OK.
|
||||||
- `device_id` claim jamais utilisé comme preuve, seul le `Bearer` parle — conforme middleware.
|
- `device_id` claim jamais utilisé comme preuve, seul le `Bearer` parle — conforme middleware.
|
||||||
- Worker no-op en mode local (`OutboxSyncWorker.kt:71`), batch 20 ≤ 100 serveur, statuts OCR, `resolveUser` trim compatible, password jamais trimé — OK.
|
- Worker no-op en mode local (`OutboxSyncWorker.kt:111`), batch 20 ≤ 100 serveur, statuts OCR, `resolveUser` trim compatible, password jamais trimé — OK.
|
||||||
- Deep-links : aucun défini (absence, pas de bug) ; args nav `folderResourceId`/`documentResourceId`/`ids` cohérents, 32-hex sans `/`.
|
- Deep-links : aucun défini (absence, pas de bug) ; args nav `folderResourceId`/`documentResourceId`/`ids` cohérents, 32-hex sans `/`.
|
||||||
- Hilt : `MainActivity @AndroidEntryPoint`, tous `hiltViewModel()` ↔ `@HiltViewModel`, scopes corrects — aucune injection manquante.
|
- Hilt : `MainActivity @AndroidEntryPoint`, tous `hiltViewModel()` ↔ `@HiltViewModel`, scopes corrects — aucune injection manquante.
|
||||||
- Pas de recomposition infinie trouvée ; `collectAsStateWithLifecycle` partout ; placeholder cloud-only correct (`DocumentContentViewer.kt:39-47`) ; recherche 100 % locale conforme V1 ; back stack onglets correct (`saveState`/`restoreState`) ; `SelectionState` volatile documenté volontaire.
|
- Pas de recomposition infinie trouvée ; `collectAsStateWithLifecycle` partout ; placeholder cloud-only correct (`DocumentContentViewer.kt:39-47`) ; recherche 100 % locale conforme V1 ; back stack onglets correct (`saveState`/`restoreState`) ; `SelectionState` volatile documenté volontaire.
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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[]` | — |
|
||||||
|
|
||||||
|
|||||||
@@ -21,9 +21,32 @@ set -euo pipefail
|
|||||||
./gradlew :app:assembleDebug -q
|
./gradlew :app:assembleDebug -q
|
||||||
APK="app/build/outputs/apk/debug/app-debug.apk"
|
APK="app/build/outputs/apk/debug/app-debug.apk"
|
||||||
if [ "${usage_target?}" = "emulator" ]; then
|
if [ "${usage_target?}" = "emulator" ]; then
|
||||||
adb -e install -r "$APK"
|
ADB_FLAGS=(-e)
|
||||||
else
|
else
|
||||||
adb -d install -r "$APK"
|
ADB_FLAGS=(-d)
|
||||||
|
fi
|
||||||
|
# adb natif s'il fonctionne (PATH + binaire exécutable sur cet OS)...
|
||||||
|
if command -v adb >/dev/null 2>&1 && adb version >/dev/null 2>&1; then
|
||||||
|
adb "${ADB_FLAGS[@]}" install -r "$APK"
|
||||||
|
# ...sinon repli NixOS : l'adb du SDK est un binaire FHS dynamiquement
|
||||||
|
# lié, on l'exécute via steam-run (cf. local.properties pour sdk.dir).
|
||||||
|
elif command -v steam-run >/dev/null 2>&1; then
|
||||||
|
SDK_DIR="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-}}"
|
||||||
|
if [ -z "$SDK_DIR" ] && [ -f local.properties ]; then
|
||||||
|
SDK_DIR="$(sed -n 's/^sdk\.dir=//p' local.properties | head -n 1)"
|
||||||
|
fi
|
||||||
|
if [ -z "$SDK_DIR" ] && [ -d "$HOME/Android/Sdk" ]; then
|
||||||
|
SDK_DIR="$HOME/Android/Sdk"
|
||||||
|
fi
|
||||||
|
if [ -z "$SDK_DIR" ] || [ ! -x "$SDK_DIR/platform-tools/adb" ]; then
|
||||||
|
echo "adb introuvable : définissez ANDROID_HOME ou sdk.dir dans local.properties." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-}:$HOME/.nix-profile/lib:/run/opengl-driver/lib"
|
||||||
|
steam-run "$SDK_DIR/platform-tools/adb" "${ADB_FLAGS[@]}" install -r "$APK"
|
||||||
|
else
|
||||||
|
echo "adb ne fonctionne pas sur cet OS et steam-run est absent (NixOS)." >&2
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
'''
|
'''
|
||||||
|
|
||||||
|
|||||||
@@ -84,6 +84,11 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// m19 : export du schéma Room (`app/schemas/`) pour détecter les dérives en CI.
|
||||||
|
ksp {
|
||||||
|
arg("room.schemaLocation", "$projectDir/schemas")
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(libs.androidx.core.ktx)
|
implementation(libs.androidx.core.ktx)
|
||||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
|
|||||||
@@ -0,0 +1,730 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 16,
|
||||||
|
"identityHash": "ec10fdb23d5da3a76a73222e9c404561",
|
||||||
|
"entities": [
|
||||||
|
{
|
||||||
|
"tableName": "folders",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `exists` INTEGER, `parent_resource_id` TEXT, `owner_id` TEXT, `sync_status` TEXT NOT NULL, `created_in_app` INTEGER NOT NULL DEFAULT 0, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceId",
|
||||||
|
"columnName": "resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "uri",
|
||||||
|
"columnName": "uri",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "name",
|
||||||
|
"columnName": "name",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "exists",
|
||||||
|
"columnName": "exists",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "parentResourceId",
|
||||||
|
"columnName": "parent_resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "ownerId",
|
||||||
|
"columnName": "owner_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "syncStatus",
|
||||||
|
"columnName": "sync_status",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "createdInApp",
|
||||||
|
"columnName": "created_in_app",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "addedAt",
|
||||||
|
"columnName": "added_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "updatedAt",
|
||||||
|
"columnName": "updated_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": true,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_folders_resource_id",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_folders_uri",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"uri"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_folders_parent_resource_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"parent_resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foreignKeys": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "user_preferences",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`key`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "key",
|
||||||
|
"columnName": "key",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "value",
|
||||||
|
"columnName": "value",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "updatedAt",
|
||||||
|
"columnName": "updated_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"key"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [],
|
||||||
|
"foreignKeys": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "files",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `folder_resource_id` TEXT NOT NULL, `extension` TEXT, `size` INTEGER NOT NULL, `mime_type` TEXT, `exists` INTEGER, `last_modified` INTEGER, `owner_id` TEXT, `category` TEXT, `sync_status` TEXT NOT NULL, `content` TEXT, `processed` INTEGER NOT NULL, `ocr_text` TEXT, `ocr_attempts` INTEGER NOT NULL, `ocr_queued_at` INTEGER, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceId",
|
||||||
|
"columnName": "resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "uri",
|
||||||
|
"columnName": "uri",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "name",
|
||||||
|
"columnName": "name",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "folderResourceId",
|
||||||
|
"columnName": "folder_resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "extension",
|
||||||
|
"columnName": "extension",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "size",
|
||||||
|
"columnName": "size",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "mimeType",
|
||||||
|
"columnName": "mime_type",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "exists",
|
||||||
|
"columnName": "exists",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "lastModified",
|
||||||
|
"columnName": "last_modified",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "ownerId",
|
||||||
|
"columnName": "owner_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "category",
|
||||||
|
"columnName": "category",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "syncStatus",
|
||||||
|
"columnName": "sync_status",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "content",
|
||||||
|
"columnName": "content",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "processed",
|
||||||
|
"columnName": "processed",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "ocrText",
|
||||||
|
"columnName": "ocr_text",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "ocrAttempts",
|
||||||
|
"columnName": "ocr_attempts",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "ocrQueuedAt",
|
||||||
|
"columnName": "ocr_queued_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "addedAt",
|
||||||
|
"columnName": "added_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "updatedAt",
|
||||||
|
"columnName": "updated_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": true,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_files_resource_id",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_files_uri",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"uri"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_files_folder_resource_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"folder_resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_folder_resource_id` ON `${TABLE_NAME}` (`folder_resource_id`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_files_category",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"category"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_category` ON `${TABLE_NAME}` (`category`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_files_exists_processed_sync_status",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"exists",
|
||||||
|
"processed",
|
||||||
|
"sync_status"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` ON `${TABLE_NAME}` (`exists`, `processed`, `sync_status`)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foreignKeys": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "pending_operations",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_id` TEXT, `operation_id` TEXT NOT NULL, `ref_type` TEXT, `ref_id` INTEGER, `resource_id` TEXT, `resource_type` TEXT, `operation` TEXT NOT NULL, `payload` TEXT NOT NULL, `parent_resource_id` TEXT, `status` TEXT NOT NULL, `attempts` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "deviceId",
|
||||||
|
"columnName": "device_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "operationId",
|
||||||
|
"columnName": "operation_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "refType",
|
||||||
|
"columnName": "ref_type",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "refId",
|
||||||
|
"columnName": "ref_id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceId",
|
||||||
|
"columnName": "resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceType",
|
||||||
|
"columnName": "resource_type",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "operation",
|
||||||
|
"columnName": "operation",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "payload",
|
||||||
|
"columnName": "payload",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "parentResourceId",
|
||||||
|
"columnName": "parent_resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "status",
|
||||||
|
"columnName": "status",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "attempts",
|
||||||
|
"columnName": "attempts",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "createdAt",
|
||||||
|
"columnName": "created_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "updatedAt",
|
||||||
|
"columnName": "updated_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": true,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_pending_operations_device_id_operation_id",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"device_id",
|
||||||
|
"operation_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_pending_operations_device_id_operation_id` ON `${TABLE_NAME}` (`device_id`, `operation_id`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_pending_operations_status",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"status"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_status` ON `${TABLE_NAME}` (`status`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_pending_operations_resource_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_pending_operations_resource_id_operation_status",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"resource_id",
|
||||||
|
"operation",
|
||||||
|
"status"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` ON `${TABLE_NAME}` (`resource_id`, `operation`, `status`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_pending_operations_parent_resource_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"parent_resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foreignKeys": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "scan_sessions",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `root_folder_id` TEXT, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceId",
|
||||||
|
"columnName": "resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "rootFolderId",
|
||||||
|
"columnName": "root_folder_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "status",
|
||||||
|
"columnName": "status",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "createdAt",
|
||||||
|
"columnName": "created_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "updatedAt",
|
||||||
|
"columnName": "updated_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": true,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_scan_sessions_resource_id",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_sessions_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foreignKeys": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "scan_pages",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `session_id` INTEGER NOT NULL, `temp_uri` TEXT NOT NULL, `corners_json` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, FOREIGN KEY(`session_id`) REFERENCES `scan_sessions`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceId",
|
||||||
|
"columnName": "resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "sessionId",
|
||||||
|
"columnName": "session_id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "tempUri",
|
||||||
|
"columnName": "temp_uri",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "cornersJson",
|
||||||
|
"columnName": "corners_json",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "width",
|
||||||
|
"columnName": "width",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "height",
|
||||||
|
"columnName": "height",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "sortOrder",
|
||||||
|
"columnName": "sort_order",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "status",
|
||||||
|
"columnName": "status",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "createdAt",
|
||||||
|
"columnName": "created_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": true,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_scan_pages_resource_id",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"resource_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_pages_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_scan_pages_session_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"session_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_session_id` ON `${TABLE_NAME}` (`session_id`)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "index_scan_pages_sort_order",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"sort_order"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_sort_order` ON `${TABLE_NAME}` (`sort_order`)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foreignKeys": [
|
||||||
|
{
|
||||||
|
"table": "scan_sessions",
|
||||||
|
"onDelete": "CASCADE",
|
||||||
|
"onUpdate": "NO ACTION",
|
||||||
|
"columns": [
|
||||||
|
"session_id"
|
||||||
|
],
|
||||||
|
"referencedColumns": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "resource_permissions",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resource_id` TEXT NOT NULL, `resource_type` TEXT NOT NULL, `effective_access` TEXT NOT NULL, `owner_id` TEXT, `shared_by_id` TEXT, `expires_at` INTEGER, `cached_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`resource_id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceId",
|
||||||
|
"columnName": "resource_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "resourceType",
|
||||||
|
"columnName": "resource_type",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "effectiveAccess",
|
||||||
|
"columnName": "effective_access",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "ownerId",
|
||||||
|
"columnName": "owner_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "sharedById",
|
||||||
|
"columnName": "shared_by_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "expiresAt",
|
||||||
|
"columnName": "expires_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "cachedAt",
|
||||||
|
"columnName": "cached_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "updatedAt",
|
||||||
|
"columnName": "updated_at",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"resource_id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_resource_permissions_expires_at",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"expires_at"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` ON `${TABLE_NAME}` (`expires_at`)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foreignKeys": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"views": [],
|
||||||
|
"setupQueries": [
|
||||||
|
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||||
|
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ec10fdb23d5da3a76a73222e9c404561')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,6 +41,16 @@
|
|||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
<!-- Liens de partage `kazier://share/<token>` (32-hex) : ouverture
|
||||||
|
dans l'écran de résolution (route publique, sans auth). -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data
|
||||||
|
android:scheme="kazier"
|
||||||
|
android:host="share" />
|
||||||
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
</application>
|
</application>
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,20 @@ class SecureTokenStore @Inject constructor(
|
|||||||
override fun getExpiresAt(): Long? =
|
override fun getExpiresAt(): Long? =
|
||||||
prefs.getLong(KEY_EXPIRES_AT, -1L).takeIf { it >= 0L }
|
prefs.getLong(KEY_EXPIRES_AT, -1L).takeIf { it >= 0L }
|
||||||
|
|
||||||
|
override fun getCredentials(): Credentials? {
|
||||||
|
val username = prefs.getString(KEY_USERNAME, null)?.takeIf { it.isNotBlank() } ?: return null
|
||||||
|
val password = prefs.getString(KEY_PASSWORD, null)?.takeIf { it.isNotEmpty() } ?: return null
|
||||||
|
return Credentials(username, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun saveCredentials(username: String, password: String) {
|
||||||
|
prefs.edit().putString(KEY_USERNAME, username).putString(KEY_PASSWORD, password).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun clearCredentials() {
|
||||||
|
prefs.edit().remove(KEY_USERNAME).remove(KEY_PASSWORD).apply()
|
||||||
|
}
|
||||||
|
|
||||||
override fun save(token: String, user: UserDto, expiresAt: Long?) {
|
override fun save(token: String, user: UserDto, expiresAt: Long?) {
|
||||||
prefs.edit()
|
prefs.edit()
|
||||||
.putString(KEY_TOKEN, token)
|
.putString(KEY_TOKEN, token)
|
||||||
@@ -70,5 +84,7 @@ class SecureTokenStore @Inject constructor(
|
|||||||
private const val KEY_TOKEN = "kazier.auth_token"
|
private const val KEY_TOKEN = "kazier.auth_token"
|
||||||
private const val KEY_ACCOUNT = "kazier.account"
|
private const val KEY_ACCOUNT = "kazier.account"
|
||||||
private const val KEY_EXPIRES_AT = "kazier.expires_at"
|
private const val KEY_EXPIRES_AT = "kazier.expires_at"
|
||||||
|
private const val KEY_USERNAME = "kazier.auth_username"
|
||||||
|
private const val KEY_PASSWORD = "kazier.auth_password"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,9 @@ package com.kazier.mobile.auth
|
|||||||
|
|
||||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
|
import com.kazier.mobile.data.remote.ApiException
|
||||||
import com.kazier.mobile.data.remote.dto.UserDto
|
import com.kazier.mobile.data.remote.dto.UserDto
|
||||||
|
import com.kazier.mobile.data.repository.AuthRepository
|
||||||
import com.kazier.mobile.domain.ActiveUserStore
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.domain.LocalModeStore
|
import com.kazier.mobile.domain.LocalModeStore
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -10,8 +12,23 @@ import javax.inject.Singleton
|
|||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.SharedFlow
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import timber.log.Timber
|
||||||
|
|
||||||
|
/** Événements de session vers l'UI (re-login silencieux, lot 3). */
|
||||||
|
sealed interface AuthEvent {
|
||||||
|
/** Le token a été renouvelé sans action utilisateur — rester connecté. */
|
||||||
|
data class Reauthenticated(val user: UserDto) : AuthEvent
|
||||||
|
|
||||||
|
/** Plus de session récupérable — afficher le login (pré-rempli si possible). */
|
||||||
|
data class SessionExpired(val username: String?) : AuthEvent
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Orchestration de la session (restauration/sauvegarde/purge) : relie le store
|
* Orchestration de la session (restauration/sauvegarde/purge) : relie le store
|
||||||
@@ -20,8 +37,15 @@ import kotlinx.coroutines.withContext
|
|||||||
* ([LocalModeStore]) pour survivre aux redémarrages.
|
* ([LocalModeStore]) pour survivre aux redémarrages.
|
||||||
*
|
*
|
||||||
* Le callback 401 est possédé ici (singleton, M25) — jamais par un ViewModel :
|
* Le callback 401 est possédé ici (singleton, M25) — jamais par un ViewModel :
|
||||||
* après `onCleared`, un token expiré/révoqué continue de purger la session
|
* après `onCleared`, un token expiré/révoqué continue d'être traité (le worker
|
||||||
* (le worker cesse alors de rejouer l'outbox sous un token mort).
|
* cesse alors de rejouer l'outbox sous un token mort).
|
||||||
|
*
|
||||||
|
* Re-login silencieux (lot 3) : les identifiants saisis au login sont
|
||||||
|
* persistés chiffrés ; sur 401 (ou token expiré détecté en proactif), une
|
||||||
|
* seule tentative de `POST /auth/login` est jouée (single-flight). Succès →
|
||||||
|
* [AuthEvent.Reauthenticated] (file conservée si même compte) ; identifiants
|
||||||
|
* rejetés → purge complète + [AuthEvent.SessionExpired]. La requête en vol
|
||||||
|
* ayant subi le 401 n'est PAS rejouée — l'appelant la relance (pull, retry).
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class SessionManager @Inject constructor(
|
class SessionManager @Inject constructor(
|
||||||
@@ -31,14 +55,22 @@ class SessionManager @Inject constructor(
|
|||||||
private val localModeStore: LocalModeStore,
|
private val localModeStore: LocalModeStore,
|
||||||
private val pendingOperationDao: PendingOperationDao,
|
private val pendingOperationDao: PendingOperationDao,
|
||||||
private val apiClient: ApiClient,
|
private val apiClient: ApiClient,
|
||||||
|
private val authRepository: AuthRepository,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
|
||||||
|
/** Single-flight du re-login : N 401 concurrents → 1 seul `POST /auth/login`. */
|
||||||
|
private val reloginMutex = Mutex()
|
||||||
|
|
||||||
|
private val _events = MutableSharedFlow<AuthEvent>(extraBufferCapacity = 4)
|
||||||
|
val events: SharedFlow<AuthEvent> = _events.asSharedFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
// 401 sur un endpoint protégé (token expiré/révoqué, compte supprimé)
|
// 401 sur un endpoint protégé (token expiré/révoqué, compte supprimé)
|
||||||
// → purge de la session. Le 401 du login et des routes publiques est
|
// → re-login silencieux puis purge si irrécupérable. Le 401 du login
|
||||||
// exonéré côté ApiClient (skipUnauthorizedHandling).
|
// et des routes publiques est exonéré côté ApiClient
|
||||||
|
// (skipUnauthorizedHandling).
|
||||||
apiClient.onUnauthorized = { handleUnauthorized() }
|
apiClient.onUnauthorized = { handleUnauthorized() }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,10 +82,18 @@ class SessionManager @Inject constructor(
|
|||||||
AuthSession(token = token, user = user, expiresAt = tokenStore.getExpiresAt())
|
AuthSession(token = token, user = user, expiresAt = tokenStore.getExpiresAt())
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun save(token: String, user: UserDto, expiresAt: Long? = null) =
|
suspend fun save(
|
||||||
withContext(Dispatchers.IO) {
|
token: String,
|
||||||
|
user: UserDto,
|
||||||
|
expiresAt: Long? = null,
|
||||||
|
username: String? = null,
|
||||||
|
password: String? = null,
|
||||||
|
) = withContext(Dispatchers.IO) {
|
||||||
val previousUserId = activeUserStore.get()
|
val previousUserId = activeUserStore.get()
|
||||||
tokenStore.save(token, user, expiresAt)
|
tokenStore.save(token, user, expiresAt)
|
||||||
|
if (username != null && password != null) {
|
||||||
|
tokenStore.saveCredentials(username, password)
|
||||||
|
}
|
||||||
activeUserStore.set(user.id)
|
activeUserStore.set(user.id)
|
||||||
localModeStore.clear()
|
localModeStore.clear()
|
||||||
tokenProvider.current = token
|
tokenProvider.current = token
|
||||||
@@ -69,6 +109,7 @@ class SessionManager @Inject constructor(
|
|||||||
|
|
||||||
suspend fun clear() = withContext(Dispatchers.IO) {
|
suspend fun clear() = withContext(Dispatchers.IO) {
|
||||||
tokenStore.clear()
|
tokenStore.clear()
|
||||||
|
tokenStore.clearCredentials()
|
||||||
activeUserStore.clear()
|
activeUserStore.clear()
|
||||||
tokenProvider.current = null
|
tokenProvider.current = null
|
||||||
// Sign-out explicite : la file non poussée est abandonnée (C5, voir
|
// Sign-out explicite : la file non poussée est abandonnée (C5, voir
|
||||||
@@ -77,16 +118,73 @@ 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 {
|
||||||
|
reloginMutex.withLock { silentReloginLocked() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-login proactif (démarrage, retour foreground) : si le token en
|
||||||
|
* mémoire est absent ou expiré et que des identifiants sont sauvés, tente
|
||||||
|
* un renouvellement. Vrai si un token frais est disponible au retour.
|
||||||
|
*/
|
||||||
|
suspend fun trySilentRelogin(nowMs: Long = System.currentTimeMillis()): Boolean =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
if (tokenProvider.current != null && !isTokenExpired(nowMs)) return@withContext true
|
||||||
|
reloginMutex.withLock { silentReloginLocked() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Corps du re-login, sous [reloginMutex]. Vrai si la session est (à
|
||||||
|
* nouveau) valide. Émet [AuthEvent.Reauthenticated] en cas de succès et
|
||||||
|
* [AuthEvent.SessionExpired] quand rien n'est récupérable.
|
||||||
|
*/
|
||||||
|
private suspend fun silentReloginLocked(): Boolean {
|
||||||
|
// Re-vérification sous mutex : un re-login concurrent vient peut-être
|
||||||
|
// de rafraîchir le token pendant l'attente du verrou (N 401 → 1 login).
|
||||||
|
if (tokenProvider.current != null && !isTokenExpired()) return true
|
||||||
|
val creds = runCatching { tokenStore.getCredentials() }.getOrNull()
|
||||||
|
if (creds == null) {
|
||||||
|
purgeToExpired(username = null)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
val response = authRepository.login(creds.username, creds.password)
|
||||||
|
save(response.token, response.user, response.expiresAt)
|
||||||
|
Timber.d("auth: re-login silencieux OK pour %s", creds.username)
|
||||||
|
_events.tryEmit(AuthEvent.Reauthenticated(response.user))
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (e is ApiException && e.code == "UNAUTHORIZED") {
|
||||||
|
// Identifiants rejetés (mot de passe changé ailleurs, compte
|
||||||
|
// supprimé) : ne plus jamais les rejouer.
|
||||||
|
Timber.w("auth: re-login rejeté, purge des identifiants")
|
||||||
|
runCatching { tokenStore.clearCredentials() }
|
||||||
|
purgeToExpired(username = creds.username)
|
||||||
|
} else {
|
||||||
|
// Transitoire (réseau/5xx) : token mort, identifiants conservés
|
||||||
|
// pour une tentative ultérieure (prochain démarrage/login).
|
||||||
|
Timber.w(e, "auth: re-login transitoire, session expirée")
|
||||||
|
purgeToExpired(username = creds.username)
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Purge token + compte actif (file intacte, cf. C5) + événement UI. */
|
||||||
|
private suspend fun purgeToExpired(username: String?) {
|
||||||
|
val knownUsername = username ?: runCatching { tokenStore.getUser()?.username }.getOrNull()
|
||||||
|
tokenProvider.current = null
|
||||||
runCatching { tokenStore.clear() }
|
runCatching { tokenStore.clear() }
|
||||||
runCatching { activeUserStore.clear() }
|
runCatching { activeUserStore.clear() }
|
||||||
}
|
_events.tryEmit(AuthEvent.SessionExpired(knownUsername))
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ import com.kazier.mobile.data.remote.dto.UserDto
|
|||||||
* Persistance du token paseto, du profil compte et de l'expiration du token
|
* Persistance du token paseto, du profil compte et de l'expiration du token
|
||||||
* (claim `expires_at` du login, TTL 7 j). Implémentation : [SecureTokenStore]
|
* (claim `expires_at` du login, TTL 7 j). Implémentation : [SecureTokenStore]
|
||||||
* (Keystore + AES, jamais en clair dans SQLite).
|
* (Keystore + AES, jamais en clair dans SQLite).
|
||||||
|
*
|
||||||
|
* Les identifiants (username + password) sont persistés à part pour le
|
||||||
|
* re-login silencieux sur 401 (lot 3) : ils survivent à la purge du token
|
||||||
|
* ([clear] ne les touche pas) et ne tombent qu'au sign-out explicite
|
||||||
|
* ([clearCredentials]) ou quand le serveur les rejette (401 au re-login).
|
||||||
*/
|
*/
|
||||||
interface TokenStore {
|
interface TokenStore {
|
||||||
|
|
||||||
@@ -18,5 +23,19 @@ interface TokenStore {
|
|||||||
|
|
||||||
fun save(token: String, user: UserDto, expiresAt: Long?)
|
fun save(token: String, user: UserDto, expiresAt: Long?)
|
||||||
|
|
||||||
|
/** Purge token + compte + expiration — jamais les identifiants. */
|
||||||
fun clear()
|
fun clear()
|
||||||
|
|
||||||
|
/** Identifiants du re-login silencieux — null si jamais connectés. */
|
||||||
|
fun getCredentials(): Credentials?
|
||||||
|
|
||||||
|
fun saveCredentials(username: String, password: String)
|
||||||
|
|
||||||
|
fun clearCredentials()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Identifiants persistés (chiffrés) pour le re-login silencieux. */
|
||||||
|
data class Credentials(
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
)
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ import androidx.room.RoomDatabase
|
|||||||
import com.kazier.mobile.data.local.dao.FileDao
|
import com.kazier.mobile.data.local.dao.FileDao
|
||||||
import com.kazier.mobile.data.local.dao.FolderDao
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
|
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
|
||||||
import com.kazier.mobile.data.local.dao.ScanDao
|
import com.kazier.mobile.data.local.dao.ScanDao
|
||||||
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||||
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||||
import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
||||||
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||||
@@ -27,14 +29,20 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
|||||||
* operation_id) (contrat outbox docs/api-v1.md §6.1).
|
* operation_id) (contrat outbox docs/api-v1.md §6.1).
|
||||||
* v13: index composites files(exists, processed, sync_status) et
|
* v13: index composites files(exists, processed, sync_status) et
|
||||||
* pending_operations(resource_id, operation, status) (requêtes review/OCR/gates).
|
* pending_operations(resource_id, operation, status) (requêtes review/OCR/gates).
|
||||||
|
* v14: parent_resource_id sur pending_operations (cascade P8).
|
||||||
|
* v15: backfill exists NULL→1 sur folders/files (M13).
|
||||||
|
* v16: table resource_permissions (cache snapshot, M27).
|
||||||
*/
|
*/
|
||||||
@Database(
|
@Database(
|
||||||
entities = [
|
entities = [
|
||||||
FolderEntity::class, UserPreferenceEntity::class, FileEntity::class,
|
FolderEntity::class, UserPreferenceEntity::class, FileEntity::class,
|
||||||
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
|
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
|
||||||
|
ResourcePermissionEntity::class,
|
||||||
],
|
],
|
||||||
version = 14,
|
version = 16,
|
||||||
exportSchema = false,
|
// m19 : schéma exporté (`app/schemas/`) — toute dérive non migrée casse
|
||||||
|
// la compilation au lieu de briqueter les utilisateurs au démarrage.
|
||||||
|
exportSchema = true,
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
|
|
||||||
@@ -43,4 +51,5 @@ abstract class AppDatabase : RoomDatabase() {
|
|||||||
abstract fun fileDao(): FileDao
|
abstract fun fileDao(): FileDao
|
||||||
abstract fun pendingOperationDao(): PendingOperationDao
|
abstract fun pendingOperationDao(): PendingOperationDao
|
||||||
abstract fun scanDao(): ScanDao
|
abstract fun scanDao(): ScanDao
|
||||||
|
abstract fun resourcePermissionDao(): ResourcePermissionDao
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.kazier.mobile.data.local
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Échappe les jokers `LIKE` (`%`, `_`) et l'échappement lui-même (`\`) dans
|
||||||
|
* un fragment destiné à une requête `... LIKE ... ESCAPE '\'` (m5, m7).
|
||||||
|
* Sans ça, un `%`/`_` saisi (recherche) ou présent (uris SAF encodées
|
||||||
|
* `%3A…`) agit comme joker : match-all en recherche, sur-sélection au walk.
|
||||||
|
*/
|
||||||
|
internal fun String.escapeLike(): String =
|
||||||
|
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
@@ -15,6 +15,12 @@ interface FileDao {
|
|||||||
@Query("SELECT * FROM files ORDER BY name ASC")
|
@Query("SELECT * FROM files ORDER BY name ASC")
|
||||||
suspend fun getAll(): List<FileEntity>
|
suspend fun getAll(): List<FileEntity>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lignes sous une racine SAF (m5) — voir `FolderDao.getUnderRoot`.
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM files WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
|
||||||
|
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FileEntity>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Repasse C4 : lignes déjà journalisées (`exists = 0`) dont les octets
|
* Repasse C4 : lignes déjà journalisées (`exists = 0`) dont les octets
|
||||||
* sont peut-être encore sur le disque (journal-first, crash ou refus SAF
|
* sont peut-être encore sur le disque (journal-first, crash ou refus SAF
|
||||||
@@ -39,10 +45,17 @@ interface FileDao {
|
|||||||
@Query("SELECT * FROM files WHERE uri = :uri LIMIT 1")
|
@Query("SELECT * FROM files WHERE uri = :uri LIMIT 1")
|
||||||
suspend fun getByUri(uri: String): FileEntity?
|
suspend fun getByUri(uri: String): FileEntity?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recherche par nom (m7) : `:query` arrive déjà échappé (`escapeLike`,
|
||||||
|
* `%`/`_` littéraux, pas des jokers) avec `ESCAPE '\'`. `COLLATE NOCASE`
|
||||||
|
* sur l'opérande gauche pour une casse ASCII insensible explicite
|
||||||
|
* (le repli Unicode « ete » → « ÉTÉ » demanderait une colonne normalisée,
|
||||||
|
* hors scope — voir FEEDBACK).
|
||||||
|
*/
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT * FROM files
|
SELECT * FROM files
|
||||||
WHERE "exists" = 1
|
WHERE "exists" = 1
|
||||||
AND (:query IS NULL OR name LIKE '%' || :query || '%')
|
AND (:query IS NULL OR name COLLATE NOCASE LIKE '%' || :query || '%' ESCAPE '\')
|
||||||
AND (:category IS NULL OR category = :category)
|
AND (:category IS NULL OR category = :category)
|
||||||
ORDER BY name ASC
|
ORDER BY name ASC
|
||||||
""")
|
""")
|
||||||
|
|||||||
@@ -18,6 +18,14 @@ interface FolderDao {
|
|||||||
@Query("SELECT * FROM folders ORDER BY name ASC")
|
@Query("SELECT * FROM folders ORDER BY name ASC")
|
||||||
suspend fun getAll(): List<FolderEntity>
|
suspend fun getAll(): List<FolderEntity>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lignes sous une racine SAF (m5) : le walk et sa réconciliation ne
|
||||||
|
* scannent plus toute la table par racine. `:escapedRoot` est la racine
|
||||||
|
* avec `%`, `_`, `\` échappés côté appelant (`ESCAPE '\'`).
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM folders WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
|
||||||
|
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FolderEntity>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Repasse C4 (dossiers) : voir `FileDao.getMissingWithUri`. Un dossier
|
* Repasse C4 (dossiers) : voir `FileDao.getMissingWithUri`. Un dossier
|
||||||
* n'est re-supprimé physiquement que si toute sa descendance Room est
|
* n'est re-supprimé physiquement que si toute sa descendance Room est
|
||||||
|
|||||||
+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>
|
||||||
}
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.kazier.mobile.data.local.dao
|
||||||
|
|
||||||
|
import androidx.room.Dao
|
||||||
|
import androidx.room.Query
|
||||||
|
import androidx.room.Upsert
|
||||||
|
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||||
|
|
||||||
|
@Dao
|
||||||
|
interface ResourcePermissionDao {
|
||||||
|
|
||||||
|
@Upsert
|
||||||
|
suspend fun upsertAll(perms: List<ResourcePermissionEntity>)
|
||||||
|
|
||||||
|
@Query("SELECT * FROM resource_permissions WHERE resource_id = :resourceId LIMIT 1")
|
||||||
|
suspend fun getByResourceId(resourceId: String): ResourcePermissionEntity?
|
||||||
|
|
||||||
|
/** Grants périmés à masquer localement (`expires_at` passé). */
|
||||||
|
@Query("SELECT * FROM resource_permissions WHERE expires_at IS NOT NULL AND expires_at <= :now")
|
||||||
|
suspend fun getExpired(now: Long): List<ResourcePermissionEntity>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convergence du pull complet : oublie les grants absents du snapshot
|
||||||
|
* (révocation/expiration côté serveur).
|
||||||
|
*/
|
||||||
|
@Query("DELETE FROM resource_permissions WHERE resource_id NOT IN (:snapshotIds)")
|
||||||
|
suspend fun deleteNotIn(snapshotIds: List<String>)
|
||||||
|
|
||||||
|
@Query("DELETE FROM resource_permissions")
|
||||||
|
suspend fun clear()
|
||||||
|
}
|
||||||
@@ -42,8 +42,9 @@ data class FileEntity(
|
|||||||
val size: Long,
|
val size: Long,
|
||||||
@ColumnInfo(name = "mime_type")
|
@ColumnInfo(name = "mime_type")
|
||||||
val mimeType: String? = null,
|
val mimeType: String? = null,
|
||||||
|
// M13 : voir `FolderEntity.exists` — défaut 1, backfill en migration 14→15.
|
||||||
@ColumnInfo(name = "exists")
|
@ColumnInfo(name = "exists")
|
||||||
val exists: Int? = null,
|
val exists: Int? = 1,
|
||||||
@ColumnInfo(name = "last_modified")
|
@ColumnInfo(name = "last_modified")
|
||||||
val lastModified: Long? = null,
|
val lastModified: Long? = null,
|
||||||
@ColumnInfo(name = "owner_id")
|
@ColumnInfo(name = "owner_id")
|
||||||
|
|||||||
@@ -32,8 +32,11 @@ data class FolderEntity(
|
|||||||
val uri: String? = null,
|
val uri: String? = null,
|
||||||
@ColumnInfo(name = "name")
|
@ColumnInfo(name = "name")
|
||||||
val name: String,
|
val name: String,
|
||||||
|
// M13 : défaut 1 — une ligne sans `exists` explicite restait invisible
|
||||||
|
// des requêtes `WHERE exists = 1`. La colonne reste nullable côté schéma
|
||||||
|
// (pas de rewrite), le backfill NULL→1 est fait en migration 14→15.
|
||||||
@ColumnInfo(name = "exists")
|
@ColumnInfo(name = "exists")
|
||||||
val exists: Int? = null,
|
val exists: Int? = 1,
|
||||||
@ColumnInfo(name = "parent_resource_id")
|
@ColumnInfo(name = "parent_resource_id")
|
||||||
val parentResourceId: String? = null,
|
val parentResourceId: String? = null,
|
||||||
@ColumnInfo(name = "owner_id")
|
@ColumnInfo(name = "owner_id")
|
||||||
|
|||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package com.kazier.mobile.data.local.entity
|
||||||
|
|
||||||
|
import androidx.room.ColumnInfo
|
||||||
|
import androidx.room.Entity
|
||||||
|
import androidx.room.Index
|
||||||
|
import androidx.room.PrimaryKey
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache local du snapshot `GET /sync/permissions` (M27, docs/api-v1.md §6.2).
|
||||||
|
*
|
||||||
|
* Une ligne = la permission effective connue pour une ressource NON possédée
|
||||||
|
* (les ressources `owner` ne sont pas stockées : l'ownership se résout depuis
|
||||||
|
* les lignes `files`/`folders`). Fondement de [canAccess][com.kazier.mobile.data.repository.ShareRepository.canAccess]
|
||||||
|
* sans réseau : rang effectif, expiration du grant et fraîcheur du snapshot
|
||||||
|
* (TTL 24h → downgrade lecture seule).
|
||||||
|
*/
|
||||||
|
@Entity(
|
||||||
|
tableName = "resource_permissions",
|
||||||
|
indices = [
|
||||||
|
Index(value = ["expires_at"]),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
data class ResourcePermissionEntity(
|
||||||
|
@PrimaryKey
|
||||||
|
@ColumnInfo(name = "resource_id")
|
||||||
|
val resourceId: String,
|
||||||
|
@ColumnInfo(name = "resource_type")
|
||||||
|
val resourceType: String,
|
||||||
|
@ColumnInfo(name = "effective_access")
|
||||||
|
val effectiveAccess: String,
|
||||||
|
@ColumnInfo(name = "owner_id")
|
||||||
|
val ownerId: String? = null,
|
||||||
|
@ColumnInfo(name = "shared_by_id")
|
||||||
|
val sharedById: String? = null,
|
||||||
|
/** Fin du grant, ms epoch ; null = jamais. */
|
||||||
|
@ColumnInfo(name = "expires_at")
|
||||||
|
val expiresAt: Long? = null,
|
||||||
|
/** Horodatage du snapshot serveur, ms epoch (TTL 24h). */
|
||||||
|
@ColumnInfo(name = "cached_at")
|
||||||
|
val cachedAt: Long,
|
||||||
|
@ColumnInfo(name = "updated_at")
|
||||||
|
val updatedAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Rangs d'accès effectif — `viewer < commenter < editor < owner`. */
|
||||||
|
object AccessRank {
|
||||||
|
const val VIEWER = "viewer"
|
||||||
|
const val COMMENTER = "commenter"
|
||||||
|
const val EDITOR = "editor"
|
||||||
|
const val OWNER = "owner"
|
||||||
|
|
||||||
|
fun rank(access: String?): Int = when (access) {
|
||||||
|
OWNER -> 4
|
||||||
|
EDITOR -> 3
|
||||||
|
COMMENTER -> 2
|
||||||
|
VIEWER -> 1
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
-1
@@ -33,6 +33,9 @@ import androidx.sqlite.db.SupportSQLiteDatabase
|
|||||||
* v13 : index composites `files(exists, processed, sync_status)` (review +
|
* v13 : index composites `files(exists, processed, sync_status)` (review +
|
||||||
* candidats OCR auto) et `pending_operations(resource_id, operation, status)`
|
* candidats OCR auto) et `pending_operations(resource_id, operation, status)`
|
||||||
* (gates outbox create/move) — requêtes à chaud sans full-table scan.
|
* (gates outbox create/move) — requêtes à chaud sans full-table scan.
|
||||||
|
* v14 : colonne `parent_resource_id` sur `pending_operations` (cascade P8).
|
||||||
|
* v15 : backfill `exists` NULL→1 sur `folders`/`files` (M13) + défaut Kotlin 1.
|
||||||
|
* v16 : table `resource_permissions` (cache snapshot, M27) + index `expires_at`.
|
||||||
*/
|
*/
|
||||||
object Migrations {
|
object Migrations {
|
||||||
|
|
||||||
@@ -246,7 +249,49 @@ object Migrations {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M13 : backfill `exists` NULL→1 sur `folders` et `files`. Les lignes
|
||||||
|
* insérées sans `exists` explicite (défaut Kotlin `null` avant ce fix)
|
||||||
|
* étaient invisibles des requêtes `WHERE exists = 1` — elles
|
||||||
|
* réapparaissent comme présentes, état le plus sûr (le walk les
|
||||||
|
* re-marque `exists = 0` si elles ont vraiment disparu).
|
||||||
|
*/
|
||||||
|
private val MIGRATION_14_15 = object : Migration(14, 15) {
|
||||||
|
override fun migrate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL("UPDATE `folders` SET `exists` = 1 WHERE `exists` IS NULL")
|
||||||
|
db.execSQL("UPDATE `files` SET `exists` = 1 WHERE `exists` IS NULL")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M27 : cache du snapshot permissions — table `resource_permissions`
|
||||||
|
* (rang effectif + expiration + fraîcheur, fondement de `canAccess`).
|
||||||
|
*/
|
||||||
|
private val MIGRATION_15_16 = object : Migration(15, 16) {
|
||||||
|
override fun migrate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS `resource_permissions` (
|
||||||
|
`resource_id` TEXT NOT NULL,
|
||||||
|
`resource_type` TEXT NOT NULL,
|
||||||
|
`effective_access` TEXT NOT NULL,
|
||||||
|
`owner_id` TEXT,
|
||||||
|
`shared_by_id` TEXT,
|
||||||
|
`expires_at` INTEGER,
|
||||||
|
`cached_at` INTEGER NOT NULL,
|
||||||
|
`updated_at` INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY(`resource_id`)
|
||||||
|
)
|
||||||
|
""".trimIndent(),
|
||||||
|
)
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` " +
|
||||||
|
"ON `resource_permissions` (`expires_at`)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val ALL: Array<Migration> = arrayOf(
|
val ALL: Array<Migration> = arrayOf(
|
||||||
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14,
|
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -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,
|
||||||
@@ -140,15 +155,19 @@ data class SyncFailedDto(
|
|||||||
@Json(name = "message") val message: String,
|
@Json(name = "message") val message: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2). */
|
/**
|
||||||
|
* Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2, miroir de
|
||||||
|
* `ResourcePermission` Go : `sharedById *string`, `expiresAt *int64` ms epoch).
|
||||||
|
* M27 : typés (fini les `Any?` jamais lus) — lus par le cache et `canAccess`.
|
||||||
|
*/
|
||||||
data class ResourcePermissionDto(
|
data class ResourcePermissionDto(
|
||||||
@Json(name = "resource_id") val resourceId: String,
|
@Json(name = "resource_id") val resourceId: String,
|
||||||
@Json(name = "resourceType") val resourceType: String,
|
@Json(name = "resourceType") val resourceType: String,
|
||||||
@Json(name = "effectiveAccess") val effectiveAccess: String,
|
@Json(name = "effectiveAccess") val effectiveAccess: String,
|
||||||
@Json(name = "inherit") val inherit: Boolean,
|
@Json(name = "inherit") val inherit: Boolean,
|
||||||
@Json(name = "ownerId") val ownerId: String? = null,
|
@Json(name = "ownerId") val ownerId: String? = null,
|
||||||
@Json(name = "sharedById") val sharedById: Any? = null,
|
@Json(name = "sharedById") val sharedById: String? = null,
|
||||||
@Json(name = "expiresAt") val expiresAt: Any? = null,
|
@Json(name = "expiresAt") val expiresAt: Long? = null,
|
||||||
@Json(name = "cachedAt") val cachedAt: Long,
|
@Json(name = "cachedAt") val cachedAt: Long,
|
||||||
@Json(name = "updatedAt") val updatedAt: Long,
|
@Json(name = "updatedAt") val updatedAt: Long,
|
||||||
@Json(name = "name") val name: String = "",
|
@Json(name = "name") val name: String = "",
|
||||||
|
|||||||
+10
-2
@@ -2,6 +2,7 @@ package com.kazier.mobile.data.repository
|
|||||||
|
|
||||||
import androidx.room.withTransaction
|
import androidx.room.withTransaction
|
||||||
import com.kazier.mobile.data.local.AppDatabase
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.escapeLike
|
||||||
import com.kazier.mobile.data.local.dao.FileDao
|
import com.kazier.mobile.data.local.dao.FileDao
|
||||||
import com.kazier.mobile.data.local.dao.FolderDao
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
@@ -46,10 +47,13 @@ class FileRepository @Inject constructor(
|
|||||||
/** Fichiers visibles de toute l'arborescence — écran d'accueil (grille par date). */
|
/** Fichiers visibles de toute l'arborescence — écran d'accueil (grille par date). */
|
||||||
fun observeAllVisible(): Flow<List<FileEntity>> = fileDao.observeAllVisible()
|
fun observeAllVisible(): Flow<List<FileEntity>> = fileDao.observeAllVisible()
|
||||||
|
|
||||||
/** Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel). */
|
/**
|
||||||
|
* Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel).
|
||||||
|
* m7 : la saisie est échappée (`%`/`_` littéraux, pas des jokers).
|
||||||
|
*/
|
||||||
fun searchFiles(query: String?, category: String?): Flow<List<FileEntity>> =
|
fun searchFiles(query: String?, category: String?): Flow<List<FileEntity>> =
|
||||||
fileDao.searchWithFilters(
|
fileDao.searchWithFilters(
|
||||||
query = query?.trim()?.takeIf { it.isNotEmpty() },
|
query = query?.trim()?.takeIf { it.isNotEmpty() }?.escapeLike(),
|
||||||
category = category,
|
category = category,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -171,6 +175,10 @@ class FileRepository @Inject constructor(
|
|||||||
|
|
||||||
suspend fun getAll(): List<FileEntity> = fileDao.getAll()
|
suspend fun getAll(): List<FileEntity> = fileDao.getAll()
|
||||||
|
|
||||||
|
/** Lignes sous une racine SAF (m5) — voir `FolderRepository.getUnderRoot`. */
|
||||||
|
suspend fun getUnderRoot(rootUri: String): List<FileEntity> =
|
||||||
|
fileDao.getUnderRoot(rootUri, rootUri.escapeLike())
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upsert local d'un fichier SAF — miroir de `saveFile()` JS : déduplication
|
* Upsert local d'un fichier SAF — miroir de `saveFile()` JS : déduplication
|
||||||
* par `resource_id` ou `uri`, conservation de l'identité/sync_status/owner.
|
* par `resource_id` ou `uri`, conservation de l'identité/sync_status/owner.
|
||||||
|
|||||||
+13
-2
@@ -2,6 +2,7 @@ package com.kazier.mobile.data.repository
|
|||||||
|
|
||||||
import androidx.room.withTransaction
|
import androidx.room.withTransaction
|
||||||
import com.kazier.mobile.data.local.AppDatabase
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.escapeLike
|
||||||
import com.kazier.mobile.data.local.dao.FolderDao
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
import com.kazier.mobile.data.local.entity.FolderStatus
|
import com.kazier.mobile.data.local.entity.FolderStatus
|
||||||
@@ -44,6 +45,13 @@ class FolderRepository @Inject constructor(
|
|||||||
|
|
||||||
suspend fun getAll(): List<FolderEntity> = folderDao.getAll()
|
suspend fun getAll(): List<FolderEntity> = folderDao.getAll()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lignes sous une racine SAF (m5) : la racine est échappée pour le `LIKE`
|
||||||
|
* (les uris SAF contiennent des `%` d'encodage et parfois des `_`).
|
||||||
|
*/
|
||||||
|
suspend fun getUnderRoot(rootUri: String): List<FolderEntity> =
|
||||||
|
folderDao.getUnderRoot(rootUri, rootUri.escapeLike())
|
||||||
|
|
||||||
/** Snapshot des sous-dossiers visibles d'un dossier (opérations batch hors UI). */
|
/** Snapshot des sous-dossiers visibles d'un dossier (opérations batch hors UI). */
|
||||||
suspend fun getChildren(parentResourceId: String): List<FolderEntity> =
|
suspend fun getChildren(parentResourceId: String): List<FolderEntity> =
|
||||||
folderDao.getByParentOnce(parentResourceId)
|
folderDao.getByParentOnce(parentResourceId)
|
||||||
@@ -83,7 +91,8 @@ class FolderRepository @Inject constructor(
|
|||||||
resourceId = dto.id,
|
resourceId = dto.id,
|
||||||
uri = existing?.uri,
|
uri = existing?.uri,
|
||||||
name = dto.name,
|
name = dto.name,
|
||||||
exists = existing?.exists,
|
// M13 : une ligne serveur nouvelle n'a pas d'`exists` local — 1 par défaut.
|
||||||
|
exists = existing?.exists ?: 1,
|
||||||
parentResourceId = dto.parentId,
|
parentResourceId = dto.parentId,
|
||||||
ownerId = existing?.ownerId,
|
ownerId = existing?.ownerId,
|
||||||
// Le snapshot serveur confirme la présence cloud : si une copie
|
// Le snapshot serveur confirme la présence cloud : si une copie
|
||||||
@@ -144,7 +153,9 @@ class FolderRepository @Inject constructor(
|
|||||||
resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(),
|
resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(),
|
||||||
uri = input.uri,
|
uri = input.uri,
|
||||||
name = input.name,
|
name = input.name,
|
||||||
exists = input.exists?.let { if (it) 1 else 0 },
|
// M13 : `null` (défaut de `SaveFolderInput`) = présent, jamais NULL
|
||||||
|
// en base — sinon la ligne disparaît des requêtes `exists = 1`.
|
||||||
|
exists = if (input.exists != false) 1 else 0,
|
||||||
parentResourceId = effectiveParent,
|
parentResourceId = effectiveParent,
|
||||||
// `owner_id` Room = user_id du compte actif, jamais l'identité device.
|
// `owner_id` Room = user_id du compte actif, jamais l'identité device.
|
||||||
ownerId = ownerId ?: existing?.ownerId ?: activeUserStore.get(),
|
ownerId = ownerId ?: existing?.ownerId ?: activeUserStore.get(),
|
||||||
|
|||||||
@@ -62,12 +62,27 @@ class OcrRepository @Inject constructor(
|
|||||||
/**
|
/**
|
||||||
* Poll toutes les 3 s (docs §5) jusqu'à l'état terminal. [onProgress] est
|
* Poll toutes les 3 s (docs §5) jusqu'à l'état terminal. [onProgress] est
|
||||||
* appelé à chaque réponse du serveur (état courant exposé à l'UI).
|
* appelé à chaque réponse du serveur (état courant exposé à l'UI).
|
||||||
|
*
|
||||||
|
* m20 : borné (deadline + nombre max de polls) — un job resté `processing`
|
||||||
|
* (stale claim serveur) levait sinon une coroutine tenue indéfiniment.
|
||||||
|
* Le timeout remonte en `ApiException("OCR_TIMEOUT")`, géré comme échec
|
||||||
|
* par les appelants (`processAuto` → `Failed`, viewer → message d'erreur).
|
||||||
*/
|
*/
|
||||||
suspend fun poll(jobId: String, onProgress: (OcrJobDto) -> Unit = {}): OcrJobDto {
|
suspend fun poll(
|
||||||
|
jobId: String,
|
||||||
|
timeoutMs: Long = POLL_TIMEOUT_MS,
|
||||||
|
onProgress: (OcrJobDto) -> Unit = {},
|
||||||
|
): OcrJobDto {
|
||||||
|
val deadline = System.currentTimeMillis() + timeoutMs
|
||||||
|
var polls = 0
|
||||||
while (true) {
|
while (true) {
|
||||||
val job = apiClient.getOcrJob(jobId)
|
val job = apiClient.getOcrJob(jobId)
|
||||||
onProgress(job)
|
onProgress(job)
|
||||||
if (job.status in OcrJobStatus.TERMINAL) return job
|
if (job.status in OcrJobStatus.TERMINAL) return job
|
||||||
|
polls++
|
||||||
|
if (polls >= POLL_MAX_ATTEMPTS || System.currentTimeMillis() >= deadline) {
|
||||||
|
throw ApiException("OCR_TIMEOUT", "OCR sans réponse (job $jobId)", 0)
|
||||||
|
}
|
||||||
delay(POLL_INTERVAL_MS)
|
delay(POLL_INTERVAL_MS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -144,6 +159,9 @@ class OcrRepository @Inject constructor(
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val POLL_INTERVAL_MS = 3_000L
|
const val POLL_INTERVAL_MS = 3_000L
|
||||||
|
/** Timeout du poll (m20) : 10 min ≈ 200 polls × 3 s. */
|
||||||
|
const val POLL_TIMEOUT_MS = 10 * 60 * 1_000L
|
||||||
|
const val POLL_MAX_ATTEMPTS = 200
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -146,9 +146,89 @@ class OutboxRepository @Inject constructor(
|
|||||||
payload = mapOf("granteeUserId" to granteeUserId),
|
payload = mapOf("granteeUserId" to granteeUserId),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raccourci `update_metadata` — payload `{ name }` (rename d'une ressource
|
||||||
|
* partagée, `editor+`, docs/api-v1.md §6.1). m21 : rend le rename partagé
|
||||||
|
* émissible — l'op n'avait aucun écrivain côté client.
|
||||||
|
*/
|
||||||
|
suspend fun enqueueUpdateMetadata(
|
||||||
|
resourceId: String,
|
||||||
|
resourceType: String,
|
||||||
|
name: String,
|
||||||
|
): String = enqueue(
|
||||||
|
operation = PendingOperationType.UPDATE_METADATA,
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
payload = mapOf("name" to name),
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raccourci `update_share` — même payload que `share` (m21 : update d'un
|
||||||
|
* partage existant inopérant sans écrivain).
|
||||||
|
*/
|
||||||
|
suspend fun enqueueUpdateShare(
|
||||||
|
resourceId: String,
|
||||||
|
resourceType: String,
|
||||||
|
granteeUserId: String,
|
||||||
|
access: String,
|
||||||
|
inherit: Boolean = true,
|
||||||
|
expiresAt: Long? = null,
|
||||||
|
): String = enqueue(
|
||||||
|
operation = PendingOperationType.UPDATE_SHARE,
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
payload = buildMap {
|
||||||
|
put("granteeUserId", granteeUserId)
|
||||||
|
put("access", access)
|
||||||
|
put("inherit", inherit)
|
||||||
|
expiresAt?.let { put("expiresAt", it) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raccourci `create_link` — payload `{ token, access, expiresAt? }`
|
||||||
|
* (m21 : liens publics inopérants sans écrivain). Le `token` 32-hex est
|
||||||
|
* généré côté client (`GenerateId`) : c'est l'identifiant du lien.
|
||||||
|
*/
|
||||||
|
suspend fun enqueueCreateLink(
|
||||||
|
resourceId: String,
|
||||||
|
resourceType: String,
|
||||||
|
token: String,
|
||||||
|
access: String,
|
||||||
|
expiresAt: Long? = null,
|
||||||
|
): String = enqueue(
|
||||||
|
operation = PendingOperationType.CREATE_LINK,
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
payload = buildMap {
|
||||||
|
put("token", token)
|
||||||
|
put("access", access)
|
||||||
|
expiresAt?.let { put("expiresAt", it) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Raccourci `revoke_link` — payload `{ token }` (m21). */
|
||||||
|
suspend fun enqueueRevokeLink(
|
||||||
|
resourceId: String,
|
||||||
|
resourceType: String,
|
||||||
|
token: String,
|
||||||
|
): String = enqueue(
|
||||||
|
operation = PendingOperationType.REVOKE_LINK,
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
payload = mapOf("token" to token),
|
||||||
|
)
|
||||||
|
|
||||||
/** 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)
|
||||||
|
}
|
||||||
+140
-11
@@ -4,11 +4,15 @@ import androidx.room.withTransaction
|
|||||||
import com.kazier.mobile.data.local.AppDatabase
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
import com.kazier.mobile.data.local.dao.FileDao
|
import com.kazier.mobile.data.local.dao.FileDao
|
||||||
import com.kazier.mobile.data.local.dao.FolderDao
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
|
import com.kazier.mobile.data.local.entity.AccessRank
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
import com.kazier.mobile.domain.ActiveUserStore
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
|
import com.kazier.mobile.domain.PrefKeys
|
||||||
import com.kazier.mobile.domain.SyncPlacement
|
import com.kazier.mobile.domain.SyncPlacement
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -21,8 +25,17 @@ import javax.inject.Singleton
|
|||||||
* de l'utilisateur. Les ressources non possédées (viewer/commenter/editor)
|
* de l'utilisateur. Les ressources non possédées (viewer/commenter/editor)
|
||||||
* sont importées en tant que lignes cloud-only (`uri = NULL`, `sync_status = "cloud"`).
|
* sont importées en tant que lignes cloud-only (`uri = NULL`, `sync_status = "cloud"`).
|
||||||
*
|
*
|
||||||
* Un pull complet (`after=0`) est effectué au login et à la restauration de
|
* M27 — delta, expiration et `canAccess` :
|
||||||
* session pour garantir la convergence (révocations = disparition du snapshot).
|
* - le `cachedAt` du dernier pull est persisté (`user_preferences`) : pull
|
||||||
|
* complet (`after = null`) au premier appel, au login/restauration
|
||||||
|
* (`forceFull = true`) et quand le cache dépasse le TTL 24h ; delta
|
||||||
|
* (`after = cachedAt`) sinon — la convergence (lignes absentes = révoquées)
|
||||||
|
* ne tourne que sur pull complet ;
|
||||||
|
* - chaque grant non-owner est persisté en `resource_permissions` (rang,
|
||||||
|
* expiration, fraîcheur) : un grant expiré (`expiresAt` passé) masque la
|
||||||
|
* ligne locale au lieu de rester visible jusqu'au prochain login ;
|
||||||
|
* - [canAccess] répond offline (ownership local, puis rang persisté, avec
|
||||||
|
* downgrade lecture seule après TTL sans reseed).
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ShareRepository @Inject constructor(
|
class ShareRepository @Inject constructor(
|
||||||
@@ -32,31 +45,60 @@ class ShareRepository @Inject constructor(
|
|||||||
) {
|
) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Récupère le snapshot complet des permissions et hydrate Room.
|
* Récupère le snapshot des permissions et hydrate Room + le cache.
|
||||||
*
|
*
|
||||||
* Pour chaque permission non-owner :
|
* Pour chaque permission non-owner non expirée :
|
||||||
* - Folders : upsert cloud-only (uri=null, name, parentId, ownerId)
|
* - Folders : upsert cloud-only (uri=null, name, parentId, ownerId)
|
||||||
* - Files : upsert cloud-only (uri=null, name, folderResourceId, ownerId, processed=true)
|
* - Files : upsert cloud-only (uri=null, name, folderResourceId, ownerId, processed=true)
|
||||||
*
|
*
|
||||||
* Convergence : les lignes cloud-only absentes du snapshot complet sont
|
* Convergence (pull complet uniquement) : les lignes cloud-only absentes
|
||||||
* marquées `exists = 0`.
|
* du snapshot complet sont marquées `exists = 0`, et les grants du cache
|
||||||
|
* absents sont oubliés.
|
||||||
*/
|
*/
|
||||||
suspend fun syncSnapshot() {
|
suspend fun syncSnapshot(forceFull: Boolean = false) {
|
||||||
// `ownerId` serveur = user_id : comparer au compte actif, jamais au device.
|
// `ownerId` serveur = user_id : comparer au compte actif, jamais au device.
|
||||||
val currentUserId = activeUserStore.get()
|
val currentUserId = activeUserStore.get()
|
||||||
val permissions = apiClient.syncPermissions()
|
val prefs = appDatabase.userPreferenceDao()
|
||||||
|
val permDao = appDatabase.resourcePermissionDao()
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
|
val cachedAt = prefs.getValue(PrefKeys.PERMISSIONS_CACHED_AT)?.toLongOrNull()
|
||||||
|
val full = forceFull || cachedAt == null || now - cachedAt > PERMISSION_TTL_MS
|
||||||
|
val permissions = apiClient.syncPermissions(if (full) null else cachedAt)
|
||||||
|
|
||||||
val folderDao = appDatabase.folderDao()
|
val folderDao = appDatabase.folderDao()
|
||||||
val fileDao = appDatabase.fileDao()
|
val fileDao = appDatabase.fileDao()
|
||||||
|
|
||||||
val snapshotFolderIds = mutableSetOf<String>()
|
val snapshotFolderIds = mutableSetOf<String>()
|
||||||
val snapshotFileIds = mutableSetOf<String>()
|
val snapshotFileIds = mutableSetOf<String>()
|
||||||
|
val snapshotPermIds = mutableSetOf<String>()
|
||||||
|
|
||||||
appDatabase.withTransaction {
|
appDatabase.withTransaction {
|
||||||
for (perm in permissions) {
|
for (perm in permissions) {
|
||||||
|
if (perm.effectiveAccess == "owner") continue
|
||||||
|
snapshotPermIds += perm.resourceId
|
||||||
|
permDao.upsertAll(
|
||||||
|
listOf(
|
||||||
|
ResourcePermissionEntity(
|
||||||
|
resourceId = perm.resourceId,
|
||||||
|
resourceType = perm.resourceType,
|
||||||
|
effectiveAccess = perm.effectiveAccess,
|
||||||
|
ownerId = perm.ownerId,
|
||||||
|
sharedById = perm.sharedById,
|
||||||
|
expiresAt = perm.expiresAt,
|
||||||
|
// Fraîcheur = heure locale du pull (M27) : le TTL
|
||||||
|
// mesure « 24h sans reseed », pas l'horloge serveur
|
||||||
|
// (skew). `perm.cachedAt` sert au delta `after`.
|
||||||
|
cachedAt = now,
|
||||||
|
updatedAt = perm.updatedAt,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if (isExpired(perm.expiresAt, now)) {
|
||||||
|
// Grant expiré : masquer la ligne locale au lieu d'hydrater.
|
||||||
|
markSharedMissing(perm.resourceId, perm.resourceType, currentUserId, now, folderDao, fileDao)
|
||||||
|
continue
|
||||||
|
}
|
||||||
when {
|
when {
|
||||||
perm.effectiveAccess == "owner" -> Unit
|
|
||||||
perm.resourceType == "folder" -> {
|
perm.resourceType == "folder" -> {
|
||||||
snapshotFolderIds += perm.resourceId
|
snapshotFolderIds += perm.resourceId
|
||||||
upsertSharedFolder(perm, now, folderDao)
|
upsertSharedFolder(perm, now, folderDao)
|
||||||
@@ -68,6 +110,7 @@ class ShareRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (full) {
|
||||||
// Convergence : marquer les lignes cloud-only d'autrui absentes du
|
// Convergence : marquer les lignes cloud-only d'autrui absentes du
|
||||||
// snapshot comme disparues (révocation / expiration côté serveur).
|
// snapshot comme disparues (révocation / expiration côté serveur).
|
||||||
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le
|
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le
|
||||||
@@ -89,15 +132,96 @@ class ShareRepository @Inject constructor(
|
|||||||
fileDao.markMissing(file.resourceId, now)
|
fileDao.markMissing(file.resourceId, now)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Oublie les grants du cache absents du snapshot complet.
|
||||||
|
if (snapshotPermIds.isEmpty()) {
|
||||||
|
permDao.clear()
|
||||||
|
} else {
|
||||||
|
permDao.deleteNotIn(snapshotPermIds.toList())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Grants périmés connus du cache (delta ou TTL) : masquer localement.
|
||||||
|
for (expired in permDao.getExpired(now)) {
|
||||||
|
markSharedMissing(expired.resourceId, expired.resourceType, currentUserId, now, folderDao, fileDao)
|
||||||
|
}
|
||||||
|
|
||||||
|
prefs.upsert(
|
||||||
|
UserPreferenceEntity(
|
||||||
|
PrefKeys.PERMISSIONS_CACHED_AT,
|
||||||
|
now.toString(),
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Timber.d(
|
Timber.d(
|
||||||
"syncSnapshot: hydrated %d folders, %d files",
|
"syncSnapshot: hydrated %d folders, %d files (full=%s)",
|
||||||
snapshotFolderIds.size,
|
snapshotFolderIds.size,
|
||||||
snapshotFileIds.size,
|
snapshotFileIds.size,
|
||||||
|
full,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Droit offline sur une ressource (docs/api-v1.md §6.2) : ownership local
|
||||||
|
* d'abord (`owner` implique tout), sinon rang persisté du snapshot.
|
||||||
|
* Grant expiré → refusé ; snapshot périmé (TTL 24h sans reseed) →
|
||||||
|
* downgrade lecture seule (`viewer` exigé au plus).
|
||||||
|
*/
|
||||||
|
suspend fun canAccess(resourceId: String, required: String = AccessRank.VIEWER): Boolean {
|
||||||
|
val requiredRank = AccessRank.rank(required)
|
||||||
|
if (requiredRank <= 0) return false
|
||||||
|
val currentUserId = activeUserStore.get()
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (currentUserId != null) {
|
||||||
|
val folderOwner = appDatabase.folderDao().getByResourceId(resourceId)?.ownerId
|
||||||
|
val fileOwner = if (folderOwner == null) {
|
||||||
|
appDatabase.fileDao().getByResourceId(resourceId)?.ownerId
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
if (folderOwner == currentUserId || fileOwner == currentUserId) return true
|
||||||
|
}
|
||||||
|
val perm = appDatabase.resourcePermissionDao().getByResourceId(resourceId) ?: return false
|
||||||
|
if (isExpired(perm.expiresAt, now)) return false
|
||||||
|
val effective = if (now - perm.cachedAt > PERMISSION_TTL_MS) {
|
||||||
|
// Stale : downgrade lecture seule.
|
||||||
|
minOf(AccessRank.rank(perm.effectiveAccess), AccessRank.rank(AccessRank.VIEWER))
|
||||||
|
} else {
|
||||||
|
AccessRank.rank(perm.effectiveAccess)
|
||||||
|
}
|
||||||
|
return effective >= requiredRank
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isExpired(expiresAt: Long?, now: Long): Boolean =
|
||||||
|
expiresAt != null && expiresAt <= now
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Masque une ligne partagée cloud-only d'autrui (`exists = 0`) — jamais
|
||||||
|
* une copie physique locale ni une ressource possédée.
|
||||||
|
*/
|
||||||
|
private suspend fun markSharedMissing(
|
||||||
|
resourceId: String,
|
||||||
|
resourceType: String,
|
||||||
|
currentUserId: String?,
|
||||||
|
now: Long,
|
||||||
|
folderDao: FolderDao,
|
||||||
|
fileDao: FileDao,
|
||||||
|
) {
|
||||||
|
if (currentUserId == null) return
|
||||||
|
if (resourceType == "folder") {
|
||||||
|
val folder = folderDao.getByResourceId(resourceId) ?: return
|
||||||
|
if (isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists)) {
|
||||||
|
folderDao.markMissing(resourceId, now)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val file = fileDao.getByResourceId(resourceId) ?: return
|
||||||
|
if (isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists)) {
|
||||||
|
fileDao.markMissing(resourceId, now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ligne hébergée cloud (uri NULL), non possédée localement, encore visible.
|
* Ligne hébergée cloud (uri NULL), non possédée localement, encore visible.
|
||||||
* Absente du snapshot → ressource partagée révoquée/expirée → marquer disparue.
|
* Absente du snapshot → ressource partagée révoquée/expirée → marquer disparue.
|
||||||
@@ -164,4 +288,9 @@ class ShareRepository @Inject constructor(
|
|||||||
)
|
)
|
||||||
fileDao.upsert(entity)
|
fileDao.upsert(entity)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** TTL du snapshot permissions (docs/api-v1.md §6.2) : 24h. */
|
||||||
|
const val PERMISSION_TTL_MS = 24 * 60 * 60 * 1000L
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,7 @@ import com.kazier.mobile.data.local.AppDatabase
|
|||||||
import com.kazier.mobile.data.local.dao.FileDao
|
import com.kazier.mobile.data.local.dao.FileDao
|
||||||
import com.kazier.mobile.data.local.dao.FolderDao
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
|
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
|
||||||
import com.kazier.mobile.data.local.dao.ScanDao
|
import com.kazier.mobile.data.local.dao.ScanDao
|
||||||
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
||||||
import com.kazier.mobile.data.local.migration.Migrations
|
import com.kazier.mobile.data.local.migration.Migrations
|
||||||
@@ -25,6 +26,13 @@ object DatabaseModule {
|
|||||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
||||||
Room.databaseBuilder(context, AppDatabase::class.java, "dot.db")
|
Room.databaseBuilder(context, AppDatabase::class.java, "dot.db")
|
||||||
.addMigrations(*Migrations.ALL)
|
.addMigrations(*Migrations.ALL)
|
||||||
|
// m15 : un APK plus ancien que la DB (downgrade) ne doit plus
|
||||||
|
// crasher en `IllegalStateException` brut — reconstruction
|
||||||
|
// destructive documentée : le miroir SAF se reconstruit au walk
|
||||||
|
// suivant, les données serveur restent la source de vérité.
|
||||||
|
// Perte acceptée : l'outbox non poussée (mutations locales) —
|
||||||
|
// cas rare (rollback d'APK), préféré au crash au démarrage.
|
||||||
|
.fallbackToDestructiveMigrationOnDowngrade()
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@@ -41,4 +49,7 @@ object DatabaseModule {
|
|||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
fun provideScanDao(db: AppDatabase): ScanDao = db.scanDao()
|
fun provideScanDao(db: AppDatabase): ScanDao = db.scanDao()
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
fun provideResourcePermissionDao(db: AppDatabase): ResourcePermissionDao = db.resourcePermissionDao()
|
||||||
}
|
}
|
||||||
@@ -8,4 +8,6 @@ object PrefKeys {
|
|||||||
const val SYNC_MODE = "sync_mode"
|
const val SYNC_MODE = "sync_mode"
|
||||||
const val THEME = "theme"
|
const val THEME = "theme"
|
||||||
const val SERVER_URL = "server_url"
|
const val SERVER_URL = "server_url"
|
||||||
|
/** Dernier pull `GET /sync/permissions` réussi, ms epoch (M27 : delta + TTL 24h). */
|
||||||
|
const val PERMISSIONS_CACHED_AT = "permissions_cached_at"
|
||||||
}
|
}
|
||||||
@@ -81,13 +81,18 @@ class FileDeleter @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Suppression cloud uniquement (outbox `delete_resource`).
|
* Suppression cloud uniquement (outbox `delete_resource` + tombstone locale).
|
||||||
* Le fichier local n\'est pas touché. N\'a de sens que si la ressource a
|
* Le fichier physique local n'est pas touché, mais la ligne Room passe
|
||||||
* déjà été poussée (gate « processed » : un fichier jamais envoyé est no-op).
|
* `exists = 0` dans la MÊME transaction (M5) : sans ça la ressource restait
|
||||||
|
* affichée, le walk la revoyait et `refreshFromServer` ne supprime jamais
|
||||||
|
* de lignes → fantôme local vs serveur supprimé. N'a de sens que si la
|
||||||
|
* ressource a déjà été poussée (gate « processed »).
|
||||||
*/
|
*/
|
||||||
private suspend fun deleteInCloud(file: FileEntity): Boolean {
|
private suspend fun deleteInCloud(file: FileEntity): Boolean {
|
||||||
var ok = false
|
var ok = false
|
||||||
runCatching {
|
runCatching {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
appDatabase.withTransaction {
|
||||||
// Jamais poussé (create encore pending) : annulation (M19), pas
|
// Jamais poussé (create encore pending) : annulation (M19), pas
|
||||||
// de delete — le serveur n'a rien à oublier. Poussé (synced) :
|
// de delete — le serveur n'a rien à oublier. Poussé (synced) :
|
||||||
// `delete_resource`, le serveur connaît la ressource.
|
// `delete_resource`, le serveur connaît la ressource.
|
||||||
@@ -95,6 +100,8 @@ class FileDeleter @Inject constructor(
|
|||||||
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||||
}
|
}
|
||||||
|
fileRepository.markMissing(file.resourceId, now)
|
||||||
|
}
|
||||||
ok = true
|
ok = true
|
||||||
Timber.d("enqueued cloud delete for %s", file.resourceId)
|
Timber.d("enqueued cloud delete for %s", file.resourceId)
|
||||||
}.onFailure { e ->
|
}.onFailure { e ->
|
||||||
|
|||||||
@@ -87,13 +87,19 @@ class FolderDeleter @Inject constructor(
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Suppression cloud uniquement (outbox `delete_resource`), physique intact. */
|
/**
|
||||||
|
* Suppression cloud uniquement (outbox `delete_resource` + tombstone locale,
|
||||||
|
* M5) : le dossier et toute sa descendance Room passent `exists = 0` dans
|
||||||
|
* la MÊME transaction — le physique reste intact mais l'arbre disparaît de
|
||||||
|
* l'UI et le walk ne le ressuscite plus (garde `hasPendingDeleteOperation`).
|
||||||
|
*/
|
||||||
private suspend fun deleteInCloud(folder: FolderEntity): Boolean {
|
private suspend fun deleteInCloud(folder: FolderEntity): Boolean {
|
||||||
var ok = false
|
var ok = false
|
||||||
runCatching {
|
runCatching {
|
||||||
outboxRepository.cancelPendingCreates(folder.resourceId)
|
val tree = collectDescendants(folder.resourceId)
|
||||||
if (outboxRepository.hasSyncedCreateOperationAnyType(folder.resourceId)) {
|
val now = System.currentTimeMillis()
|
||||||
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder")
|
appDatabase.withTransaction {
|
||||||
|
treeMarkMissing(folder, tree, now)
|
||||||
}
|
}
|
||||||
ok = true
|
ok = true
|
||||||
Timber.d("enqueued cloud delete for folder %s", folder.resourceId)
|
Timber.d("enqueued cloud delete for folder %s", folder.resourceId)
|
||||||
|
|||||||
@@ -29,6 +29,12 @@ import javax.inject.Singleton
|
|||||||
*
|
*
|
||||||
* L'ordre outbox est garanti par l'insertion séquentielle : `create_resource`
|
* L'ordre outbox est garanti par l'insertion séquentielle : `create_resource`
|
||||||
* du dossier fusionné avant les `move_resource`, avant les `delete_resource`.
|
* du dossier fusionné avant les `move_resource`, avant les `delete_resource`.
|
||||||
|
*
|
||||||
|
* M9 — reprise après crash : chaque étape est transactionnelle et idempotente
|
||||||
|
* (dossier réutilisé, contenus déjà déplacés naturellement ignorés), et une
|
||||||
|
* source n'est supprimée que si elle est réellement vide après déplacement
|
||||||
|
* (gate de vidage) — jamais de suppression d'un dossier dont le contenu n'a
|
||||||
|
* pas pu être déplacé, jamais de doublon serveur à la relance.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class FolderMerger @Inject constructor(
|
class FolderMerger @Inject constructor(
|
||||||
@@ -68,7 +74,10 @@ class FolderMerger @Inject constructor(
|
|||||||
val files = fileRepository.getFilesInFolder(src.resourceId)
|
val files = fileRepository.getFilesInFolder(src.resourceId)
|
||||||
if (files.isNotEmpty()) {
|
if (files.isNotEmpty()) {
|
||||||
fileMover.moveFiles(files.map { it.resourceId }, merged.resourceId)
|
fileMover.moveFiles(files.map { it.resourceId }, merged.resourceId)
|
||||||
movedFiles += files.size
|
// Ne compte que les fichiers réellement partis (relecture :
|
||||||
|
// `moveFiles` ignore silencieusement les refus SAF, et une
|
||||||
|
// relance après crash ne doit pas recompter les déjà-déplacés).
|
||||||
|
movedFiles += files.size - fileRepository.getFilesInFolder(src.resourceId).size
|
||||||
}
|
}
|
||||||
val subFolders = folderRepository.getChildren(src.resourceId)
|
val subFolders = folderRepository.getChildren(src.resourceId)
|
||||||
if (subFolders.isNotEmpty()) {
|
if (subFolders.isNotEmpty()) {
|
||||||
@@ -80,6 +89,14 @@ class FolderMerger @Inject constructor(
|
|||||||
folderRepository.reparentSubFolders(movable.map { it.resourceId }, merged.resourceId)
|
folderRepository.reparentSubFolders(movable.map { it.resourceId }, merged.resourceId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Gate de vidage (M9) : ne supprimer que les sources
|
||||||
|
// réellement vidées — un refus SAF silencieux ne doit jamais
|
||||||
|
// mener à la suppression d'un contenu non déplacé.
|
||||||
|
val filesLeft = fileRepository.getFilesInFolder(src.resourceId).size
|
||||||
|
val foldersLeft = folderRepository.getChildren(src.resourceId).size
|
||||||
|
if (filesLeft > 0 || foldersLeft > 0) {
|
||||||
|
error("source non vidée : $filesLeft fichier(s), $foldersLeft dossier(s) restants")
|
||||||
|
}
|
||||||
}.isSuccess
|
}.isSuccess
|
||||||
if (ok) {
|
if (ok) {
|
||||||
readyToDelete += src
|
readyToDelete += src
|
||||||
|
|||||||
@@ -72,13 +72,18 @@ class DeviceSync @Inject constructor(
|
|||||||
// Phase 1 — listing SAF (I/O disque, HORS transaction).
|
// Phase 1 — listing SAF (I/O disque, HORS transaction).
|
||||||
val folders = scanner.scanTree(Uri.parse(rootUri))
|
val folders = scanner.scanTree(Uri.parse(rootUri))
|
||||||
|
|
||||||
// Phase 2 — écritures Room (transaction courte, SQL pur).
|
// Phase 2 — écritures Room par lots (m5) : chaque lot est sa propre
|
||||||
return appDatabase.withTransaction {
|
// transaction courte au lieu d'une transaction géante (N upserts +
|
||||||
|
// full-table scans sous verrou écriture → lecteurs Room bloqués,
|
||||||
|
// jank/ANR). L'ordre parent-avant-enfant est préservé (itération
|
||||||
|
// séquentielle, seules les frontières de commit changent).
|
||||||
val seen = HashSet<String>()
|
val seen = HashSet<String>()
|
||||||
val resourceIdByUri = HashMap<String, String>()
|
val resourceIdByUri = HashMap<String, String>()
|
||||||
var fileCount = 0
|
var fileCount = 0
|
||||||
|
|
||||||
for (folder in folders) {
|
for (chunk in folders.chunked(SYNC_BATCH)) {
|
||||||
|
appDatabase.withTransaction {
|
||||||
|
for (folder in chunk) {
|
||||||
seen += folder.uri
|
seen += folder.uri
|
||||||
val parentResourceId = if (folder.parentUri == null) {
|
val parentResourceId = if (folder.parentUri == null) {
|
||||||
null
|
null
|
||||||
@@ -103,12 +108,18 @@ class DeviceSync @Inject constructor(
|
|||||||
)
|
)
|
||||||
resourceIdByUri[folder.uri] = saved.resourceId
|
resourceIdByUri[folder.uri] = saved.resourceId
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (folder in folders) {
|
val fileWrites = folders.flatMap { folder ->
|
||||||
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne
|
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne
|
||||||
// sont pas rattachés à la racine, ils attendent le walk suivant.
|
// sont pas rattachés à la racine, ils attendent le walk suivant.
|
||||||
val folderResourceId = resourceIdByUri[folder.uri] ?: continue
|
val folderResourceId = resourceIdByUri[folder.uri] ?: return@flatMap emptyList()
|
||||||
for (file in folder.files) {
|
folder.files.map { file -> folderResourceId to file }
|
||||||
|
}
|
||||||
|
for (chunk in fileWrites.chunked(SYNC_BATCH)) {
|
||||||
|
appDatabase.withTransaction {
|
||||||
|
for ((folderResourceId, file) in chunk) {
|
||||||
seen += file.uri
|
seen += file.uri
|
||||||
fileRepository.saveLocalFile(
|
fileRepository.saveLocalFile(
|
||||||
input = SaveFileInput(
|
input = SaveFileInput(
|
||||||
@@ -125,12 +136,15 @@ class DeviceSync @Inject constructor(
|
|||||||
fileCount++
|
fileCount++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var missing = 0
|
var missing = 0
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
for (folder in folderRepository.getAll()) {
|
// Réconciliation scopée à la racine (m5) : fini les `getAll()`
|
||||||
|
// O(racines×DB) — le SQL filtre par préfixe d'uri (échappé).
|
||||||
|
for (folder in folderRepository.getUnderRoot(rootUri)) {
|
||||||
val folderUri = folder.uri
|
val folderUri = folder.uri
|
||||||
if (folder.exists != 0 && folderUri != null && isChildOf(folderUri, rootUri) && folderUri !in seen &&
|
if (folder.exists != 0 && folderUri != null && folderUri !in seen &&
|
||||||
!outboxRepository.hasPendingMoveOperation(folder.resourceId)
|
!outboxRepository.hasPendingMoveOperation(folder.resourceId)
|
||||||
) {
|
) {
|
||||||
folderRepository.markMissing(folder.resourceId, now)
|
folderRepository.markMissing(folder.resourceId, now)
|
||||||
@@ -140,7 +154,7 @@ class DeviceSync @Inject constructor(
|
|||||||
missing++
|
missing++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (file in fileRepository.getAll()) {
|
for (file in fileRepository.getUnderRoot(rootUri)) {
|
||||||
val fileUri = file.uri
|
val fileUri = file.uri
|
||||||
// Un `move_resource` encore `pending` fait de l'outbox la
|
// Un `move_resource` encore `pending` fait de l'outbox la
|
||||||
// source de vérité du placement : on ne masque jamais une ligne
|
// source de vérité du placement : on ne masque jamais une ligne
|
||||||
@@ -149,7 +163,7 @@ class DeviceSync @Inject constructor(
|
|||||||
// Un move déjà `synced` ne protège plus : si le fichier a
|
// Un move déjà `synced` ne protège plus : si le fichier a
|
||||||
// ensuite disparu du disque, c'est une vraie suppression
|
// ensuite disparu du disque, c'est une vraie suppression
|
||||||
// (sinon fantôme `exists = 1` éternel, M4).
|
// (sinon fantôme `exists = 1` éternel, M4).
|
||||||
if (file.exists != 0 && fileUri != null && isChildOf(fileUri, rootUri) && fileUri !in seen &&
|
if (file.exists != 0 && fileUri != null && fileUri !in seen &&
|
||||||
!outboxRepository.hasPendingMoveOperation(file.resourceId)
|
!outboxRepository.hasPendingMoveOperation(file.resourceId)
|
||||||
) {
|
) {
|
||||||
fileRepository.markMissing(file.resourceId, now)
|
fileRepository.markMissing(file.resourceId, now)
|
||||||
@@ -158,12 +172,13 @@ class DeviceSync @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing)
|
return SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isChildOf(uri: String, rootUri: String): Boolean =
|
companion object {
|
||||||
uri == rootUri || uri.startsWith("$rootUri/")
|
/** Taille des lots d'upserts Room du walk (m5 : transactions courtes). */
|
||||||
|
private const val SYNC_BATCH = 200
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun String.extensionOrNull(): String? {
|
private fun String.extensionOrNull(): String? {
|
||||||
|
|||||||
@@ -106,31 +106,52 @@ class SyncViewModel @Inject constructor(
|
|||||||
delay(FIRST_DELAY_MS)
|
delay(FIRST_DELAY_MS)
|
||||||
while (isActive) {
|
while (isActive) {
|
||||||
_walkInProgress.value = true
|
_walkInProgress.value = true
|
||||||
|
try {
|
||||||
|
var changed = false
|
||||||
runCatching { deviceSync.syncAll() }
|
runCatching { deviceSync.syncAll() }
|
||||||
.onSuccess { results ->
|
.onSuccess { results ->
|
||||||
if (results.isNotEmpty()) Timber.d("syncAll: %s", results)
|
if (results.isNotEmpty()) Timber.d("syncAll: %s", results)
|
||||||
// Les nouvelles ressources découvertes sont dans l'outbox
|
changed = results.any { it.folders > 0 || it.files > 0 || it.missing > 0 }
|
||||||
// → drainer vers POST /sync/ops (single-flight via KEEP).
|
|
||||||
OutboxSyncWorker.enqueue(appContext)
|
|
||||||
// OCR auto : uploader les octets des fichiers récemment promus (local-cloud).
|
|
||||||
OcrAutoWorker.enqueue(appContext)
|
|
||||||
// Repasse C4 : les suppressions journalisées dont les
|
// Repasse C4 : les suppressions journalisées dont les
|
||||||
// octets ont survécu (crash entre journal et SAF).
|
// octets ont survécu (crash entre journal et SAF).
|
||||||
runCatching {
|
runCatching {
|
||||||
fileDeleter.sweepPendingPhysicalDeletes() +
|
fileDeleter.sweepPendingPhysicalDeletes() +
|
||||||
folderDeleter.sweepPendingPhysicalDeletes()
|
folderDeleter.sweepPendingPhysicalDeletes()
|
||||||
}.onSuccess { swept ->
|
}.onSuccess { swept ->
|
||||||
if (swept > 0) Timber.d("sweep: %d suppressions physiques rattrapées", swept)
|
if (swept > 0) {
|
||||||
|
Timber.d("sweep: %d suppressions physiques rattrapées", swept)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
}.onFailure { e ->
|
}.onFailure { e ->
|
||||||
Timber.w(e, "sweep failed, retrying later")
|
Timber.w(e, "sweep failed, retrying later")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.onFailure { e -> Timber.w(e, "syncAll failed, retrying later") }
|
.onFailure { e ->
|
||||||
|
if (e is CancellationException) throw e
|
||||||
|
Timber.w(e, "syncAll failed, retrying later")
|
||||||
|
}
|
||||||
// Hydrate les ressources partagées depuis le snapshot serveur.
|
// Hydrate les ressources partagées depuis le snapshot serveur.
|
||||||
// Échec réseau toléré : le prochain tick réessaiera.
|
// Échec réseau toléré : le prochain tick réessaiera.
|
||||||
runCatching { shareRepository.syncSnapshot() }
|
runCatching { shareRepository.syncSnapshot() }
|
||||||
.onFailure { e -> Timber.d("syncSnapshot failed, retrying later: %s", e.message) }
|
.onFailure { e ->
|
||||||
|
if (e is CancellationException) throw e
|
||||||
|
Timber.d("syncSnapshot failed, retrying later: %s", e.message)
|
||||||
|
}
|
||||||
|
// m2 : ne réveiller WorkManager que si le tick a produit
|
||||||
|
// quelque chose (walk/sweep) ou si l'outbox attend un drain
|
||||||
|
// (op partagée depuis l'UI, drain précédent interrompu…).
|
||||||
|
// Les nouvelles ressources découvertes sont dans l'outbox
|
||||||
|
// → drainer vers POST /sync/ops (single-flight via KEEP) ;
|
||||||
|
// OCR auto : octets des fichiers récemment promus.
|
||||||
|
if (changed || pendingOperationDao.countPending() > 0) {
|
||||||
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
|
OcrAutoWorker.enqueue(appContext)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
// m1 : le badge « syncing » retombe même si le scope est
|
||||||
|
// annulé ou si le snapshot réseau a échoué.
|
||||||
_walkInProgress.value = false
|
_walkInProgress.value = false
|
||||||
|
}
|
||||||
delay(INTERVAL_MS)
|
delay(INTERVAL_MS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,21 +38,40 @@ 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).
|
// Snapshot complet des permissions partagées (convergence, M27).
|
||||||
runCatching { shareRepository.syncSnapshot() }
|
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).
|
|
||||||
runCatching { shareRepository.syncSnapshot() }
|
|
||||||
.onFailure { e -> Timber.d("syncSnapshot on login failed: %s", e.message) }
|
|
||||||
}
|
}
|
||||||
.onFailure { e ->
|
.onFailure { e ->
|
||||||
val error = when (e) {
|
val error = when (e) {
|
||||||
@@ -86,6 +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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package com.kazier.mobile.ui.auth
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Visibility
|
||||||
|
import androidx.compose.material.icons.filled.VisibilityOff
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.text.input.VisualTransformation
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formulaire d'authentification partagé (Login + Réglages) : validation
|
||||||
|
* inline (champs non vides), touche Done = submit, œil voir/masquer le mot
|
||||||
|
* de passe, erreur centrée sous le bouton.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun LoginForm(
|
||||||
|
username: String,
|
||||||
|
onUsernameChange: (String) -> Unit,
|
||||||
|
password: String,
|
||||||
|
onPasswordChange: (String) -> Unit,
|
||||||
|
submitting: Boolean,
|
||||||
|
errorRes: Int?,
|
||||||
|
submitLabel: String,
|
||||||
|
onSubmit: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
var passwordVisible by rememberSaveable { mutableStateOf(false) }
|
||||||
|
// Pas d'appel réseau pour des champs vides — validation pure UI.
|
||||||
|
val canSubmit = !submitting && username.isNotBlank() && password.isNotBlank()
|
||||||
|
val submitIfValid = { if (canSubmit) onSubmit() }
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = modifier,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = username,
|
||||||
|
onValueChange = onUsernameChange,
|
||||||
|
label = { Text(stringResource(R.string.login_username)) },
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(
|
||||||
|
keyboardType = KeyboardType.Text,
|
||||||
|
imeAction = ImeAction.Next,
|
||||||
|
),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = password,
|
||||||
|
onValueChange = onPasswordChange,
|
||||||
|
label = { Text(stringResource(R.string.login_password)) },
|
||||||
|
singleLine = true,
|
||||||
|
visualTransformation = if (passwordVisible) {
|
||||||
|
VisualTransformation.None
|
||||||
|
} else {
|
||||||
|
PasswordVisualTransformation()
|
||||||
|
},
|
||||||
|
trailingIcon = {
|
||||||
|
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||||
|
Icon(
|
||||||
|
imageVector = if (passwordVisible) {
|
||||||
|
Icons.Filled.VisibilityOff
|
||||||
|
} else {
|
||||||
|
Icons.Filled.Visibility
|
||||||
|
},
|
||||||
|
contentDescription = stringResource(
|
||||||
|
if (passwordVisible) {
|
||||||
|
R.string.login_hide_password
|
||||||
|
} else {
|
||||||
|
R.string.login_show_password
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
keyboardOptions = KeyboardOptions(
|
||||||
|
keyboardType = KeyboardType.Password,
|
||||||
|
imeAction = ImeAction.Done,
|
||||||
|
),
|
||||||
|
keyboardActions = KeyboardActions(onDone = { submitIfValid() }),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
Button(
|
||||||
|
onClick = submitIfValid,
|
||||||
|
enabled = canSubmit,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
if (submitting) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
strokeWidth = 2.dp,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Text(submitLabel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (errorRes != null) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(errorRes),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,42 +8,47 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
|||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.imePadding
|
import androidx.compose.foundation.layout.imePadding
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Premier écran : choix explicite entre compte serveur et mode local, puis
|
||||||
|
* formulaire de connexion. Le mode local est expliqué avant d'être choisi
|
||||||
|
* (pas un petit lien d'esquive sous le formulaire).
|
||||||
|
*
|
||||||
|
* Après expiration de session (`expired`), le formulaire s'ouvre directement
|
||||||
|
* avec le username pré-rempli et un avis explicite — pas de repassage par
|
||||||
|
* l'écran de choix.
|
||||||
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun LoginScreen(
|
fun LoginScreen(
|
||||||
viewModel: AuthViewModel = hiltViewModel(),
|
viewModel: AuthViewModel = hiltViewModel(),
|
||||||
|
expired: Boolean = false,
|
||||||
|
initialUsername: String? = null,
|
||||||
) {
|
) {
|
||||||
val loginUi by viewModel.loginUiState.collectAsStateWithLifecycle()
|
val loginUi by viewModel.loginUiState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
var username by rememberSaveable { mutableStateOf("") }
|
var username by rememberSaveable { mutableStateOf(initialUsername.orEmpty()) }
|
||||||
var password by rememberSaveable { mutableStateOf("") }
|
var password by rememberSaveable { mutableStateOf("") }
|
||||||
|
var showForm by rememberSaveable { mutableStateOf(expired) }
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -60,70 +65,68 @@ fun LoginScreen(
|
|||||||
color = MaterialTheme.colorScheme.primary,
|
color = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(8.dp))
|
||||||
|
|
||||||
|
if (!showForm) {
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.login_subtitle),
|
text = stringResource(R.string.login_choice_subtitle),
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
|
||||||
Spacer(Modifier.height(32.dp))
|
|
||||||
|
|
||||||
OutlinedTextField(
|
|
||||||
value = username,
|
|
||||||
onValueChange = { username = it },
|
|
||||||
label = { Text(stringResource(R.string.login_username)) },
|
|
||||||
singleLine = true,
|
|
||||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(12.dp))
|
|
||||||
OutlinedTextField(
|
|
||||||
value = password,
|
|
||||||
onValueChange = { password = it },
|
|
||||||
label = { Text(stringResource(R.string.login_password)) },
|
|
||||||
singleLine = true,
|
|
||||||
visualTransformation = PasswordVisualTransformation(),
|
|
||||||
keyboardOptions = KeyboardOptions(
|
|
||||||
keyboardType = KeyboardType.Password,
|
|
||||||
imeAction = ImeAction.Done,
|
|
||||||
),
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(24.dp))
|
|
||||||
|
|
||||||
Button(
|
|
||||||
onClick = { viewModel.signIn(username, password) },
|
|
||||||
enabled = !loginUi.isSubmitting,
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
if (loginUi.isSubmitting) {
|
|
||||||
CircularProgressIndicator(
|
|
||||||
modifier = Modifier.size(20.dp),
|
|
||||||
strokeWidth = 2.dp,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Text(stringResource(R.string.login_submit))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
loginUi.error?.let { error ->
|
|
||||||
Spacer(Modifier.height(12.dp))
|
|
||||||
Text(
|
|
||||||
text = stringResource(authErrorResFor(error)),
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.error,
|
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
)
|
)
|
||||||
|
Spacer(Modifier.height(32.dp))
|
||||||
|
Button(
|
||||||
|
onClick = { showForm = true },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.login_submit))
|
||||||
}
|
}
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
Spacer(Modifier.height(16.dp))
|
OutlinedButton(
|
||||||
TextButton(onClick = viewModel::continueWithoutAccount) {
|
onClick = viewModel::continueWithoutAccount,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
Text(stringResource(R.string.login_skip))
|
Text(stringResource(R.string.login_skip))
|
||||||
}
|
}
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.skip_message),
|
text = stringResource(R.string.skip_message),
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
)
|
)
|
||||||
|
} else {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.login_subtitle),
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
if (expired) {
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.login_session_expired),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(32.dp))
|
||||||
|
|
||||||
|
LoginForm(
|
||||||
|
username = username,
|
||||||
|
onUsernameChange = { username = it },
|
||||||
|
password = password,
|
||||||
|
onPasswordChange = { password = it },
|
||||||
|
submitting = loginUi.isSubmitting,
|
||||||
|
errorRes = loginUi.error?.let(::authErrorResFor),
|
||||||
|
submitLabel = stringResource(R.string.login_submit),
|
||||||
|
onSubmit = { viewModel.signIn(username, password) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
TextButton(onClick = { showForm = false }) {
|
||||||
|
Text(stringResource(R.string.back))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+13
-9
@@ -17,25 +17,27 @@ import androidx.compose.material3.TextButton
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.data.local.entity.FileStatus
|
import com.kazier.mobile.data.local.entity.FileStatus
|
||||||
import com.kazier.mobile.features.saf.FileDeleter
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
|
import com.kazier.mobile.ui.theme.NavItemShape
|
||||||
|
import java.io.Serializable
|
||||||
|
|
||||||
/** Résultat de l\'analyse de compatibilité entre les fichiers et le mode choisi. */
|
/** Résultat de l'analyse de compatibilité entre les fichiers et le mode choisi. */
|
||||||
data class DeleteReview(
|
data class DeleteReview(
|
||||||
val mode: FileDeleter.DeleteMode,
|
val mode: FileDeleter.DeleteMode,
|
||||||
val total: Int,
|
val total: Int,
|
||||||
val incompatibleCount: Int,
|
val incompatibleCount: Int,
|
||||||
) {
|
) : Serializable {
|
||||||
val hasWarning: Boolean get() = incompatibleCount > 0
|
val hasWarning: Boolean get() = incompatibleCount > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,15 +63,16 @@ fun DeleteDropdownButton(
|
|||||||
onModeSelected: (FileDeleter.DeleteMode) -> Unit,
|
onModeSelected: (FileDeleter.DeleteMode) -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
var expanded by remember { mutableStateOf(false) }
|
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||||
val tint = if (enabled) MaterialTheme.colorScheme.error
|
val tint = if (enabled) MaterialTheme.colorScheme.error
|
||||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
val deleteLabel = stringResource(R.string.delete)
|
||||||
|
|
||||||
Box(modifier = modifier) {
|
Box(modifier = modifier) {
|
||||||
Surface(
|
Surface(
|
||||||
onClick = { if (enabled) expanded = true },
|
onClick = { if (enabled) expanded = true },
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
shape = androidx.compose.foundation.shape.RoundedCornerShape(20.dp),
|
shape = NavItemShape,
|
||||||
color = if (enabled) MaterialTheme.colorScheme.errorContainer
|
color = if (enabled) MaterialTheme.colorScheme.errorContainer
|
||||||
else MaterialTheme.colorScheme.surfaceVariant,
|
else MaterialTheme.colorScheme.surfaceVariant,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
@@ -84,15 +87,16 @@ fun DeleteDropdownButton(
|
|||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.Delete,
|
imageVector = Icons.Filled.Delete,
|
||||||
contentDescription = null,
|
contentDescription = deleteLabel,
|
||||||
tint = tint,
|
tint = tint,
|
||||||
modifier = Modifier.size(20.dp),
|
modifier = Modifier.size(20.dp),
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.delete),
|
text = deleteLabel,
|
||||||
color = tint,
|
color = tint,
|
||||||
fontSize = 11.sp,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
Icon(
|
Icon(
|
||||||
|
|||||||
+31
-13
@@ -9,12 +9,15 @@ import androidx.compose.material.icons.filled.Movie
|
|||||||
import androidx.compose.material.icons.filled.MusicNote
|
import androidx.compose.material.icons.filled.MusicNote
|
||||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||||
import androidx.compose.material.icons.filled.TextSnippet
|
import androidx.compose.material.icons.filled.TextSnippet
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.domain.FileCategory
|
import com.kazier.mobile.domain.FileCategory
|
||||||
import com.kazier.mobile.domain.computeCategory
|
import com.kazier.mobile.domain.computeCategory
|
||||||
@@ -31,17 +34,32 @@ val FileCategory.icon: ImageVector
|
|||||||
FileCategory.OTHER -> Icons.Filled.InsertDriveFile
|
FileCategory.OTHER -> Icons.Filled.InsertDriveFile
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Teinte dédiée à chaque catégorie de document. */
|
/** Teinte dédiée à chaque catégorie — déclinaison light/dark lisible sur les deux thèmes. */
|
||||||
val FileCategory.color: Color
|
@Composable
|
||||||
get() = when (this) {
|
fun FileCategory.color(): androidx.compose.ui.graphics.Color {
|
||||||
FileCategory.PDF -> Color(0xFFD32F2F)
|
val dark = isSystemInDarkTheme()
|
||||||
FileCategory.OFFICE -> Color(0xFF1565C0)
|
return when (this) {
|
||||||
FileCategory.IMAGE -> Color(0xFF2E7D32)
|
FileCategory.PDF -> if (dark) androidx.compose.ui.graphics.Color(0xFFE57373) else androidx.compose.ui.graphics.Color(0xFFD32F2F)
|
||||||
FileCategory.TEXT -> Color(0xFF546E7A)
|
FileCategory.OFFICE -> if (dark) androidx.compose.ui.graphics.Color(0xFF90CAF9) else androidx.compose.ui.graphics.Color(0xFF1565C0)
|
||||||
FileCategory.VIDEO -> Color(0xFF6A1B9A)
|
FileCategory.IMAGE -> if (dark) androidx.compose.ui.graphics.Color(0xFF81C784) else androidx.compose.ui.graphics.Color(0xFF2E7D32)
|
||||||
FileCategory.AUDIO -> Color(0xFFAD1457)
|
FileCategory.TEXT -> if (dark) androidx.compose.ui.graphics.Color(0xFFB0BEC5) else androidx.compose.ui.graphics.Color(0xFF546E7A)
|
||||||
FileCategory.OTHER -> Color(0xFF757575)
|
FileCategory.VIDEO -> if (dark) androidx.compose.ui.graphics.Color(0xFFCE93D8) else androidx.compose.ui.graphics.Color(0xFF6A1B9A)
|
||||||
|
FileCategory.AUDIO -> if (dark) androidx.compose.ui.graphics.Color(0xFFF48FB1) else androidx.compose.ui.graphics.Color(0xFFAD1457)
|
||||||
|
FileCategory.OTHER -> if (dark) androidx.compose.ui.graphics.Color(0xFFBDBDBD) else androidx.compose.ui.graphics.Color(0xFF757575)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Libellé i18n de la catégorie — utilisé comme contentDescription. */
|
||||||
|
@Composable
|
||||||
|
fun FileCategory.label(): String = when (this) {
|
||||||
|
FileCategory.PDF -> stringResource(R.string.category_pdf)
|
||||||
|
FileCategory.OFFICE -> stringResource(R.string.category_office)
|
||||||
|
FileCategory.IMAGE -> stringResource(R.string.category_image)
|
||||||
|
FileCategory.TEXT -> stringResource(R.string.category_text)
|
||||||
|
FileCategory.VIDEO -> stringResource(R.string.category_video)
|
||||||
|
FileCategory.AUDIO -> stringResource(R.string.category_audio)
|
||||||
|
FileCategory.OTHER -> stringResource(R.string.category_other)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Catégorie d'un fichier : valeur stockée (`category`, colonne ajoutée en v4)
|
* Catégorie d'un fichier : valeur stockée (`category`, colonne ajoutée en v4)
|
||||||
@@ -63,8 +81,8 @@ fun FileCategoryIcon(
|
|||||||
val category = file.categoryValue()
|
val category = file.categoryValue()
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = category.icon,
|
imageVector = category.icon,
|
||||||
contentDescription = null,
|
contentDescription = category.label(),
|
||||||
tint = category.color,
|
tint = category.color(),
|
||||||
modifier = modifier.size(size),
|
modifier = modifier.size(size),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
+2
-2
@@ -7,7 +7,6 @@ import androidx.compose.foundation.layout.Row
|
|||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
@@ -19,6 +18,7 @@ import androidx.compose.ui.res.stringResource
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
|
import com.kazier.mobile.ui.theme.ThumbShape
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Un fichier est « à traiter » s'il est présent physiquement et jamais encore
|
* Un fichier est « à traiter » s'il est présent physiquement et jamais encore
|
||||||
@@ -41,7 +41,7 @@ fun FilePendingReviewBadge(
|
|||||||
) {
|
) {
|
||||||
if (!file.isPendingReview()) return
|
if (!file.isPendingReview()) return
|
||||||
Surface(
|
Surface(
|
||||||
shape = RoundedCornerShape(8.dp),
|
shape = ThumbShape,
|
||||||
color = MaterialTheme.colorScheme.tertiaryContainer,
|
color = MaterialTheme.colorScheme.tertiaryContainer,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
) {
|
) {
|
||||||
|
|||||||
+21
-9
@@ -5,12 +5,14 @@ import androidx.compose.material.icons.Icons
|
|||||||
import androidx.compose.material.icons.filled.Cloud
|
import androidx.compose.material.icons.filled.Cloud
|
||||||
import androidx.compose.material.icons.filled.CloudDone
|
import androidx.compose.material.icons.filled.CloudDone
|
||||||
import androidx.compose.material.icons.filled.CloudOff
|
import androidx.compose.material.icons.filled.CloudOff
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.data.local.entity.FileStatus
|
import com.kazier.mobile.data.local.entity.FileStatus
|
||||||
|
|
||||||
@@ -35,13 +37,23 @@ private val FileSyncPlacement.icon: ImageVector
|
|||||||
FileSyncPlacement.LOCAL_CLOUD -> Icons.Filled.CloudDone
|
FileSyncPlacement.LOCAL_CLOUD -> Icons.Filled.CloudDone
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Teinte dédiée à chaque placement. */
|
/** Teinte dédiée à chaque placement — déclinaison light/dark. */
|
||||||
private val FileSyncPlacement.color: Color
|
@Composable
|
||||||
get() = when (this) {
|
private fun FileSyncPlacement.color(): androidx.compose.ui.graphics.Color {
|
||||||
FileSyncPlacement.LOCAL -> Color(0xFFF57F17)
|
val dark = isSystemInDarkTheme()
|
||||||
FileSyncPlacement.CLOUD -> Color(0xFF1565C0)
|
return when (this) {
|
||||||
FileSyncPlacement.LOCAL_CLOUD -> Color(0xFF2E7D32)
|
FileSyncPlacement.LOCAL -> if (dark) androidx.compose.ui.graphics.Color(0xFFFFB74D) else androidx.compose.ui.graphics.Color(0xFFB26A00)
|
||||||
|
FileSyncPlacement.CLOUD -> if (dark) androidx.compose.ui.graphics.Color(0xFF90CAF9) else androidx.compose.ui.graphics.Color(0xFF1565C0)
|
||||||
|
FileSyncPlacement.LOCAL_CLOUD -> if (dark) androidx.compose.ui.graphics.Color(0xFF81C784) else androidx.compose.ui.graphics.Color(0xFF2E7D32)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun FileSyncPlacement.label(): String = when (this) {
|
||||||
|
FileSyncPlacement.LOCAL -> stringResource(R.string.sync_placement_local)
|
||||||
|
FileSyncPlacement.CLOUD -> stringResource(R.string.sync_placement_cloud)
|
||||||
|
FileSyncPlacement.LOCAL_CLOUD -> stringResource(R.string.sync_placement_local_cloud)
|
||||||
|
}
|
||||||
|
|
||||||
/** Statut de sync d'un fichier — présence device / serveur distant. */
|
/** Statut de sync d'un fichier — présence device / serveur distant. */
|
||||||
@Composable
|
@Composable
|
||||||
@@ -53,8 +65,8 @@ fun FileSyncStatusIcon(
|
|||||||
val placement = file.syncPlacement()
|
val placement = file.syncPlacement()
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = placement.icon,
|
imageVector = placement.icon,
|
||||||
contentDescription = null,
|
contentDescription = placement.label(),
|
||||||
tint = placement.color,
|
tint = placement.color(),
|
||||||
modifier = modifier.size(size),
|
modifier = modifier.size(size),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,6 @@ package com.kazier.mobile.ui.components
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.produceState
|
import androidx.compose.runtime.produceState
|
||||||
@@ -13,12 +12,12 @@ import androidx.compose.ui.graphics.Shape
|
|||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import coil.request.ImageRequest
|
import coil.request.ImageRequest
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.domain.FileCategory
|
import com.kazier.mobile.domain.FileCategory
|
||||||
import com.kazier.mobile.features.thumbnails.ThumbnailStore
|
import com.kazier.mobile.features.thumbnails.ThumbnailStore
|
||||||
|
import com.kazier.mobile.ui.theme.ThumbShape
|
||||||
import dagger.hilt.EntryPoint
|
import dagger.hilt.EntryPoint
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
import dagger.hilt.android.EntryPointAccessors
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
@@ -41,7 +40,7 @@ fun FileThumbnail(
|
|||||||
file: FileEntity,
|
file: FileEntity,
|
||||||
size: Dp,
|
size: Dp,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
shape: Shape = RoundedCornerShape(8.dp),
|
shape: Shape = ThumbShape,
|
||||||
) {
|
) {
|
||||||
val category = file.categoryValue()
|
val category = file.categoryValue()
|
||||||
if (category != FileCategory.IMAGE && category != FileCategory.PDF) {
|
if (category != FileCategory.IMAGE && category != FileCategory.PDF) {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import androidx.compose.material3.TextButton
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
@@ -20,7 +20,7 @@ fun FolderNameDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onConfirm: (String) -> Unit,
|
onConfirm: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
var name by remember { mutableStateOf("") }
|
var name by rememberSaveable { mutableStateOf("") }
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
title = { Text(stringResource(R.string.new_folder_name_title)) },
|
title = { Text(stringResource(R.string.new_folder_name_title)) },
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.kazier.mobile.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formattage de taille centralisé (Phase 0) : remplace les 5 copies
|
||||||
|
* (`FolderList`, `FolderDetail`, `Search`, `Document`, `SwipeCardDeck`,
|
||||||
|
* `PdfBuilder`) dont 2 en français en dur (`o/ko/Mo`).
|
||||||
|
* Utilise les strings i18n `unit_bytes / unit_kilobytes / unit_megabytes`.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun formatFileSize(bytes: Long): String {
|
||||||
|
val safe = bytes.coerceAtLeast(0)
|
||||||
|
if (safe < 1_024) {
|
||||||
|
return "$safe ${stringResource(R.string.unit_bytes)}"
|
||||||
|
}
|
||||||
|
if (safe < 1_024 * 1_024) {
|
||||||
|
val kb = safe / 1_024f
|
||||||
|
return String.format(
|
||||||
|
Locale.getDefault(),
|
||||||
|
"%.1f %s",
|
||||||
|
kb,
|
||||||
|
stringResource(R.string.unit_kilobytes),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val mb = safe / (1_024f * 1_024f)
|
||||||
|
return String.format(
|
||||||
|
Locale.getDefault(),
|
||||||
|
"%.1f %s",
|
||||||
|
mb,
|
||||||
|
stringResource(R.string.unit_megabytes),
|
||||||
|
)
|
||||||
|
}
|
||||||
+331
@@ -0,0 +1,331 @@
|
|||||||
|
package com.kazier.mobile.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.rememberModalBottomSheetState
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||||
|
import com.kazier.mobile.features.connection.ServerConnectionStatus
|
||||||
|
import com.kazier.mobile.features.sync.SyncViewModel
|
||||||
|
import com.kazier.mobile.ui.theme.PendingDark
|
||||||
|
import com.kazier.mobile.ui.theme.PendingLight
|
||||||
|
import com.kazier.mobile.ui.theme.PillShape
|
||||||
|
import com.kazier.mobile.ui.theme.SuccessDark
|
||||||
|
import com.kazier.mobile.ui.theme.SuccessLight
|
||||||
|
import com.kazier.mobile.ui.theme.SyncingDark
|
||||||
|
import com.kazier.mobile.ui.theme.SyncingLight
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pastille de statut unique du header : un point coloré (ou spinner pendant
|
||||||
|
* une synchro) + un libellé. Un appui ouvre le bottom-sheet « état » :
|
||||||
|
* statut serveur, bouton de test, résumé de la file d'envoi et accès à son
|
||||||
|
* détail.
|
||||||
|
*
|
||||||
|
* En mode local il n'y a rien à pousser : la pastille affiche « Mode local »
|
||||||
|
* et le sheet l'explique sans proposer de test (le tap-à-vérifier serait
|
||||||
|
* une impasse).
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun HeaderStatusAction(
|
||||||
|
syncViewModel: SyncViewModel,
|
||||||
|
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||||
|
val syncStatus by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
||||||
|
var showSheet by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var showQueue by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
|
val isLocal = connectionStatus == ServerConnectionStatus.Local
|
||||||
|
val dark = isSystemInDarkTheme()
|
||||||
|
val onlineGreen = if (dark) SuccessDark else SuccessLight
|
||||||
|
val pendingAmber = if (dark) PendingDark else PendingLight
|
||||||
|
val syncingAccent = if (dark) SyncingDark else SyncingLight
|
||||||
|
|
||||||
|
val (dotColor, label, showSpinner) = when {
|
||||||
|
isLocal -> Triple(
|
||||||
|
MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
stringResource(R.string.status_local),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
connectionStatus == ServerConnectionStatus.Checking -> Triple(
|
||||||
|
pendingAmber,
|
||||||
|
stringResource(R.string.status_checking),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
syncStatus.syncing -> Triple(
|
||||||
|
syncingAccent,
|
||||||
|
stringResource(R.string.sync_syncing),
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
syncStatus.pending > 0 -> {
|
||||||
|
val text = if (syncStatus.pending == 1) {
|
||||||
|
stringResource(R.string.sync_pending_count_one)
|
||||||
|
} else {
|
||||||
|
stringResource(R.string.sync_pending_count, syncStatus.pending)
|
||||||
|
}
|
||||||
|
val color = if (connectionStatus == ServerConnectionStatus.Offline) {
|
||||||
|
MaterialTheme.colorScheme.error
|
||||||
|
} else {
|
||||||
|
pendingAmber
|
||||||
|
}
|
||||||
|
Triple(color, text, false)
|
||||||
|
}
|
||||||
|
syncStatus.failed > 0 -> Triple(
|
||||||
|
MaterialTheme.colorScheme.error,
|
||||||
|
stringResource(R.string.sync_summary_failed, syncStatus.failed),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
connectionStatus == ServerConnectionStatus.Offline -> Triple(
|
||||||
|
MaterialTheme.colorScheme.error,
|
||||||
|
stringResource(R.string.status_offline),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
else -> Triple(
|
||||||
|
onlineGreen,
|
||||||
|
stringResource(R.string.status_online),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val tapLabel = stringResource(R.string.sync_tap_to_view)
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.clip(PillShape)
|
||||||
|
.clickable(
|
||||||
|
role = Role.Button,
|
||||||
|
onClickLabel = tapLabel,
|
||||||
|
onClick = { showSheet = true },
|
||||||
|
)
|
||||||
|
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
) {
|
||||||
|
if (showSpinner) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(12.dp),
|
||||||
|
strokeWidth = 2.dp,
|
||||||
|
color = dotColor,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(8.dp)
|
||||||
|
.background(dotColor, CircleShape),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = label,
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showSheet) {
|
||||||
|
ModalBottomSheet(
|
||||||
|
onDismissRequest = { showSheet = false },
|
||||||
|
sheetState = rememberModalBottomSheetState(),
|
||||||
|
) {
|
||||||
|
StatusSheetContent(
|
||||||
|
connectionStatus = connectionStatus,
|
||||||
|
syncStatus = syncStatus,
|
||||||
|
onTest = connectionStatusViewModel::checkNow,
|
||||||
|
onViewQueue = {
|
||||||
|
showSheet = false
|
||||||
|
showQueue = true
|
||||||
|
},
|
||||||
|
onDismiss = { showSheet = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showQueue) {
|
||||||
|
SyncOperationsDialog(
|
||||||
|
status = syncStatus,
|
||||||
|
onDismiss = { showQueue = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun StatusSheetContent(
|
||||||
|
connectionStatus: ServerConnectionStatus,
|
||||||
|
syncStatus: SyncViewModel.SyncStatus,
|
||||||
|
onTest: () -> Unit,
|
||||||
|
onViewQueue: () -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
val isLocal = connectionStatus == ServerConnectionStatus.Local
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 24.dp)
|
||||||
|
.padding(bottom = 32.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.status_sheet_title),
|
||||||
|
style = MaterialTheme.typography.titleLarge,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
)
|
||||||
|
StatusServerRow(
|
||||||
|
status = connectionStatus,
|
||||||
|
onTest = onTest,
|
||||||
|
)
|
||||||
|
if (isLocal) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.skip_message),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
HorizontalDivider()
|
||||||
|
StatusSyncSection(
|
||||||
|
status = syncStatus,
|
||||||
|
onViewQueue = onViewQueue,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
TextButton(
|
||||||
|
onClick = onDismiss,
|
||||||
|
modifier = Modifier.align(Alignment.End),
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.settings_close))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun StatusServerRow(
|
||||||
|
status: ServerConnectionStatus,
|
||||||
|
onTest: () -> Unit,
|
||||||
|
) {
|
||||||
|
val dark = isSystemInDarkTheme()
|
||||||
|
val dotColor = when (status) {
|
||||||
|
ServerConnectionStatus.Checking -> if (dark) PendingDark else PendingLight
|
||||||
|
ServerConnectionStatus.Online -> if (dark) SuccessDark else SuccessLight
|
||||||
|
ServerConnectionStatus.Offline -> MaterialTheme.colorScheme.error
|
||||||
|
ServerConnectionStatus.Local -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
}
|
||||||
|
val label = stringResource(
|
||||||
|
when (status) {
|
||||||
|
ServerConnectionStatus.Checking -> R.string.status_checking
|
||||||
|
ServerConnectionStatus.Online -> R.string.status_online
|
||||||
|
ServerConnectionStatus.Offline -> R.string.status_offline
|
||||||
|
ServerConnectionStatus.Local -> R.string.status_local
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(12.dp)
|
||||||
|
.background(dotColor, CircleShape),
|
||||||
|
)
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.settings_server),
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = label,
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (status != ServerConnectionStatus.Local) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onTest,
|
||||||
|
enabled = status != ServerConnectionStatus.Checking,
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.settings_test_connection))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun StatusSyncSection(
|
||||||
|
status: SyncViewModel.SyncStatus,
|
||||||
|
onViewQueue: () -> Unit,
|
||||||
|
) {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.dashboard_sync_title),
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
when {
|
||||||
|
status.syncing -> {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.sync_syncing),
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
status.pending > 0 -> {
|
||||||
|
Text(
|
||||||
|
text = if (status.pending == 1) {
|
||||||
|
stringResource(R.string.sync_pending_count_one)
|
||||||
|
} else {
|
||||||
|
stringResource(R.string.sync_pending_count, status.pending)
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
status.failed > 0 -> {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.sync_summary_failed, status.failed),
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.sync_idle),
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OutlinedButton(onClick = onViewQueue) {
|
||||||
|
Text(stringResource(R.string.status_sheet_view_queue))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.kazier.mobile.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.BorderStroke
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import com.kazier.mobile.ui.theme.KazierDimens
|
||||||
|
import com.kazier.mobile.ui.theme.ListCardShape
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Carte de liste unifiée (Phase 0) : remplace les 3 recettes dispersées
|
||||||
|
* (`surfaceVariant+elev 1dp`, `surface+elev 1dp`, `#F7F8FA + border #EAEAEA`).
|
||||||
|
* Couleurs 100% thème → lisible en dark mode.
|
||||||
|
*
|
||||||
|
* Le clic (simple ou combiné long) se gère via `modifier` pour préserver
|
||||||
|
* les `combinedClickable` de sélection — pas de `onClick` M3 ici.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun KazierCard(
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
content: @Composable () -> Unit,
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = modifier,
|
||||||
|
shape = ListCardShape,
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
|
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
border = BorderStroke(
|
||||||
|
KazierDimens.CardBorderWidth,
|
||||||
|
MaterialTheme.colorScheme.outlineVariant,
|
||||||
|
),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = KazierDimens.CardElevation),
|
||||||
|
content = { content() },
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.kazier.mobile.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CTA « documents à traiter » partagé (dashboard + écran Fichiers) : la
|
||||||
|
* file review reste joignable même sans passer par le dashboard.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ReviewCtaCard(
|
||||||
|
count: Int,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val label = stringResource(R.string.dashboard_review_title, count)
|
||||||
|
KazierCard(
|
||||||
|
modifier = modifier.clickable(
|
||||||
|
role = Role.Button,
|
||||||
|
onClickLabel = label,
|
||||||
|
onClick = onClick,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(20.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = label,
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.dashboard_review_hint),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.padding(top = 4.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,11 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.selected
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* État du mode multi-sélection (long-press pour entrer, tap pour cocher).
|
* État du mode multi-sélection (long-press pour entrer, tap pour cocher).
|
||||||
@@ -50,12 +54,16 @@ fun rememberSelectionState(): SelectionState = remember { SelectionState() }
|
|||||||
fun SelectionStatusIcon(selected: Boolean, modifier: Modifier = Modifier) {
|
fun SelectionStatusIcon(selected: Boolean, modifier: Modifier = Modifier) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = if (selected) Icons.Filled.CheckCircle else Icons.Filled.RadioButtonUnchecked,
|
imageVector = if (selected) Icons.Filled.CheckCircle else Icons.Filled.RadioButtonUnchecked,
|
||||||
contentDescription = null,
|
contentDescription = stringResource(
|
||||||
|
if (selected) R.string.selection_selected else R.string.selection_unselected,
|
||||||
|
),
|
||||||
tint = if (selected) {
|
tint = if (selected) {
|
||||||
MaterialTheme.colorScheme.primary
|
MaterialTheme.colorScheme.primary
|
||||||
} else {
|
} else {
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
},
|
},
|
||||||
modifier = modifier.size(24.dp),
|
modifier = modifier
|
||||||
|
.size(24.dp)
|
||||||
|
.semantics { this.selected = selected },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package com.kazier.mobile.ui.components
|
|
||||||
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.semantics.Role
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import com.kazier.mobile.R
|
|
||||||
import com.kazier.mobile.features.connection.ServerConnectionStatus
|
|
||||||
import com.kazier.mobile.ui.theme.InactiveGray
|
|
||||||
|
|
||||||
private val OnlineGreen = Color(0xFF2E7D32)
|
|
||||||
private val CheckingAmber = Color(0xFFF9A825)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pilule de statut serveur affichée dans le header : cercle coloré + libellé.
|
|
||||||
* Un appui relance une vérification immédiate du serveur.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
fun ServerStatusBadge(
|
|
||||||
status: ServerConnectionStatus,
|
|
||||||
onClick: () -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
) {
|
|
||||||
val (dotColor, labelRes) = when (status) {
|
|
||||||
ServerConnectionStatus.Checking -> CheckingAmber to R.string.status_checking
|
|
||||||
ServerConnectionStatus.Online -> OnlineGreen to R.string.status_online
|
|
||||||
ServerConnectionStatus.Offline -> MaterialTheme.colorScheme.error to R.string.status_offline
|
|
||||||
ServerConnectionStatus.Local -> InactiveGray to R.string.status_local
|
|
||||||
}
|
|
||||||
val label = stringResource(labelRes)
|
|
||||||
val tapLabel = stringResource(R.string.status_tap_to_recheck)
|
|
||||||
val shape = RoundedCornerShape(percent = 50)
|
|
||||||
|
|
||||||
Row(
|
|
||||||
modifier = modifier
|
|
||||||
.clip(shape)
|
|
||||||
.clickable(
|
|
||||||
role = Role.Button,
|
|
||||||
onClickLabel = tapLabel,
|
|
||||||
onClick = onClick,
|
|
||||||
)
|
|
||||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
|
||||||
) {
|
|
||||||
Box(
|
|
||||||
modifier = Modifier
|
|
||||||
.size(8.dp)
|
|
||||||
.background(dotColor, CircleShape),
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = label,
|
|
||||||
style = MaterialTheme.typography.labelMedium,
|
|
||||||
fontWeight = FontWeight.Medium,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+13
-9
@@ -2,6 +2,7 @@ package com.kazier.mobile.ui.components
|
|||||||
|
|
||||||
import android.text.format.DateUtils
|
import android.text.format.DateUtils
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
@@ -20,7 +21,6 @@ import androidx.compose.material3.TextButton
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
@@ -28,10 +28,13 @@ import com.kazier.mobile.R
|
|||||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
import com.kazier.mobile.features.sync.SyncViewModel
|
import com.kazier.mobile.features.sync.SyncViewModel
|
||||||
|
import com.kazier.mobile.ui.theme.ErrorDark
|
||||||
private val StatusPending = Color(0xFF1E88E5)
|
import com.kazier.mobile.ui.theme.ErrorLight
|
||||||
private val StatusSynced = Color(0xFF2E7D32)
|
import com.kazier.mobile.ui.theme.KazierDimens
|
||||||
private val StatusFailed = Color(0xFFC62828)
|
import com.kazier.mobile.ui.theme.SuccessDark
|
||||||
|
import com.kazier.mobile.ui.theme.SuccessLight
|
||||||
|
import com.kazier.mobile.ui.theme.SyncingDark
|
||||||
|
import com.kazier.mobile.ui.theme.SyncingLight
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dialogue « liste des sync » : dernières opérations de l'outbox (tous statuts),
|
* Dialogue « liste des sync » : dernières opérations de l'outbox (tous statuts),
|
||||||
@@ -58,7 +61,7 @@ internal fun SyncOperationsDialog(
|
|||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.heightIn(max = 360.dp),
|
.heightIn(max = KazierDimens.DialogListMaxHeight),
|
||||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||||
) {
|
) {
|
||||||
items(status.operations, key = { it.id }) { op ->
|
items(status.operations, key = { it.id }) { op ->
|
||||||
@@ -99,10 +102,11 @@ private fun SyncListSummary(status: SyncViewModel.SyncStatus) {
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun SyncOperationRow(op: PendingOperationEntity) {
|
private fun SyncOperationRow(op: PendingOperationEntity) {
|
||||||
|
val dark = isSystemInDarkTheme()
|
||||||
val (dotColor, statusLabel) = when (op.status) {
|
val (dotColor, statusLabel) = when (op.status) {
|
||||||
PendingOpStatus.PENDING -> StatusPending to stringResource(R.string.sync_status_pending)
|
PendingOpStatus.PENDING -> (if (dark) SyncingDark else SyncingLight) to stringResource(R.string.sync_status_pending)
|
||||||
PendingOpStatus.SYNCED -> StatusSynced to stringResource(R.string.sync_status_synced)
|
PendingOpStatus.SYNCED -> (if (dark) SuccessDark else SuccessLight) to stringResource(R.string.sync_status_synced)
|
||||||
else -> StatusFailed to stringResource(R.string.sync_status_failed)
|
else -> (if (dark) ErrorDark else ErrorLight) to stringResource(R.string.sync_status_failed)
|
||||||
}
|
}
|
||||||
val opLabel = operationLabel(op.operation)
|
val opLabel = operationLabel(op.operation)
|
||||||
val time = DateUtils.getRelativeTimeSpanString(op.createdAt).toString()
|
val time = DateUtils.getRelativeTimeSpanString(op.createdAt).toString()
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
package com.kazier.mobile.ui.components
|
|
||||||
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
|
||||||
import androidx.compose.material.icons.filled.Check
|
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
|
||||||
import androidx.compose.material3.Icon
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.semantics.Role
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|
||||||
import com.kazier.mobile.R
|
|
||||||
import com.kazier.mobile.features.sync.SyncViewModel
|
|
||||||
|
|
||||||
private val SyncingAccent = Color(0xFF1E88E5)
|
|
||||||
private val PendingAmber = Color(0xFFF9A825)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pilule de statut de synchro affichée dans le header : spinner quand une marche
|
|
||||||
* SAF ou un drain outbox est en cours, compteur d'ops en attente sinon, coche
|
|
||||||
* quand tout est poussé. Un appui ouvre la « liste des sync » (dernières ops).
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
fun SyncStatusBadge(
|
|
||||||
status: SyncViewModel.SyncStatus,
|
|
||||||
onClick: () -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
) {
|
|
||||||
val (accent, label, showSpinner) = when {
|
|
||||||
status.syncing -> {
|
|
||||||
Triple(SyncingAccent, stringResource(R.string.sync_syncing), true)
|
|
||||||
}
|
|
||||||
status.pending > 0 -> {
|
|
||||||
val label = if (status.pending == 1) {
|
|
||||||
stringResource(R.string.sync_pending_count_one)
|
|
||||||
} else {
|
|
||||||
stringResource(R.string.sync_pending_count, status.pending)
|
|
||||||
}
|
|
||||||
Triple(PendingAmber, label, false)
|
|
||||||
}
|
|
||||||
else -> Triple(
|
|
||||||
MaterialTheme.colorScheme.primary,
|
|
||||||
stringResource(R.string.sync_idle),
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val shape = RoundedCornerShape(percent = 50)
|
|
||||||
val tapLabel = stringResource(R.string.sync_tap_to_view)
|
|
||||||
|
|
||||||
Row(
|
|
||||||
modifier = modifier
|
|
||||||
.clip(shape)
|
|
||||||
.clickable(
|
|
||||||
role = Role.Button,
|
|
||||||
onClickLabel = tapLabel,
|
|
||||||
onClick = onClick,
|
|
||||||
)
|
|
||||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
|
||||||
) {
|
|
||||||
if (showSpinner) {
|
|
||||||
CircularProgressIndicator(
|
|
||||||
modifier = Modifier.size(12.dp),
|
|
||||||
strokeWidth = 2.dp,
|
|
||||||
color = accent,
|
|
||||||
)
|
|
||||||
} else if (status.pending > 0) {
|
|
||||||
Box(
|
|
||||||
modifier = Modifier
|
|
||||||
.size(14.dp)
|
|
||||||
.background(accent, CircleShape),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = status.pending.coerceAtMost(99).toString(),
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = Color.White,
|
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Filled.Check,
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = Modifier.size(12.dp),
|
|
||||||
tint = accent,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Text(
|
|
||||||
text = label,
|
|
||||||
style = MaterialTheme.typography.labelMedium,
|
|
||||||
fontWeight = FontWeight.Medium,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Composable prêt-à-poser dans un header : badge + dialogue « liste des sync ».
|
|
||||||
* Le dialogue est géré localement (état `showList`), aucun wiring externe.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
fun SyncStatusAction(
|
|
||||||
syncViewModel: SyncViewModel,
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
) {
|
|
||||||
val status by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
|
||||||
var showList by rememberSaveable { mutableStateOf(false) }
|
|
||||||
|
|
||||||
SyncStatusBadge(
|
|
||||||
status = status,
|
|
||||||
onClick = { showList = true },
|
|
||||||
modifier = modifier,
|
|
||||||
)
|
|
||||||
|
|
||||||
if (showList) {
|
|
||||||
SyncOperationsDialog(
|
|
||||||
status = status,
|
|
||||||
onDismiss = { showList = false },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
package com.kazier.mobile.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.kazier.mobile.ui.theme.KazierDimens
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bouton d'action vertical (icône + libellé `labelSmall` ellipsé) : tient
|
||||||
|
* sur 360dp là où des boutons horizontaux icône+texte seraient tronqués
|
||||||
|
* (exports du scan, ajouts du PdfBuilder).
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun VerticalActionButton(
|
||||||
|
icon: ImageVector,
|
||||||
|
label: String,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
enabled: Boolean = true,
|
||||||
|
outlined: Boolean = true,
|
||||||
|
) {
|
||||||
|
val content: @Composable () -> Unit = {
|
||||||
|
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
|
Icon(
|
||||||
|
imageVector = icon,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = label,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (outlined) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onClick,
|
||||||
|
enabled = enabled,
|
||||||
|
modifier = modifier.heightIn(min = KazierDimens.MinTouchTarget),
|
||||||
|
content = { content() },
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Button(
|
||||||
|
onClick = onClick,
|
||||||
|
enabled = enabled,
|
||||||
|
modifier = modifier.heightIn(min = KazierDimens.MinTouchTarget),
|
||||||
|
content = { content() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.Arrangement
|
|||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Visibility
|
import androidx.compose.material.icons.filled.Visibility
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
@@ -23,6 +22,7 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
|
import com.kazier.mobile.ui.theme.PillShape
|
||||||
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersViewModel
|
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersViewModel
|
||||||
|
|
||||||
/** Seuil au-delà duquel le badge affiche « 99+ » au lieu du compte exact. */
|
/** Seuil au-delà duquel le badge affiche « 99+ » au lieu du compte exact. */
|
||||||
@@ -47,7 +47,7 @@ fun WatchedFoldersBadge(
|
|||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.clip(RoundedCornerShape(percent = 50))
|
.clip(PillShape)
|
||||||
.clickable(
|
.clickable(
|
||||||
role = Role.Button,
|
role = Role.Button,
|
||||||
onClickLabel = contentDescription,
|
onClickLabel = contentDescription,
|
||||||
|
|||||||
@@ -9,20 +9,27 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
|||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
|
||||||
import androidx.compose.material.icons.filled.CheckCircle
|
import androidx.compose.material.icons.filled.CheckCircle
|
||||||
import androidx.compose.material.icons.filled.DocumentScanner
|
import androidx.compose.material.icons.filled.DocumentScanner
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material.icons.filled.Sync
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.FloatingActionButton
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SmallFloatingActionButton
|
import androidx.compose.material3.SmallFloatingActionButton
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
|
||||||
|
import androidx.compose.material3.pulltorefresh.pullToRefresh
|
||||||
|
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
@@ -32,9 +39,11 @@ import androidx.hilt.navigation.compose.hiltViewModel
|
|||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||||
|
import com.kazier.mobile.features.connection.ServerConnectionStatus
|
||||||
import com.kazier.mobile.features.sync.SyncViewModel
|
import com.kazier.mobile.features.sync.SyncViewModel
|
||||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
import com.kazier.mobile.ui.components.KazierCard
|
||||||
|
import com.kazier.mobile.ui.components.ReviewCtaCard
|
||||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||||
import com.kazier.mobile.ui.navigation.NavTab
|
import com.kazier.mobile.ui.navigation.NavTab
|
||||||
|
|
||||||
@@ -51,16 +60,27 @@ fun DashboardScreen(
|
|||||||
) {
|
) {
|
||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||||
val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle()
|
val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle()
|
||||||
|
val syncStatus by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
||||||
|
// Mode local : rien n'est poussé vers le serveur, la carte sync est inutile.
|
||||||
|
val isLocal = connectionStatus == ServerConnectionStatus.Local
|
||||||
|
val showSyncCard = !isLocal && (syncStatus.syncing || syncStatus.pending > 0 || syncStatus.failed > 0)
|
||||||
|
|
||||||
|
// Tirer-pour-actualiser = revérifier le serveur (review + file sont déjà
|
||||||
|
// temps réel via les flows, il n'y a rien d'autre à recharger ici).
|
||||||
|
var userRefresh by rememberSaveable { mutableStateOf(false) }
|
||||||
|
val isRefreshing = userRefresh && connectionStatus == ServerConnectionStatus.Checking
|
||||||
|
LaunchedEffect(connectionStatus) {
|
||||||
|
if (connectionStatus != ServerConnectionStatus.Checking) userRefresh = false
|
||||||
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = { Text(stringResource(R.string.dashboard)) },
|
title = { Text(stringResource(R.string.dashboard)) },
|
||||||
actions = {
|
actions = {
|
||||||
SyncStatusAction(syncViewModel = syncViewModel)
|
HeaderStatusAction(
|
||||||
ServerStatusBadge(
|
syncViewModel = syncViewModel,
|
||||||
status = connectionStatus,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
onClick = connectionStatusViewModel::checkNow,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -81,20 +101,43 @@ fun DashboardScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
) { padding ->
|
) { padding ->
|
||||||
Column(
|
val pullState = rememberPullToRefreshState()
|
||||||
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding)
|
.padding(padding)
|
||||||
|
.pullToRefresh(
|
||||||
|
state = pullState,
|
||||||
|
// Mode local : rien à revérifier — geste désactivé, sinon
|
||||||
|
// l'indicateur resterait coincé (jamais de cycle vrai→faux).
|
||||||
|
enabled = !isLocal,
|
||||||
|
isRefreshing = isRefreshing,
|
||||||
|
onRefresh = {
|
||||||
|
userRefresh = true
|
||||||
|
connectionStatusViewModel.checkNow()
|
||||||
|
},
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
.padding(16.dp),
|
.padding(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
if (unprocessed > 0) {
|
if (unprocessed > 0) {
|
||||||
ReviewCard(
|
ReviewCtaCard(
|
||||||
count = unprocessed,
|
count = unprocessed,
|
||||||
onClick = onOpenReview,
|
onClick = onOpenReview,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
} else {
|
}
|
||||||
|
if (showSyncCard) {
|
||||||
|
SyncSummaryCard(
|
||||||
|
status = syncStatus,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (unprocessed == 0 && !showSyncCard) {
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
@@ -119,38 +162,70 @@ fun DashboardScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
PullToRefreshDefaults.Indicator(
|
||||||
|
state = pullState,
|
||||||
|
isRefreshing = isRefreshing,
|
||||||
|
modifier = Modifier.align(Alignment.TopCenter),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résumé de la file de synchro (état déjà exposé par [SyncViewModel]) :
|
||||||
|
* marche en cours, opérations en attente, échecs — sans nouveau ViewModel.
|
||||||
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
private fun ReviewCard(
|
private fun SyncSummaryCard(
|
||||||
count: Int,
|
status: SyncViewModel.SyncStatus,
|
||||||
onClick: () -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
Card(onClick = onClick, modifier = modifier) {
|
KazierCard(modifier = modifier) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(20.dp),
|
modifier = Modifier.padding(20.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
|
if (status.syncing) {
|
||||||
|
CircularProgressIndicator(modifier = Modifier.size(28.dp))
|
||||||
|
} else {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Filled.Sync,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(28.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.dashboard_review_title, count),
|
text = stringResource(R.string.dashboard_sync_title),
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
)
|
)
|
||||||
|
if (status.syncing) {
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.dashboard_review_hint),
|
text = stringResource(R.string.sync_syncing),
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
modifier = Modifier.padding(top = 4.dp),
|
modifier = Modifier.padding(top = 4.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Icon(
|
if (status.pending > 0) {
|
||||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
Text(
|
||||||
contentDescription = null,
|
text = stringResource(R.string.sync_pending_count, status.pending),
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.padding(top = 4.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (status.failed > 0) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.sync_summary_failed, status.failed),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
modifier = Modifier.padding(top = 4.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+71
-78
@@ -18,7 +18,6 @@ import androidx.compose.foundation.pager.HorizontalPager
|
|||||||
import androidx.compose.foundation.pager.rememberPagerState
|
import androidx.compose.foundation.pager.rememberPagerState
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
@@ -29,12 +28,12 @@ import androidx.compose.material.icons.filled.Close
|
|||||||
import androidx.compose.material.icons.filled.Delete
|
import androidx.compose.material.icons.filled.Delete
|
||||||
import androidx.compose.material.icons.filled.DocumentScanner
|
import androidx.compose.material.icons.filled.DocumentScanner
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material3.ButtonDefaults
|
||||||
import androidx.compose.material3.CardDefaults
|
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.DropdownMenu
|
import androidx.compose.material3.DropdownMenu
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.FilledTonalButton
|
||||||
import androidx.compose.material3.FloatingActionButton
|
import androidx.compose.material3.FloatingActionButton
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
@@ -70,7 +69,6 @@ import androidx.compose.ui.res.stringResource
|
|||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import androidx.core.view.WindowCompat
|
import androidx.core.view.WindowCompat
|
||||||
import androidx.core.view.WindowInsetsCompat
|
import androidx.core.view.WindowInsetsCompat
|
||||||
import androidx.core.view.WindowInsetsControllerCompat
|
import androidx.core.view.WindowInsetsControllerCompat
|
||||||
@@ -86,14 +84,17 @@ import com.kazier.mobile.features.ocr.OcrViewModel
|
|||||||
import com.kazier.mobile.features.saf.FileDeleter
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
import com.kazier.mobile.features.sync.SyncViewModel
|
import com.kazier.mobile.features.sync.SyncViewModel
|
||||||
import com.kazier.mobile.ui.components.DeleteConfirmDialog
|
import com.kazier.mobile.ui.components.DeleteConfirmDialog
|
||||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
import com.kazier.mobile.ui.components.KazierCard
|
||||||
import com.kazier.mobile.ui.components.categoryValue
|
import com.kazier.mobile.ui.components.categoryValue
|
||||||
|
import com.kazier.mobile.ui.components.formatFileSize
|
||||||
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
||||||
import com.kazier.mobile.ui.document.content.ImageViewer
|
import com.kazier.mobile.ui.document.content.ImageViewer
|
||||||
import com.kazier.mobile.ui.document.content.PdfFocusViewer
|
import com.kazier.mobile.ui.document.content.PdfFocusViewer
|
||||||
import com.kazier.mobile.ui.document.content.TextFocusViewer
|
import com.kazier.mobile.ui.document.content.TextFocusViewer
|
||||||
import com.kazier.mobile.ui.document.content.ZoomableContent
|
import com.kazier.mobile.ui.document.content.ZoomableContent
|
||||||
|
import com.kazier.mobile.ui.theme.PillShape
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
@@ -123,7 +124,6 @@ fun DocumentViewerScreen(
|
|||||||
val documents by viewModel.documents.collectAsStateWithLifecycle()
|
val documents by viewModel.documents.collectAsStateWithLifecycle()
|
||||||
val viewerState by viewModel.uiState.collectAsStateWithLifecycle()
|
val viewerState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val ocrState by ocrViewModel.uiState.collectAsStateWithLifecycle()
|
val ocrState by ocrViewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
|
||||||
val pagerState = rememberPagerState(pageCount = { documents.size })
|
val pagerState = rememberPagerState(pageCount = { documents.size })
|
||||||
|
|
||||||
// M30 : survit à la rotation (`rememberSaveable`) — `savedPage` mémorise
|
// M30 : survit à la rotation (`rememberSaveable`) — `savedPage` mémorise
|
||||||
@@ -197,7 +197,7 @@ fun DocumentViewerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Confirmation avant suppression d'un document déjà traité.
|
// Confirmation avant suppression d'un document déjà traité.
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
var fullscreen by rememberSaveable { mutableStateOf(false) }
|
var fullscreen by rememberSaveable { mutableStateOf(false) }
|
||||||
@@ -252,10 +252,9 @@ fun DocumentViewerScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
actions = {
|
actions = {
|
||||||
SyncStatusAction(syncViewModel = syncViewModel)
|
HeaderStatusAction(
|
||||||
ServerStatusBadge(
|
syncViewModel = syncViewModel,
|
||||||
status = connectionStatus,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
onClick = connectionStatusViewModel::checkNow,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -276,6 +275,17 @@ fun DocumentViewerScreen(
|
|||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding),
|
.padding(padding),
|
||||||
) {
|
) {
|
||||||
|
if (documents.isEmpty()) {
|
||||||
|
// Chargement initial : le pager serait vide sans repère.
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.weight(1f),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
HorizontalPager(
|
HorizontalPager(
|
||||||
state = pagerState,
|
state = pagerState,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -293,6 +303,7 @@ fun DocumentViewerScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// Barre d'action fixe pilotée par le document affiché : garder
|
// Barre d'action fixe pilotée par le document affiché : garder
|
||||||
// ou supprimer un document en attente de review, ou supprimer
|
// ou supprimer un document en attente de review, ou supprimer
|
||||||
// (local / cloud / les deux) un document déjà traité.
|
// (local / cloud / les deux) un document déjà traité.
|
||||||
@@ -388,7 +399,8 @@ private fun FocusDocumentReader(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Cadre commun du mode focus : fond noir plein écran, un tap (l'indicatrice de
|
* Cadre commun du mode focus : fond noir plein écran, un tap (l'indicatrice de
|
||||||
* position est optionnelle) quitte le mode.
|
* position est optionnelle) quitte le mode. Un hint discret « toucher pour
|
||||||
|
* quitter » s'affiche 3 s à l'entrée pour lever l'ambiguïté tap / pinch.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
private fun FocusScaffold(
|
private fun FocusScaffold(
|
||||||
@@ -398,6 +410,11 @@ private fun FocusScaffold(
|
|||||||
position: String? = null,
|
position: String? = null,
|
||||||
content: @Composable () -> Unit,
|
content: @Composable () -> Unit,
|
||||||
) {
|
) {
|
||||||
|
var showHint by remember(file.resourceId) { mutableStateOf(true) }
|
||||||
|
LaunchedEffect(file.resourceId) {
|
||||||
|
delay(3_000)
|
||||||
|
showHint = false
|
||||||
|
}
|
||||||
Box(
|
Box(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
@@ -407,12 +424,28 @@ private fun FocusScaffold(
|
|||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
content()
|
content()
|
||||||
|
if (showHint) {
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier
|
||||||
|
.align(Alignment.TopCenter)
|
||||||
|
.padding(top = 16.dp),
|
||||||
|
shape = PillShape,
|
||||||
|
color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.focus_tap_to_exit),
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.inverseOnSurface,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
if (position != null) {
|
if (position != null) {
|
||||||
Surface(
|
Surface(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.BottomCenter)
|
.align(Alignment.BottomCenter)
|
||||||
.padding(bottom = 16.dp),
|
.padding(bottom = 16.dp),
|
||||||
shape = RoundedCornerShape(percent = 50),
|
shape = PillShape,
|
||||||
color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f),
|
color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f),
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
@@ -549,14 +582,11 @@ private fun DocumentViewerPage(
|
|||||||
|
|
||||||
Spacer(Modifier.height(16.dp))
|
Spacer(Modifier.height(16.dp))
|
||||||
|
|
||||||
Card(
|
KazierCard(modifier = Modifier.fillMaxWidth()) {
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
|
||||||
) {
|
|
||||||
Column(modifier = Modifier
|
Column(modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(16.dp)) {
|
.padding(16.dp)) {
|
||||||
MetadataRow(stringResource(R.string.document_size), formatSize(file.size))
|
MetadataRow(stringResource(R.string.document_size), formatFileSize(file.size))
|
||||||
MetadataRow(stringResource(R.string.document_type), fileTypeLabel(file))
|
MetadataRow(stringResource(R.string.document_type), fileTypeLabel(file))
|
||||||
MetadataRow(stringResource(R.string.document_added_at), formatDateTime(file.addedAt))
|
MetadataRow(stringResource(R.string.document_added_at), formatDateTime(file.addedAt))
|
||||||
file.lastModified?.let { lastModified ->
|
file.lastModified?.let { lastModified ->
|
||||||
@@ -599,7 +629,7 @@ private fun DocumentActionBar(
|
|||||||
) {
|
) {
|
||||||
if (pendingReview) {
|
if (pendingReview) {
|
||||||
Surface(
|
Surface(
|
||||||
shape = RoundedCornerShape(percent = 50),
|
shape = PillShape,
|
||||||
color = MaterialTheme.colorScheme.secondaryContainer,
|
color = MaterialTheme.colorScheme.secondaryContainer,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
@@ -610,7 +640,10 @@ private fun DocumentActionBar(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(12.dp))
|
Spacer(Modifier.height(12.dp))
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(48.dp)) {
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterHorizontally),
|
||||||
|
) {
|
||||||
DocumentActionButton(
|
DocumentActionButton(
|
||||||
icon = Icons.Filled.Close,
|
icon = Icons.Filled.Close,
|
||||||
contentDescription = stringResource(R.string.review_delete),
|
contentDescription = stringResource(R.string.review_delete),
|
||||||
@@ -653,7 +686,7 @@ private fun DocumentActionBar(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Bouton « OCR » — même gabarit que le menu Supprimer (Surface 88×48). */
|
/** Bouton « OCR » M3 — gabarit adaptatif (plus de Surface 88×48 fixe). */
|
||||||
@Composable
|
@Composable
|
||||||
private fun DocumentOcrButton(
|
private fun DocumentOcrButton(
|
||||||
label: Int,
|
label: Int,
|
||||||
@@ -661,38 +694,23 @@ private fun DocumentOcrButton(
|
|||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
val tint = if (enabled) MaterialTheme.colorScheme.primary
|
val labelText = stringResource(label)
|
||||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
FilledTonalButton(
|
||||||
|
onClick = onClick,
|
||||||
Surface(
|
|
||||||
onClick = { if (enabled) onClick() },
|
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
shape = RoundedCornerShape(20.dp),
|
|
||||||
color = if (enabled) MaterialTheme.colorScheme.primaryContainer
|
|
||||||
else MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
) {
|
) {
|
||||||
Box(
|
|
||||||
modifier = Modifier.size(width = 88.dp, height = 48.dp),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.DocumentScanner,
|
imageVector = Icons.Filled.DocumentScanner,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = tint,
|
|
||||||
modifier = Modifier.size(20.dp),
|
modifier = Modifier.size(20.dp),
|
||||||
)
|
)
|
||||||
|
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(label),
|
text = labelText,
|
||||||
color = tint,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -815,45 +833,34 @@ private fun DocumentDeleteMenu(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
val modes = deleteModesFor(file)
|
val modes = deleteModesFor(file)
|
||||||
var expanded by remember { mutableStateOf(false) }
|
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||||
val tint = if (enabled) MaterialTheme.colorScheme.error
|
val deleteLabel = stringResource(R.string.delete)
|
||||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
|
||||||
|
|
||||||
Box(modifier = modifier) {
|
Box(modifier = modifier) {
|
||||||
Surface(
|
FilledTonalButton(
|
||||||
onClick = { if (enabled) expanded = true },
|
onClick = { expanded = true },
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
shape = RoundedCornerShape(20.dp),
|
colors = ButtonDefaults.filledTonalButtonColors(
|
||||||
color = if (enabled) MaterialTheme.colorScheme.errorContainer
|
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||||
else MaterialTheme.colorScheme.surfaceVariant,
|
contentColor = MaterialTheme.colorScheme.onErrorContainer,
|
||||||
|
),
|
||||||
) {
|
) {
|
||||||
Box(
|
|
||||||
modifier = Modifier.size(width = 88.dp, height = 48.dp),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.Delete,
|
imageVector = Icons.Filled.Delete,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = tint,
|
|
||||||
modifier = Modifier.size(20.dp),
|
modifier = Modifier.size(20.dp),
|
||||||
)
|
)
|
||||||
|
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.delete),
|
text = deleteLabel,
|
||||||
color = tint,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
)
|
)
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.ArrowDropDown,
|
imageVector = Icons.Filled.ArrowDropDown,
|
||||||
contentDescription = null,
|
contentDescription = deleteLabel,
|
||||||
tint = tint,
|
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
DropdownMenu(
|
DropdownMenu(
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
@@ -964,17 +971,3 @@ private fun formatDateTime(millis: Long): String {
|
|||||||
val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(dateTime)
|
val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(dateTime)
|
||||||
return "$day $time"
|
return "$day $time"
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Miroir de `formatSize` (app/index.tsx). */
|
|
||||||
@Composable
|
|
||||||
private fun formatSize(bytes: Long): String {
|
|
||||||
if (bytes < 1_024) {
|
|
||||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
|
||||||
}
|
|
||||||
if (bytes < 1_024 * 1_024) {
|
|
||||||
val kb = bytes / 1_024f
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
|
||||||
}
|
|
||||||
val mb = bytes / (1_024f * 1_024f)
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
|
||||||
}
|
|
||||||
+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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+366
@@ -0,0 +1,366 @@
|
|||||||
|
package com.kazier.mobile.ui.document.content
|
||||||
|
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.pdf.PdfRenderer
|
||||||
|
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, 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 : le `PdfRenderer` système exige un descripteur de fichier —
|
||||||
|
* les octets sont écrits dans un fichier temporaire du `cacheDir`
|
||||||
|
* (`stream-<resourceId>.pdf`), supprimé à la sortie. Première page affichée
|
||||||
|
* (aperçu streaming, pas de navigation complète).
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun RemotePdfViewer(file: FileEntity, bytes: ByteArray, modifier: Modifier = Modifier) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
var tmpFile by remember(file.resourceId) { mutableStateOf<File?>(null) }
|
||||||
|
var loadFailed by remember(file.resourceId) { mutableStateOf(false) }
|
||||||
|
|
||||||
|
LaunchedEffect(file.resourceId, bytes) {
|
||||||
|
loadFailed = false
|
||||||
|
tmpFile = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val tmp = File(context.cacheDir, "stream-${file.resourceId}.pdf")
|
||||||
|
tmp.writeBytes(bytes)
|
||||||
|
tmp
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
if (tmpFile == null) loadFailed = 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 {
|
||||||
|
loadFailed || (tmp != null && !tmp.exists()) -> Text(
|
||||||
|
text = stringResource(R.string.document_cannot_read),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
modifier = modifier,
|
||||||
|
)
|
||||||
|
tmp == null -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
}
|
||||||
|
else -> RemotePdfFirstPage(tmp = tmp, modifier = modifier)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RemotePdfFirstPage(tmp: File, modifier: Modifier = Modifier) {
|
||||||
|
var bitmap by remember(tmp.absolutePath) { mutableStateOf<android.graphics.Bitmap?>(null) }
|
||||||
|
var failed by remember(tmp.absolutePath) { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(tmp.absolutePath) {
|
||||||
|
failed = false
|
||||||
|
bitmap = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val pfd = ParcelFileDescriptor.open(tmp, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||||
|
val renderer = PdfRenderer(pfd)
|
||||||
|
try {
|
||||||
|
if (renderer.pageCount <= 0) return@runCatching null
|
||||||
|
val page = renderer.openPage(0)
|
||||||
|
try {
|
||||||
|
val width = (page.width * 2f).toInt().coerceIn(1, 4096)
|
||||||
|
val height = (page.height * 2f).toInt().coerceIn(1, 4096)
|
||||||
|
val bmp = android.graphics.Bitmap.createBitmap(
|
||||||
|
width, height, android.graphics.Bitmap.Config.ARGB_8888,
|
||||||
|
)
|
||||||
|
page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||||
|
bmp
|
||||||
|
} finally {
|
||||||
|
page.close()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
renderer.close()
|
||||||
|
pfd.close()
|
||||||
|
}
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
if (bitmap == null) failed = true
|
||||||
|
}
|
||||||
|
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
when {
|
||||||
|
bitmap != null -> Image(
|
||||||
|
bitmap = bitmap!!.asImageBitmap(),
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
|
failed -> Text(
|
||||||
|
text = stringResource(R.string.document_cannot_read),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
)
|
||||||
|
else -> CircularProgressIndicator()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val REMOTE_TEXT_MAX = 512 * 1024
|
||||||
+47
-55
@@ -2,6 +2,7 @@ package com.kazier.mobile.ui.folderdetail
|
|||||||
|
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.combinedClickable
|
import androidx.compose.foundation.combinedClickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -20,14 +21,12 @@ import androidx.compose.material.icons.filled.Close
|
|||||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||||
import androidx.compose.material.icons.filled.Folder
|
import androidx.compose.material.icons.filled.Folder
|
||||||
import androidx.compose.material.icons.filled.MoreVert
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
import androidx.compose.material.icons.filled.Refresh
|
|
||||||
import androidx.compose.material3.Card
|
|
||||||
import androidx.compose.material3.CardDefaults
|
|
||||||
import androidx.compose.material3.DropdownMenu
|
import androidx.compose.material3.DropdownMenu
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SnackbarHost
|
import androidx.compose.material3.SnackbarHost
|
||||||
@@ -44,6 +43,7 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
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
|
||||||
@@ -58,11 +58,12 @@ import com.kazier.mobile.ui.components.FilePendingReviewBadge
|
|||||||
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
||||||
import com.kazier.mobile.ui.components.FileThumbnail
|
import com.kazier.mobile.ui.components.FileThumbnail
|
||||||
import com.kazier.mobile.ui.components.FolderNameDialog
|
import com.kazier.mobile.ui.components.FolderNameDialog
|
||||||
|
import com.kazier.mobile.ui.components.KazierCard
|
||||||
|
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||||
import com.kazier.mobile.ui.components.MoveFolderPickerDialog
|
import com.kazier.mobile.ui.components.MoveFolderPickerDialog
|
||||||
import com.kazier.mobile.ui.components.SelectionState
|
import com.kazier.mobile.ui.components.SelectionState
|
||||||
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
||||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
import com.kazier.mobile.ui.components.formatFileSize
|
||||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
|
||||||
import com.kazier.mobile.ui.components.rememberSelectionState
|
import com.kazier.mobile.ui.components.rememberSelectionState
|
||||||
import com.kazier.mobile.features.saf.FileDeleter
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
import com.kazier.mobile.ui.components.DeleteConfirmDialog
|
import com.kazier.mobile.ui.components.DeleteConfirmDialog
|
||||||
@@ -74,7 +75,6 @@ import com.kazier.mobile.ui.auth.AuthState
|
|||||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||||
import com.kazier.mobile.ui.share.ShareBottomSheet
|
import com.kazier.mobile.ui.share.ShareBottomSheet
|
||||||
import com.kazier.mobile.ui.share.ShareViewModel
|
import com.kazier.mobile.ui.share.ShareViewModel
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -92,7 +92,6 @@ fun FolderDetailScreen(
|
|||||||
) {
|
) {
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
|
||||||
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val selection = rememberSelectionState()
|
val selection = rememberSelectionState()
|
||||||
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
@@ -101,10 +100,10 @@ fun FolderDetailScreen(
|
|||||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
var showShareSheet by rememberSaveable { mutableStateOf(false) }
|
var showShareSheet by rememberSaveable { mutableStateOf(false) }
|
||||||
var showMoreMenu by rememberSaveable { mutableStateOf(false) }
|
var showMoreMenu by rememberSaveable { mutableStateOf(false) }
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
var pendingDeleteReview by rememberSaveable { mutableStateOf<DeleteReview?>(null) }
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
val deletedLabel = stringResource(R.string.delete)
|
val deletedLabel = stringResource(R.string.delete_success)
|
||||||
|
|
||||||
// M33 : le gate `canShare` dépend du token — recalculé au login/logout.
|
// M33 : le gate `canShare` dépend du token — recalculé au login/logout.
|
||||||
LaunchedEffect(authState) {
|
LaunchedEffect(authState) {
|
||||||
@@ -187,10 +186,9 @@ fun FolderDetailScreen(
|
|||||||
contentDescription = stringResource(R.string.create_folder),
|
contentDescription = stringResource(R.string.create_folder),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
SyncStatusAction(syncViewModel = syncViewModel)
|
HeaderStatusAction(
|
||||||
ServerStatusBadge(
|
syncViewModel = syncViewModel,
|
||||||
status = connectionStatus,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
onClick = connectionStatusViewModel::checkNow,
|
|
||||||
)
|
)
|
||||||
Box {
|
Box {
|
||||||
IconButton(onClick = { showMoreMenu = true }) {
|
IconButton(onClick = { showMoreMenu = true }) {
|
||||||
@@ -330,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,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -364,6 +363,24 @@ private fun FolderDetailContent(
|
|||||||
contentPadding = PaddingValues(16.dp),
|
contentPadding = PaddingValues(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
|
if (isRefreshing) {
|
||||||
|
item(key = "refreshing") {
|
||||||
|
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (error != null) {
|
||||||
|
item(key = "error") {
|
||||||
|
Text(
|
||||||
|
text = error,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 8.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
items(subFolders, key = { it.resourceId }) { folder ->
|
items(subFolders, key = { it.resourceId }) { folder ->
|
||||||
FolderRow(folder, onClick = { onOpenFolder(folder.resourceId) })
|
FolderRow(folder, onClick = { onOpenFolder(folder.resourceId) })
|
||||||
}
|
}
|
||||||
@@ -389,28 +406,19 @@ private fun FolderDetailContent(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (error != null) {
|
|
||||||
item(key = "error") {
|
|
||||||
Text(
|
|
||||||
text = error,
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.error,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(vertical = 8.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun FolderRow(folder: FolderEntity, onClick: () -> Unit) {
|
private fun FolderRow(folder: FolderEntity, onClick: () -> Unit) {
|
||||||
Card(
|
KazierCard(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable(
|
||||||
|
role = Role.Button,
|
||||||
|
onClickLabel = folder.name,
|
||||||
onClick = onClick,
|
onClick = onClick,
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
),
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -421,7 +429,7 @@ private fun FolderRow(folder: FolderEntity, onClick: () -> Unit) {
|
|||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.Folder,
|
imageVector = Icons.Filled.Folder,
|
||||||
contentDescription = null,
|
contentDescription = folder.name,
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier.size(28.dp),
|
modifier = Modifier.size(28.dp),
|
||||||
)
|
)
|
||||||
@@ -450,9 +458,7 @@ private fun FileRow(
|
|||||||
onOpenDocument: () -> Unit,
|
onOpenDocument: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val selected = file.resourceId in selection.ids
|
val selected = file.resourceId in selection.ids
|
||||||
Card(
|
KazierCard(
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.combinedClickable(
|
.combinedClickable(
|
||||||
@@ -479,7 +485,7 @@ private fun FileRow(
|
|||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = formatSize(file.size),
|
text = formatFileSize(file.size),
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
@@ -498,17 +504,3 @@ private fun FileRow(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Miroir de `formatSize` (app/folder/[id].tsx). */
|
|
||||||
@Composable
|
|
||||||
private fun formatSize(bytes: Long): String {
|
|
||||||
if (bytes < 1_024) {
|
|
||||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
|
||||||
}
|
|
||||||
if (bytes < 1_024 * 1_024) {
|
|
||||||
val kb = bytes / 1_024f
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
|
||||||
}
|
|
||||||
val mb = bytes / (1_024f * 1_024f)
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
|
||||||
}
|
|
||||||
+67
-67
@@ -5,7 +5,6 @@ import android.net.Uri
|
|||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.foundation.BorderStroke
|
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
import androidx.compose.foundation.combinedClickable
|
import androidx.compose.foundation.combinedClickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
@@ -23,7 +22,6 @@ import androidx.compose.foundation.layout.width
|
|||||||
import androidx.compose.foundation.layout.widthIn
|
import androidx.compose.foundation.layout.widthIn
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Add
|
import androidx.compose.material.icons.filled.Add
|
||||||
import androidx.compose.material.icons.filled.ArrowUpward
|
import androidx.compose.material.icons.filled.ArrowUpward
|
||||||
@@ -34,12 +32,9 @@ import androidx.compose.material.icons.filled.DocumentScanner
|
|||||||
import androidx.compose.material.icons.filled.EditNote
|
import androidx.compose.material.icons.filled.EditNote
|
||||||
import androidx.compose.material.icons.filled.Folder
|
import androidx.compose.material.icons.filled.Folder
|
||||||
import androidx.compose.material.icons.filled.MoreVert
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
import androidx.compose.material.icons.filled.Refresh
|
|
||||||
import androidx.compose.material.icons.filled.Share
|
import androidx.compose.material.icons.filled.Share
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.Card
|
|
||||||
import androidx.compose.material3.CardDefaults
|
|
||||||
import androidx.compose.material3.DropdownMenu
|
import androidx.compose.material3.DropdownMenu
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
@@ -57,6 +52,9 @@ import androidx.compose.material3.Surface
|
|||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
|
||||||
|
import androidx.compose.material3.pulltorefresh.pullToRefresh
|
||||||
|
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -66,7 +64,6 @@ 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.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
@@ -74,7 +71,6 @@ 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.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
@@ -94,11 +90,12 @@ import com.kazier.mobile.ui.components.FilePendingReviewBadge
|
|||||||
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
||||||
import com.kazier.mobile.ui.components.FileThumbnail
|
import com.kazier.mobile.ui.components.FileThumbnail
|
||||||
import com.kazier.mobile.ui.components.FolderNameDialog
|
import com.kazier.mobile.ui.components.FolderNameDialog
|
||||||
|
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||||
|
import com.kazier.mobile.ui.components.KazierCard
|
||||||
|
import com.kazier.mobile.ui.components.ReviewCtaCard
|
||||||
import com.kazier.mobile.ui.components.SelectionState
|
import com.kazier.mobile.ui.components.SelectionState
|
||||||
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
||||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
import com.kazier.mobile.ui.components.formatFileSize
|
||||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
|
||||||
import com.kazier.mobile.ui.components.rememberSelectionState
|
import com.kazier.mobile.ui.components.rememberSelectionState
|
||||||
import com.kazier.mobile.ui.components.reviewDelete
|
import com.kazier.mobile.ui.components.reviewDelete
|
||||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||||
@@ -110,15 +107,16 @@ import com.kazier.mobile.ui.auth.AuthState
|
|||||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||||
import com.kazier.mobile.ui.share.ShareBottomSheet
|
import com.kazier.mobile.ui.share.ShareBottomSheet
|
||||||
import com.kazier.mobile.ui.share.ShareViewModel
|
import com.kazier.mobile.ui.share.ShareViewModel
|
||||||
|
import com.kazier.mobile.ui.theme.NavItemShape
|
||||||
|
import com.kazier.mobile.ui.theme.NavPillShape
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
/** Dossier cible du partage : id + nom affiché dans le sheet. */
|
/** Dossier cible du partage : id + nom affiché dans le sheet. */
|
||||||
private data class ShareTarget(
|
private data class ShareTarget(
|
||||||
val resourceId: String,
|
val resourceId: String,
|
||||||
val name: String,
|
val name: String,
|
||||||
)
|
) : java.io.Serializable
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -128,12 +126,14 @@ fun FolderListScreen(
|
|||||||
onOpenDocument: (String) -> Unit,
|
onOpenDocument: (String) -> Unit,
|
||||||
onBuildPdf: (List<String>) -> Unit,
|
onBuildPdf: (List<String>) -> Unit,
|
||||||
onOpenScan: () -> Unit,
|
onOpenScan: () -> Unit,
|
||||||
|
onOpenReview: () -> Unit,
|
||||||
syncViewModel: SyncViewModel,
|
syncViewModel: SyncViewModel,
|
||||||
connectionStatusViewModel: ConnectionStatusViewModel,
|
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||||
authViewModel: AuthViewModel,
|
authViewModel: AuthViewModel,
|
||||||
viewModel: FolderListViewModel = hiltViewModel(),
|
viewModel: FolderListViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
|
val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle()
|
||||||
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||||
val shareViewModel: ShareViewModel = hiltViewModel()
|
val shareViewModel: ShareViewModel = hiltViewModel()
|
||||||
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
||||||
@@ -145,13 +145,13 @@ fun FolderListScreen(
|
|||||||
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
var pendingDeleteReview by rememberSaveable { mutableStateOf<DeleteReview?>(null) }
|
||||||
var pendingFolderIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
var pendingFolderIds by rememberSaveable { mutableStateOf<List<String>>(emptyList()) }
|
||||||
var pendingFileIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
var pendingFileIds by rememberSaveable { mutableStateOf<List<String>>(emptyList()) }
|
||||||
var shareTarget by remember { mutableStateOf<ShareTarget?>(null) }
|
var shareTarget by rememberSaveable { mutableStateOf<ShareTarget?>(null) }
|
||||||
var showShareMenu by rememberSaveable { mutableStateOf(false) }
|
var showShareMenu by rememberSaveable { mutableStateOf(false) }
|
||||||
var shareEnabled by remember { mutableStateOf(false) }
|
var shareEnabled by rememberSaveable { mutableStateOf(false) }
|
||||||
var showCreateMenu by rememberSaveable { mutableStateOf(false) }
|
var showCreateMenu by rememberSaveable { mutableStateOf(false) }
|
||||||
var showNoteDialog by rememberSaveable { mutableStateOf(false) }
|
var showNoteDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
@@ -203,7 +203,7 @@ fun FolderListScreen(
|
|||||||
|
|
||||||
LaunchedEffect(uiState.deleteSuccess) {
|
LaunchedEffect(uiState.deleteSuccess) {
|
||||||
if (uiState.deleteSuccess) {
|
if (uiState.deleteSuccess) {
|
||||||
snackbarHostState.showSnackbar(context.getString(R.string.delete))
|
snackbarHostState.showSnackbar(context.getString(R.string.delete_success))
|
||||||
viewModel.clearDeleteSuccess()
|
viewModel.clearDeleteSuccess()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -294,14 +294,10 @@ fun FolderListScreen(
|
|||||||
},
|
},
|
||||||
actions = {
|
actions = {
|
||||||
if (!uiState.moveMode && !selection.active) {
|
if (!uiState.moveMode && !selection.active) {
|
||||||
SyncStatusAction(syncViewModel = syncViewModel)
|
HeaderStatusAction(
|
||||||
ServerStatusBadge(
|
syncViewModel = syncViewModel,
|
||||||
status = connectionStatus,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
onClick = connectionStatusViewModel::checkNow,
|
|
||||||
)
|
)
|
||||||
IconButton(onClick = viewModel::refresh) {
|
|
||||||
Icon(Icons.Filled.Refresh, contentDescription = stringResource(R.string.refresh))
|
|
||||||
}
|
|
||||||
if (uiState.view == HomeView.FOLDERS && connectionStatus != ServerConnectionStatus.Local) {
|
if (uiState.view == HomeView.FOLDERS && connectionStatus != ServerConnectionStatus.Local) {
|
||||||
Box {
|
Box {
|
||||||
IconButton(onClick = { showShareMenu = true }) {
|
IconButton(onClick = { showShareMenu = true }) {
|
||||||
@@ -460,11 +456,30 @@ fun FolderListScreen(
|
|||||||
},
|
},
|
||||||
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
|
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
|
||||||
) { padding ->
|
) { padding ->
|
||||||
Column(
|
// Mode local : le refresh serveur est no-op — geste désactivé, sinon
|
||||||
|
// l'indicateur resterait coincé (jamais de cycle vrai→faux).
|
||||||
|
val pullState = rememberPullToRefreshState()
|
||||||
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.padding(padding)
|
.padding(padding)
|
||||||
.fillMaxSize(),
|
.fillMaxSize()
|
||||||
|
.pullToRefresh(
|
||||||
|
state = pullState,
|
||||||
|
enabled = connectionStatus != ServerConnectionStatus.Local,
|
||||||
|
isRefreshing = uiState.isRefreshing,
|
||||||
|
onRefresh = viewModel::refresh,
|
||||||
|
),
|
||||||
) {
|
) {
|
||||||
|
Column(modifier = Modifier.fillMaxSize()) {
|
||||||
|
if (unprocessed > 0 && !selection.active && !uiState.moveMode) {
|
||||||
|
ReviewCtaCard(
|
||||||
|
count = unprocessed,
|
||||||
|
onClick = onOpenReview,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(start = 16.dp, end = 16.dp, top = 12.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
if (!selection.active) {
|
if (!selection.active) {
|
||||||
HomeViewSelector(
|
HomeViewSelector(
|
||||||
selected = uiState.view,
|
selected = uiState.view,
|
||||||
@@ -496,6 +511,12 @@ fun FolderListScreen(
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
PullToRefreshDefaults.Indicator(
|
||||||
|
state = pullState,
|
||||||
|
isRefreshing = uiState.isRefreshing,
|
||||||
|
modifier = Modifier.align(Alignment.TopCenter),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (showCreateDialog) {
|
if (showCreateDialog) {
|
||||||
@@ -564,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,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -595,7 +617,7 @@ private fun HomeViewSelector(
|
|||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Surface(
|
Surface(
|
||||||
shape = RoundedCornerShape(30.dp),
|
shape = NavPillShape,
|
||||||
color = MaterialTheme.colorScheme.surface,
|
color = MaterialTheme.colorScheme.surface,
|
||||||
shadowElevation = 8.dp,
|
shadowElevation = 8.dp,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -642,7 +664,7 @@ private fun ViewSegment(
|
|||||||
Surface(
|
Surface(
|
||||||
onClick = onClick,
|
onClick = onClick,
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
shape = RoundedCornerShape(20.dp),
|
shape = NavItemShape,
|
||||||
color = if (selected) MaterialTheme.colorScheme.primaryContainer
|
color = if (selected) MaterialTheme.colorScheme.primaryContainer
|
||||||
else MaterialTheme.colorScheme.surface,
|
else MaterialTheme.colorScheme.surface,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
@@ -656,14 +678,14 @@ private fun ViewSegment(
|
|||||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = icon,
|
imageVector = icon,
|
||||||
contentDescription = null,
|
contentDescription = label,
|
||||||
tint = tint,
|
tint = tint,
|
||||||
modifier = Modifier.size(22.dp),
|
modifier = Modifier.size(22.dp),
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = label,
|
text = label,
|
||||||
color = tint,
|
color = tint,
|
||||||
fontSize = 11.sp,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
|
fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
|
||||||
@@ -866,7 +888,7 @@ private fun FolderBrowserContent(
|
|||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(top = 8.dp, bottom = 4.dp),
|
.padding(top = 8.dp, bottom = 4.dp),
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = null)
|
Icon(Icons.Filled.CreateNewFolder, contentDescription = stringResource(R.string.create_folder))
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text(stringResource(R.string.create_folder))
|
Text(stringResource(R.string.create_folder))
|
||||||
}
|
}
|
||||||
@@ -1006,9 +1028,7 @@ private fun FolderRow(
|
|||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val selected = folder.resourceId in selection.ids
|
val selected = folder.resourceId in selection.ids
|
||||||
Card(
|
KazierCard(
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(bottom = 8.dp)
|
.padding(bottom = 8.dp)
|
||||||
@@ -1030,7 +1050,7 @@ private fun FolderRow(
|
|||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.Folder,
|
imageVector = Icons.Filled.Folder,
|
||||||
contentDescription = null,
|
contentDescription = folder.name,
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier.size(28.dp),
|
modifier = Modifier.size(28.dp),
|
||||||
)
|
)
|
||||||
@@ -1064,11 +1084,7 @@ private fun FileCard(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
val selected = file.resourceId in selection.ids
|
val selected = file.resourceId in selection.ids
|
||||||
Card(
|
KazierCard(
|
||||||
colors = CardDefaults.cardColors(containerColor = Color(0xFFF7F8FA)),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
|
||||||
border = BorderStroke(1.dp, Color(0xFFEAEAEA)),
|
|
||||||
shape = RoundedCornerShape(10.dp),
|
|
||||||
modifier = modifier.combinedClickable(
|
modifier = modifier.combinedClickable(
|
||||||
onClick = {
|
onClick = {
|
||||||
if (selection.active) selection.toggle(file.resourceId) else onClick()
|
if (selection.active) selection.toggle(file.resourceId) else onClick()
|
||||||
@@ -1104,7 +1120,7 @@ private fun FileCard(
|
|||||||
)
|
)
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(4.dp))
|
||||||
Text(
|
Text(
|
||||||
text = formatSize(file.size),
|
text = formatFileSize(file.size),
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
@@ -1121,9 +1137,7 @@ private fun BrowseFileRow(
|
|||||||
onOpenDocument: () -> Unit,
|
onOpenDocument: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val selected = file.resourceId in selection.ids
|
val selected = file.resourceId in selection.ids
|
||||||
Card(
|
KazierCard(
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(bottom = 6.dp)
|
.padding(bottom = 6.dp)
|
||||||
@@ -1153,7 +1167,7 @@ private fun BrowseFileRow(
|
|||||||
fontWeight = FontWeight.Medium,
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = formatSize(file.size),
|
text = formatFileSize(file.size),
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
@@ -1173,20 +1187,6 @@ private fun BrowseFileRow(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Miroir de `formatSize` (app/index.tsx). */
|
|
||||||
@Composable
|
|
||||||
private fun formatSize(bytes: Long): String {
|
|
||||||
if (bytes < 1_024) {
|
|
||||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
|
||||||
}
|
|
||||||
if (bytes < 1_024 * 1_024) {
|
|
||||||
val kb = bytes / 1_024f
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
|
||||||
}
|
|
||||||
val mb = bytes / (1_024f * 1_024f)
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Création d'une note : titre requis, corps de texte libre. */
|
/** Création d'une note : titre requis, corps de texte libre. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun NoteDialog(
|
private fun NoteDialog(
|
||||||
|
|||||||
@@ -23,11 +23,13 @@ import com.kazier.mobile.features.saf.SafFolderCreator
|
|||||||
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
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.flow.flatMapLatest
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
import kotlinx.coroutines.flow.flowOf
|
import kotlinx.coroutines.flow.flowOf
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
@@ -60,6 +62,10 @@ class FolderListViewModel @Inject constructor(
|
|||||||
private val _defaultRootId = MutableStateFlow(defaultRootStore.get())
|
private val _defaultRootId = MutableStateFlow(defaultRootStore.get())
|
||||||
val defaultRootId: StateFlow<String?> = _defaultRootId.asStateFlow()
|
val defaultRootId: StateFlow<String?> = _defaultRootId.asStateFlow()
|
||||||
|
|
||||||
|
/** Documents locaux restant à traiter — CTA review persistant (même source que le dashboard). */
|
||||||
|
val unprocessedCount: StateFlow<Int> = fileRepository.observeUnprocessedCount()
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialValue = 0)
|
||||||
|
|
||||||
/** Dossier courant de l'explorateur Dossiers (null = racine par défaut). */
|
/** Dossier courant de l'explorateur Dossiers (null = racine par défaut). */
|
||||||
private val _browseFolderId = MutableStateFlow<String?>(null)
|
private val _browseFolderId = MutableStateFlow<String?>(null)
|
||||||
|
|
||||||
|
|||||||
@@ -6,17 +6,20 @@ import androidx.compose.foundation.layout.Arrangement
|
|||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.RowScope
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.heightIn
|
import androidx.compose.foundation.layout.heightIn
|
||||||
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.widthIn
|
import androidx.compose.foundation.layout.widthIn
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Add
|
||||||
import androidx.compose.material.icons.filled.Dashboard
|
import androidx.compose.material.icons.filled.Dashboard
|
||||||
import androidx.compose.material.icons.filled.DriveFileMove
|
import androidx.compose.material.icons.filled.DriveFileMove
|
||||||
import androidx.compose.material.icons.filled.Folder
|
import androidx.compose.material.icons.filled.Folder
|
||||||
import androidx.compose.material.icons.filled.MergeType
|
import androidx.compose.material.icons.filled.MergeType
|
||||||
|
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||||
|
import androidx.compose.material.icons.filled.Save
|
||||||
import androidx.compose.material.icons.filled.Search
|
import androidx.compose.material.icons.filled.Search
|
||||||
import androidx.compose.material.icons.filled.Settings
|
import androidx.compose.material.icons.filled.Settings
|
||||||
import androidx.compose.material.icons.filled.Share
|
import androidx.compose.material.icons.filled.Share
|
||||||
@@ -38,10 +41,12 @@ import androidx.compose.ui.res.stringResource
|
|||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.ui.components.DeleteDropdownButton
|
|
||||||
import com.kazier.mobile.features.saf.FileDeleter
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
|
import com.kazier.mobile.ui.components.DeleteDropdownButton
|
||||||
|
import com.kazier.mobile.ui.theme.KazierDimens
|
||||||
|
import com.kazier.mobile.ui.theme.NavItemShape
|
||||||
|
import com.kazier.mobile.ui.theme.NavPillShape
|
||||||
|
|
||||||
enum class NavTab(val route: String) {
|
enum class NavTab(val route: String) {
|
||||||
FILES(Routes.FILES),
|
FILES(Routes.FILES),
|
||||||
@@ -64,11 +69,11 @@ private val TAB_ITEMS = listOf(
|
|||||||
TabItem(NavTab.SETTINGS, Icons.Filled.Settings, Icons.Outlined.Settings, R.string.nav_settings),
|
TabItem(NavTab.SETTINGS, Icons.Filled.Settings, Icons.Outlined.Settings, R.string.nav_settings),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** Conteneur pill commun aux 4 barres flottantes (nav + sélection + déplacement). */
|
||||||
@Composable
|
@Composable
|
||||||
fun FloatingNavBar(
|
private fun FloatingPillContainer(
|
||||||
selected: NavTab,
|
|
||||||
onSelect: (NavTab) -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
|
content: @Composable RowScope.() -> Unit,
|
||||||
) {
|
) {
|
||||||
Box(
|
Box(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
@@ -77,25 +82,38 @@ fun FloatingNavBar(
|
|||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Surface(
|
Surface(
|
||||||
shape = RoundedCornerShape(30.dp),
|
shape = NavPillShape,
|
||||||
color = MaterialTheme.colorScheme.surface,
|
color = MaterialTheme.colorScheme.surface,
|
||||||
shadowElevation = 8.dp,
|
shadowElevation = KazierDimens.NavElevation,
|
||||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
modifier = Modifier.widthIn(max = KazierDimens.ListMaxWidth).fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(vertical = 8.dp, horizontal = 8.dp),
|
modifier = Modifier.padding(vertical = 8.dp, horizontal = 8.dp),
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun FloatingNavBar(
|
||||||
|
selected: NavTab,
|
||||||
|
onSelect: (NavTab) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
FloatingPillContainer(modifier = modifier) {
|
||||||
TAB_ITEMS.forEach { item ->
|
TAB_ITEMS.forEach { item ->
|
||||||
val isActive = item.tab == selected
|
val isActive = item.tab == selected
|
||||||
val icon = if (isActive) item.filled else item.outlined
|
val icon = if (isActive) item.filled else item.outlined
|
||||||
val tint = if (isActive) MaterialTheme.colorScheme.primary
|
val tint = if (isActive) MaterialTheme.colorScheme.primary
|
||||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
val label = stringResource(item.labelRes)
|
||||||
|
|
||||||
Surface(
|
Surface(
|
||||||
onClick = { onSelect(item.tab) },
|
onClick = { onSelect(item.tab) },
|
||||||
shape = RoundedCornerShape(20.dp),
|
shape = NavItemShape,
|
||||||
color = if (isActive) MaterialTheme.colorScheme.primaryContainer
|
color = if (isActive) MaterialTheme.colorScheme.primaryContainer
|
||||||
else MaterialTheme.colorScheme.surface,
|
else MaterialTheme.colorScheme.surface,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
@@ -109,14 +127,14 @@ fun FloatingNavBar(
|
|||||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = icon,
|
imageVector = icon,
|
||||||
contentDescription = null,
|
contentDescription = label,
|
||||||
tint = tint,
|
tint = tint,
|
||||||
modifier = Modifier.size(22.dp),
|
modifier = Modifier.size(22.dp),
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(item.labelRes),
|
text = label,
|
||||||
color = tint,
|
color = tint,
|
||||||
fontSize = 11.sp,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
fontWeight = if (isActive) FontWeight.Bold else FontWeight.Medium,
|
fontWeight = if (isActive) FontWeight.Bold else FontWeight.Medium,
|
||||||
@@ -127,8 +145,6 @@ fun FloatingNavBar(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Barre d'actions affichée à la place de la nav quand le mode multi-sélection est actif. */
|
/** Barre d'actions affichée à la place de la nav quand le mode multi-sélection est actif. */
|
||||||
@@ -140,23 +156,7 @@ fun SelectionNavBar(
|
|||||||
enabled: Boolean,
|
enabled: Boolean,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
Box(
|
FloatingPillContainer(modifier = modifier) {
|
||||||
modifier = modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(start = 20.dp, end = 20.dp, bottom = 16.dp),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Surface(
|
|
||||||
shape = RoundedCornerShape(30.dp),
|
|
||||||
color = MaterialTheme.colorScheme.surface,
|
|
||||||
shadowElevation = 8.dp,
|
|
||||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(vertical = 8.dp, horizontal = 8.dp),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
label = stringResource(R.string.move_files),
|
label = stringResource(R.string.move_files),
|
||||||
icon = Icons.Filled.DriveFileMove,
|
icon = Icons.Filled.DriveFileMove,
|
||||||
@@ -177,8 +177,6 @@ fun SelectionNavBar(
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Barre d'actions multi-sélection propre aux dossiers : partage + suppression. */
|
/** Barre d'actions multi-sélection propre aux dossiers : partage + suppression. */
|
||||||
@@ -190,23 +188,7 @@ fun FolderSelectionNavBar(
|
|||||||
deleteEnabled: Boolean,
|
deleteEnabled: Boolean,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
Box(
|
FloatingPillContainer(modifier = modifier) {
|
||||||
modifier = modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(start = 20.dp, end = 20.dp, bottom = 16.dp),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Surface(
|
|
||||||
shape = RoundedCornerShape(30.dp),
|
|
||||||
color = MaterialTheme.colorScheme.surface,
|
|
||||||
shadowElevation = 8.dp,
|
|
||||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(vertical = 8.dp, horizontal = 8.dp),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
label = stringResource(R.string.share_action),
|
label = stringResource(R.string.share_action),
|
||||||
icon = Icons.Filled.Share,
|
icon = Icons.Filled.Share,
|
||||||
@@ -220,7 +202,40 @@ fun FolderSelectionNavBar(
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Barre d'actions de l'étape « pages scannées » : même pilule flottante que le reste de l'app. */
|
||||||
|
@Composable
|
||||||
|
fun ScanSessionNavBar(
|
||||||
|
onAddPage: () -> Unit,
|
||||||
|
onExportPdf: () -> Unit,
|
||||||
|
onExport: () -> Unit,
|
||||||
|
canExport: Boolean,
|
||||||
|
actionsEnabled: Boolean = true,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
FloatingPillContainer(modifier = modifier) {
|
||||||
|
SelectionAction(
|
||||||
|
label = stringResource(R.string.scan_add_page),
|
||||||
|
icon = Icons.Filled.Add,
|
||||||
|
enabled = actionsEnabled,
|
||||||
|
onClick = onAddPage,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
SelectionAction(
|
||||||
|
label = stringResource(R.string.scan_export_pdf),
|
||||||
|
icon = Icons.Filled.PictureAsPdf,
|
||||||
|
enabled = actionsEnabled && canExport,
|
||||||
|
onClick = onExportPdf,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
SelectionAction(
|
||||||
|
label = stringResource(R.string.scan_export),
|
||||||
|
icon = Icons.Filled.Save,
|
||||||
|
enabled = actionsEnabled && canExport,
|
||||||
|
onClick = onExport,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,23 +246,8 @@ fun MoveTargetBar(
|
|||||||
onMoveHere: () -> Unit,
|
onMoveHere: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
Box(
|
FloatingPillContainer(modifier = modifier) {
|
||||||
modifier = modifier
|
val label = stringResource(R.string.move_here_count, fileCount)
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(start = 20.dp, end = 20.dp, bottom = 16.dp),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Surface(
|
|
||||||
shape = RoundedCornerShape(30.dp),
|
|
||||||
color = MaterialTheme.colorScheme.surface,
|
|
||||||
shadowElevation = 8.dp,
|
|
||||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
Button(
|
Button(
|
||||||
onClick = onMoveHere,
|
onClick = onMoveHere,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -256,16 +256,14 @@ fun MoveTargetBar(
|
|||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.DriveFileMove,
|
imageVector = Icons.Filled.DriveFileMove,
|
||||||
contentDescription = null,
|
contentDescription = label,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.move_here_count, fileCount),
|
text = label,
|
||||||
modifier = Modifier.padding(start = 8.dp),
|
modifier = Modifier.padding(start = 8.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -281,7 +279,7 @@ private fun SelectionAction(
|
|||||||
Surface(
|
Surface(
|
||||||
onClick = onClick,
|
onClick = onClick,
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
shape = RoundedCornerShape(20.dp),
|
shape = NavItemShape,
|
||||||
color = if (enabled) MaterialTheme.colorScheme.primaryContainer
|
color = if (enabled) MaterialTheme.colorScheme.primaryContainer
|
||||||
else MaterialTheme.colorScheme.surfaceVariant,
|
else MaterialTheme.colorScheme.surfaceVariant,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
@@ -295,14 +293,14 @@ private fun SelectionAction(
|
|||||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = icon,
|
imageVector = icon,
|
||||||
contentDescription = null,
|
contentDescription = label,
|
||||||
tint = tint,
|
tint = tint,
|
||||||
modifier = Modifier.size(22.dp),
|
modifier = Modifier.size(22.dp),
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = label,
|
text = label,
|
||||||
color = tint,
|
color = tint,
|
||||||
fontSize = 11.sp,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package com.kazier.mobile.ui.navigation
|
package com.kazier.mobile.ui.navigation
|
||||||
|
|
||||||
|
import androidx.compose.animation.EnterTransition
|
||||||
|
import androidx.compose.animation.ExitTransition
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
@@ -13,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
|
||||||
@@ -25,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 {
|
||||||
@@ -41,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"
|
||||||
@@ -103,7 +111,12 @@ fun NavGraph(
|
|||||||
Box(modifier = Modifier.fillMaxSize()) {
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
NavHost(
|
NavHost(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
startDestination = Routes.FILES,
|
startDestination = Routes.DASHBOARD,
|
||||||
|
// Pas de transition animée entre les vues : changement instantané.
|
||||||
|
enterTransition = { EnterTransition.None },
|
||||||
|
exitTransition = { ExitTransition.None },
|
||||||
|
popEnterTransition = { EnterTransition.None },
|
||||||
|
popExitTransition = { ExitTransition.None },
|
||||||
) {
|
) {
|
||||||
composable(Routes.FILES) {
|
composable(Routes.FILES) {
|
||||||
FolderListScreen(
|
FolderListScreen(
|
||||||
@@ -112,6 +125,7 @@ fun NavGraph(
|
|||||||
onOpenDocument = { id -> navController.navigate(Routes.document(id)) },
|
onOpenDocument = { id -> navController.navigate(Routes.document(id)) },
|
||||||
onBuildPdf = { ids -> navController.navigate(Routes.pdfBuilder(ids)) },
|
onBuildPdf = { ids -> navController.navigate(Routes.pdfBuilder(ids)) },
|
||||||
onOpenScan = { navController.navigate(Routes.SCAN) },
|
onOpenScan = { navController.navigate(Routes.SCAN) },
|
||||||
|
onOpenReview = { navController.navigate(Routes.REVIEW) },
|
||||||
syncViewModel = syncViewModel,
|
syncViewModel = syncViewModel,
|
||||||
connectionStatusViewModel = connectionStatusViewModel,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
authViewModel = authViewModel,
|
authViewModel = authViewModel,
|
||||||
@@ -225,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() },
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+71
-49
@@ -18,29 +18,29 @@ import androidx.compose.foundation.lazy.items
|
|||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
import androidx.compose.material.icons.filled.Add
|
import androidx.compose.material.icons.filled.Add
|
||||||
import androidx.compose.material.icons.filled.Check
|
|
||||||
import androidx.compose.material.icons.filled.Close
|
import androidx.compose.material.icons.filled.Close
|
||||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||||
import androidx.compose.material.icons.filled.Image
|
import androidx.compose.material.icons.filled.Image
|
||||||
import androidx.compose.material.icons.filled.MergeType
|
import androidx.compose.material.icons.filled.MergeType
|
||||||
|
import androidx.compose.material.icons.filled.Search
|
||||||
import androidx.compose.material.icons.filled.TextSnippet
|
import androidx.compose.material.icons.filled.TextSnippet
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material3.Checkbox
|
||||||
import androidx.compose.material3.CardDefaults
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.ModalBottomSheet
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
import androidx.compose.material3.OutlinedButton
|
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.SnackbarDuration
|
||||||
import androidx.compose.material3.SnackbarHost
|
import androidx.compose.material3.SnackbarHost
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.SnackbarResult
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
@@ -57,6 +57,7 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
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.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
@@ -68,11 +69,13 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||||
|
import com.kazier.mobile.ui.components.KazierCard
|
||||||
|
import com.kazier.mobile.ui.components.VerticalActionButton
|
||||||
|
import com.kazier.mobile.ui.components.formatFileSize
|
||||||
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -111,8 +114,22 @@ fun PdfBuilderScreen(
|
|||||||
LaunchedEffect(isReady) {
|
LaunchedEffect(isReady) {
|
||||||
if (isReady) showNameDialog = true
|
if (isReady) showNameDialog = true
|
||||||
}
|
}
|
||||||
|
// Plus d'auto-navigation à la sauvegarde : un Snackbar « PDF créé / Voir »
|
||||||
|
// laisse l'utilisateur dans le panier ; l'ouverture est explicite.
|
||||||
|
// `savedAnnouncedFor` (UI seule) évite le re-snackbar à la rotation.
|
||||||
|
val savedLabel = stringResource(R.string.pdf_builder_saved)
|
||||||
|
val viewLabel = stringResource(R.string.pdf_builder_view)
|
||||||
|
var savedAnnouncedFor by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
LaunchedEffect(savedResourceId) {
|
LaunchedEffect(savedResourceId) {
|
||||||
if (savedResourceId != null) onOpenDocument(savedResourceId)
|
if (savedResourceId != null && savedAnnouncedFor != savedResourceId) {
|
||||||
|
savedAnnouncedFor = savedResourceId
|
||||||
|
val result = snackbarHostState.showSnackbar(
|
||||||
|
message = savedLabel,
|
||||||
|
actionLabel = viewLabel,
|
||||||
|
duration = SnackbarDuration.Long,
|
||||||
|
)
|
||||||
|
if (result == SnackbarResult.ActionPerformed) onOpenDocument(savedResourceId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
LaunchedEffect(failureMessage) {
|
LaunchedEffect(failureMessage) {
|
||||||
if (failureMessage != null) {
|
if (failureMessage != null) {
|
||||||
@@ -257,7 +274,12 @@ private fun SelectFilesSheet(
|
|||||||
// `remember(files)`, chaque update Room recréait la sélection et effaçait
|
// `remember(files)`, chaque update Room recréait la sélection et effaçait
|
||||||
// les cases cochées en cours.
|
// les cases cochées en cours.
|
||||||
var selected by remember(existingIds) { mutableStateOf(existingIds.toMutableSet()) }
|
var selected by remember(existingIds) { mutableStateOf(existingIds.toMutableSet()) }
|
||||||
|
var searchQuery by rememberSaveable { mutableStateOf("") }
|
||||||
val sheetState = rememberModalBottomSheetState()
|
val sheetState = rememberModalBottomSheetState()
|
||||||
|
val visibleFiles = remember(files, searchQuery) {
|
||||||
|
if (searchQuery.isBlank()) files
|
||||||
|
else files.filter { it.name.contains(searchQuery, ignoreCase = true) }
|
||||||
|
}
|
||||||
|
|
||||||
ModalBottomSheet(
|
ModalBottomSheet(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
@@ -269,18 +291,33 @@ private fun SelectFilesSheet(
|
|||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
modifier = Modifier.padding(horizontal = 16.dp),
|
modifier = Modifier.padding(horizontal = 16.dp),
|
||||||
)
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = searchQuery,
|
||||||
|
onValueChange = { searchQuery = it },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
||||||
|
placeholder = { Text(stringResource(R.string.pdf_builder_search_files)) },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
)
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
contentPadding = PaddingValues(16.dp),
|
contentPadding = PaddingValues(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
) {
|
) {
|
||||||
items(files, key = { it.resourceId }) { file ->
|
items(visibleFiles, key = { it.resourceId }) { file ->
|
||||||
|
val checked = file.resourceId in selected
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.clickable {
|
.clickable(
|
||||||
if (file.resourceId in selected) selected.remove(file.resourceId)
|
role = Role.Checkbox,
|
||||||
|
onClickLabel = file.name,
|
||||||
|
onClick = {
|
||||||
|
if (checked) selected.remove(file.resourceId)
|
||||||
else selected.add(file.resourceId)
|
else selected.add(file.resourceId)
|
||||||
}
|
},
|
||||||
|
)
|
||||||
.padding(vertical = 8.dp),
|
.padding(vertical = 8.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
@@ -294,19 +331,17 @@ private fun SelectFilesSheet(
|
|||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = formatSize(file.size),
|
text = formatFileSize(file.size),
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Icon(
|
Checkbox(
|
||||||
imageVector = Icons.Filled.Check,
|
checked = checked,
|
||||||
contentDescription = null,
|
onCheckedChange = {
|
||||||
tint = if (file.resourceId in selected) {
|
if (checked) selected.remove(file.resourceId)
|
||||||
MaterialTheme.colorScheme.primary
|
else selected.add(file.resourceId)
|
||||||
} else {
|
|
||||||
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -332,7 +367,7 @@ private fun NamePdfDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onConfirm: (String) -> Unit,
|
onConfirm: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
var name by remember { mutableStateOf(defaultName) }
|
var name by rememberSaveable { mutableStateOf(defaultName) }
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
title = { Text(stringResource(R.string.pdf_builder_name_title)) },
|
title = { Text(stringResource(R.string.pdf_builder_name_title)) },
|
||||||
@@ -366,7 +401,7 @@ private fun AddNoteDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onConfirm: (String) -> Unit,
|
onConfirm: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
var body by remember { mutableStateOf("") }
|
var body by rememberSaveable { mutableStateOf("") }
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
title = { Text(stringResource(R.string.pdf_builder_add_note)) },
|
title = { Text(stringResource(R.string.pdf_builder_add_note)) },
|
||||||
@@ -404,10 +439,7 @@ private fun BuilderItemRow(
|
|||||||
onPreview: (() -> Unit)?,
|
onPreview: (() -> Unit)?,
|
||||||
) {
|
) {
|
||||||
val previewModifier = if (onPreview != null) Modifier.clickable(onClick = onPreview) else Modifier
|
val previewModifier = if (onPreview != null) Modifier.clickable(onClick = onPreview) else Modifier
|
||||||
Card(
|
KazierCard(modifier = Modifier.fillMaxWidth()) {
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
|
||||||
) {
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -419,13 +451,13 @@ private fun BuilderItemRow(
|
|||||||
is PdfBuilderItem.FileItem -> FileCategoryIcon(file = item.file, size = 24.dp)
|
is PdfBuilderItem.FileItem -> FileCategoryIcon(file = item.file, size = 24.dp)
|
||||||
is PdfBuilderItem.NoteItem -> Icon(
|
is PdfBuilderItem.NoteItem -> Icon(
|
||||||
imageVector = Icons.Filled.TextSnippet,
|
imageVector = Icons.Filled.TextSnippet,
|
||||||
contentDescription = null,
|
contentDescription = stringResource(R.string.pdf_builder_note),
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier.size(24.dp),
|
modifier = Modifier.size(24.dp),
|
||||||
)
|
)
|
||||||
is PdfBuilderItem.FilePathItem -> Icon(
|
is PdfBuilderItem.FilePathItem -> Icon(
|
||||||
imageVector = Icons.Filled.Image,
|
imageVector = Icons.Filled.Image,
|
||||||
contentDescription = null,
|
contentDescription = item.file.name,
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier.size(24.dp),
|
modifier = Modifier.size(24.dp),
|
||||||
)
|
)
|
||||||
@@ -450,14 +482,14 @@ private fun BuilderItemRow(
|
|||||||
is PdfBuilderItem.FileItem -> if (isFailed) {
|
is PdfBuilderItem.FileItem -> if (isFailed) {
|
||||||
stringResource(R.string.pdf_builder_unreadable)
|
stringResource(R.string.pdf_builder_unreadable)
|
||||||
} else {
|
} else {
|
||||||
formatSize(item.file.size)
|
formatFileSize(item.file.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
is PdfBuilderItem.NoteItem -> item.body
|
is PdfBuilderItem.NoteItem -> item.body
|
||||||
.replace('\n', ' ')
|
.replace('\n', ' ')
|
||||||
.take(80)
|
.take(80)
|
||||||
|
|
||||||
is PdfBuilderItem.FilePathItem -> formatSize(item.file.length())
|
is PdfBuilderItem.FilePathItem -> formatFileSize(item.file.length())
|
||||||
},
|
},
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = if (isFailed) MaterialTheme.colorScheme.error
|
color = if (isFailed) MaterialTheme.colorScheme.error
|
||||||
@@ -547,24 +579,22 @@ private fun BuilderActions(
|
|||||||
) {
|
) {
|
||||||
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
OutlinedButton(
|
VerticalActionButton(
|
||||||
|
icon = Icons.Filled.Add,
|
||||||
|
label = stringResource(R.string.pdf_builder_add_files),
|
||||||
onClick = onAddFile,
|
onClick = onAddFile,
|
||||||
enabled = !building,
|
enabled = !building,
|
||||||
|
outlined = true,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
) {
|
)
|
||||||
Icon(Icons.Filled.Add, contentDescription = null)
|
VerticalActionButton(
|
||||||
Spacer(Modifier.width(6.dp))
|
icon = Icons.Filled.TextSnippet,
|
||||||
Text(stringResource(R.string.pdf_builder_add_files))
|
label = stringResource(R.string.pdf_builder_add_note),
|
||||||
}
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = onAddNote,
|
onClick = onAddNote,
|
||||||
enabled = !building,
|
enabled = !building,
|
||||||
|
outlined = true,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
) {
|
)
|
||||||
Icon(Icons.Filled.TextSnippet, contentDescription = null)
|
|
||||||
Spacer(Modifier.width(6.dp))
|
|
||||||
Text(stringResource(R.string.pdf_builder_add_note))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Button(
|
Button(
|
||||||
onClick = onAssemble,
|
onClick = onAssemble,
|
||||||
@@ -580,11 +610,3 @@ private fun BuilderActions(
|
|||||||
|
|
||||||
private val DEFAULT_DATE_FORMAT: DateTimeFormatter =
|
private val DEFAULT_DATE_FORMAT: DateTimeFormatter =
|
||||||
DateTimeFormatter.ofPattern("dd-MM-yyyy")
|
DateTimeFormatter.ofPattern("dd-MM-yyyy")
|
||||||
|
|
||||||
private fun formatSize(bytes: Long): String {
|
|
||||||
if (bytes < 1_024) return "$bytes o"
|
|
||||||
if (bytes < 1_024 * 1_024) {
|
|
||||||
return String.format(Locale.getDefault(), "%.1f ko", bytes / 1_024f)
|
|
||||||
}
|
|
||||||
return String.format(Locale.getDefault(), "%.1f Mo", bytes / (1_024f * 1_024f))
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
package com.kazier.mobile.ui.review
|
package com.kazier.mobile.ui.review
|
||||||
|
|
||||||
|
import androidx.compose.animation.AnimatedContent
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.scaleIn
|
||||||
|
import androidx.compose.animation.scaleOut
|
||||||
|
import androidx.compose.animation.togetherWith
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -27,7 +33,9 @@ import androidx.compose.ui.text.style.TextOverflow
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||||
|
import com.kazier.mobile.ui.components.formatFileSize
|
||||||
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
||||||
|
import com.kazier.mobile.ui.theme.SheetShape
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
@@ -49,17 +57,13 @@ fun SwipeCardDeck(
|
|||||||
) {
|
) {
|
||||||
Box(modifier = modifier) {
|
Box(modifier = modifier) {
|
||||||
val visible = cards.take(MAX_STACK)
|
val visible = cards.take(MAX_STACK)
|
||||||
|
val top = visible.firstOrNull()
|
||||||
|
|
||||||
visible.asReversed().forEach { file ->
|
// Cartes d'arrière-plan : profondeur = distance au dessus (0 = dessus).
|
||||||
val depth = visible.indexOf(file)
|
visible.asReversed().forEachIndexed { reversedIndex, file ->
|
||||||
|
val depth = visible.size - 1 - reversedIndex
|
||||||
|
if (depth == 0) return@forEachIndexed
|
||||||
key(file.resourceId) {
|
key(file.resourceId) {
|
||||||
if (depth == 0) {
|
|
||||||
TopCard(
|
|
||||||
file = file,
|
|
||||||
onOpenExternalFailed = onOpenExternalFailed,
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
StackedCard(
|
StackedCard(
|
||||||
file = file,
|
file = file,
|
||||||
depth = depth,
|
depth = depth,
|
||||||
@@ -67,6 +71,28 @@ fun SwipeCardDeck(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Carte du dessus : transition fondu + échelle à chaque document —
|
||||||
|
// fini la disparition brutale au garder/supprimer.
|
||||||
|
AnimatedContent(
|
||||||
|
targetState = top?.resourceId,
|
||||||
|
transitionSpec = {
|
||||||
|
(fadeIn() + scaleIn(initialScale = 0.96f)) togetherWith
|
||||||
|
(fadeOut() + scaleOut(targetScale = 0.96f))
|
||||||
|
},
|
||||||
|
label = "review-top-card",
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
) { topId ->
|
||||||
|
val file = visible.firstOrNull { it.resourceId == topId }
|
||||||
|
if (file != null) {
|
||||||
|
key(file.resourceId) {
|
||||||
|
TopCard(
|
||||||
|
file = file,
|
||||||
|
onOpenExternalFailed = onOpenExternalFailed,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -155,7 +181,7 @@ private fun ReviewCardMetaBar(file: FileEntity, modifier: Modifier = Modifier) {
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "${formatSize(file.size)} • ${formatDate(file)}",
|
text = "${formatFileSize(file.size)} • ${formatDate(file)}",
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
@@ -163,16 +189,6 @@ private fun ReviewCardMetaBar(file: FileEntity, modifier: Modifier = Modifier) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun formatSize(bytes: Long): String {
|
|
||||||
val kb = 1024.0
|
|
||||||
val mb = kb * 1024
|
|
||||||
return when {
|
|
||||||
bytes >= mb -> String.format(Locale.getDefault(), "%.1f Mo", bytes / mb)
|
|
||||||
bytes >= kb -> String.format(Locale.getDefault(), "%.1f ko", bytes / kb)
|
|
||||||
else -> "$bytes o"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun formatDate(file: FileEntity): String {
|
private fun formatDate(file: FileEntity): String {
|
||||||
val millis = file.lastModified ?: file.addedAt
|
val millis = file.lastModified ?: file.addedAt
|
||||||
return DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
|
return DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
|
||||||
@@ -180,7 +196,7 @@ private fun formatDate(file: FileEntity): String {
|
|||||||
.format(Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate())
|
.format(Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate())
|
||||||
}
|
}
|
||||||
|
|
||||||
private val CardShape = RoundedCornerShape(20.dp)
|
private val CardShape = SheetShape
|
||||||
private const val MAX_STACK = 3
|
private const val MAX_STACK = 3
|
||||||
private const val STACK_SHRINK = 0.045f
|
private const val STACK_SHRINK = 0.045f
|
||||||
private const val STACK_OFFSET_DP = 18f
|
private const val STACK_OFFSET_DP = 18f
|
||||||
@@ -13,6 +13,7 @@ import androidx.compose.material.icons.Icons
|
|||||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
import androidx.compose.material.icons.filled.Check
|
import androidx.compose.material.icons.filled.Check
|
||||||
import androidx.compose.material.icons.filled.Close
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.FloatingActionButton
|
import androidx.compose.material3.FloatingActionButton
|
||||||
@@ -28,8 +29,10 @@ import androidx.compose.material3.TopAppBar
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
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
|
||||||
@@ -38,14 +41,12 @@ import androidx.compose.ui.res.stringResource
|
|||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.window.Dialog
|
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.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.components.ServerStatusBadge
|
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@@ -57,11 +58,10 @@ fun SwipeReviewScreen(
|
|||||||
viewModel: SwipeReviewViewModel = hiltViewModel(),
|
viewModel: SwipeReviewViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val openExternalErrorMsg = stringResource(R.string.document_open_error)
|
val openExternalErrorMsg = stringResource(R.string.document_open_error)
|
||||||
var confirmMarkAll by remember { androidx.compose.runtime.mutableStateOf(false) }
|
var confirmMarkAll by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
LaunchedEffect(state.error) {
|
LaunchedEffect(state.error) {
|
||||||
state.error?.let {
|
state.error?.let {
|
||||||
@@ -91,10 +91,9 @@ fun SwipeReviewScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
actions = {
|
actions = {
|
||||||
SyncStatusAction(syncViewModel = syncViewModel)
|
HeaderStatusAction(
|
||||||
ServerStatusBadge(
|
syncViewModel = syncViewModel,
|
||||||
status = connectionStatus,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
onClick = connectionStatusViewModel::checkNow,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -156,31 +155,11 @@ fun SwipeReviewScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (confirmMarkAll) {
|
if (confirmMarkAll) {
|
||||||
Dialog(onDismissRequest = { confirmMarkAll = false }) {
|
AlertDialog(
|
||||||
androidx.compose.material3.Surface(
|
onDismissRequest = { confirmMarkAll = false },
|
||||||
shape = MaterialTheme.shapes.medium,
|
title = { Text(stringResource(R.string.review_mark_all_title)) },
|
||||||
tonalElevation = 3.dp,
|
text = { Text(stringResource(R.string.review_mark_all_message)) },
|
||||||
) {
|
confirmButton = {
|
||||||
Column(modifier = Modifier.padding(24.dp)) {
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.review_mark_all_title),
|
|
||||||
style = MaterialTheme.typography.titleMedium,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.review_mark_all_message),
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
modifier = Modifier.padding(top = 8.dp),
|
|
||||||
)
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(top = 16.dp),
|
|
||||||
horizontalArrangement = Arrangement.End,
|
|
||||||
) {
|
|
||||||
TextButton(onClick = { confirmMarkAll = false }) {
|
|
||||||
Text(stringResource(R.string.pdf_builder_cancel))
|
|
||||||
}
|
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
confirmMarkAll = false
|
confirmMarkAll = false
|
||||||
@@ -189,10 +168,13 @@ fun SwipeReviewScreen(
|
|||||||
) {
|
) {
|
||||||
Text(stringResource(R.string.review_mark_all))
|
Text(stringResource(R.string.review_mark_all))
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { confirmMarkAll = false }) {
|
||||||
|
Text(stringResource(R.string.pdf_builder_cancel))
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
}
|
)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,7 +187,7 @@ private fun ReviewActions(
|
|||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
horizontalArrangement = Arrangement.spacedBy(48.dp),
|
horizontalArrangement = Arrangement.spacedBy(24.dp, Alignment.CenterHorizontally),
|
||||||
verticalAlignment = Alignment.Top,
|
verticalAlignment = Alignment.Top,
|
||||||
) {
|
) {
|
||||||
ReviewAction(
|
ReviewAction(
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
package com.kazier.mobile.ui.scan
|
package com.kazier.mobile.ui.scan
|
||||||
|
|
||||||
import android.Manifest.permission.CAMERA
|
import android.Manifest.permission.CAMERA
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.Settings
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
|
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
@@ -26,6 +34,7 @@ import androidx.compose.runtime.LaunchedEffect
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -34,10 +43,12 @@ import androidx.compose.ui.res.stringResource
|
|||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.core.app.ActivityCompat
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
|
import com.kazier.mobile.ui.navigation.ScanSessionNavBar
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Route unique du scanner — gère la permission caméra, le basculement entre
|
* Route unique du scanner — gère la permission caméra, le basculement entre
|
||||||
@@ -59,11 +70,18 @@ fun ScanFlowScreen(
|
|||||||
val pages by viewModel.pages.collectAsStateWithLifecycle()
|
val pages by viewModel.pages.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
val activity = context as? Activity
|
||||||
var hasCameraPermission by remember {
|
var hasCameraPermission by remember {
|
||||||
mutableStateOf(ContextCompat.checkSelfPermission(context, CAMERA) == PackageManager.PERMISSION_GRANTED)
|
mutableStateOf(ContextCompat.checkSelfPermission(context, CAMERA) == PackageManager.PERMISSION_GRANTED)
|
||||||
}
|
}
|
||||||
|
// Refus définitif (« ne plus demander ») : la demande système ne
|
||||||
|
// réapparaîtra plus — on propose les Réglages au lieu d'un cul-de-sac.
|
||||||
|
var permanentlyDenied by rememberSaveable { mutableStateOf(false) }
|
||||||
val launcher = rememberLauncherForActivityResult(RequestPermission()) { granted ->
|
val launcher = rememberLauncherForActivityResult(RequestPermission()) { granted ->
|
||||||
hasCameraPermission = granted
|
hasCameraPermission = granted
|
||||||
|
permanentlyDenied = !granted && activity?.let {
|
||||||
|
!ActivityCompat.shouldShowRequestPermissionRationale(it, CAMERA)
|
||||||
|
} ?: false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Retour écran précédent à l'export (observé une seule fois).
|
// Retour écran précédent à l'export (observé une seule fois).
|
||||||
@@ -85,7 +103,7 @@ fun ScanFlowScreen(
|
|||||||
// Confirmation avant de quitter le scanner quand des pages sont en cours :
|
// Confirmation avant de quitter le scanner quand des pages sont en cours :
|
||||||
// la flèche CAMERA et le back système feront tous deux valider par un
|
// la flèche CAMERA et le back système feront tous deux valider par un
|
||||||
// dialogue (sinon abandon = suppression des pages capturées).
|
// dialogue (sinon abandon = suppression des pages capturées).
|
||||||
var showExitConfirm by remember { mutableStateOf(false) }
|
var showExitConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
val requestExit: () -> Unit = {
|
val requestExit: () -> Unit = {
|
||||||
if (pages.isNotEmpty()) {
|
if (pages.isNotEmpty()) {
|
||||||
@@ -140,6 +158,19 @@ fun ScanFlowScreen(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||||
|
bottomBar = {
|
||||||
|
if (stage == ScanStage.SESSION) {
|
||||||
|
ScanSessionNavBar(
|
||||||
|
onAddPage = viewModel::openCamera,
|
||||||
|
onExportPdf = viewModel::exportPdf,
|
||||||
|
onExport = viewModel::export,
|
||||||
|
canExport = pages.isNotEmpty(),
|
||||||
|
// Le voile `busy` ne couvre que le contenu : sans ça la
|
||||||
|
// barre resterait cliquable pendant l'export.
|
||||||
|
actionsEnabled = !busy,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
) { padding ->
|
) { padding ->
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -156,7 +187,15 @@ fun ScanFlowScreen(
|
|||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
CameraRationale(
|
CameraRationale(
|
||||||
|
permanentlyDenied = permanentlyDenied,
|
||||||
onGrant = { launcher.launch(CAMERA) },
|
onGrant = { launcher.launch(CAMERA) },
|
||||||
|
onOpenSettings = {
|
||||||
|
val intent = Intent(
|
||||||
|
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||||
|
Uri.fromParts("package", context.packageName, null),
|
||||||
|
)
|
||||||
|
context.startActivity(intent)
|
||||||
|
},
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -172,9 +211,15 @@ fun ScanFlowScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (busy) {
|
if (busy) {
|
||||||
CircularProgressIndicator(
|
// Voile + spinner : bloque les interactions derrière le loader.
|
||||||
modifier = Modifier.align(Alignment.Center),
|
Box(
|
||||||
)
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.32f)),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (showExitConfirm) {
|
if (showExitConfirm) {
|
||||||
@@ -199,20 +244,34 @@ fun ScanFlowScreen(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun CameraRationale(
|
private fun CameraRationale(
|
||||||
|
permanentlyDenied: Boolean,
|
||||||
onGrant: () -> Unit,
|
onGrant: () -> Unit,
|
||||||
|
onOpenSettings: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
Box(modifier = modifier, contentAlignment = Alignment.Center) {
|
Box(modifier = modifier, contentAlignment = Alignment.Center) {
|
||||||
androidx.compose.foundation.layout.Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.scan_permission_rationale),
|
text = stringResource(R.string.scan_permission_rationale),
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
modifier = Modifier.padding(horizontal = 32.dp),
|
modifier = Modifier.padding(horizontal = 32.dp),
|
||||||
)
|
)
|
||||||
TextButton(onClick = onGrant, modifier = Modifier.padding(top = 16.dp)) {
|
if (permanentlyDenied) {
|
||||||
|
Button(onClick = onOpenSettings) {
|
||||||
|
Text(stringResource(R.string.scan_permission_open_settings))
|
||||||
|
}
|
||||||
|
TextButton(onClick = onGrant) {
|
||||||
|
Text(stringResource(R.string.scan_permission_grant))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Button(onClick = onGrant) {
|
||||||
Text(stringResource(R.string.scan_permission_grant))
|
Text(stringResource(R.string.scan_permission_grant))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -10,40 +10,33 @@ import androidx.compose.foundation.layout.padding
|
|||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.itemsIndexed
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Add
|
|
||||||
import androidx.compose.material.icons.filled.Delete
|
import androidx.compose.material.icons.filled.Delete
|
||||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
|
||||||
import androidx.compose.material.icons.filled.Save
|
|
||||||
import androidx.compose.material3.Button
|
|
||||||
import androidx.compose.material3.Card
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||||
|
import com.kazier.mobile.ui.components.KazierCard
|
||||||
|
import com.kazier.mobile.ui.theme.ThumbShape
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Étape « session » : pages capturées (miniatures), réordonnancement,
|
* Étape « session » : pages capturées (miniatures), réordonnancement et
|
||||||
* suppression, ajout d'une page et export vers le dossier Kazier
|
* suppression. Les actions (ajouter, exporter PDF, exporter) vivent dans la
|
||||||
* (1 fichier JPEG = 1 `create_resource` outbox).
|
* pilule flottante du [ScanFlowScreen] (même style que Fichiers/Dashboard).
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun SessionStage(
|
fun SessionStage(
|
||||||
@@ -87,37 +80,6 @@ fun SessionStage(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(16.dp),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
|
||||||
) {
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = viewModel::openCamera,
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
) {
|
|
||||||
Icon(imageVector = Icons.Filled.Add, contentDescription = null)
|
|
||||||
Text(stringResource(R.string.scan_add_page), modifier = Modifier.padding(start = 4.dp))
|
|
||||||
}
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = viewModel::exportPdf,
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
enabled = pages.isNotEmpty(),
|
|
||||||
) {
|
|
||||||
Icon(imageVector = Icons.Filled.PictureAsPdf, contentDescription = null)
|
|
||||||
Text(stringResource(R.string.scan_export_pdf), modifier = Modifier.padding(start = 4.dp))
|
|
||||||
}
|
|
||||||
Button(
|
|
||||||
onClick = viewModel::export,
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
enabled = pages.isNotEmpty(),
|
|
||||||
) {
|
|
||||||
Icon(imageVector = Icons.Filled.Save, contentDescription = null)
|
|
||||||
Text(stringResource(R.string.scan_export), modifier = Modifier.padding(start = 4.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,18 +93,18 @@ private fun PageCard(
|
|||||||
onMoveDown: () -> Unit,
|
onMoveDown: () -> Unit,
|
||||||
onDelete: () -> Unit,
|
onDelete: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Card(modifier = Modifier.fillMaxWidth()) {
|
KazierCard(modifier = Modifier.fillMaxWidth()) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(8.dp),
|
modifier = Modifier.padding(8.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
AsyncImage(
|
AsyncImage(
|
||||||
model = File(page.tempUri),
|
model = File(page.tempUri),
|
||||||
contentDescription = null,
|
contentDescription = stringResource(R.string.scan_pages_count, index + 1),
|
||||||
contentScale = ContentScale.Crop,
|
contentScale = ContentScale.Crop,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.size(64.dp)
|
.size(64.dp)
|
||||||
.clip(RoundedCornerShape(8.dp)),
|
.clip(ThumbShape),
|
||||||
)
|
)
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package com.kazier.mobile.ui.search
|
package com.kazier.mobile.ui.search
|
||||||
|
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.foundation.BorderStroke
|
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
import androidx.compose.foundation.combinedClickable
|
import androidx.compose.foundation.combinedClickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
@@ -18,15 +17,14 @@ import androidx.compose.foundation.layout.width
|
|||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.LazyRow
|
import androidx.compose.foundation.lazy.LazyRow
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Clear
|
||||||
import androidx.compose.material.icons.filled.Close
|
import androidx.compose.material.icons.filled.Close
|
||||||
import androidx.compose.material.icons.filled.Search
|
import androidx.compose.material.icons.filled.Search
|
||||||
import androidx.compose.material3.Card
|
|
||||||
import androidx.compose.material3.CardDefaults
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.FilterChip
|
import androidx.compose.material3.FilterChip
|
||||||
import androidx.compose.material3.FilterChipDefaults
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
@@ -45,9 +43,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.graphics.Color
|
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
@@ -65,13 +64,15 @@ import com.kazier.mobile.ui.components.DeleteWarningDialog
|
|||||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||||
import com.kazier.mobile.ui.components.FilePendingReviewBadge
|
import com.kazier.mobile.ui.components.FilePendingReviewBadge
|
||||||
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
||||||
|
import com.kazier.mobile.ui.components.KazierCard
|
||||||
|
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||||
import com.kazier.mobile.ui.components.MoveFolderPickerDialog
|
import com.kazier.mobile.ui.components.MoveFolderPickerDialog
|
||||||
import com.kazier.mobile.ui.components.SelectionState
|
import com.kazier.mobile.ui.components.SelectionState
|
||||||
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
||||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
import com.kazier.mobile.ui.components.formatFileSize
|
||||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
import com.kazier.mobile.ui.components.label
|
||||||
import com.kazier.mobile.ui.components.color
|
|
||||||
import com.kazier.mobile.ui.components.icon
|
import com.kazier.mobile.ui.components.icon
|
||||||
|
import com.kazier.mobile.ui.components.color
|
||||||
import com.kazier.mobile.ui.components.rememberSelectionState
|
import com.kazier.mobile.ui.components.rememberSelectionState
|
||||||
import com.kazier.mobile.ui.components.reviewDelete
|
import com.kazier.mobile.ui.components.reviewDelete
|
||||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||||
@@ -91,7 +92,6 @@ fun SearchScreen(
|
|||||||
viewModel: SearchViewModel = hiltViewModel(),
|
viewModel: SearchViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
|
||||||
val moveFolders by viewModel.moveFolders.collectAsStateWithLifecycle()
|
val moveFolders by viewModel.moveFolders.collectAsStateWithLifecycle()
|
||||||
val moveError by viewModel.moveError.collectAsStateWithLifecycle()
|
val moveError by viewModel.moveError.collectAsStateWithLifecycle()
|
||||||
val deleteError by viewModel.deleteError.collectAsStateWithLifecycle()
|
val deleteError by viewModel.deleteError.collectAsStateWithLifecycle()
|
||||||
@@ -100,10 +100,10 @@ fun SearchScreen(
|
|||||||
var showMoveDialog by rememberSaveable { mutableStateOf(false) }
|
var showMoveDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
var pendingDeleteReview by rememberSaveable { mutableStateOf<DeleteReview?>(null) }
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
val deletedLabel = stringResource(R.string.delete)
|
val deletedLabel = stringResource(R.string.delete_success)
|
||||||
|
|
||||||
LaunchedEffect(moveError) {
|
LaunchedEffect(moveError) {
|
||||||
val message = moveError
|
val message = moveError
|
||||||
@@ -156,10 +156,9 @@ fun SearchScreen(
|
|||||||
},
|
},
|
||||||
actions = {
|
actions = {
|
||||||
if (!selection.active) {
|
if (!selection.active) {
|
||||||
SyncStatusAction(syncViewModel = syncViewModel)
|
HeaderStatusAction(
|
||||||
ServerStatusBadge(
|
syncViewModel = syncViewModel,
|
||||||
status = connectionStatus,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
onClick = connectionStatusViewModel::checkNow,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -274,6 +273,7 @@ private fun SearchContent(
|
|||||||
onOpenDocument: (String) -> Unit,
|
onOpenDocument: (String) -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
|
val keyboardController = LocalSoftwareKeyboardController.current
|
||||||
Column(
|
Column(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
@@ -286,9 +286,23 @@ private fun SearchContent(
|
|||||||
onValueChange = onQueryChange,
|
onValueChange = onQueryChange,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
||||||
|
trailingIcon = {
|
||||||
|
if (uiState.query.isNotBlank() && !selection.active) {
|
||||||
|
IconButton(onClick = { onQueryChange("") }) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Clear,
|
||||||
|
contentDescription = stringResource(R.string.search_clear),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
placeholder = { Text(stringResource(R.string.search_hint)) },
|
placeholder = { Text(stringResource(R.string.search_hint)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
enabled = !selection.active,
|
enabled = !selection.active,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||||
|
keyboardActions = KeyboardActions(
|
||||||
|
onSearch = { keyboardController?.hide() },
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
LazyRow(
|
LazyRow(
|
||||||
@@ -307,7 +321,7 @@ private fun SearchContent(
|
|||||||
}
|
}
|
||||||
items(FileCategory.entries, key = { it.name }) { category ->
|
items(FileCategory.entries, key = { it.name }) { category ->
|
||||||
CategoryChip(
|
CategoryChip(
|
||||||
label = categoryLabel(category),
|
label = category.label(),
|
||||||
selected = uiState.selectedCategory == category.dbValue,
|
selected = uiState.selectedCategory == category.dbValue,
|
||||||
enabled = !selection.active,
|
enabled = !selection.active,
|
||||||
onClick = { onCategorySelect(category.dbValue) },
|
onClick = { onCategorySelect(category.dbValue) },
|
||||||
@@ -342,29 +356,14 @@ private fun CategoryChip(
|
|||||||
{
|
{
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = cat.icon,
|
imageVector = cat.icon,
|
||||||
contentDescription = null,
|
contentDescription = cat.label(),
|
||||||
tint = cat.color,
|
tint = cat.color(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
colors = FilterChipDefaults.filterChipColors(
|
|
||||||
containerColor = Color(0xFFF7F8FA),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Libellé français de la catégorie (store = enum.name, affichage = label localisé). */
|
|
||||||
@Composable
|
|
||||||
private fun categoryLabel(category: FileCategory): String = when (category) {
|
|
||||||
FileCategory.PDF -> stringResource(R.string.category_pdf)
|
|
||||||
FileCategory.OFFICE -> stringResource(R.string.category_office)
|
|
||||||
FileCategory.IMAGE -> stringResource(R.string.category_image)
|
|
||||||
FileCategory.TEXT -> stringResource(R.string.category_text)
|
|
||||||
FileCategory.VIDEO -> stringResource(R.string.category_video)
|
|
||||||
FileCategory.AUDIO -> stringResource(R.string.category_audio)
|
|
||||||
FileCategory.OTHER -> stringResource(R.string.category_other)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun SearchResults(
|
private fun SearchResults(
|
||||||
uiState: SearchUiState,
|
uiState: SearchUiState,
|
||||||
@@ -413,6 +412,15 @@ private fun SearchResults(
|
|||||||
modifier = Modifier.padding(top = 4.dp),
|
modifier = Modifier.padding(top = 4.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
item(key = "results-count") {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.search_results_count, uiState.results.size),
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.padding(top = 4.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
items(uiState.results, key = { it.resourceId }) { file ->
|
items(uiState.results, key = { it.resourceId }) { file ->
|
||||||
SearchResultCard(
|
SearchResultCard(
|
||||||
@@ -434,11 +442,7 @@ private fun SearchResultCard(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
val selected = file.resourceId in selection.ids
|
val selected = file.resourceId in selection.ids
|
||||||
Card(
|
KazierCard(
|
||||||
colors = CardDefaults.cardColors(containerColor = Color(0xFFF7F8FA)),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
|
||||||
border = BorderStroke(1.dp, Color(0xFFEAEAEA)),
|
|
||||||
shape = RoundedCornerShape(10.dp),
|
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.combinedClickable(
|
.combinedClickable(
|
||||||
@@ -466,9 +470,11 @@ private fun SearchResultCard(
|
|||||||
)
|
)
|
||||||
Spacer(Modifier.height(2.dp))
|
Spacer(Modifier.height(2.dp))
|
||||||
Text(
|
Text(
|
||||||
text = file.extension?.let { it.uppercase(Locale.getDefault()) } ?: formatSize(file.size),
|
text = resultSubtitle(file),
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.width(12.dp))
|
Spacer(Modifier.width(12.dp))
|
||||||
@@ -480,11 +486,6 @@ private fun SearchResultCard(
|
|||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
) {
|
) {
|
||||||
FilePendingReviewBadge(file = file)
|
FilePendingReviewBadge(file = file)
|
||||||
Text(
|
|
||||||
text = formatSize(file.size),
|
|
||||||
style = MaterialTheme.typography.labelMedium,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
FileSyncStatusIcon(file = file, size = 18.dp)
|
FileSyncStatusIcon(file = file, size = 18.dp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -492,15 +493,10 @@ private fun SearchResultCard(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Sous-titre résultat : `EXT · taille` si l'extension existe, sinon la taille seule. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun formatSize(bytes: Long): String {
|
private fun resultSubtitle(file: FileEntity): String {
|
||||||
if (bytes < 1_024) {
|
val size = formatFileSize(file.size)
|
||||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
val ext = file.extension?.takeIf { it.isNotBlank() }?.uppercase(Locale.getDefault())
|
||||||
}
|
return if (ext != null) "$ext · $size" else size
|
||||||
if (bytes < 1_024 * 1_024) {
|
|
||||||
val kb = bytes / 1_024f
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
|
||||||
}
|
|
||||||
val mb = bytes / (1_024f * 1_024f)
|
|
||||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
package com.kazier.mobile.ui.settings
|
package com.kazier.mobile.ui.settings
|
||||||
|
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
|
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.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
@@ -14,22 +16,24 @@ import androidx.compose.foundation.text.KeyboardOptions
|
|||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.DarkMode
|
import androidx.compose.material.icons.filled.DarkMode
|
||||||
|
import androidx.compose.material.icons.filled.Dns
|
||||||
import androidx.compose.material.icons.filled.Folder
|
import androidx.compose.material.icons.filled.Folder
|
||||||
import androidx.compose.material.icons.filled.Person
|
import androidx.compose.material.icons.filled.Person
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.FilterChip
|
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.RadioButton
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
@@ -40,8 +44,6 @@ import androidx.compose.ui.res.stringResource
|
|||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
@@ -51,9 +53,9 @@ 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.AuthState
|
import com.kazier.mobile.ui.auth.AuthState
|
||||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||||
|
import com.kazier.mobile.ui.auth.LoginForm
|
||||||
import com.kazier.mobile.ui.auth.authErrorResFor
|
import com.kazier.mobile.ui.auth.authErrorResFor
|
||||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
|
||||||
import com.kazier.mobile.ui.components.WatchedFoldersBadge
|
import com.kazier.mobile.ui.components.WatchedFoldersBadge
|
||||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||||
import com.kazier.mobile.ui.navigation.NavTab
|
import com.kazier.mobile.ui.navigation.NavTab
|
||||||
@@ -72,22 +74,31 @@ fun SettingsScreen(
|
|||||||
val theme by viewModel.theme.collectAsStateWithLifecycle()
|
val theme by viewModel.theme.collectAsStateWithLifecycle()
|
||||||
val serverUrl by viewModel.serverUrl.collectAsStateWithLifecycle()
|
val serverUrl by viewModel.serverUrl.collectAsStateWithLifecycle()
|
||||||
val testUiState by viewModel.testUiState.collectAsStateWithLifecycle()
|
val testUiState by viewModel.testUiState.collectAsStateWithLifecycle()
|
||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
|
||||||
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||||
val loginUi by authViewModel.loginUiState.collectAsStateWithLifecycle()
|
val loginUi by authViewModel.loginUiState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
var username by rememberSaveable { mutableStateOf("") }
|
var username by rememberSaveable { mutableStateOf("") }
|
||||||
var password by rememberSaveable { mutableStateOf("") }
|
var password by rememberSaveable { mutableStateOf("") }
|
||||||
|
var showThemeDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var showServerDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var showAuthDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
|
// Login réussi → refermer le dialogue et purger le mot de passe.
|
||||||
|
LaunchedEffect(authState) {
|
||||||
|
if (authState is AuthState.SignedIn) {
|
||||||
|
showAuthDialog = false
|
||||||
|
password = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = { Text(stringResource(R.string.settings)) },
|
title = { Text(stringResource(R.string.settings)) },
|
||||||
actions = {
|
actions = {
|
||||||
SyncStatusAction(syncViewModel = syncViewModel)
|
HeaderStatusAction(
|
||||||
ServerStatusBadge(
|
syncViewModel = syncViewModel,
|
||||||
status = connectionStatus,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
onClick = connectionStatusViewModel::checkNow,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -100,11 +111,12 @@ fun SettingsScreen(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding)
|
.padding(padding)
|
||||||
|
.imePadding()
|
||||||
.verticalScroll(rememberScrollState()),
|
.verticalScroll(rememberScrollState()),
|
||||||
) {
|
) {
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
// M36 : 3 états (Système/Clair/Sombre) — le Switch DARK/LIGHT
|
// Une ligne par section — le détail vit dans un dialogue,
|
||||||
// rendait SYSTEM inatteignable alors que le store le supporte.
|
// comme les dossiers système surveillés.
|
||||||
SettingsRow(
|
SettingsRow(
|
||||||
icon = { Icon(Icons.Filled.DarkMode, contentDescription = null) },
|
icon = { Icon(Icons.Filled.DarkMode, contentDescription = null) },
|
||||||
title = stringResource(R.string.settings_theme),
|
title = stringResource(R.string.settings_theme),
|
||||||
@@ -115,12 +127,7 @@ fun SettingsScreen(
|
|||||||
ThemePreference.SYSTEM -> R.string.settings_theme_system
|
ThemePreference.SYSTEM -> R.string.settings_theme_system
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
trailing = {
|
onClick = { showThemeDialog = true },
|
||||||
ThemeSelector(
|
|
||||||
selected = theme,
|
|
||||||
onSelect = viewModel::setTheme,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
|
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
@@ -135,30 +142,193 @@ fun SettingsScreen(
|
|||||||
)
|
)
|
||||||
|
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
SettingsSectionTitle(stringResource(R.string.settings_server))
|
SettingsRow(
|
||||||
|
icon = { Icon(Icons.Filled.Dns, contentDescription = null) },
|
||||||
|
title = stringResource(R.string.settings_server),
|
||||||
|
subtitle = serverUrl.ifBlank {
|
||||||
|
stringResource(R.string.settings_server_hint)
|
||||||
|
},
|
||||||
|
onClick = { showServerDialog = true },
|
||||||
|
)
|
||||||
|
|
||||||
|
HorizontalDivider()
|
||||||
|
val signedIn = authState as? AuthState.SignedIn
|
||||||
|
SettingsRow(
|
||||||
|
icon = { Icon(Icons.Filled.Person, contentDescription = null) },
|
||||||
|
title = stringResource(
|
||||||
|
if (signedIn != null) R.string.settings_disconnect
|
||||||
|
else R.string.settings_connect,
|
||||||
|
),
|
||||||
|
subtitle = when (val state = authState) {
|
||||||
|
is AuthState.SignedIn ->
|
||||||
|
stringResource(R.string.settings_connected_as, state.user.username)
|
||||||
|
AuthState.Local -> stringResource(R.string.status_local)
|
||||||
|
AuthState.Loading -> stringResource(R.string.status_checking)
|
||||||
|
else -> stringResource(R.string.settings_sign_in_hint)
|
||||||
|
},
|
||||||
|
onClick = { showAuthDialog = true },
|
||||||
|
)
|
||||||
|
|
||||||
|
HorizontalDivider()
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showThemeDialog) {
|
||||||
|
ThemeDialog(
|
||||||
|
selected = theme,
|
||||||
|
onSelect = viewModel::setTheme,
|
||||||
|
onDismiss = { showThemeDialog = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showServerDialog) {
|
||||||
|
ServerDialog(
|
||||||
|
serverUrl = serverUrl,
|
||||||
|
onServerUrlChange = viewModel::onServerUrlChange,
|
||||||
|
isTesting = testUiState.isTesting,
|
||||||
|
success = testUiState.success,
|
||||||
|
onTest = viewModel::testConnection,
|
||||||
|
onDismiss = { showServerDialog = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showAuthDialog) {
|
||||||
|
when (val state = authState) {
|
||||||
|
is AuthState.SignedIn -> {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showAuthDialog = false },
|
||||||
|
title = { Text(stringResource(R.string.settings_disconnect)) },
|
||||||
|
text = {
|
||||||
|
Text(stringResource(R.string.settings_disconnect_confirm, state.user.username))
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
authViewModel.signOutToLocal()
|
||||||
|
showAuthDialog = false
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.settings_disconnect))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showAuthDialog = false }) {
|
||||||
|
Text(stringResource(R.string.settings_cancel))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
AuthState.Loading -> Unit
|
||||||
|
else -> {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showAuthDialog = false },
|
||||||
|
title = { Text(stringResource(R.string.settings_connect)) },
|
||||||
|
text = {
|
||||||
|
LoginForm(
|
||||||
|
username = username,
|
||||||
|
onUsernameChange = { username = it },
|
||||||
|
password = password,
|
||||||
|
onPasswordChange = { password = it },
|
||||||
|
submitting = loginUi.isSubmitting,
|
||||||
|
errorRes = loginUi.error?.let(::authErrorResFor),
|
||||||
|
submitLabel = stringResource(R.string.settings_connect),
|
||||||
|
onSubmit = { authViewModel.signIn(username, password) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
confirmButton = {},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ThemeDialog(
|
||||||
|
selected: ThemePreference,
|
||||||
|
onSelect: (ThemePreference) -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
val options = listOf(
|
||||||
|
ThemePreference.SYSTEM to R.string.settings_theme_system,
|
||||||
|
ThemePreference.LIGHT to R.string.settings_theme_light,
|
||||||
|
ThemePreference.DARK to R.string.settings_theme_dark,
|
||||||
|
)
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(stringResource(R.string.settings_theme_choose)) },
|
||||||
|
text = {
|
||||||
|
Column {
|
||||||
|
options.forEach { (preference, labelRes) ->
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable {
|
||||||
|
onSelect(preference)
|
||||||
|
onDismiss()
|
||||||
|
}
|
||||||
|
.padding(vertical = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
RadioButton(
|
||||||
|
selected = selected == preference,
|
||||||
|
onClick = {
|
||||||
|
onSelect(preference)
|
||||||
|
onDismiss()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = stringResource(labelRes),
|
||||||
|
modifier = Modifier.padding(start = 8.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = onDismiss) {
|
||||||
|
Text(stringResource(R.string.settings_close))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ServerDialog(
|
||||||
|
serverUrl: String,
|
||||||
|
onServerUrlChange: (String) -> Unit,
|
||||||
|
isTesting: Boolean,
|
||||||
|
success: Boolean?,
|
||||||
|
onTest: () -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(stringResource(R.string.settings_server)) },
|
||||||
|
text = {
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = serverUrl,
|
value = serverUrl,
|
||||||
onValueChange = viewModel::onServerUrlChange,
|
onValueChange = onServerUrlChange,
|
||||||
label = { Text(stringResource(R.string.settings_server_url)) },
|
label = { Text(stringResource(R.string.settings_server_url)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
keyboardOptions = KeyboardOptions(
|
keyboardOptions = KeyboardOptions(
|
||||||
keyboardType = KeyboardType.Uri,
|
keyboardType = KeyboardType.Uri,
|
||||||
imeAction = ImeAction.Done,
|
imeAction = ImeAction.Done,
|
||||||
),
|
),
|
||||||
modifier = Modifier
|
modifier = Modifier.fillMaxWidth(),
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 16.dp),
|
|
||||||
)
|
)
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onClick = viewModel::testConnection,
|
onClick = onTest,
|
||||||
enabled = !testUiState.isTesting,
|
enabled = !isTesting,
|
||||||
) {
|
) {
|
||||||
if (testUiState.isTesting) {
|
if (isTesting) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(18.dp),
|
modifier = Modifier.size(18.dp),
|
||||||
strokeWidth = 2.dp,
|
strokeWidth = 2.dp,
|
||||||
@@ -167,15 +337,15 @@ fun SettingsScreen(
|
|||||||
Text(stringResource(R.string.settings_test_connection))
|
Text(stringResource(R.string.settings_test_connection))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
testUiState.success?.let { success ->
|
success?.let {
|
||||||
Spacer(Modifier.size(16.dp))
|
Spacer(Modifier.size(16.dp))
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(
|
text = stringResource(
|
||||||
if (success) R.string.settings_test_success
|
if (it) R.string.settings_test_success
|
||||||
else R.string.settings_test_failure,
|
else R.string.settings_test_failure,
|
||||||
),
|
),
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = if (success) {
|
color = if (it) {
|
||||||
MaterialTheme.colorScheme.primary
|
MaterialTheme.colorScheme.primary
|
||||||
} else {
|
} else {
|
||||||
MaterialTheme.colorScheme.error
|
MaterialTheme.colorScheme.error
|
||||||
@@ -183,120 +353,13 @@ fun SettingsScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
HorizontalDivider()
|
|
||||||
when (val state = authState) {
|
|
||||||
is AuthState.SignedIn -> {
|
|
||||||
SettingsRow(
|
|
||||||
icon = { Icon(Icons.Filled.Person, contentDescription = null) },
|
|
||||||
title = stringResource(R.string.settings_connected_as, state.user.username),
|
|
||||||
subtitle = stringResource(R.string.settings),
|
|
||||||
trailing = {
|
|
||||||
TextButton(onClick = authViewModel::signOutToLocal) {
|
|
||||||
Text(stringResource(R.string.settings_disconnect))
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
confirmButton = {
|
||||||
|
TextButton(onClick = onDismiss) {
|
||||||
|
Text(stringResource(R.string.settings_close))
|
||||||
}
|
}
|
||||||
AuthState.Loading -> Unit
|
},
|
||||||
else -> {
|
|
||||||
SettingsSectionTitle(stringResource(R.string.settings_connect))
|
|
||||||
OutlinedTextField(
|
|
||||||
value = username,
|
|
||||||
onValueChange = { username = it },
|
|
||||||
label = { Text(stringResource(R.string.login_username)) },
|
|
||||||
singleLine = true,
|
|
||||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 16.dp),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(12.dp))
|
|
||||||
OutlinedTextField(
|
|
||||||
value = password,
|
|
||||||
onValueChange = { password = it },
|
|
||||||
label = { Text(stringResource(R.string.login_password)) },
|
|
||||||
singleLine = true,
|
|
||||||
visualTransformation = PasswordVisualTransformation(),
|
|
||||||
keyboardOptions = KeyboardOptions(
|
|
||||||
keyboardType = KeyboardType.Password,
|
|
||||||
imeAction = ImeAction.Done,
|
|
||||||
),
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 16.dp),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(12.dp))
|
|
||||||
Button(
|
|
||||||
onClick = { authViewModel.signIn(username, password) },
|
|
||||||
enabled = !loginUi.isSubmitting,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 16.dp),
|
|
||||||
) {
|
|
||||||
if (loginUi.isSubmitting) {
|
|
||||||
CircularProgressIndicator(
|
|
||||||
modifier = Modifier.size(20.dp),
|
|
||||||
strokeWidth = 2.dp,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Text(stringResource(R.string.settings_connect))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
loginUi.error?.let { error ->
|
|
||||||
Text(
|
|
||||||
text = stringResource(authErrorResFor(error)),
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.error,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
HorizontalDivider()
|
|
||||||
Spacer(Modifier.height(16.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun ThemeSelector(
|
|
||||||
selected: ThemePreference,
|
|
||||||
onSelect: (ThemePreference) -> Unit,
|
|
||||||
) {
|
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
|
||||||
ThemeChip(
|
|
||||||
label = stringResource(R.string.settings_theme_system),
|
|
||||||
selected = selected == ThemePreference.SYSTEM,
|
|
||||||
onClick = { onSelect(ThemePreference.SYSTEM) },
|
|
||||||
)
|
|
||||||
ThemeChip(
|
|
||||||
label = stringResource(R.string.settings_theme_light),
|
|
||||||
selected = selected == ThemePreference.LIGHT,
|
|
||||||
onClick = { onSelect(ThemePreference.LIGHT) },
|
|
||||||
)
|
|
||||||
ThemeChip(
|
|
||||||
label = stringResource(R.string.settings_theme_dark),
|
|
||||||
selected = selected == ThemePreference.DARK,
|
|
||||||
onClick = { onSelect(ThemePreference.DARK) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun ThemeChip(
|
|
||||||
label: String,
|
|
||||||
selected: Boolean,
|
|
||||||
onClick: () -> Unit,
|
|
||||||
) {
|
|
||||||
FilterChip(
|
|
||||||
selected = selected,
|
|
||||||
onClick = onClick,
|
|
||||||
label = { Text(label) },
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -335,14 +398,3 @@ private fun SettingsRow(
|
|||||||
trailing()
|
trailing()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun SettingsSectionTitle(title: String) {
|
|
||||||
Text(
|
|
||||||
text = title,
|
|
||||||
style = MaterialTheme.typography.titleSmall,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
color = MaterialTheme.colorScheme.primary,
|
|
||||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -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,40 +1,58 @@
|
|||||||
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.Box
|
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
|
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.KeyboardArrowDown
|
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.DropdownMenu
|
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||||
|
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.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
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.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
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
/** Niveau d'accès sélectionnable — miroir de `ShareAccessLevel`. */
|
/** Niveau d'accès sélectionnable — miroir de `ShareAccessLevel`. */
|
||||||
private data class AccessOption(
|
private data class AccessOption(
|
||||||
@@ -48,22 +66,33 @@ 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 remember { mutableStateOf("") }
|
// Confirmation visible avant fermeture : fini l'auto-dismiss silencieux.
|
||||||
var access by remember { mutableStateOf(ShareAccessLevel.VIEWER) }
|
var justShared by rememberSaveable { mutableStateOf(false) }
|
||||||
val sheetState = rememberModalBottomSheetState()
|
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||||
|
|
||||||
LaunchedEffect(enqueued) {
|
LaunchedEffect(state.enqueued) {
|
||||||
if (enqueued) onDismiss()
|
if (state.enqueued && !justShared) {
|
||||||
|
justShared = true
|
||||||
|
delay(1_200)
|
||||||
|
onDismiss()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ModalBottomSheet(
|
ModalBottomSheet(
|
||||||
@@ -73,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),
|
||||||
@@ -89,22 +119,241 @@ fun ShareBottomSheet(
|
|||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (state.pendingCount > 0) {
|
||||||
|
Text(
|
||||||
|
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,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenLinkSection(
|
||||||
|
resolving = state.resolving,
|
||||||
|
resolved = state.resolvedLink,
|
||||||
|
resolveError = state.resolveError,
|
||||||
|
onResolve = { viewModel.resolveLink(it) },
|
||||||
|
onClear = { viewModel.clearResolved() },
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onDismiss,
|
||||||
|
enabled = !state.sharing,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.share_cancel))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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(
|
OutlinedTextField(
|
||||||
value = username,
|
value = username,
|
||||||
onValueChange = { username = it },
|
onValueChange = { username = it },
|
||||||
label = { Text(stringResource(R.string.share_username_hint)) },
|
label = { Text(stringResource(R.string.share_username_hint)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
|
enabled = !justShared,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.share_access_label),
|
|
||||||
style = MaterialTheme.typography.labelLarge,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
AccessDropdown(
|
AccessDropdown(
|
||||||
selected = access,
|
selected = access,
|
||||||
onSelect = { access = it },
|
onSelect = { access = it },
|
||||||
|
enabled = !justShared,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -118,59 +367,275 @@ fun ShareBottomSheet(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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(
|
Button(
|
||||||
onClick = { onShare(username.trim(), access) },
|
onClick = { onShare(username.trim(), access) },
|
||||||
enabled = username.isNotBlank() && !sharing,
|
enabled = username.isNotBlank() && !sharing && !justShared,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
if (sharing) {
|
if (sharing) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||||
modifier = Modifier.size(20.dp),
|
|
||||||
strokeWidth = 2.dp,
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
Icon(Icons.Filled.Share, contentDescription = null)
|
Icon(Icons.Filled.Share, contentDescription = null)
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text(stringResource(R.string.share_submit))
|
Text(stringResource(R.string.share_submit))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
OutlinedButton(
|
}
|
||||||
onClick = onDismiss,
|
|
||||||
enabled = !sharing,
|
@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(),
|
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))
|
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)
|
||||||
@Composable
|
@Composable
|
||||||
private fun AccessDropdown(
|
private fun AccessDropdown(
|
||||||
selected: String,
|
selected: String,
|
||||||
onSelect: (String) -> Unit,
|
onSelect: (String) -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
|
enabled: Boolean = true,
|
||||||
) {
|
) {
|
||||||
var expanded by remember { mutableStateOf(false) }
|
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||||
val selectedLabel = ACCESS_OPTIONS.firstOrNull { it.value == selected }?.labelRes
|
val selectedLabel = ACCESS_OPTIONS.firstOrNull { it.value == selected }?.labelRes
|
||||||
?: ACCESS_OPTIONS.first().labelRes
|
?: ACCESS_OPTIONS.first().labelRes
|
||||||
|
|
||||||
Box(modifier = modifier) {
|
ExposedDropdownMenuBox(
|
||||||
OutlinedButton(
|
expanded = expanded,
|
||||||
onClick = { expanded = true },
|
onExpandedChange = { if (enabled) expanded = it },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = modifier,
|
||||||
) {
|
) {
|
||||||
Text(
|
OutlinedTextField(
|
||||||
text = stringResource(selectedLabel),
|
value = stringResource(selectedLabel),
|
||||||
modifier = Modifier.weight(1f),
|
onValueChange = {},
|
||||||
textAlign = TextAlign.Start,
|
readOnly = true,
|
||||||
|
enabled = enabled,
|
||||||
|
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||||
|
colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(),
|
||||||
|
modifier = Modifier
|
||||||
|
.menuAnchor(MenuAnchorType.PrimaryNotEditable)
|
||||||
|
.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
Icon(
|
ExposedDropdownMenu(
|
||||||
imageVector = Icons.Filled.KeyboardArrowDown,
|
|
||||||
contentDescription = null,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
DropdownMenu(
|
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
onDismissRequest = { expanded = false },
|
onDismissRequest = { expanded = false },
|
||||||
) {
|
) {
|
||||||
@@ -181,6 +646,7 @@ private fun AccessDropdown(
|
|||||||
onSelect(option.value)
|
onSelect(option.value)
|
||||||
expanded = false
|
expanded = false
|
||||||
},
|
},
|
||||||
|
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.kazier.mobile.ui.share
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extraction d'un token de lien de partage depuis une saisie utilisateur.
|
||||||
|
*
|
||||||
|
* Formats acceptés : 32-hex brut, URL deep-link `kazier://share/<token>`,
|
||||||
|
* ou URL API `…/shares/links/<token>`. Retourne le token normalisé
|
||||||
|
* (lowercase) ou null si rien d'exploitable.
|
||||||
|
*/
|
||||||
|
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)[:/]([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,11 +193,173 @@ 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()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,31 @@ package com.kazier.mobile.ui.theme
|
|||||||
|
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
|
// Marque — inchangée (contrat visuel existant).
|
||||||
val BrandBlue = Color(0xFF1A73E8)
|
val BrandBlue = Color(0xFF1A73E8)
|
||||||
|
val BrandBlueDark = Color(0xFF004A9E)
|
||||||
val BondBlueLight = Color(0xFFD2E3FC)
|
val BondBlueLight = Color(0xFFD2E3FC)
|
||||||
|
val BondBlueContainerDark = Color(0xFF004A77)
|
||||||
val InactiveGray = Color(0xFF6B7280)
|
val InactiveGray = Color(0xFF6B7280)
|
||||||
|
|
||||||
|
// Cartes / bordures — déclinaison light + dark (ne plus hardcoder en UI).
|
||||||
val CardBackground = Color(0xFFF7F8FA)
|
val CardBackground = Color(0xFFF7F8FA)
|
||||||
|
val CardBackgroundDark = Color(0xFF1E1F22)
|
||||||
val CardBorder = Color(0xFFEAEAEA)
|
val CardBorder = Color(0xFFEAEAEA)
|
||||||
|
val CardBorderDark = Color(0xFF333639)
|
||||||
|
|
||||||
|
// Sémantique métier — paires light/dark lisibles sur fond clair ET sombre.
|
||||||
|
val SuccessLight = Color(0xFF2E7D32)
|
||||||
|
val SuccessDark = Color(0xFF81C784)
|
||||||
|
val WarningLight = Color(0xFFB26A00)
|
||||||
|
val WarningDark = Color(0xFFFFB74D)
|
||||||
|
val InfoLight = Color(0xFF1565C0)
|
||||||
|
val InfoDark = Color(0xFF90CAF9)
|
||||||
|
val ErrorLight = Color(0xFFB3261E)
|
||||||
|
val ErrorDark = Color(0xFFF2B8B5)
|
||||||
|
|
||||||
|
// Pastilles sync / serveur — versions lisibles en dark (texte blanc exclu).
|
||||||
|
val SyncingLight = Color(0xFF1E88E5)
|
||||||
|
val SyncingDark = Color(0xFF90CAF9)
|
||||||
|
val PendingLight = Color(0xFFB26A00)
|
||||||
|
val PendingDark = Color(0xFFFFB74D)
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.kazier.mobile.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
|
/** Espacements et élévations partagés — évite les valeurs magiques dispersées. */
|
||||||
|
object KazierDimens {
|
||||||
|
val SpacingXxs = 2.dp
|
||||||
|
val SpacingXs = 4.dp
|
||||||
|
val SpacingSm = 8.dp
|
||||||
|
val SpacingMd = 12.dp
|
||||||
|
val SpacingLg = 16.dp
|
||||||
|
val SpacingXl = 20.dp
|
||||||
|
|
||||||
|
val CardElevation = 1.dp
|
||||||
|
val NavElevation = 8.dp
|
||||||
|
val CardBorderWidth = 1.dp
|
||||||
|
|
||||||
|
val ListMaxWidth = 400.dp
|
||||||
|
val DialogListMaxHeight = 360.dp
|
||||||
|
val MinTouchTarget = 48.dp
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.kazier.mobile.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.Shapes
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
|
/** Rayons unifiés : cartes 12dp, sheets/dialogs 20dp, pills 28dp. */
|
||||||
|
val KazierShapes = Shapes(
|
||||||
|
extraSmall = RoundedCornerShape(8.dp),
|
||||||
|
small = RoundedCornerShape(12.dp),
|
||||||
|
medium = RoundedCornerShape(20.dp),
|
||||||
|
large = RoundedCornerShape(28.dp),
|
||||||
|
extraLarge = RoundedCornerShape(30.dp),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Formes nommées pour les usages récurrents (listes, nav, badges). */
|
||||||
|
val ListCardShape = RoundedCornerShape(12.dp)
|
||||||
|
val SheetShape = RoundedCornerShape(20.dp)
|
||||||
|
val PillShape = RoundedCornerShape(percent = 50)
|
||||||
|
val NavPillShape = RoundedCornerShape(30.dp)
|
||||||
|
val NavItemShape = RoundedCornerShape(20.dp)
|
||||||
|
val ThumbShape = RoundedCornerShape(8.dp)
|
||||||
@@ -4,18 +4,61 @@ import androidx.compose.material3.MaterialTheme
|
|||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
import androidx.compose.material3.lightColorScheme
|
import androidx.compose.material3.lightColorScheme
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
import com.kazier.mobile.domain.ThemePreference
|
import com.kazier.mobile.domain.ThemePreference
|
||||||
|
|
||||||
private val LightColors = lightColorScheme(
|
private val LightColors = lightColorScheme(
|
||||||
primary = BrandBlue,
|
primary = BrandBlue,
|
||||||
onPrimary = androidx.compose.ui.graphics.Color.White,
|
onPrimary = Color.White,
|
||||||
|
primaryContainer = BondBlueLight,
|
||||||
|
onPrimaryContainer = BrandBlueDark,
|
||||||
secondary = InactiveGray,
|
secondary = InactiveGray,
|
||||||
|
onSecondary = Color.White,
|
||||||
|
secondaryContainer = CardBackground,
|
||||||
|
onSecondaryContainer = Color(0xFF1A1C1E),
|
||||||
|
tertiary = SuccessLight,
|
||||||
|
onTertiary = Color.White,
|
||||||
|
tertiaryContainer = Color(0xFFE3F2E6),
|
||||||
|
onTertiaryContainer = Color(0xFF1B4D1F),
|
||||||
|
error = ErrorLight,
|
||||||
|
onError = Color.White,
|
||||||
|
errorContainer = Color(0xFFF9DEDC),
|
||||||
|
onErrorContainer = Color(0xFF410E0B),
|
||||||
|
surface = Color(0xFFFFFBFE),
|
||||||
|
onSurface = Color(0xFF1A1C1E),
|
||||||
surfaceVariant = CardBackground,
|
surfaceVariant = CardBackground,
|
||||||
|
onSurfaceVariant = Color(0xFF43474E),
|
||||||
|
surfaceContainerLowest = Color.White,
|
||||||
|
surfaceContainerLow = CardBackground,
|
||||||
|
outline = Color(0xFFC3C6CF),
|
||||||
|
outlineVariant = CardBorder,
|
||||||
)
|
)
|
||||||
|
|
||||||
private val DarkColors = darkColorScheme(
|
private val DarkColors = darkColorScheme(
|
||||||
primary = BondBlueLight,
|
primary = BondBlueLight,
|
||||||
onPrimary = androidx.compose.ui.graphics.Color.Black,
|
onPrimary = Color(0xFF001D35),
|
||||||
|
primaryContainer = BondBlueContainerDark,
|
||||||
|
onPrimaryContainer = BondBlueLight,
|
||||||
|
secondary = Color(0xFF9AA0AA),
|
||||||
|
onSecondary = Color(0xFF1A1C1E),
|
||||||
|
secondaryContainer = CardBackgroundDark,
|
||||||
|
onSecondaryContainer = Color(0xFFE2E2E6),
|
||||||
|
tertiary = SuccessDark,
|
||||||
|
onTertiary = Color(0xFF00330A),
|
||||||
|
tertiaryContainer = Color(0xFF1B4D1F),
|
||||||
|
onTertiaryContainer = Color(0xFFE3F2E6),
|
||||||
|
error = ErrorDark,
|
||||||
|
onError = Color(0xFF601410),
|
||||||
|
errorContainer = Color(0xFF8C1D18),
|
||||||
|
onErrorContainer = Color(0xFFF9DEDC),
|
||||||
|
surface = Color(0xFF141218),
|
||||||
|
onSurface = Color(0xFFE6E0E9),
|
||||||
|
surfaceVariant = CardBackgroundDark,
|
||||||
|
onSurfaceVariant = Color(0xFFCAC4D0),
|
||||||
|
surfaceContainerLowest = Color(0xFF0F0D13),
|
||||||
|
surfaceContainerLow = CardBackgroundDark,
|
||||||
|
outline = Color(0xFF4A4E57),
|
||||||
|
outlineVariant = CardBorderDark,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -39,6 +82,7 @@ fun KazierTheme(
|
|||||||
MaterialTheme(
|
MaterialTheme(
|
||||||
colorScheme = if (darkTheme) DarkColors else LightColors,
|
colorScheme = if (darkTheme) DarkColors else LightColors,
|
||||||
typography = Typography,
|
typography = Typography,
|
||||||
|
shapes = KazierShapes,
|
||||||
content = content,
|
content = content,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,16 +6,46 @@ import androidx.compose.ui.text.font.FontWeight
|
|||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
val Typography = Typography(
|
val Typography = Typography(
|
||||||
bodyLarge = TextStyle(
|
headlineSmall = TextStyle(
|
||||||
fontSize = 16.sp,
|
fontSize = 20.sp,
|
||||||
lineHeight = 24.sp,
|
lineHeight = 28.sp,
|
||||||
fontWeight = FontWeight.Normal,
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
),
|
||||||
|
headlineMedium = TextStyle(
|
||||||
|
fontSize = 24.sp,
|
||||||
|
lineHeight = 32.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
),
|
||||||
|
titleSmall = TextStyle(
|
||||||
|
fontSize = 14.sp,
|
||||||
|
lineHeight = 20.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
),
|
),
|
||||||
titleMedium = TextStyle(
|
titleMedium = TextStyle(
|
||||||
fontSize = 16.sp,
|
fontSize = 16.sp,
|
||||||
lineHeight = 24.sp,
|
lineHeight = 24.sp,
|
||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
),
|
),
|
||||||
|
bodyLarge = TextStyle(
|
||||||
|
fontSize = 16.sp,
|
||||||
|
lineHeight = 24.sp,
|
||||||
|
fontWeight = FontWeight.Normal,
|
||||||
|
),
|
||||||
|
bodyMedium = TextStyle(
|
||||||
|
fontSize = 14.sp,
|
||||||
|
lineHeight = 20.sp,
|
||||||
|
fontWeight = FontWeight.Normal,
|
||||||
|
),
|
||||||
|
bodySmall = TextStyle(
|
||||||
|
fontSize = 12.sp,
|
||||||
|
lineHeight = 16.sp,
|
||||||
|
fontWeight = FontWeight.Normal,
|
||||||
|
),
|
||||||
|
labelSmall = TextStyle(
|
||||||
|
fontSize = 11.sp,
|
||||||
|
lineHeight = 16.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
),
|
||||||
labelMedium = TextStyle(
|
labelMedium = TextStyle(
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
lineHeight = 16.sp,
|
lineHeight = 16.sp,
|
||||||
|
|||||||
+59
-14
@@ -16,26 +16,30 @@ import androidx.compose.foundation.layout.size
|
|||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
import androidx.compose.material.icons.filled.Add
|
import androidx.compose.material.icons.filled.Add
|
||||||
import androidx.compose.material.icons.filled.Folder
|
import androidx.compose.material.icons.filled.Folder
|
||||||
|
import androidx.compose.material.icons.filled.Refresh
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.HorizontalDivider
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.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.draw.clip
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
@@ -65,6 +69,20 @@ fun WatchedFoldersScreen(
|
|||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val folderLabel = stringResource(R.string.folder)
|
val folderLabel = stringResource(R.string.folder)
|
||||||
|
val importDoneLabel = stringResource(R.string.settings_import_done)
|
||||||
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
|
// Erreur d'import → snackbar (une fois par message, auto-dismiss).
|
||||||
|
LaunchedEffect(importState.error) {
|
||||||
|
importState.error?.let { snackbarHostState.showSnackbar(it) }
|
||||||
|
}
|
||||||
|
// Fin d'import sans erreur → confirmation (succès silencieux sinon).
|
||||||
|
var wasImporting by remember { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(importState.isImporting) {
|
||||||
|
if (wasImporting && !importState.isImporting && importState.error == null) {
|
||||||
|
snackbarHostState.showSnackbar(importDoneLabel)
|
||||||
|
}
|
||||||
|
wasImporting = importState.isImporting
|
||||||
|
}
|
||||||
val pickFolderLauncher = rememberLauncherForActivityResult(
|
val pickFolderLauncher = rememberLauncherForActivityResult(
|
||||||
ActivityResultContracts.OpenDocumentTree(),
|
ActivityResultContracts.OpenDocumentTree(),
|
||||||
) { uri: Uri? ->
|
) { uri: Uri? ->
|
||||||
@@ -96,6 +114,7 @@ fun WatchedFoldersScreen(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
|
||||||
) { padding ->
|
) { padding ->
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -128,15 +147,20 @@ fun WatchedFoldersScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
items(folders, key = { it.resourceId }) { root ->
|
items(folders, key = { it.resourceId }) { root ->
|
||||||
WatchedFolderRow(root)
|
WatchedFolderRow(
|
||||||
HorizontalDivider()
|
folder = root,
|
||||||
|
rescanEnabled = !importState.isImporting,
|
||||||
|
onRescan = { uri ->
|
||||||
|
syncViewModel.importRoot(uri = uri, name = root.name)
|
||||||
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (folders.isEmpty() && !importState.isImporting) {
|
if (folders.isEmpty() && !importState.isImporting) {
|
||||||
item(key = "empty") {
|
item(key = "empty") {
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.settings_saf_folders_empty),
|
text = stringResource(R.string.settings_saf_folders_empty),
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -150,7 +174,20 @@ fun WatchedFoldersScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun WatchedFolderRow(folder: FolderEntity) {
|
private fun WatchedFolderRow(
|
||||||
|
folder: FolderEntity,
|
||||||
|
rescanEnabled: Boolean,
|
||||||
|
onRescan: (uri: String) -> Unit,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
// Nom lisible du dossier au lieu de l'URI brute `content://…`.
|
||||||
|
val location = remember(folder.uri) {
|
||||||
|
folder.uri?.let { raw ->
|
||||||
|
runCatching {
|
||||||
|
Uri.parse(raw)?.safDisplayName(context)
|
||||||
|
}.getOrNull()?.takeIf { it.isNotBlank() && it != folder.name }
|
||||||
|
}
|
||||||
|
}
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -160,12 +197,9 @@ private fun WatchedFolderRow(folder: FolderEntity) {
|
|||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.Folder,
|
imageVector = Icons.Filled.Folder,
|
||||||
contentDescription = null,
|
contentDescription = folder.name,
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier
|
modifier = Modifier.size(28.dp),
|
||||||
.size(40.dp)
|
|
||||||
.clip(CircleShape)
|
|
||||||
.padding(8.dp),
|
|
||||||
)
|
)
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
Text(
|
||||||
@@ -175,9 +209,9 @@ private fun WatchedFolderRow(folder: FolderEntity) {
|
|||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
folder.uri?.let { uri ->
|
location?.let {
|
||||||
Text(
|
Text(
|
||||||
text = uri,
|
text = it,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
@@ -185,5 +219,16 @@ private fun WatchedFolderRow(folder: FolderEntity) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
folder.uri?.let { uri ->
|
||||||
|
IconButton(
|
||||||
|
onClick = { onRescan(uri) },
|
||||||
|
enabled = rescanEnabled,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Filled.Refresh,
|
||||||
|
contentDescription = stringResource(R.string.refresh),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
<string name="dashboard_review_title">%1$d document(s) to review</string>
|
<string name="dashboard_review_title">%1$d document(s) to review</string>
|
||||||
<string name="dashboard_review_hint">Review them in swipe mode: keep (and sync) or delete.</string>
|
<string name="dashboard_review_hint">Review them in swipe mode: keep (and sync) or delete.</string>
|
||||||
<string name="dashboard_all_processed">All up to date — nothing to review.</string>
|
<string name="dashboard_all_processed">All up to date — nothing to review.</string>
|
||||||
|
<string name="dashboard_sync_title">Sync</string>
|
||||||
|
|
||||||
<!-- Review mode (swipe) -->
|
<!-- Review mode (swipe) -->
|
||||||
<string name="review_title">New documents</string>
|
<string name="review_title">New documents</string>
|
||||||
@@ -83,7 +84,18 @@
|
|||||||
<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="login_show_password">Show password</string>
|
||||||
|
<string name="login_hide_password">Hide password</string>
|
||||||
|
<string name="scan_permission_open_settings">Open Settings</string>
|
||||||
|
|
||||||
<!-- Server OCR -->
|
<!-- Server OCR -->
|
||||||
<string name="ocr_action">OCR</string>
|
<string name="ocr_action">OCR</string>
|
||||||
@@ -124,6 +136,18 @@
|
|||||||
<string name="settings_saf_folders_empty">No watched folders yet.</string>
|
<string name="settings_saf_folders_empty">No watched folders yet.</string>
|
||||||
<string name="settings_watched_folders">Watched system folders</string>
|
<string name="settings_watched_folders">Watched system folders</string>
|
||||||
<string name="settings_watched_folders_hint">View watched folders</string>
|
<string name="settings_watched_folders_hint">View watched folders</string>
|
||||||
|
<string name="settings_theme_choose">Choose theme</string>
|
||||||
|
<string name="settings_server_hint">Configure the server address</string>
|
||||||
|
<string name="settings_sign_in_hint">Sign in to your server</string>
|
||||||
|
<string name="settings_not_connected">Not signed in</string>
|
||||||
|
<string name="settings_disconnect_confirm">Sign out from %1$s?</string>
|
||||||
|
<string name="settings_close">Close</string>
|
||||||
|
<string name="settings_cancel">Cancel</string>
|
||||||
|
<string name="settings_import_done">Import finished</string>
|
||||||
|
|
||||||
|
<!-- Single header status pill + status bottom-sheet -->
|
||||||
|
<string name="status_sheet_title">Connection status</string>
|
||||||
|
<string name="status_sheet_view_queue">View queue</string>
|
||||||
<string name="watched_count_many">99+</string>
|
<string name="watched_count_many">99+</string>
|
||||||
|
|
||||||
<!-- Search -->
|
<!-- Search -->
|
||||||
@@ -132,6 +156,8 @@
|
|||||||
<string name="search_empty">Type a search or pick a category</string>
|
<string name="search_empty">Type a search or pick a category</string>
|
||||||
<string name="search_recent">Recent documents</string>
|
<string name="search_recent">Recent documents</string>
|
||||||
<string name="search_no_results">No results</string>
|
<string name="search_no_results">No results</string>
|
||||||
|
<string name="search_results_count">%1$d result(s)</string>
|
||||||
|
<string name="search_clear">Clear search</string>
|
||||||
<string name="category_all">All</string>
|
<string name="category_all">All</string>
|
||||||
<string name="category_pdf">PDF</string>
|
<string name="category_pdf">PDF</string>
|
||||||
<string name="category_office">Office</string>
|
<string name="category_office">Office</string>
|
||||||
@@ -151,7 +177,9 @@
|
|||||||
<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="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>
|
||||||
|
|
||||||
<!-- Server status (header badge) -->
|
<!-- Server status (header badge) -->
|
||||||
@@ -163,26 +191,31 @@
|
|||||||
|
|
||||||
<!-- Sync status (badge + outbox list) -->
|
<!-- Sync status (badge + outbox list) -->
|
||||||
<string name="sync_syncing">Syncing…</string>
|
<string name="sync_syncing">Syncing…</string>
|
||||||
<string name="sync_pending_count">%1$d pending</string>
|
<string name="sync_pending_count">%1$d to send</string>
|
||||||
<string name="sync_pending_count_one">1 pending</string>
|
<string name="sync_pending_count_one">1 to send</string>
|
||||||
<string name="sync_idle">Up to date</string>
|
<string name="sync_idle">Up to date</string>
|
||||||
<string name="sync_tap_to_view">Sync — tap to view the operations list</string>
|
<string name="sync_tap_to_view">Status — tap for details</string>
|
||||||
<string name="sync_list_title">Sync list</string>
|
<string name="sync_list_title">Sync</string>
|
||||||
<string name="sync_list_empty">No operations yet.</string>
|
<string name="sync_list_empty">Nothing here yet.</string>
|
||||||
<string name="sync_list_close">Close</string>
|
<string name="sync_list_close">Close</string>
|
||||||
<string name="sync_summary_total">%1$d operations</string>
|
<string name="sync_summary_total">%1$d items</string>
|
||||||
<string name="sync_summary_pending">%1$d pending</string>
|
<string name="sync_summary_pending">%1$d to send</string>
|
||||||
<string name="sync_summary_failed">%1$d failed</string>
|
<string name="sync_summary_failed">%1$d failed</string>
|
||||||
<string name="sync_status_pending">Pending</string>
|
<string name="sync_status_pending">To send</string>
|
||||||
<string name="sync_status_synced">Synced</string>
|
<string name="sync_status_synced">Sent</string>
|
||||||
<string name="sync_status_failed">Failed</string>
|
<string name="sync_status_failed">Failed</string>
|
||||||
<string name="sync_op_create">Create resource</string>
|
<string name="sync_op_create">Added</string>
|
||||||
<string name="sync_op_move">Move</string>
|
<string name="sync_op_move">Move</string>
|
||||||
<string name="sync_op_delete">Delete</string>
|
<string name="sync_op_delete">Delete</string>
|
||||||
<string name="sync_op_update">Update</string>
|
<string name="sync_op_update">Update</string>
|
||||||
|
<string name="sync_placement_local">Local-only file</string>
|
||||||
|
<string name="sync_placement_cloud">Cloud-only file</string>
|
||||||
|
<string name="sync_placement_local_cloud">Synced file</string>
|
||||||
|
|
||||||
<!-- Multi-select + PDF assembly -->
|
<!-- Multi-select + PDF assembly -->
|
||||||
<string name="selection_count">%1$d selected</string>
|
<string name="selection_count">%1$d selected</string>
|
||||||
|
<string name="selection_selected">Selected</string>
|
||||||
|
<string name="selection_unselected">Not selected</string>
|
||||||
<string name="selection_assemble">Assemble PDF</string>
|
<string name="selection_assemble">Assemble PDF</string>
|
||||||
<string name="selection_cancel">Cancel selection</string>
|
<string name="selection_cancel">Cancel selection</string>
|
||||||
|
|
||||||
@@ -217,6 +250,8 @@
|
|||||||
<string name="pdf_builder_name_hint">e.g. january_invoices</string>
|
<string name="pdf_builder_name_hint">e.g. january_invoices</string>
|
||||||
<string name="pdf_builder_name_save">Save</string>
|
<string name="pdf_builder_name_save">Save</string>
|
||||||
<string name="pdf_builder_saved">PDF created</string>
|
<string name="pdf_builder_saved">PDF created</string>
|
||||||
|
<string name="pdf_builder_view">View</string>
|
||||||
|
<string name="pdf_builder_search_files">Search files…</string>
|
||||||
<string name="pdf_builder_preview">Preview</string>
|
<string name="pdf_builder_preview">Preview</string>
|
||||||
<string name="pdf_builder_close_preview">Close preview</string>
|
<string name="pdf_builder_close_preview">Close preview</string>
|
||||||
<string name="pdf_generated_folder">Generated PDFs</string>
|
<string name="pdf_generated_folder">Generated PDFs</string>
|
||||||
@@ -268,6 +303,7 @@
|
|||||||
<string name="delete_confirm_button">Confirm</string>
|
<string name="delete_confirm_button">Confirm</string>
|
||||||
<string name="delete_cancel">Cancel</string>
|
<string name="delete_cancel">Cancel</string>
|
||||||
<string name="delete_error">Error while deleting</string>
|
<string name="delete_error">Error while deleting</string>
|
||||||
|
<string name="delete_success">Items deleted</string>
|
||||||
|
|
||||||
<!-- Sharing (share grants) -->
|
<!-- Sharing (share grants) -->
|
||||||
<string name="share_title">Share with a user</string>
|
<string name="share_title">Share with a user</string>
|
||||||
@@ -280,6 +316,32 @@
|
|||||||
<string name="share_cancel">Cancel</string>
|
<string name="share_cancel">Cancel</string>
|
||||||
<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_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>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
<string name="dashboard_review_title">%1$d document(s) à traiter</string>
|
<string name="dashboard_review_title">%1$d document(s) à traiter</string>
|
||||||
<string name="dashboard_review_hint">Révise-les en mode swipe : garder (et synchroniser) ou supprimer.</string>
|
<string name="dashboard_review_hint">Révise-les en mode swipe : garder (et synchroniser) ou supprimer.</string>
|
||||||
<string name="dashboard_all_processed">Tout est à jour — aucun document à traiter.</string>
|
<string name="dashboard_all_processed">Tout est à jour — aucun document à traiter.</string>
|
||||||
|
<string name="dashboard_sync_title">Synchronisation</string>
|
||||||
|
|
||||||
<!-- Mode review (swipe) -->
|
<!-- Mode review (swipe) -->
|
||||||
<string name="review_title">Nouveaux documents</string>
|
<string name="review_title">Nouveaux documents</string>
|
||||||
@@ -83,7 +84,18 @@
|
|||||||
<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="login_show_password">Afficher le mot de passe</string>
|
||||||
|
<string name="login_hide_password">Masquer le mot de passe</string>
|
||||||
|
<string name="scan_permission_open_settings">Ouvrir les Réglages</string>
|
||||||
|
|
||||||
<!-- OCR serveur -->
|
<!-- OCR serveur -->
|
||||||
<string name="ocr_action">OCR</string>
|
<string name="ocr_action">OCR</string>
|
||||||
@@ -124,6 +136,18 @@
|
|||||||
<string name="settings_saf_folders_empty">Aucun dossier surveillé pour le moment.</string>
|
<string name="settings_saf_folders_empty">Aucun dossier surveillé pour le moment.</string>
|
||||||
<string name="settings_watched_folders">Dossiers système surveillés</string>
|
<string name="settings_watched_folders">Dossiers système surveillés</string>
|
||||||
<string name="settings_watched_folders_hint">Consulter les dossiers surveillés</string>
|
<string name="settings_watched_folders_hint">Consulter les dossiers surveillés</string>
|
||||||
|
<string name="settings_theme_choose">Choisir le thème</string>
|
||||||
|
<string name="settings_server_hint">Configurer l\'adresse du serveur</string>
|
||||||
|
<string name="settings_sign_in_hint">Se connecter à ton serveur</string>
|
||||||
|
<string name="settings_not_connected">Non connecté</string>
|
||||||
|
<string name="settings_disconnect_confirm">Se déconnecter du compte %1$s ?</string>
|
||||||
|
<string name="settings_close">Fermer</string>
|
||||||
|
<string name="settings_cancel">Annuler</string>
|
||||||
|
<string name="settings_import_done">Import terminé</string>
|
||||||
|
|
||||||
|
<!-- Pastille statut unique du header + bottom-sheet état -->
|
||||||
|
<string name="status_sheet_title">État de la connexion</string>
|
||||||
|
<string name="status_sheet_view_queue">Voir la file</string>
|
||||||
<string name="watched_count_many">99+</string>
|
<string name="watched_count_many">99+</string>
|
||||||
|
|
||||||
<!-- Recherche -->
|
<!-- Recherche -->
|
||||||
@@ -132,6 +156,8 @@
|
|||||||
<string name="search_empty">Saisis une recherche ou choisis une catégorie</string>
|
<string name="search_empty">Saisis une recherche ou choisis une catégorie</string>
|
||||||
<string name="search_recent">Documents récents</string>
|
<string name="search_recent">Documents récents</string>
|
||||||
<string name="search_no_results">Aucun résultat</string>
|
<string name="search_no_results">Aucun résultat</string>
|
||||||
|
<string name="search_results_count">%1$d résultat(s)</string>
|
||||||
|
<string name="search_clear">Effacer la recherche</string>
|
||||||
<string name="category_all">Tous</string>
|
<string name="category_all">Tous</string>
|
||||||
<string name="category_pdf">PDF</string>
|
<string name="category_pdf">PDF</string>
|
||||||
<string name="category_office">Bureautique</string>
|
<string name="category_office">Bureautique</string>
|
||||||
@@ -151,7 +177,9 @@
|
|||||||
<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="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>
|
||||||
|
|
||||||
<!-- Statut serveur (badge du header) -->
|
<!-- Statut serveur (badge du header) -->
|
||||||
@@ -163,26 +191,31 @@
|
|||||||
|
|
||||||
<!-- Statut de synchronisation (badge + liste outbox) -->
|
<!-- Statut de synchronisation (badge + liste outbox) -->
|
||||||
<string name="sync_syncing">Synchro…</string>
|
<string name="sync_syncing">Synchro…</string>
|
||||||
<string name="sync_pending_count">%1$d en attente</string>
|
<string name="sync_pending_count">%1$d à envoyer</string>
|
||||||
<string name="sync_pending_count_one">1 en attente</string>
|
<string name="sync_pending_count_one">1 à envoyer</string>
|
||||||
<string name="sync_idle">À jour</string>
|
<string name="sync_idle">À jour</string>
|
||||||
<string name="sync_tap_to_view">Synchro — appuyer pour voir la liste des ops</string>
|
<string name="sync_tap_to_view">État — appuyer pour voir le détail</string>
|
||||||
<string name="sync_list_title">Liste des sync</string>
|
<string name="sync_list_title">Synchronisation</string>
|
||||||
<string name="sync_list_empty">Aucune opération pour le moment.</string>
|
<string name="sync_list_empty">Aucun élément pour le moment.</string>
|
||||||
<string name="sync_list_close">Fermer</string>
|
<string name="sync_list_close">Fermer</string>
|
||||||
<string name="sync_summary_total">%1$d opérations</string>
|
<string name="sync_summary_total">%1$d éléments</string>
|
||||||
<string name="sync_summary_pending">%1$d en attente</string>
|
<string name="sync_summary_pending">%1$d à envoyer</string>
|
||||||
<string name="sync_summary_failed">%1$d échouée(s)</string>
|
<string name="sync_summary_failed">%1$d en échec</string>
|
||||||
<string name="sync_status_pending">En attente</string>
|
<string name="sync_status_pending">À envoyer</string>
|
||||||
<string name="sync_status_synced">Poussée</string>
|
<string name="sync_status_synced">Envoyé</string>
|
||||||
<string name="sync_status_failed">Échouée</string>
|
<string name="sync_status_failed">En échec</string>
|
||||||
<string name="sync_op_create">Création de ressource</string>
|
<string name="sync_op_create">Ajout</string>
|
||||||
<string name="sync_op_move">Déplacement</string>
|
<string name="sync_op_move">Déplacement</string>
|
||||||
<string name="sync_op_delete">Suppression</string>
|
<string name="sync_op_delete">Suppression</string>
|
||||||
<string name="sync_op_update">Mise à jour</string>
|
<string name="sync_op_update">Mise à jour</string>
|
||||||
|
<string name="sync_placement_local">Fichier local uniquement</string>
|
||||||
|
<string name="sync_placement_cloud">Fichier distant uniquement</string>
|
||||||
|
<string name="sync_placement_local_cloud">Fichier synchronisé</string>
|
||||||
|
|
||||||
<!-- Sélection multi-fichiers + assemblage PDF -->
|
<!-- Sélection multi-fichiers + assemblage PDF -->
|
||||||
<string name="selection_count">%1$d sélectionné(s)</string>
|
<string name="selection_count">%1$d sélectionné(s)</string>
|
||||||
|
<string name="selection_selected">Sélectionné</string>
|
||||||
|
<string name="selection_unselected">Non sélectionné</string>
|
||||||
<string name="selection_assemble">Assembler en PDF</string>
|
<string name="selection_assemble">Assembler en PDF</string>
|
||||||
<string name="selection_cancel">Annuler la sélection</string>
|
<string name="selection_cancel">Annuler la sélection</string>
|
||||||
|
|
||||||
@@ -217,6 +250,8 @@
|
|||||||
<string name="pdf_builder_name_hint">ex. factures_janvier</string>
|
<string name="pdf_builder_name_hint">ex. factures_janvier</string>
|
||||||
<string name="pdf_builder_name_save">Enregistrer</string>
|
<string name="pdf_builder_name_save">Enregistrer</string>
|
||||||
<string name="pdf_builder_saved">PDF créé</string>
|
<string name="pdf_builder_saved">PDF créé</string>
|
||||||
|
<string name="pdf_builder_view">Voir</string>
|
||||||
|
<string name="pdf_builder_search_files">Rechercher un fichier…</string>
|
||||||
<string name="pdf_builder_preview">Aperçu</string>
|
<string name="pdf_builder_preview">Aperçu</string>
|
||||||
<string name="pdf_builder_close_preview">Fermer l\'aperçu</string>
|
<string name="pdf_builder_close_preview">Fermer l\'aperçu</string>
|
||||||
<string name="pdf_generated_folder">PDF générés</string>
|
<string name="pdf_generated_folder">PDF générés</string>
|
||||||
@@ -268,6 +303,7 @@
|
|||||||
<string name="delete_confirm_button">Confirmer</string>
|
<string name="delete_confirm_button">Confirmer</string>
|
||||||
<string name="delete_cancel">Annuler</string>
|
<string name="delete_cancel">Annuler</string>
|
||||||
<string name="delete_error">Erreur lors de la suppression</string>
|
<string name="delete_error">Erreur lors de la suppression</string>
|
||||||
|
<string name="delete_success">Éléments supprimés</string>
|
||||||
|
|
||||||
<!-- Partage (share grants) -->
|
<!-- Partage (share grants) -->
|
||||||
<string name="share_title">Partager avec un utilisateur</string>
|
<string name="share_title">Partager avec un utilisateur</string>
|
||||||
@@ -280,6 +316,32 @@
|
|||||||
<string name="share_cancel">Annuler</string>
|
<string name="share_cancel">Annuler</string>
|
||||||
<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_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>
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package com.kazier.mobile.data.local.dao
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* m7 : la recherche `LIKE` échappe `%`/`_` (littéraux, pas des jokers) —
|
||||||
|
* « 100% » ne matchait pas tout avant le fix. La casse ASCII reste
|
||||||
|
* insensible (`COLLATE NOCASE`).
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class SearchEscapeTest {
|
||||||
|
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var fileDao: FileDao
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
fileDao = db.fileDao()
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun pourcentage_litteral_ne_match_pas_tout() = runTest {
|
||||||
|
fileDao.upsert(file("a".repeat(32), "100%.txt"))
|
||||||
|
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
||||||
|
fileDao.upsert(file("c".repeat(32), "normal.txt"))
|
||||||
|
|
||||||
|
// Le repository échappe avant d'appeler le DAO — on rejoue ici le
|
||||||
|
// contrat (`escapeLike`) pour verrouiller le comportement SQL.
|
||||||
|
val escaped = "100%".escapeLikeForTest()
|
||||||
|
val rows = fileDao.searchWithFilters(escaped, null).first()
|
||||||
|
|
||||||
|
assertEquals(listOf("100%.txt"), rows.map { it.name })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun underscore_litteral_ne_match_pas_tout() = runTest {
|
||||||
|
fileDao.upsert(file("a".repeat(32), "100%.txt"))
|
||||||
|
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
||||||
|
fileDao.upsert(file("c".repeat(32), "axb.txt"))
|
||||||
|
|
||||||
|
val rows = fileDao.searchWithFilters("a\\_b", null).first()
|
||||||
|
|
||||||
|
assertEquals(listOf("a_b.txt"), rows.map { it.name })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun recherche_insensible_a_la_casse_ascii() = runTest {
|
||||||
|
fileDao.upsert(file("a".repeat(32), "Rapport.TXT"))
|
||||||
|
|
||||||
|
val rows = fileDao.searchWithFilters("rapport", null).first()
|
||||||
|
|
||||||
|
assertEquals(listOf("Rapport.TXT"), rows.map { it.name })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun file(resourceId: String, name: String) = FileEntity(
|
||||||
|
resourceId = resourceId,
|
||||||
|
name = name,
|
||||||
|
folderResourceId = "f".repeat(32),
|
||||||
|
size = 10L,
|
||||||
|
exists = 1,
|
||||||
|
addedAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Miroir de `escapeLike` (interne au main) : `%`/`_`/`\` échappés. */
|
||||||
|
private fun String.escapeLikeForTest(): String =
|
||||||
|
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val NOW = 1_700_000_000_000L
|
||||||
|
}
|
||||||
|
}
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
package com.kazier.mobile.data.local.migration
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||||
|
import androidx.sqlite.db.SupportSQLiteOpenHelper
|
||||||
|
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M13 : la migration 14→15 backfill `exists` NULL→1 sur `folders` et `files`.
|
||||||
|
* Les lignes insérées sans `exists` explicite (défaut Kotlin `null` avant ce
|
||||||
|
* fix) étaient invisibles des requêtes `WHERE exists = 1` — elles
|
||||||
|
* réapparaissent comme présentes, état le plus sûr (le walk les re-marque
|
||||||
|
* `exists = 0` si elles ont vraiment disparu). Les lignes déjà à 0/1 sont
|
||||||
|
* intactes.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class Migration14To15Test {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun migration_backfill_exists_null_vers_1_sans_toucher_les_lignes_renseignees() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val helper = FrameworkSQLiteOpenHelperFactory().create(
|
||||||
|
SupportSQLiteOpenHelper.Configuration.builder(context)
|
||||||
|
.name(null)
|
||||||
|
.callback(V14Callback())
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
val db = helper.writableDatabase
|
||||||
|
db.execSQL(
|
||||||
|
"INSERT INTO `folders` (`resource_id`, `name`, `exists`, `sync_status`, `added_at`, `updated_at`) " +
|
||||||
|
"VALUES ('f-null', 'Null', NULL, 'local', 1, 1), ('f-zero', 'Zero', 0, 'local', 1, 1), ('f-one', 'One', 1, 'local', 1, 1)",
|
||||||
|
)
|
||||||
|
db.execSQL(
|
||||||
|
"INSERT INTO `files` (`resource_id`, `name`, `folder_resource_id`, `size`, `exists`, `added_at`, `updated_at`) " +
|
||||||
|
"VALUES ('d-null', 'n.txt', 'f-one', 10, NULL, 1, 1), ('d-zero', 'z.txt', 'f-one', 10, 0, 1, 1)",
|
||||||
|
)
|
||||||
|
|
||||||
|
val migration = Migrations.ALL.first { it.startVersion == 14 && it.endVersion == 15 }
|
||||||
|
migration.migrate(db)
|
||||||
|
|
||||||
|
db.query("SELECT `resource_id`, `exists` FROM `folders` ORDER BY `resource_id`").use { cursor ->
|
||||||
|
val rows = mutableMapOf<String, Int>()
|
||||||
|
while (cursor.moveToNext()) rows[cursor.getString(0)] = cursor.getInt(1)
|
||||||
|
assertEquals(mapOf("f-null" to 1, "f-one" to 1, "f-zero" to 0), rows)
|
||||||
|
}
|
||||||
|
db.query("SELECT `resource_id`, `exists` FROM `files` ORDER BY `resource_id`").use { cursor ->
|
||||||
|
val rows = mutableMapOf<String, Int>()
|
||||||
|
while (cursor.moveToNext()) rows[cursor.getString(0)] = cursor.getInt(1)
|
||||||
|
assertEquals(mapOf("d-null" to 1, "d-zero" to 0), rows)
|
||||||
|
}
|
||||||
|
helper.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Schéma v14 minimal de `folders`/`files` (colonne `exists` nullable). */
|
||||||
|
private class V14Callback : SupportSQLiteOpenHelper.Callback(14) {
|
||||||
|
override fun onCreate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE TABLE `folders` (" +
|
||||||
|
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
|
||||||
|
"`resource_id` TEXT NOT NULL, " +
|
||||||
|
"`uri` TEXT, " +
|
||||||
|
"`name` TEXT NOT NULL, " +
|
||||||
|
"`exists` INTEGER, " +
|
||||||
|
"`parent_resource_id` TEXT, " +
|
||||||
|
"`owner_id` TEXT, " +
|
||||||
|
"`sync_status` TEXT NOT NULL, " +
|
||||||
|
"`created_in_app` INTEGER NOT NULL DEFAULT 0, " +
|
||||||
|
"`added_at` INTEGER NOT NULL, " +
|
||||||
|
"`updated_at` INTEGER NOT NULL)",
|
||||||
|
)
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE TABLE `files` (" +
|
||||||
|
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
|
||||||
|
"`resource_id` TEXT NOT NULL, " +
|
||||||
|
"`uri` TEXT, " +
|
||||||
|
"`name` TEXT NOT NULL, " +
|
||||||
|
"`folder_resource_id` TEXT NOT NULL, " +
|
||||||
|
"`extension` TEXT, " +
|
||||||
|
"`size` INTEGER NOT NULL, " +
|
||||||
|
"`mime_type` TEXT, " +
|
||||||
|
"`exists` INTEGER, " +
|
||||||
|
"`added_at` INTEGER NOT NULL, " +
|
||||||
|
"`updated_at` INTEGER NOT NULL)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onUpgrade(
|
||||||
|
db: SupportSQLiteDatabase,
|
||||||
|
oldVersion: Int,
|
||||||
|
newVersion: Int,
|
||||||
|
) = Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
+79
@@ -0,0 +1,79 @@
|
|||||||
|
package com.kazier.mobile.data.local.migration
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||||
|
import androidx.sqlite.db.SupportSQLiteOpenHelper
|
||||||
|
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M27 : la migration 15→16 crée la table `resource_permissions` (cache du
|
||||||
|
* snapshot `GET /sync/permissions`, fondement de `canAccess`) + son index
|
||||||
|
* `expires_at`. Une coquille SQL briquerait l'app au démarrage après update.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class Migration15To16Test {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun migration_cree_la_table_et_l_index() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val helper = FrameworkSQLiteOpenHelperFactory().create(
|
||||||
|
SupportSQLiteOpenHelper.Configuration.builder(context)
|
||||||
|
.name(null)
|
||||||
|
.callback(EmptyV15Callback())
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
val db = helper.writableDatabase
|
||||||
|
|
||||||
|
val migration = Migrations.ALL.first { it.startVersion == 15 && it.endVersion == 16 }
|
||||||
|
migration.migrate(db)
|
||||||
|
|
||||||
|
val tables = mutableListOf<String>()
|
||||||
|
db.query(
|
||||||
|
"SELECT `name` FROM `sqlite_master` WHERE `type` = 'table' AND `name` = 'resource_permissions'",
|
||||||
|
).use { cursor ->
|
||||||
|
while (cursor.moveToNext()) tables += cursor.getString(0)
|
||||||
|
}
|
||||||
|
assertTrue("table resource_permissions manquante", tables.contains("resource_permissions"))
|
||||||
|
|
||||||
|
val columns = mutableListOf<String>()
|
||||||
|
db.query("PRAGMA table_info(`resource_permissions`)").use { cursor ->
|
||||||
|
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||||
|
while (cursor.moveToNext()) columns += cursor.getString(nameIdx)
|
||||||
|
}
|
||||||
|
for (expected in listOf(
|
||||||
|
"resource_id", "resource_type", "effective_access", "owner_id",
|
||||||
|
"shared_by_id", "expires_at", "cached_at", "updated_at",
|
||||||
|
)) {
|
||||||
|
assertTrue("colonne $expected manquante", columns.contains(expected))
|
||||||
|
}
|
||||||
|
|
||||||
|
var indexFound = false
|
||||||
|
db.query("PRAGMA index_list(`resource_permissions`)").use { cursor ->
|
||||||
|
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||||
|
while (cursor.moveToNext()) {
|
||||||
|
if (cursor.getString(nameIdx) == "index_resource_permissions_expires_at") {
|
||||||
|
indexFound = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue("index expires_at manquant", indexFound)
|
||||||
|
helper.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private class EmptyV15Callback : SupportSQLiteOpenHelper.Callback(15) {
|
||||||
|
override fun onCreate(db: SupportSQLiteDatabase) = Unit
|
||||||
|
|
||||||
|
override fun onUpgrade(
|
||||||
|
db: SupportSQLiteDatabase,
|
||||||
|
oldVersion: Int,
|
||||||
|
newVersion: Int,
|
||||||
|
) = Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()))
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user