V3 S7 : preview cloud + export chiffré + release 1.2.0
Release / release-apk (push) Successful in 8m58s
Release / release-docker (push) Successful in 3m47s
CI / docker (push) Successful in 7s
CI / lint-backend (push) Successful in 1m44s
CI / lint-mobile (push) Failing after 18m59s
CI / test-backend (push) Successful in 2m12s
CI / test-mobile (push) Successful in 8m50s
CI / build-backend (push) Successful in 45s

Backend : resource_previews (000024), GET /files/:id/preview (JPEG
512, images pur Go, PDF page 1 via pdftoppm + poppler au Dockerfile,
cache régénéré sur changement, 404 NO_PREVIEW sinon), POST /export
{password 8+} -> zip AES-256 streamé (fichiers vifs possédés +
manifest.json avec faits, metadata-only sans octets). Deps :
alexmullins/zip, x/image directs. Tests service + handlers + migrations.

Mobile : vignettes distantes (une requête/session puis cache WebP
versionné, garde tried, icône sinon), FileThumbnail cloud-only,
export (mot de passe jamais persisté, cache + partage FileProvider),
bouton Partager ACTION_SEND. Impression papier reportée V4. FR/EN.

Contrat docs/api-v1.md, V3.md (S7 livré, V3 close), AGENTS.md,
VERSION 1.2.0 + CHANGELOG.
This commit is contained in:
venture
2026-09-26 15:08:31 +02:00
parent 1e38e6e4ee
commit 4316da578f
56 changed files with 2004 additions and 37 deletions
+5 -5
View File
@@ -2,7 +2,7 @@
## Project Status ## Project Status
`backend/` (Go) et `mobile-kotlin/` (Kotlin/Android) ont du scaffolding en place. Le client mobile est **local-first** : il reflète le SAF dans une base Room (v16, migrations, DAO) et pousse les **métadonnées** de ses mutations locales via un **outbox transactionnel** (`pending_operations` + worker WorkManager → `POST /sync/ops`). Upload physique ciblée (pipeline OCR : `POST /files/upload` + `resourceId`), streaming lecture des fichiers distants (`GET /files/:id/content`, jamais persisté), OCR serveur consommé côté client, recherche locale via Room (+ recherche serveur exposée mais non consommée). `backend/` (Go) et `mobile-kotlin/` (Kotlin/Android) ont du scaffolding en place. Le client mobile est **local-first** : il reflète le SAF dans une base Room (v22, migrations, DAO) et pousse les **métadonnées** de ses mutations locales via un **outbox transactionnel** (`pending_operations` + worker WorkManager → `POST /sync/ops`). Upload physique ciblée (pipeline OCR : `POST /files/upload` + `resourceId`), streaming lecture des fichiers distants (`GET /files/:id/content`, jamais persisté + vignettes `GET /files/:id/preview` en cache), OCR serveur consommé côté client, recherche locale via Room FTS (+ facettes, + recherche serveur exposée), export chiffré (`POST /export`).
## Architecture ## Architecture
@@ -38,7 +38,7 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
- `config/` — env (`godotenv`, optionnel) + defaults: `PORT`, `DATABASE_URL`, `UPLOAD_DIR`, `MAX_FILE_SIZE_MB`, `OCR_LANG`, `AUTH_SECRET` (secret des tokens paseto), `ADMIN_USERNAME`/`ADMIN_PASSWORD` (bootstrap du premier admin) - `config/` — env (`godotenv`, optionnel) + defaults: `PORT`, `DATABASE_URL`, `UPLOAD_DIR`, `MAX_FILE_SIZE_MB`, `OCR_LANG`, `AUTH_SECRET` (secret des tokens paseto), `ADMIN_USERNAME`/`ADMIN_PASSWORD` (bootstrap du premier admin)
- `models/` — domain entities (users, devices, documents/resources, clients) - `models/` — domain entities (users, devices, documents/resources, clients)
- `service/` — business logic (permissions, upload, create folder, move, **sync outbox + snapshot**, bootstrap admin) - `service/` — business logic (permissions, upload, create folder, move, **sync outbox + snapshot**, bootstrap admin)
- `handlers/` — HTTP handlers (health, devices register, **auth/login**, **users resolve + change password**, files CRUD/upload/search, folders, **sync/ops + sync/permissions, ocr/jobs, files/:id/content, files/:id/shares, files/:id/links, files/:id/placements, groups CRUD + membres** — réels) ; middleware `RequireAuth` - `handlers/` — HTTP handlers (health, devices register/list/revoke, **auth/login**, **users resolve + change password (révoque les tokens) + usage**, files CRUD/upload/search (+facettes) , folders, **sync/ops + sync/permissions, ocr/jobs, files/:id/content, files/:id/preview, files/:id/shares, files/:id/links, files/:id/placements, files/:id/versions, files/:id/facts, files/:id/relations, trash, duplicates, export, groups CRUD + membres** — réels) ; middleware `RequireAuth` (+ révocation `tv`, devices si `EnforceDeviceExists`)
- `repository/` — Postgres persistence (`repository.Resources` : insert/list/get/soft-delete scoping `owner_id`, search, move, rename, root-name unique index, `ListOwned` pour le snapshot, `OpenContent` (bytes streaming + lazy healing `has_content`), `ListShares`/`ListLinks` (owner-only), `SetHasContent` ; `repository.Devices` : Upsert, Exists, MarkUser ; `repository.Operations` : trace outbox idempotente `(device_id, operation_id)` ; `repository.OcrJobs` : jobs queued→processing→done/failed ; `repository.Users` : GetByUsernameNormalized, ResolveExact, UpdatePassword ; `repository.Shares` : Upsert/UpsertGroup/Revoke, CreateLink/RevokeLink, ListActiveForResource, ListActiveLinksForResource, snapshot `ListEffectivePermissions` (grants user + groupe) ; `repository.Groups` : Create/ListForUser/AddMember/RemoveMember/Delete (V2-6, un niveau, sans imbrication) ; `repository.Placements` : EnsureLocation/Report/ListForResource (V2 multi-device) ; IDs sont TEXT 32-hex, `NewID()` = `crypto/rand` 16 octets hex (jamais UUID conversion, cf. `docs/api-v1.md`) - `repository/` — Postgres persistence (`repository.Resources` : insert/list/get/soft-delete scoping `owner_id`, search, move, rename, root-name unique index, `ListOwned` pour le snapshot, `OpenContent` (bytes streaming + lazy healing `has_content`), `ListShares`/`ListLinks` (owner-only), `SetHasContent` ; `repository.Devices` : Upsert, Exists, MarkUser ; `repository.Operations` : trace outbox idempotente `(device_id, operation_id)` ; `repository.OcrJobs` : jobs queued→processing→done/failed ; `repository.Users` : GetByUsernameNormalized, ResolveExact, UpdatePassword ; `repository.Shares` : Upsert/UpsertGroup/Revoke, CreateLink/RevokeLink, ListActiveForResource, ListActiveLinksForResource, snapshot `ListEffectivePermissions` (grants user + groupe) ; `repository.Groups` : Create/ListForUser/AddMember/RemoveMember/Delete (V2-6, un niveau, sans imbrication) ; `repository.Placements` : EnsureLocation/Report/ListForResource (V2 multi-device) ; IDs sont TEXT 32-hex, `NewID()` = `crypto/rand` 16 octets hex (jamais UUID conversion, cf. `docs/api-v1.md`)
- `db/` — package migrations (`golang-migrate/v4`, embarquées via `embed` dans `db/migrations/*.sql`, 000001→000016) : `db.MigrateDatabase(url)` au boot du serveur ; test harness `db/migrations_test.go` (up → assertions schéma → down, `TEST_DATABASE_URL`, skip si PG indisponible) ; `dbtest/` — helper cross-package pour les tests repo/handlers (crée la DB test si absente, reset schema, migrate ; skip si PG down) - `db/` — package migrations (`golang-migrate/v4`, embarquées via `embed` dans `db/migrations/*.sql`, 000001→000016) : `db.MigrateDatabase(url)` au boot du serveur ; test harness `db/migrations_test.go` (up → assertions schéma → down, `TEST_DATABASE_URL`, skip si PG indisponible) ; `dbtest/` — helper cross-package pour les tests repo/handlers (crée la DB test si absente, reset schema, migrate ; skip si PG down)
- `ocr/` — OCR engine behind an interface (Tesseract system call, `OCR_LANG` défaut `fra+eng`) - `ocr/` — OCR engine behind an interface (Tesseract system call, `OCR_LANG` défaut `fra+eng`)
@@ -52,16 +52,16 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
- Entry point: `app/src/main/java/com/kazier/mobile/KazierApplication.kt` (Hilt + `HiltWorkerFactory`) + `MainActivity.kt` (Hilt) ; navigation Compose dans `ui/navigation/` (`NavGraph.kt`, `KazierApp.kt`) - Entry point: `app/src/main/java/com/kazier/mobile/KazierApplication.kt` (Hilt + `HiltWorkerFactory`) + `MainActivity.kt` (Hilt) ; navigation Compose dans `ui/navigation/` (`NavGraph.kt`, `KazierApp.kt`)
- Data layer — `data/`: - Data layer — `data/`:
- `data/local/` — Room SQLite (DB `dot.db`, **version 18**, `Migrations.kt` : tables `folders`, `files` (+ `category`, `processed`, `content`, `ocr_text`, `ocr_attempts`, `ocr_queued_at`, `bytes_uploaded`, `bytes_upload_attempts`, `has_content_server`, `wanted_offline`), `user_preferences`, `pending_operations` (+ `device_id`, `parent_resource_id`), `scan_sessions`, `scan_pages`, `resource_permissions`) : entités + DAO, tri (`FileOrdering`), schéma exporté (`app/schemas/`, m19) ; flag `processed` sur `files` (mode review « traiter », local au device, **gate de sync** : un fichier pas encore traité n'est jamais poussé) ; outbox transactionnel `pending_operations` - `data/local/` — Room SQLite (DB `dot.db`, **version 22**, `Migrations.kt` : tables `folders`, `files` (+ `category`, `processed`, `content`, `ocr_text`, `ocr_attempts`, `ocr_queued_at`, `bytes_uploaded`, `bytes_upload_attempts`, `has_content_server`, `wanted_offline`, `trashed_at`), `user_preferences`, `pending_operations` (+ `device_id`, `parent_resource_id`), `scan_sessions`, `scan_pages`, `resource_permissions`, `resource_facts`, `files_fts` (FTS4 + triggers `FtsTriggers`), `resource_links`, `collections`) : entités + DAO, tri (`FileOrdering`), schéma exporté (`app/schemas/`, m22) ; flag `processed` sur `files` (mode review « traiter », local au device, **gate de sync** : un fichier pas encore traité n'est jamais poussé) ; outbox transactionnel `pending_operations`
- `data/remote/` — Retrofit/Moshi : `ApiService.kt` + `dto/Dtos.kt` = **contrat HTTP** (`{ data, meta }`, erreurs `{ error: { code, message } }`) ; `ApiClient.kt` normalise les réponses ; interceptors OkHttp (`AuthInterceptor`, `ServerUrlInterceptor`) ; `SafMultipart.kt` (multipart SAF paresseux partagé upload OCR + V2) - `data/remote/` — Retrofit/Moshi : `ApiService.kt` + `dto/Dtos.kt` = **contrat HTTP** (`{ data, meta }`, erreurs `{ error: { code, message } }`) ; `ApiClient.kt` normalise les réponses ; interceptors OkHttp (`AuthInterceptor`, `ServerUrlInterceptor`) ; `SafMultipart.kt` (multipart SAF paresseux partagé upload OCR + V2)
- `data/repository/` — `FolderRepository`, `FileRepository`, `AuthRepository`, `OutboxRepository` (enqueue `create_resource`/`move_resource`/`delete_resource` + ops partage `share`/`update_share`/`revoke_share`/`create_link`/`revoke_link` + `report_bytes` V2 (`{ hasBytes }`, nouvel `operation_id` par état), écrivains dans la même transaction Room que la mutation parente ; pour un fichier SAF, la mutation parente du `create_resource` est le **garder** de la review (`markProcessed`), et `hasCreateOperation` en garde l'unicité), `ShareRepository` (hydratation + delta + `canAccess` depuis `GET /sync/permissions`), `OcrRepository` (upload ciblé + jobs + `syncFromServer`), `RemoteContentRepository` (streaming `GET /files/:id/content`, jamais persisté ; **upload V2** des octets après metadata synced, `bytes_uploaded` ; **download V2** vers SAF + rattachement, `wanted_offline`) - `data/repository/` — `FolderRepository`, `FileRepository`, `AuthRepository`, `OutboxRepository` (enqueue `create_resource` (+`scanSessionId` S5)/`move_resource`/`update_metadata` (+`baseUpdatedAt` S6)/`trash_resource`/`restore_resource`/`purge_resource` (V3, `delete_resource` legacy mappé serveur) + ops partage `share`/`update_share`/`revoke_share`/`create_link` (expiration 7j défaut)/`revoke_link` + `report_bytes` V2 (`{ hasBytes }`, nouvel `operation_id` par état) + `correct_facts` S3 (full-replace jeu `user`), écrivains dans la même transaction Room que la mutation parente ; pour un fichier SAF, la mutation parente du `create_resource` est le **garder** de la review (`markProcessed`), et `hasCreateOperation` en garde l'unicité), `ShareRepository` (hydratation + delta + `canAccess` depuis `GET /sync/permissions`), `OcrRepository` (upload ciblé + jobs + `syncFromServer`), `FactsRepository` (sync remplace-en-bloc + corrections optimistes), `LinksRepository` (graphe + verdicts REST), `TrashRepository` (restore/purge/convergence), `CollectionsRepository` (local), `DevicesRepository` (appareils + usage), `RemoteContentRepository` (streaming `GET /files/:id/content`, jamais persisté ; **upload V2** des octets après metadata synced, `bytes_uploaded` ; **download V2** vers SAF + rattachement, `wanted_offline`)
- `features/` — logique descendue côté client : - `features/` — logique descendue côté client :
- `sync/DeviceSync.kt` + `SafScanner.kt` — sync device↔SAF : **two-pass walk** (listing hors transaction puis upserts Room dans une seule transaction), réconciliation `exists = 0` (jamais de suppression), single-flight via `Mutex` ; les nouveaux **dossiers** sont journalisés dans l'outbox à la découverte, les **fichiers** uniquement au « garder » de la review (gate `processed`) - `sync/DeviceSync.kt` + `SafScanner.kt` — sync device↔SAF : **two-pass walk** (listing hors transaction puis upserts Room dans une seule transaction), réconciliation `exists = 0` (jamais de suppression), single-flight via `Mutex` ; les nouveaux **dossiers** sont journalisés dans l'outbox à la découverte, les **fichiers** uniquement au « garder » de la review (gate `processed`)
- `saf/` — `SafUris`, `SafFolderCreator`, `FileMover` (relocalisation SAF `DocumentsContract.moveDocument`, repli métadonnée seule ; le déplacement est poussé en `move_resource`), `SafFileDeleter` (suppression SAF + `delete_resource` atomique), `FileDeleter.releaseLocalCopies` (purge sûre V2-3 : gate `isReleasable`, détachement cloud-only, zéro outbox) - `saf/` — `SafUris`, `SafFolderCreator`, `FileMover` (relocalisation SAF `DocumentsContract.moveDocument`, repli métadonnée seule ; le déplacement est poussé en `move_resource`), `SafFileDeleter` (suppression SAF + `delete_resource` atomique), `FileDeleter.releaseLocalCopies` (purge sûre V2-3 : gate `isReleasable`, détachement cloud-only, zéro outbox)
- `sync/OutboxSyncWorker.kt` — worker WorkManager (`enqueueUniqueWork` KEEP, single-flight, `NetworkType.CONNECTED`, backoff 30s) qui draine `pending_operations` vers `POST /sync/ops` (batch 20, dead-letter immédiat `failed` sur erreur 4xx non-idempotente — `attempts` diagnostic, purge synced > 7 jours, **sauf `report_bytes` : dead-letter + suite du batch, jamais bloquant**) ; **schedulé** au login/restauration de session (`AuthViewModel`) et après chaque `syncAll()` (`SyncViewModel`) ; enchaîne `OcrAutoWorker` + `BytesUploadWorker` quand un fichier est promu (`DownloadWorker` sur demande hors-ligne) ; `RetentionWorker` (passe quotidienne, purge sûre des copies anciennes selon `RetentionStore`, sans réseau) - `sync/OutboxSyncWorker.kt` — worker WorkManager (`enqueueUniqueWork` KEEP, single-flight, `NetworkType.CONNECTED`, backoff 30s) qui draine `pending_operations` vers `POST /sync/ops` (batch 20, dead-letter immédiat `failed` sur erreur 4xx non-idempotente — `attempts` diagnostic, purge synced > 7 jours, **sauf `report_bytes` : dead-letter + suite du batch, jamais bloquant**) ; **schedulé** au login/restauration de session (`AuthViewModel`) et après chaque `syncAll()` (`SyncViewModel`) ; enchaîne `OcrAutoWorker` + `BytesUploadWorker` quand un fichier est promu (`DownloadWorker` sur demande hors-ligne) ; `RetentionWorker` (passe quotidienne, purge sûre des copies anciennes selon `RetentionStore`, sans réseau)
- `sync/SyncViewModel.kt` — état du sync exposé à l'UI (`SyncStatus` : marche en cours, ops en attente, dernières opérations) via le badge header `ui/components/SyncStatusBadge.kt` + `SyncOperationsDialog.kt` (« liste des sync ») - `sync/SyncViewModel.kt` — état du sync exposé à l'UI (`SyncStatus` : marche en cours, ops en attente, dernières opérations) via le badge header `ui/components/SyncStatusBadge.kt` + `SyncOperationsDialog.kt` (« liste des sync »)
- `auth/` — session (login user + token paseto + **re-login silencieux** sur 401 via identifiants chiffrés persistés, single-flight, événements `Reauthenticated`/`SessionExpired`) : `SessionManager`, `SecureTokenStore`, `TokenProvider`, `TokenStore` (+ `Credentials`) - `auth/` — session (login user + token paseto + **re-login silencieux** sur 401 via identifiants chiffrés persistés, single-flight, événements `Reauthenticated`/`SessionExpired`) : `SessionManager`, `SecureTokenStore`, `TokenProvider`, `TokenStore` (+ `Credentials`)
- `ui/` — écrans Compose : `folderlist`, `folderdetail`, `document` (contenu PDF/image/texte local + streaming distant image/texte/PDF multi-pages via `RemoteDocumentViewer`, autres types non supportés en streaming), `search` (**recherche locale** via Room, sans endpoint serveur), `settings` (URL serveur + thème + stockage/retention), `pdfbuilder` (multi-select → génération PDF), `auth` (login, mode local, avis d'expiration), `share` (`ShareBottomSheet` : grants + liens + ouverture de lien + copies V2 + groupes V2-6 ; `OpenLinkScreen` + deep-link `kazier://share/<token>`), `components`, `theme` - `ui/` — écrans Compose : `folderlist`, `folderdetail`, `document` (contenu PDF/image/texte local + streaming distant image/texte/PDF multi-pages via `RemoteDocumentViewer`, autres types non supportés en streaming + fiche faits/liens + partage ACTION_SEND), `search` (**recherche locale** via Room FTS + facettes + collections locales), `settings` (URL serveur + thème + stockage/retention + export chiffré + appareils + corbeille + doublons), `trash`, `duplicates`, `devices`, `facts` (bottom-sheet), `pdfbuilder` (multi-select → génération PDF), `auth` (login, mode local, avis d'expiration), `share` (`ShareBottomSheet` : grants + liens + ouverture de lien + copies V2 + groupes V2-6 ; `OpenLinkScreen` + deep-link `kazier://share/<token>`), `components`, `theme`
- `domain/` — stores de préférences: `DeviceIdentity`, `ActiveUserStore`, `LocalModeStore`, `ServerConfigStore`, `ThemePreferenceStore`, `RetentionStore` (`all` | `last_months:N`), `GenerateId` (identifiants 32-hex) - `domain/` — stores de préférences: `DeviceIdentity`, `ActiveUserStore`, `LocalModeStore`, `ServerConfigStore`, `ThemePreferenceStore`, `RetentionStore` (`all` | `last_months:N`), `GenerateId` (identifiants 32-hex)
- `di/` — modules Hilt (`AppModule`, `DatabaseModule`, `NetworkModule`) - `di/` — modules Hilt (`AppModule`, `DatabaseModule`, `NetworkModule`)
- Base URL serveur **configurée à l'exécution** dans les Réglages (`ServerConfigStore`, persistée en `user_preferences`), défaut `http://10.0.2.2:8080/api/v1` (pas de variable d'env) - Base URL serveur **configurée à l'exécution** dans les Réglages (`ServerConfigStore`, persistée en `user_preferences`), défaut `http://10.0.2.2:8080/api/v1` (pas de variable d'env)
+9
View File
@@ -5,6 +5,13 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve
## [Unreleased] ## [Unreleased]
## [1.2.0] - 2026-09-26
V3 « Le classeur qui comprend » : filet anti-perte, extraction générique,
recherche plein-texte + facettes, graphe documentaire, confiance & partage
sobre, preview cloud, export chiffré. Contrat consolidé (`docs/api-v1.md`),
vision et plan (`V3.md`).
### Ajouté ### Ajouté
- Corbeille V3 (S1 backend) : `DELETE /files/:id` = trash par défaut (`?mode=purge` = définitif), `POST /files/:id/restore`, `GET /trash` (paginé), trash/restore récursifs (subtree + chaîne d'ancêtres), purge auto serveur après 30j (`TrashRetention`, passe au boot + horaire). - Corbeille V3 (S1 backend) : `DELETE /files/:id` = trash par défaut (`?mode=purge` = définitif), `POST /files/:id/restore`, `GET /trash` (paginé), trash/restore récursifs (subtree + chaîne d'ancêtres), purge auto serveur après 30j (`TrashRetention`, passe au boot + horaire).
- Versions V3 (S1 backend) : table `resource_versions` (N=3, élagage auto), historique figé à chaque overwrite (`Upload` ciblé), `GET /files/:id/versions` + `POST /files/:id/versions/:n/restore` (l'actuel est à son tour versionné), upload ciblé vers trashé → `NOT_FOUND`. - Versions V3 (S1 backend) : table `resource_versions` (N=3, élagage auto), historique figé à chaque overwrite (`Upload` ciblé), `GET /files/:id/versions` + `POST /files/:id/versions/:n/restore` (l'actuel est à son tour versionné), upload ciblé vers trashé → `NOT_FOUND`.
@@ -16,6 +23,8 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve
- Relations V3 (S5) : table `resource_links` + `scan_session_id` (migration `000021`), réconciliation déterministe (same_scan via outbox, doublons via SHA-256 posé à l'upload + backfill boot, same_issuer/référence via faits effectifs, verdicts préservés, élagage auto), `GET /files/:id/relations` + verdict (owner-only), `GET /duplicates` (groupes + gain récupérable), Room v22 (links + collections), « Voir aussi » dans la fiche (verdicts en ligne), écran Doublons (garder le plus récent), collections locales (sauver/rejouer/supprimer depuis la recherche), `scanSessionId` dans les creates de scan. - Relations V3 (S5) : table `resource_links` + `scan_session_id` (migration `000021`), réconciliation déterministe (same_scan via outbox, doublons via SHA-256 posé à l'upload + backfill boot, same_issuer/référence via faits effectifs, verdicts préservés, élagage auto), `GET /files/:id/relations` + verdict (owner-only), `GET /duplicates` (groupes + gain récupérable), Room v22 (links + collections), « Voir aussi » dans la fiche (verdicts en ligne), écran Doublons (garder le plus récent), collections locales (sauver/rejouer/supprimer depuis la recherche), `scanSessionId` dans les creates de scan.
- Confiance V3 (S6) : `token_version` (migration `000022`, claim `tv`, 401 si révoqué, bump au changement de mot de passe — fin de la limite V1), quota (colonne héritée de `000001`, `000023` idempotente, 413 `QUOTA_EXCEEDED` sur créations, `GET /users/me/usage`), appareils (`GET /devices`, `DELETE /devices/:id`, `EnforceDeviceExists` en prod, écran Appareils + quota), renames concurrents transparents (`baseUpdatedAt` + `conflicts[]` non-fataux, gracieuseté 2 s, pipeline mobile persistance + dialogue), liens à expiration 7j par défaut, import « classeur » unifié (scan/note/dossier), onboarding cercle Famille. - Confiance V3 (S6) : `token_version` (migration `000022`, claim `tv`, 401 si révoqué, bump au changement de mot de passe — fin de la limite V1), quota (colonne héritée de `000001`, `000023` idempotente, 413 `QUOTA_EXCEEDED` sur créations, `GET /users/me/usage`), appareils (`GET /devices`, `DELETE /devices/:id`, `EnforceDeviceExists` en prod, écran Appareils + quota), renames concurrents transparents (`baseUpdatedAt` + `conflicts[]` non-fataux, gracieuseté 2 s, pipeline mobile persistance + dialogue), liens à expiration 7j par défaut, import « classeur » unifié (scan/note/dossier), onboarding cercle Famille.
- Corbeille V3 (S1 mobile, Room v19) : colonne `trashed_at` (files + folders, migration 18→19), tombstone `exists = 0` (requêtes `exists = 1` inchangées), `FileDeleter`/`FolderDeleter`/`SafFileDeleter` → ops `trash_resource` (plus de `delete_resource` émis), garde walk anti-résurrection + reconcile, `TrashRepository` (restore/purge/convergence `GET /trash`/expiration locale 31j), écran Corbeille (Réglages → restore/purge avec confirmation), expiration tombstones dans `RetentionWorker`, dialogue de suppression rewordé (corbeille 30j, plus « irréversible »). - Corbeille V3 (S1 mobile, Room v19) : colonne `trashed_at` (files + folders, migration 18→19), tombstone `exists = 0` (requêtes `exists = 1` inchangées), `FileDeleter`/`FolderDeleter`/`SafFileDeleter` → ops `trash_resource` (plus de `delete_resource` émis), garde walk anti-résurrection + reconcile, `TrashRepository` (restore/purge/convergence `GET /trash`/expiration locale 31j), écran Corbeille (Réglages → restore/purge avec confirmation), expiration tombstones dans `RetentionWorker`, dialogue de suppression rewordé (corbeille 30j, plus « irréversible »).
- Preview cloud V3 (S7) : table `resource_previews` (migration `000024`), `GET /files/:id/preview` (JPEG 512, images pur Go, PDF page 1 via `pdftoppm` + poppler au Dockerfile, cache régénéré sur changement, 404 `NO_PREVIEW` sinon), vignettes distantes côté mobile (une requête/session puis cache WebP versionné, garde `tried`, icône sinon).
- Export chiffré V3 (S7 C3) : `POST /export { password 8+ }` → zip AES-256 streamé (fichiers vifs possédés + `manifest.json` avec faits, tout chiffré, metadata-only sans octets), mobile (mot de passe jamais persisté, téléchargement cache, partage système via FileProvider), bouton Partager (ACTION_SEND local) sur le viewer — impression papier reportée (V4, pas de dep print).
## [1.1.0] - 2026-09-25 ## [1.1.0] - 2026-09-25
+2 -2
View File
@@ -1,6 +1,6 @@
# Kazier V3 — « Le classeur qui comprend » # Kazier V3 — « Le classeur qui comprend »
Statut : **vision validée** (2026-09-25). V1 (1.0.0, socle local-first + partage) et V2 (1.1.0, multi-device : upload/download, placements, rétention, groupes) sont livrées. Ce document est le contrat produit + plan d'exécution de la V3. Statut : **livrée en 1.2.0** (2026-09-26). V1 (1.0.0, socle local-first + partage) et V2 (1.1.0, multi-device : upload/download, placements, rétention, groupes) sont livrées. Ce document reste le contrat produit + plan d'exécution de la V3 (toutes slices S1–S7 livrées).
## 1. Positionnement (acté) ## 1. Positionnement (acté)
@@ -114,7 +114,7 @@ Sans ces 4 items, les piliers grincent. Ils sont petits et intégrés aux slices
4. **S4 — Recherche** (livré : `000020` FTS + facettes serveur + Room FTS v21 + UI filtres + B4 a11y) — done quand : « facture edf mars » trouve `scan_042.pdf` offline ET online. 4. **S4 — Recherche** (livré : `000020` FTS + facettes serveur + Room FTS v21 + UI filtres + B4 a11y) — done quand : « facture edf mars » trouve `scan_042.pdf` offline ET online.
5. **S5 — Relations + B2** (livré : `000021` links + doublons SHA-256 + same_scan outbox + `GET /relations` + verdict + `GET /duplicates` + Room v22 + « Voir aussi » + Doublons + collections locales) — done quand : fiche CNI → verso + doublon listés, invalidables ; doublons chiffrés en Mo récupérables. 5. **S5 — Relations + B2** (livré : `000021` links + doublons SHA-256 + same_scan outbox + `GET /relations` + verdict + `GET /duplicates` + Room v22 + « Voir aussi » + Doublons + collections locales) — done quand : fiche CNI → verso + doublon listés, invalidables ; doublons chiffrés en Mo récupérables.
6. **S6 — Partage sobre + A1/A2/A4 + B1 (+B5 si temps)** (livré : expiration liens 7j défaut + `000022` token_version + `000023` quota idempotente + `413 QUOTA_EXCEEDED` + `GET /devices` + `DELETE /devices/:id` + `EnforceDeviceExists` prod + écran Appareils + quota/usage + `update_metadata{baseUpdatedAt}` + `conflicts[]` + pipeline mobile + import « classeur » unifié + onboarding cercle Famille) — done quand : lien RIB expiré → `NOT_FOUND`, password changé → autres devices re-logués, device perdu révoqué, quota plein → 413 propre, rename concurrent → badge « renommé ailleurs ». 6. **S6 — Partage sobre + A1/A2/A4 + B1 (+B5 si temps)** (livré : expiration liens 7j défaut + `000022` token_version + `000023` quota idempotente + `413 QUOTA_EXCEEDED` + `GET /devices` + `DELETE /devices/:id` + `EnforceDeviceExists` prod + écran Appareils + quota/usage + `update_metadata{baseUpdatedAt}` + `conflicts[]` + pipeline mobile + import « classeur » unifié + onboarding cercle Famille) — done quand : lien RIB expiré → `NOT_FOUND`, password changé → autres devices re-logués, device perdu révoqué, quota plein → 413 propre, rename concurrent → badge « renommé ailleurs ».
7. **S7 — Preview 1ère page** (`pdf_preview` V2.md §3.3, une seule taille) + **C3 export chiffré** (`GET /export` zip + manifest) + B3 impression si temps + polish + release 1.2.0. Arbitrage stretch : **export > embeddings** (vrai 3-2-1 perçu, zéro GPU). 7. **S7 — Preview + export** (livré : `000024` previews + `GET /files/:id/preview` JPEG 512 — images pur Go, PDF via `pdftoppm` + poppler, `NO_PREVIEW` sinon — + vignettes distantes mobile + `POST /export` zip AES + manifest + partage ACTION_SEND + release 1.2.0). Impression papier reportée V4 (pas de dep print).
## 6. Tests (mêmes harnais, pas de nouveau framework) ## 6. Tests (mêmes harnais, pas de nouveau framework)
+1 -1
View File
@@ -1 +1 @@
1.1.0 1.2.0
+4 -2
View File
@@ -17,14 +17,16 @@ RUN CGO_ENABLED=0 GOOS=linux go build \
-o /out/kazier-server \ -o /out/kazier-server \
./cmd/server/main.go ./cmd/server/main.go
# --- runtime: mince, Tesseract (fra+eng) embarqué pour l'OCR --- # --- runtime: mince, Tesseract (fra+eng) embarqué pour l'OCR + poppler
# (pdftoppm) pour les vignettes PDF page 1 (V3 S7, best-effort) ---
FROM alpine:3.20 FROM alpine:3.20
RUN apk add --no-cache \ RUN apk add --no-cache \
ca-certificates \ ca-certificates \
tzdata \ tzdata \
tesseract-ocr \ tesseract-ocr \
tesseract-ocr-data-eng \ tesseract-ocr-data-eng \
tesseract-ocr-data-fra tesseract-ocr-data-fra \
poppler-utils
WORKDIR /app WORKDIR /app
+2
View File
@@ -20,6 +20,7 @@ var expectedRoutes = []string{
"GET /api/v1/files/:id/facts", "GET /api/v1/files/:id/facts",
"PATCH /api/v1/files/:id/facts", "PATCH /api/v1/files/:id/facts",
"GET /api/v1/files/:id/content", "GET /api/v1/files/:id/content",
"GET /api/v1/files/:id/preview",
"GET /api/v1/files/:id/shares", "GET /api/v1/files/:id/shares",
"GET /api/v1/files/:id/links", "GET /api/v1/files/:id/links",
"GET /api/v1/files/:id/placements", "GET /api/v1/files/:id/placements",
@@ -27,6 +28,7 @@ var expectedRoutes = []string{
"GET /api/v1/files/:id/relations", "GET /api/v1/files/:id/relations",
"POST /api/v1/files/:id/relations/verdict", "POST /api/v1/files/:id/relations/verdict",
"GET /api/v1/duplicates", "GET /api/v1/duplicates",
"POST /api/v1/export",
"POST /api/v1/files/:id/restore", "POST /api/v1/files/:id/restore",
"POST /api/v1/files/:id/versions/:n/restore", "POST /api/v1/files/:id/versions/:n/restore",
"GET /api/v1/trash", "GET /api/v1/trash",
@@ -0,0 +1 @@
DROP TABLE IF EXISTS resource_previews;
@@ -0,0 +1,13 @@
-- V3 S7 : vignettes serveur pour les fichiers cloud-only (la galerie reste
-- < 1 s sans rapatrier les octets). `resource_previews` mémorise la
-- génération servie (taille + updated_at sources) pour ne régénérer que sur
-- changement ; le fichier vit sous UPLOAD_DIR/.previews/<resource_id>.jpg
-- (jamais versionné, reconstruit à la demande). Images : pur Go (stdlib +
-- x/image). PDF : `pdftoppm` (poppler, cf. Dockerfile) page 1 ; sans l'outil
-- ou autre type → pas de preview (404 NO_PREVIEW, l'UI montre l'icône).
CREATE TABLE resource_previews (
resource_id TEXT PRIMARY KEY REFERENCES resources(resource_id) ON DELETE CASCADE,
src_size_bytes BIGINT NOT NULL,
src_updated_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
+3
View File
@@ -515,6 +515,9 @@ func TestMigrationsUpDown(t *testing.T) {
t.Error("colonne users.storage_quota_bytes manquante après 000023") t.Error("colonne users.storage_quota_bytes manquante après 000023")
} }
// --- 000024 : vignettes serveur ------------------------------------------
assertTables(t, conn, "users", "devices", "resources", "operations", "ocr_jobs", "shares", "share_links", "storage_locations", "resource_placements", "groups", "group_members", "resource_versions", "resource_facts", "resource_links", "resource_previews", "schema_migrations")
if err := MigrateDownDatabase(url); err != nil { if err := MigrateDownDatabase(url); err != nil {
t.Fatalf("migrate down: %v", err) t.Fatalf("migrate down: %v", err)
} }
+6 -4
View File
@@ -7,11 +7,15 @@ require (
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.12.0
github.com/golang-migrate/migrate/v4 v4.19.1 github.com/golang-migrate/migrate/v4 v4.19.1
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0
github.com/lib/pq v1.12.3 github.com/lib/pq v1.12.3
golang.org/x/crypto v0.52.0
golang.org/x/image v0.46.0
) )
require ( require (
aidanwoods.dev/go-result v0.3.1 // indirect aidanwoods.dev/go-result v0.3.1 // indirect
github.com/alexmullins/zip v0.0.0-20180717182244-4affb64b04d0 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect
@@ -25,7 +29,6 @@ require (
github.com/goccy/go-yaml v1.19.2 // indirect github.com/goccy/go-yaml v1.19.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
@@ -37,9 +40,8 @@ require (
github.com/ugorji/go/codec v1.3.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.22.0 // indirect golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/net v0.54.0 // indirect golang.org/x/net v0.54.0 // indirect
golang.org/x/sys v0.45.0 // indirect golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.37.0 // indirect golang.org/x/text v0.42.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect google.golang.org/protobuf v1.36.10 // indirect
) )
+8 -4
View File
@@ -6,6 +6,8 @@ github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/alexmullins/zip v0.0.0-20180717182244-4affb64b04d0 h1:BVts5dexXf4i+JX8tXlKT0aKoi38JwTXSe+3WUneX0k=
github.com/alexmullins/zip v0.0.0-20180717182244-4affb64b04d0/go.mod h1:FDIQmoMNJJl5/k7upZEnGvgWVZfFeE6qHeN7iCMbCsA=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
@@ -136,13 +138,15 @@ golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w= golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ= golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+46
View File
@@ -0,0 +1,46 @@
package handlers
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
)
type exportRequest struct {
Password string `json:"password"`
}
// ExportFull streame un zip AES-256 du compte (V3 S7 C3) :
// `POST /export { password }` (mot de passe en corps JSON, jamais en query
// — pas de fuite dans les logs). Chaque entrée (fichiers + manifest.json)
// est chiffrée. Scope : fichiers vifs possédés uniquement.
// Le mot de passe exige 8+ caractères (400 sinon) ; le zip peut être long
// (pas de cap S7 — donnée de l'utilisateur, self-hosté).
func ExportFull(c *gin.Context) {
if Store == nil || Store.Repository == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
var req exportRequest
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid JSON body (expected { password })")
return
}
if len(req.Password) < 8 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "password must be at least 8 characters")
return
}
filename := fmt.Sprintf("kazier-export-%s.zip", time.Now().UTC().Format("20060102-150405"))
c.Header("Content-Type", "application/zip")
c.Header("Content-Disposition", "attachment; filename=\""+filename+"\"")
// Erreur mid-stream : headers déjà partis — log + abort (zip tronqué,
// documenté ; le manifest chiffré en fin d'archive manque alors).
if err := Store.Export(c.Writer, userID, req.Password); err != nil {
c.Abort()
return
}
}
+38
View File
@@ -0,0 +1,38 @@
package handlers_test
import (
"net/http"
"testing"
"github.com/kazier/backend/repository"
)
// TestExportEndpoint : POST /export exige un mot de passe 8+ (400 sinon) et
// streame un zip (200 + application/zip).
func TestExportEndpoint(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "ex"), "export-test-password", device)
for _, body := range []string{`{}`, `{"password":"court"}`, `not-json`} {
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/export", token, []byte(body), "application/json")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "export-400:"+body)
}
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/export", token, []byte(`{"password":"motdepasse-8"}`), "application/json")
if rec.Code != http.StatusOK {
t.Fatalf("export: attendu 200, got %d %s", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); ct != "application/zip" {
t.Fatalf("content-type = %q", ct)
}
if cd := rec.Header().Get("Content-Disposition"); cd == "" {
t.Fatal("content-disposition manquant")
}
if rec.Body.Len() == 0 {
t.Fatal("zip vide")
}
if rec.Body.Bytes()[0] != 'P' || rec.Body.Bytes()[1] != 'K' {
t.Fatal("pas une archive zip (signature PK manquante)")
}
}
+28
View File
@@ -299,6 +299,34 @@ func FilesContent(c *gin.Context) {
c.File(info.Path) c.File(info.Path)
} }
// FilesPreview sert la vignette JPEG d'un fichier visible (V3 S7) :
// `GET /files/:id/preview` (binaire brut, hors enveloppe, `inline`).
// Générée à la demande (images pur Go, PDF page 1 via `pdftoppm`) et cachée
// jusqu'au prochain changement (taille/`updated_at`). 404 NOT_FOUND si
// invisible/metadata-only (indistinguables, pas d'énumération), 404
// NO_PREVIEW si le type ne se prévisualise pas (l'UI montre l'icône).
func FilesPreview(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
}
path, err := Store.OpenPreview(userID, id)
if err != nil {
writeError(c, err)
return
}
c.Header("Content-Type", "image/jpeg")
c.Header("Content-Disposition", "inline; filename=\""+id+".jpg\"")
c.Header("Cache-Control", "private, max-age=3600")
c.File(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")
+108
View File
@@ -0,0 +1,108 @@
package handlers_test
import (
"bytes"
"image"
"image/color"
"image/jpeg"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kazier/backend/repository"
)
// previewImageBytes génère un JPEG 640x480 uni (décodable sans fixture).
func previewImageBytes(t *testing.T) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, 640, 480))
for y := 0; y < 480; y++ {
for x := 0; x < 640; x++ {
img.Set(x, y, color.RGBA{uint8(x % 256), 128, 64, 255})
}
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, nil); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
// TestFilesPreview : JPEG 200 + image/jpeg pour une image, NO_PREVIEW pour
// un txt, NOT_FOUND si trashé/étranger. L'upload HTTP de test est capé à
// 10 o : le physique est écrit directement (même layout UPLOAD_DIR).
func TestFilesPreview(t *testing.T) {
r, store, repo := setup(t)
device := repository.NewID()
token, userID := registerAndLogin(t, r, repo, testUserUsername(device, "pv"), "preview-test-password", device)
createdID := seedPhysical(t, store.UploadDir, repo, userID, "photo.jpg", previewImageBytes(t))
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+createdID+"/preview", token, nil, "")
if rec.Code != http.StatusOK {
t.Fatalf("preview: attendu 200, got %d %s", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); ct != "image/jpeg" {
t.Fatalf("content-type = %q, attendu image/jpeg", ct)
}
if _, err := jpeg.Decode(bytes.NewReader(rec.Body.Bytes())); err != nil {
t.Fatalf("corps non-JPEG: %v", err)
}
// Txt → NO_PREVIEW (404 typé, l'UI montre l'icône).
txtID := seedPhysical(t, store.UploadDir, repo, userID, "notes.txt", []byte("hello"))
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+txtID+"/preview", token, nil, "")
expectError(t, rec, http.StatusNotFound, "NO_PREVIEW", "preview-txt")
// Trashé → NOT_FOUND (invisible d'abord, pas NO_PREVIEW).
if err := repo.Resources.TrashResource(userID, createdID); err != nil {
t.Fatalf("trash: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+createdID+"/preview", token, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "preview-trashed")
// Étranger → NOT_FOUND.
deviceB := repository.NewID()
tokenB, _ := registerAndLogin(t, r, repo, testUserUsername(deviceB, "pb"), "preview-test-password", deviceB)
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+txtID+"/preview", tokenB, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "preview-foreign")
}
// seedPhysical insère la métadonnée + écrit les octets (même layout que
// l'upload, sans passer par le multipart capé des tests).
func seedPhysical(t *testing.T, uploadDir string, repo *repository.Repository, userID, name string, content []byte) string {
t.Helper()
id := repository.NewID()
ext := ""
if i := strings.LastIndex(name, "."); i >= 0 {
ext = name[i+1:]
}
var extPtr *string
if ext != "" {
extPtr = &ext
}
mime := "application/octet-stream"
if ext == "jpg" {
mime = "image/jpeg"
}
if err := repo.Resources.InsertFile(userID, id, name, "", int64(len(content)), &mime, extPtr); err != nil {
t.Fatalf("insert: %v", err)
}
dir := filepath.Join(uploadDir, userID)
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatalf("mkdir: %v", err)
}
dest := id
if ext != "" {
dest = id + "." + ext
}
if err := os.WriteFile(filepath.Join(dir, dest), content, 0o600); err != nil {
t.Fatalf("write: %v", err)
}
if err := repo.Resources.SetHasContent(userID, id, true); err != nil {
t.Fatalf("has_content: %v", err)
}
return id
}
+2
View File
@@ -36,6 +36,7 @@ func RegisterRoutes(r *gin.Engine) {
protected.GET("/files/:id/facts", FilesGetFacts) protected.GET("/files/:id/facts", FilesGetFacts)
protected.PATCH("/files/:id/facts", FilesCorrectFacts) protected.PATCH("/files/:id/facts", FilesCorrectFacts)
protected.GET("/files/:id/content", FilesContent) protected.GET("/files/:id/content", FilesContent)
protected.GET("/files/:id/preview", FilesPreview)
protected.GET("/files/:id/shares", SharesList) protected.GET("/files/:id/shares", SharesList)
protected.GET("/files/:id/links", LinksList) protected.GET("/files/:id/links", LinksList)
protected.GET("/files/:id/placements", PlacementsList) protected.GET("/files/:id/placements", PlacementsList)
@@ -43,6 +44,7 @@ func RegisterRoutes(r *gin.Engine) {
protected.GET("/files/:id/relations", RelationsList) protected.GET("/files/:id/relations", RelationsList)
protected.POST("/files/:id/relations/verdict", RelationVerdict) protected.POST("/files/:id/relations/verdict", RelationVerdict)
protected.GET("/duplicates", DuplicatesList) protected.GET("/duplicates", DuplicatesList)
protected.POST("/export", ExportFull)
protected.POST("/files/:id/restore", FilesRestore) protected.POST("/files/:id/restore", FilesRestore)
protected.POST("/files/:id/versions/:n/restore", VersionRestore) protected.POST("/files/:id/versions/:n/restore", VersionRestore)
protected.GET("/trash", TrashList) protected.GET("/trash", TrashList)
+2
View File
@@ -32,6 +32,8 @@ func writeError(c *gin.Context, err error) {
api.Error(c, 413, "FILE_TOO_LARGE", "file exceeds the maximum allowed size") api.Error(c, 413, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
case errors.Is(err, service.ErrQuotaExceeded): case errors.Is(err, service.ErrQuotaExceeded):
api.Error(c, 413, "QUOTA_EXCEEDED", "storage quota exceeded") api.Error(c, 413, "QUOTA_EXCEEDED", "storage quota exceeded")
case errors.Is(err, service.ErrNoPreview):
api.Error(c, 404, "NO_PREVIEW", "no preview available for this file")
default: default:
// Jamais de err.Error() brut au client (fuite SQL/FS/paths, cf. // Jamais de err.Error() brut au client (fuite SQL/FS/paths, cf.
// FEEDBACK #8) : message générique, détail au log serveur. // FEEDBACK #8) : message générique, détail au log serveur.
+39
View File
@@ -0,0 +1,39 @@
package repository
import (
"database/sql"
"time"
)
// PreviewRow mémorise la vignette servie (V3 S7, migration 000024).
type PreviewRow struct {
SrcSize int64
SrcUpdatedAt time.Time
}
// GetPreview lit la génération servie. Absente → sql.ErrNoRows (régénérer).
func (r *Resources) GetPreview(resourceID string) (PreviewRow, error) {
var row PreviewRow
err := r.DB.QueryRow(
`SELECT src_size_bytes, src_updated_at FROM resource_previews WHERE resource_id = $1`,
resourceID,
).Scan(&row.SrcSize, &row.SrcUpdatedAt)
if err == sql.ErrNoRows {
return PreviewRow{}, err
}
return row, err
}
// UpsertPreview mémorise la génération servie (taille + updated_at sources).
func (r *Resources) UpsertPreview(resourceID string, srcSize int64, srcUpdatedAt time.Time) error {
_, err := r.DB.Exec(
`INSERT INTO resource_previews (resource_id, src_size_bytes, src_updated_at)
VALUES ($1, $2, $3)
ON CONFLICT (resource_id)
DO UPDATE SET src_size_bytes = EXCLUDED.src_size_bytes,
src_updated_at = EXCLUDED.src_updated_at,
created_at = NOW()`,
resourceID, srcSize, srcUpdatedAt,
)
return err
}
+65
View File
@@ -831,3 +831,68 @@ func (r *Resources) ListRootFoldersVisible(userID string) ([]FolderRow, error) {
} }
return folders, rows.Err() return folders, rows.Err()
} }
// ExportFileRow is one live file for full export (V3 S7 C3).
type ExportFileRow struct {
ID string
Name string
ParentID string
Size int64
MimeType string
Extension string
Hash string
OcrText string
HasContent bool
}
// ExportFiles returns ALL live files of a user (bounded — full export).
func (r *Resources) ExportFiles(ownerID string, limit int) ([]ExportFileRow, error) {
rows, err := r.DB.Query(
`SELECT resource_id, name, COALESCE(parent_id, ''), COALESCE(size_bytes, 0),
COALESCE(mime_type, ''), COALESCE(extension, ''),
COALESCE(content_hash, ''), COALESCE(ocr_text, ''),
COALESCE(has_content, FALSE)
FROM resources
WHERE user_id = $1 AND type = 'file' AND deleted_at IS NULL
ORDER BY created_at ASC LIMIT $2`,
ownerID, limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
out := make([]ExportFileRow, 0)
for rows.Next() {
var row ExportFileRow
if err := rows.Scan(&row.ID, &row.Name, &row.ParentID, &row.Size, &row.MimeType,
&row.Extension, &row.Hash, &row.OcrText, &row.HasContent); err != nil {
return nil, err
}
out = append(out, row)
}
return out, rows.Err()
}
// ExportFolders returns ALL live folders of a user (bounded — full export).
func (r *Resources) ExportFolders(ownerID string, limit int) ([]FolderRow, error) {
rows, err := r.DB.Query(
`SELECT resource_id, name, COALESCE(parent_id, '')
FROM resources
WHERE user_id = $1 AND type = 'folder' AND deleted_at IS NULL
ORDER BY created_at ASC LIMIT $2`,
ownerID, limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
out := make([]FolderRow, 0)
for rows.Next() {
var folder FolderRow
if err := rows.Scan(&folder.ID, &folder.Name, &folder.ParentID); err != nil {
return nil, err
}
out = append(out, folder)
}
return out, rows.Err()
}
+155
View File
@@ -0,0 +1,155 @@
package service
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
"github.com/alexmullins/zip"
)
// Export password floor (V3 S7 C3) : un backup chiffré avec "1234" est un
// placebo — même seuil que les mots de passe compte (8).
const exportMinPasswordLength = 8
// ExportMaxResources bounds a full export (V3 S7 C3) : au-delà, l'export est
// tronqué honnêtement (manifest.truncated = true) plutôt que de gonfler sans
// fin la mémoire/temps d'une requête HTTP.
const ExportMaxResources = 20000
// ExportManifestFile is the encrypted manifest inside the zip.
type ExportManifestFile struct {
Version int `json:"version"`
ExportedAt string `json:"exportedAt"`
UserID string `json:"userId"`
Truncated bool `json:"truncated"`
Folders []ExportFolderEntry `json:"folders"`
Files []ExportFileEntry `json:"files"`
}
// ExportFolderEntry mirrors a live folder (tree rebuilt via parentId).
type ExportFolderEntry struct {
ID string `json:"id"`
Name string `json:"name"`
ParentID string `json:"parentId,omitempty"`
}
// ExportFileEntry mirrors a live file (+ extracted knowledge for re-import).
type ExportFileEntry struct {
ID string `json:"id"`
Name string `json:"name"`
ParentID string `json:"parentId,omitempty"`
Size int64 `json:"size"`
MimeType string `json:"mimeType,omitempty"`
Extension string `json:"extension,omitempty"`
Hash string `json:"hash,omitempty"`
OcrText string `json:"ocrText,omitempty"`
Facts []FactDTO `json:"facts,omitempty"`
Path string `json:"path,omitempty"` // files/<id>.<ext> — absent si metadata-only
HasBytes bool `json:"hasBytes"`
}
// Export streams an AES-256 encrypted zip of the account (V3 S7 C3) : every
// entry — files AND manifest — is encrypted with password (WinZip AES, cf.
// alexmullins/zip). Scope : own live resources only (ni trashés, ni
// partagés d'autrui). Metadata-only files appear in the manifest without
// bytes (Path vide, HasBytes false). Password < 8 → error (400 côté handler).
func (s *Resources) Export(w io.Writer, ownerID, password string) error {
if len(password) < exportMinPasswordLength {
return fmt.Errorf("export password must be at least %d characters", exportMinPasswordLength)
}
folders, err := s.Repo.ExportFolders(ownerID, ExportMaxResources)
if err != nil {
return err
}
files, err := s.Repo.ExportFiles(ownerID, ExportMaxResources)
if err != nil {
return err
}
truncated := len(folders) == ExportMaxResources || len(files) == ExportMaxResources
manifest := ExportManifestFile{
Version: 1, ExportedAt: time.Now().UTC().Format(time.RFC3339),
UserID: ownerID, Truncated: truncated,
Folders: make([]ExportFolderEntry, 0, len(folders)),
Files: make([]ExportFileEntry, 0, len(files)),
}
for _, f := range folders {
manifest.Folders = append(manifest.Folders, ExportFolderEntry{
ID: f.ID, Name: f.Name, ParentID: f.ParentID,
})
}
zw := zip.NewWriter(w)
writeEncrypted := func(name string, data []byte) error {
fh := &zip.FileHeader{Name: name, Method: zip.Deflate}
fh.SetPassword(password)
fw, err := zw.CreateHeader(fh)
if err != nil {
return err
}
_, err = fw.Write(data)
return err
}
for _, f := range files {
entry := ExportFileEntry{
ID: f.ID, Name: f.Name, ParentID: f.ParentID, Size: f.Size,
MimeType: f.MimeType, Extension: f.Extension, Hash: f.Hash,
OcrText: f.OcrText,
}
// Faits joints (auto + corrections — la connaissance voyage avec).
if facts, ferr := s.Repository.Resources.ListFacts(f.ID); ferr == nil {
for _, fact := range facts {
entry.Facts = append(entry.Facts, FactDTO{
FactType: fact.Type, ValueText: fact.ValueText,
ValueNum: fact.ValueNum, ValueDate: derefString(fact.ValueDate),
Confidence: fact.Confidence, Origin: fact.Origin,
})
}
}
src, serr := s.resolvePhysical(ownerID, f.ID)
if serr != nil {
entry.HasBytes = false
manifest.Files = append(manifest.Files, entry)
continue
}
zipName := "files/" + f.ID
if f.Extension != "" {
zipName += "." + f.Extension
}
entry.Path = zipName
entry.HasBytes = true
manifest.Files = append(manifest.Files, entry)
in, err := os.Open(src)
if err != nil {
log.Printf("export: open %s: %v", f.ID, err)
continue
}
fh := &zip.FileHeader{Name: zipName, Method: zip.Deflate}
fh.SetPassword(password)
fw, err := zw.CreateHeader(fh)
if err != nil {
in.Close()
return err
}
if _, err := io.Copy(fw, in); err != nil {
in.Close()
return err
}
in.Close()
}
raw, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
return err
}
if err := writeEncrypted("manifest.json", raw); err != nil {
return err
}
return zw.Close()
}
+163
View File
@@ -0,0 +1,163 @@
package service
import (
"archive/zip"
"bytes"
"encoding/json"
"testing"
azip "github.com/alexmullins/zip"
"github.com/kazier/backend/repository"
)
// TestExportRoundTrip : zip déchiffrable avec le mot de passe, manifest
// cohérent (fichiers + faits + dossiers), octets intacts, trashés exclus.
func TestExportRoundTrip(t *testing.T) {
s := newServiceStore(t)
userID := mustCreateUser(t, s.Repository, "export-roundtrip")
folderID := repository.NewID()
if err := s.Repository.Resources.InsertFolder(userID, folderID, "Papiers", ""); err != nil {
t.Fatalf("insert folder: %v", err)
}
a, err := s.Upload(userID, multipartFileHeader(t, "a.txt", []byte("contenu-a")), folderID, "")
if err != nil {
t.Fatalf("upload a: %v", err)
}
b, err := s.Upload(userID, multipartFileHeader(t, "b.txt", []byte("contenu-b")), "", "")
if err != nil {
t.Fatalf("upload b: %v", err)
}
// Trashé : exclu de l'export.
if _, err := s.Trash(userID, b.ID); err != nil {
t.Fatalf("trash: %v", err)
}
// Metadata-only (jamais uploadé) : manifest sans octets.
metaID := repository.NewID()
if err := s.Repository.Resources.InsertFile(userID, metaID, "fantome.txt", "", 0, nil, nil); err != nil {
t.Fatalf("insert meta: %v", err)
}
var buf bytes.Buffer
if err := s.Export(&buf, userID, "motdepasse-8"); err != nil {
t.Fatalf("export: %v", err)
}
if buf.Len() == 0 {
t.Fatal("zip vide")
}
// Lecture avec le bon mot de passe (lib standard : échoue sur AES —
// on relit avec la même lib, comme un outil compatible WinZip AES).
zr, err := azip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatalf("open zip: %v", err)
}
names := map[string]bool{}
var manifestRaw []byte
for _, f := range zr.File {
names[f.Name] = true
if !f.IsEncrypted() {
t.Errorf("entrée non chiffrée: %s", f.Name)
}
f.SetPassword("motdepasse-8")
rc, err := f.Open()
if err != nil {
t.Fatalf("open %s: %v", f.Name, err)
}
var content bytes.Buffer
if _, err := content.ReadFrom(rc); err != nil {
rc.Close()
t.Fatalf("read %s: %v", f.Name, err)
}
rc.Close()
switch {
case f.Name == "manifest.json":
manifestRaw = content.Bytes()
case len(content.Bytes()) > 0 && f.Name != "manifest.json":
_ = content
}
}
var manifest ExportManifestFile
if err := json.Unmarshal(manifestRaw, &manifest); err != nil {
t.Fatalf("manifest: %v", err)
}
if manifest.Version != 1 || manifest.UserID != userID || manifest.Truncated {
t.Fatalf("manifest inattendu: %+v", manifest)
}
if len(manifest.Folders) != 1 || manifest.Folders[0].Name != "Papiers" {
t.Fatalf("dossiers: %+v", manifest.Folders)
}
if len(manifest.Files) != 2 {
t.Fatalf("fichiers manifest: %+v (attendu a + fantome, b trashé exclu)", manifest.Files)
}
byID := map[string]ExportFileEntry{}
for _, f := range manifest.Files {
byID[f.ID] = f
}
if byID[a.ID].Path == "" || !byID[a.ID].HasBytes {
t.Errorf("a doit avoir des octets: %+v", byID[a.ID])
}
if byID[metaID].Path != "" || byID[metaID].HasBytes {
t.Errorf("fantome sans octets: %+v", byID[metaID])
}
if !names["manifest.json"] || !names[byID[a.ID].Path] {
t.Fatalf("entrées zip manquantes: %v", names)
}
// Contenu chiffré : illisible sans mot de passe (lib standard échoue),
// et mauvais mot de passe refusé.
stdReader, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatalf("open std: %v", err)
}
for _, f := range stdReader.File {
rc, err := f.Open()
if err == nil {
var tmp bytes.Buffer
_, copyErr := tmp.ReadFrom(rc)
rc.Close()
if copyErr == nil && tmp.Len() > 0 {
t.Errorf("contenu lisible sans mot de passe: %s", f.Name)
}
}
}
zr2, err := azip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatalf("reopen: %v", err)
}
for _, f := range zr2.File {
if f.Name != "manifest.json" {
continue
}
f.SetPassword("mauvais-mot-de-passe")
rc, err := f.Open()
if err == nil {
var tmp bytes.Buffer
_, copyErr := tmp.ReadFrom(rc)
rc.Close()
if copyErr == nil {
t.Error("manifest déchiffré avec un mauvais mot de passe")
}
}
}
}
func TestExportPasswordFloor(t *testing.T) {
s := newServiceStore(t)
userID := mustCreateUser(t, s.Repository, "export-pw")
var buf bytes.Buffer
if err := s.Export(&buf, userID, "court"); err == nil {
t.Fatal("mot de passe court accepté")
}
// Compte vide : zip valide avec manifest seul.
if err := s.Export(&buf, userID, "motdepasse-8"); err != nil {
t.Fatalf("export vide: %v", err)
}
zr, err := azip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatalf("open: %v", err)
}
if len(zr.File) != 1 || zr.File[0].Name != "manifest.json" {
t.Fatalf("export vide inattendu: %v", zr.File)
}
}
+21 -11
View File
@@ -129,6 +129,26 @@ var ErrInvalidLinkType = errors.New("invalid link type or pair")
// hashPhysical computes the SHA-256 of the live bytes (safe resolution, // hashPhysical computes the SHA-256 of the live bytes (safe resolution,
// same pattern as OpenContent). Absent → ErrNotFound. // same pattern as OpenContent). Absent → ErrNotFound.
func (s *Resources) hashPhysical(ownerID, resourceID string) (string, error) { func (s *Resources) hashPhysical(ownerID, resourceID string) (string, error) {
resolved, err := s.resolvePhysical(ownerID, resourceID)
if err != nil {
return "", err
}
f, err := os.Open(resolved)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// resolvePhysical returns the absolute path of the live bytes (safe :
// 32-hex only, regular file, symlink contained in UploadDir).
// Absent → repository.ErrNotFound.
func (s *Resources) resolvePhysical(ownerID, resourceID string) (string, error) {
if !idPattern.MatchString(ownerID) || !idPattern.MatchString(resourceID) { if !idPattern.MatchString(ownerID) || !idPattern.MatchString(resourceID) {
return "", repository.ErrNotFound return "", repository.ErrNotFound
} }
@@ -156,17 +176,7 @@ func (s *Resources) hashPhysical(ownerID, resourceID string) (string, error) {
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
continue continue
} }
f, err := os.Open(resolved) return resolved, nil
if err != nil {
return "", err
}
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
f.Close()
return "", err
}
f.Close()
return hex.EncodeToString(h.Sum(nil)), nil
} }
return "", repository.ErrNotFound return "", repository.ErrNotFound
} }
+220
View File
@@ -0,0 +1,220 @@
package service
import (
"bytes"
"context"
"errors"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"golang.org/x/image/draw"
"golang.org/x/image/webp"
)
// ErrNoPreview signale qu'aucune vignette n'est possible (type non supporté,
// outil absent, octets illisibles). Handlers → 404 NO_PREVIEW (l'UI montre
// l'icône de catégorie au lieu de réessayer).
var ErrNoPreview = errors.New("no preview available")
// MaxPreviewEdge borne la vignette (miroir ThumbnailStore mobile, 512 px).
const MaxPreviewEdge = 512
// previewJPEGQuality compresse les vignettes (galerie rapide, artefacts invisibles à 512 px).
const previewJPEGQuality = 80
// pdftoppmTimeout borne le rendu PDF (binaire externe, jamais bloquant).
const pdftoppmTimeout = 30 * time.Second
// OpenPreview résout la vignette JPEG d'un fichier visible (viewer+, own ou
// shared) : cache `.previews/<resource_id>.jpg` régénéré quand la source a
// changé (taille ou updated_at), sinon servi tel quel. Images : pur Go.
// PDF page 1 : `pdftoppm` (poppler, cf. Dockerfile) ; absent → ErrNoPreview.
func (s *Resources) OpenPreview(userID, resourceID string) (string, error) {
row, err := s.Repo.GetFileVisible(userID, resourceID)
if err != nil {
return "", err
}
dir := filepath.Join(s.UploadDir, ".previews")
cached := filepath.Join(dir, resourceID+".jpg")
if prev, err := s.Repo.GetPreview(resourceID); err == nil {
if prev.SrcSize == row.Size && prev.SrcUpdatedAt.Equal(row.UpdatedAt) {
if fi, serr := os.Stat(cached); serr == nil && fi.Mode().IsRegular() {
return cached, nil
}
}
}
info, err := s.OpenContent(userID, resourceID)
if err != nil {
return "", err
}
kind := previewKind(row.MimeType, info.Path)
var data []byte
switch kind {
case "image":
data, err = renderImagePreview(info.Path)
case "pdf":
data, err = renderPDFPreview(info.Path)
default:
return "", ErrNoPreview
}
if err != nil {
return "", err
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", fmt.Errorf("preview dir: %w", err)
}
tmp, err := os.CreateTemp(dir, ".tmp-"+resourceID+".*.jpg")
if err != nil {
return "", fmt.Errorf("preview tmp: %w", err)
}
tmpName := tmp.Name()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
_ = os.Remove(tmpName)
return "", fmt.Errorf("preview write: %w", err)
}
if err := tmp.Close(); err != nil {
_ = os.Remove(tmpName)
return "", fmt.Errorf("preview close: %w", err)
}
if err := os.Chmod(tmpName, 0o600); err != nil {
_ = os.Remove(tmpName)
return "", fmt.Errorf("preview chmod: %w", err)
}
if err := os.Rename(tmpName, cached); err != nil {
_ = os.Remove(tmpName)
return "", fmt.Errorf("preview commit: %w", err)
}
if err := s.Repo.UpsertPreview(resourceID, row.Size, row.UpdatedAt); err != nil {
log.Printf("preview: upsert(%s): %v", resourceID, err)
}
return cached, nil
}
// previewKind classe la source : images décodables Go vs PDF vs le reste.
func previewKind(mimeType, path string) string {
mime := strings.ToLower(mimeType)
if strings.HasPrefix(mime, "image/") {
return "image"
}
ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(path), "."))
switch ext {
case "jpg", "jpeg", "png", "gif", "webp", "bmp":
return "image"
case "pdf":
return "pdf"
}
if mime == "application/pdf" {
return "pdf"
}
return ""
}
// renderImagePreview décode (jpeg/png/gif/webp) et réduit au plus grand côté
// MaxPreviewEdge, sortie JPEG. Source déjà à taille → ré-encodée telle quelle
// (uniformité du cache, coût négligeable à cette échelle).
func renderImagePreview(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, ErrNoPreview
}
defer f.Close()
var img image.Image
lower := strings.ToLower(path)
switch {
case strings.HasSuffix(lower, ".png"):
img, err = png.Decode(f)
case strings.HasSuffix(lower, ".gif"):
img, err = gif.Decode(f)
case strings.HasSuffix(lower, ".webp"):
img, err = webp.Decode(f)
default:
img, err = jpeg.Decode(f)
if err != nil {
// Extension menteuse (ex. .jpg contenant du PNG) : tente le PNG.
if _, serr := f.Seek(0, io.SeekStart); serr == nil {
img, err = png.Decode(f)
}
}
}
if err != nil {
return nil, ErrNoPreview
}
return encodeScaled(img)
}
// renderPDFPreview rend la page 1 via `pdftoppm` (poppler) puis réduit.
// Binaire absent ou PDF illisible → ErrNoPreview (jamais 500).
func renderPDFPreview(path string) ([]byte, error) {
if _, err := exec.LookPath("pdftoppm"); err != nil {
return nil, ErrNoPreview
}
dir, err := os.MkdirTemp("", "kazier-preview-*")
if err != nil {
return nil, fmt.Errorf("preview tmpdir: %w", err)
}
defer os.RemoveAll(dir)
prefix := filepath.Join(dir, "page")
ctx, cancel := context.WithTimeout(context.Background(), pdftoppmTimeout)
defer cancel()
// -r 50 : assez pour 512 px après réduction, sans pic mémoire.
cmd := exec.CommandContext(ctx, "pdftoppm", "-jpeg", "-r", "50", "-f", "1", "-l", "1", "-singlefile", path, prefix)
if out, err := cmd.CombinedOutput(); err != nil {
log.Printf("preview: pdftoppm: %v (%s)", err, strings.TrimSpace(string(out)))
return nil, ErrNoPreview
}
rendered := prefix + ".jpg"
f, err := os.Open(rendered)
if err != nil {
return nil, ErrNoPreview
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, ErrNoPreview
}
return encodeScaled(img)
}
// encodeScaled réduit au plus grand côté MaxPreviewEdge (ratio préservé) et
// encode en JPEG. Images déjà petites : recopiées à l'identique.
func encodeScaled(img image.Image) ([]byte, error) {
bounds := img.Bounds()
w, h := bounds.Dx(), bounds.Dy()
if w <= 0 || h <= 0 {
return nil, ErrNoPreview
}
scaled := img
max := w
if h > max {
max = h
}
if max > MaxPreviewEdge {
ratio := float64(MaxPreviewEdge) / float64(max)
nw, nh := int(float64(w)*ratio+0.5), int(float64(h)*ratio+0.5)
if nw < 1 {
nw = 1
}
if nh < 1 {
nh = 1
}
dst := image.NewRGBA(image.Rect(0, 0, nw, nh))
draw.CatmullRom.Scale(dst, dst.Bounds(), img, bounds, draw.Over, nil)
scaled = dst
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, scaled, &jpeg.Options{Quality: previewJPEGQuality}); err != nil {
return nil, fmt.Errorf("preview encode: %w", err)
}
return buf.Bytes(), nil
}
+160
View File
@@ -0,0 +1,160 @@
package service
import (
"bytes"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/kazier/backend/dbtest"
"github.com/kazier/backend/repository"
)
// newPreviewStore : comme newServiceStore mais avec un quota d'upload réaliste
// (les images de test dépassent les 100 octets du store par défaut).
func newPreviewStore(t *testing.T) *Resources {
t.Helper()
conn := dbtest.OpenTestDatabase(t, serviceTestURL)
repo := repository.NewRepository(conn)
return NewResources(repo, t.TempDir(), 10<<20)
}
// testImageBytes génère un JPEG 800x600 uni (décodable sans fixture).
func testImageBytes(t *testing.T) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, 800, 600))
for y := 0; y < 600; y++ {
for x := 0; x < 800; x++ {
img.Set(x, y, color.RGBA{uint8(x % 256), uint8(y % 256), 128, 255})
}
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, nil); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestOpenPreviewImage(t *testing.T) {
s := newPreviewStore(t)
userID := mustCreateUser(t, s.Repository, "preview-img")
dto, err := s.Upload(userID, multipartFileHeader(t, "photo.jpg", testImageBytes(t)), "", "")
if err != nil {
t.Fatalf("upload: %v", err)
}
path, err := s.OpenPreview(userID, dto.ID)
if err != nil {
t.Fatalf("preview: %v", err)
}
f, err := os.Open(path)
if err != nil {
t.Fatalf("open preview: %v", err)
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
t.Fatalf("preview n'est pas un JPEG: %v", err)
}
b := img.Bounds()
if b.Dx() > MaxPreviewEdge || b.Dy() > MaxPreviewEdge {
t.Fatalf("vignette trop grande: %dx%d", b.Dx(), b.Dy())
}
if b.Dx() != MaxPreviewEdge {
t.Fatalf("plus grand côté = %d, attendu %d", b.Dx(), MaxPreviewEdge)
}
// Second appel : cache (même fichier, pas de régénération).
fi1, _ := os.Stat(path)
path2, err := s.OpenPreview(userID, dto.ID)
if err != nil {
t.Fatalf("preview 2: %v", err)
}
fi2, _ := os.Stat(path2)
if !os.SameFile(fi1, fi2) {
t.Fatal("le cache aurait dû être servi")
}
// Overwrite → la vignette suit les nouveaux octets.
dto2, err := s.Upload(userID, multipartFileHeader(t, "photo.jpg", testImageBytes(t)), "", dto.ID)
if err != nil {
t.Fatalf("overwrite: %v", err)
}
_ = dto2
path3, err := s.OpenPreview(userID, dto.ID)
if err != nil {
t.Fatalf("preview 3: %v", err)
}
fi3, _ := os.Stat(path3)
if os.SameFile(fi2, fi3) {
t.Fatal("la vignette aurait dû être régénérée après overwrite")
}
}
func TestOpenPreviewUnsupported(t *testing.T) {
s := newPreviewStore(t)
userID := mustCreateUser(t, s.Repository, "preview-no")
dto, err := s.Upload(userID, multipartFileHeader(t, "notes.txt", []byte("hello")), "", "")
if err != nil {
t.Fatalf("upload: %v", err)
}
if _, err := s.OpenPreview(userID, dto.ID); err != ErrNoPreview {
t.Fatalf("txt : attendu ErrNoPreview, got %v", err)
}
// Trashé → NOT_FOUND (pas NO_PREVIEW : invisible d'abord).
if _, err := s.Trash(userID, dto.ID); err != nil {
t.Fatalf("trash: %v", err)
}
if _, err := s.OpenPreview(userID, dto.ID); err != repository.ErrNotFound {
t.Fatalf("trashé : attendu NOT_FOUND, got %v", err)
}
// Étranger → NOT_FOUND.
other := mustCreateUser(t, s.Repository, "preview-no-x")
dto2, err := s.Upload(other, multipartFileHeader(t, "img.png", testPNGBytes(t)), "", "")
if err != nil {
t.Fatalf("upload other: %v", err)
}
if _, err := s.OpenPreview(userID, dto2.ID); err != repository.ErrNotFound {
t.Fatalf("étranger : attendu NOT_FOUND, got %v", err)
}
}
func testPNGBytes(t *testing.T) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, 100, 100))
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestOpenPreviewPDF(t *testing.T) {
if _, err := exec.LookPath("pdftoppm"); err != nil {
t.Skip("pdftoppm absent (hors Docker) — rendu PDF non testé ici")
}
s := newPreviewStore(t)
userID := mustCreateUser(t, s.Repository, "preview-pdf")
pdf := []byte("%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]>>endobj\ntrailer<</Root 1 0 R>>\n")
dto, err := s.Upload(userID, multipartFileHeader(t, "doc.pdf", pdf), "", "")
if err != nil {
t.Fatalf("upload: %v", err)
}
path, err := s.OpenPreview(userID, dto.ID)
if err != nil {
t.Fatalf("preview pdf: %v", err)
}
if fi, err := os.Stat(path); err != nil || fi.Size() == 0 {
t.Fatalf("vignette pdf absente: %v", err)
}
_ = filepath.Separator
}
+3 -1
View File
@@ -41,6 +41,8 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
| 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) | | 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) |
| GET | `/files/:id/preview` | — (JPEG 512, `inline`, `Cache-Control: private, max-age=3600`, viewer+) | vignette (`image/jpeg`) — générée à la demande (images pur Go, PDF page 1 via `pdftoppm`), cachée jusqu'au prochain changement | `NOT_FOUND` (invisible/metadata-only), `NO_PREVIEW` (type non prévisualisable — icône côté client, sans réessai) |
| POST | `/export` | `{ "password" }` (8+ caractères, en corps — jamais en query) | zip AES-256 streamé (`application/zip`, `attachment`) — fichiers vifs possédés + `manifest.json`, tout chiffré | `INVALID_REQUEST` (mot de passe court/malformé) |
| DELETE | `/files/:id` | query `mode?` (`trash` défaut, `purge` = définitif) | `{ "id": "…" }` | `NOT_FOUND` | | DELETE | `/files/:id` | query `mode?` (`trash` défaut, `purge` = définitif) | `{ "id": "…" }` | `NOT_FOUND` |
| POST | `/files/:id/restore` | — | `{ "id": "…" }` | `NOT_FOUND` (absente/étrangère/purgée ; vivante = succès idempotent) | | POST | `/files/:id/restore` | — | `{ "id": "…" }` | `NOT_FOUND` (absente/étrangère/purgée ; vivante = succès idempotent) |
| GET | `/trash` | query `page?`, `pageSize?` | `TrashDto[]` (`{ id, type, name, size, trashedAt, updatedAt }` + `meta`) | — | | GET | `/trash` | query `page?`, `pageSize?` | `TrashDto[]` (`{ id, type, name, size, trashedAt, updatedAt }` + `meta`) | — |
@@ -187,7 +189,7 @@ type ResourcePermission = {
## 7. Codes d'erreur courants ## 7. Codes d'erreur courants
- Authentification : `UNAUTHORIZED` (**401** — token manquant/invalide/expiré/**révoqué** (mot de passe changé, device révoqué), compte supprimé, OU identifiants de login erronés : **indistinguables par design**, même code+message), `INVALID_DEVICE_ID` (**400** — device non enregistré au login). - Authentification : `UNAUTHORIZED` (**401** — token manquant/invalide/expiré/**révoqué** (mot de passe changé, device révoqué), compte supprimé, OU identifiants de login erronés : **indistinguables par design**, même code+message), `INVALID_DEVICE_ID` (**400** — device non enregistré au login).
- Ressources : `NOT_FOUND` (404), `NAME_CONFLICT` (409 — même nom dans le même parent, cf. `UNIQUE(parent_id, name)`, **ou à la racine**, index partiel `(user_id, name) WHERE parent_id IS NULL`), `FILE_TOO_LARGE` (413), `QUOTA_EXCEEDED` (413 — créations au-delà de `storage_quota_bytes`, 10 Go par défaut ; overwrites ciblées exemptées, gain net ~nul), `INVALID_PASSWORD` (403 sur `PATCH /users/me/password`). - Ressources : `NOT_FOUND` (404), `NO_PREVIEW` (404 — type non prévisualisable : txt, binaire inconnu, PDF sans `pdftoppm`), `NAME_CONFLICT` (409 — même nom dans le même parent, cf. `UNIQUE(parent_id, name)`, **ou à la racine**, index partiel `(user_id, name) WHERE parent_id IS NULL`), `FILE_TOO_LARGE` (413), `QUOTA_EXCEEDED` (413 — créations au-delà de `storage_quota_bytes`, 10 Go par défaut ; overwrites ciblées exemptées, gain net ~nul), `INVALID_PASSWORD` (403 sur `PATCH /users/me/password`).
- Partage : `GRANTEE_NOT_FOUND` (404 — grantee inexistant sur une op share), `GROUP_NOT_FOUND` (404 — groupe inexistant sur une op share ou un endpoint membres), `NOT_FOUND` (404 — ressource non possédée sur une op share : scoping, pas d'énumération). - Partage : `GRANTEE_NOT_FOUND` (404 — grantee inexistant sur une op share), `GROUP_NOT_FOUND` (404 — groupe inexistant sur une op share ou un endpoint membres), `NOT_FOUND` (404 — ressource non possédée sur une op share : scoping, pas d'énumération).
- Client-only : `NETWORK_ERROR`, `INVALID_RESPONSE` (2xx mais corps d'enveloppe invalide), `HTTP_<status>` (fallback). Statut `SERVICE_UNAVAILABLE` (503) si le backend n'est pas initialisé. - Client-only : `NETWORK_ERROR`, `INVALID_RESPONSE` (2xx mais corps d'enveloppe invalide), `HTTP_<status>` (fallback). Statut `SERVICE_UNAVAILABLE` (503) si le backend n'est pas initialisé.
- **V1 finale : toutes les routes sont réelles** (pas de 501 restant). - **V1 finale : toutes les routes sont réelles** (pas de 501 restant).
@@ -33,6 +33,18 @@
tools:node="remove" /> tools:node="remove" />
</provider> </provider>
<!-- Partage de l'export chiffré (V3 S7) : FileProvider sur le cache
(jamais d'URI file:// vers une autre app). -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
@@ -32,6 +32,7 @@ import com.kazier.mobile.data.remote.dto.SyncOpsResult
import com.kazier.mobile.data.remote.dto.CorrectFactsDto import com.kazier.mobile.data.remote.dto.CorrectFactsDto
import com.kazier.mobile.data.remote.dto.DeviceDto import com.kazier.mobile.data.remote.dto.DeviceDto
import com.kazier.mobile.data.remote.dto.DuplicateGroupDto import com.kazier.mobile.data.remote.dto.DuplicateGroupDto
import com.kazier.mobile.data.remote.dto.ExportRequestDto
import com.kazier.mobile.data.remote.dto.FactDto import com.kazier.mobile.data.remote.dto.FactDto
import com.kazier.mobile.data.remote.dto.RelationDto import com.kazier.mobile.data.remote.dto.RelationDto
import com.kazier.mobile.data.remote.dto.RelationVerdictDto import com.kazier.mobile.data.remote.dto.RelationVerdictDto
@@ -43,6 +44,7 @@ import okhttp3.MultipartBody
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import okio.IOException import okio.IOException
import retrofit2.Response import retrofit2.Response
import timber.log.Timber import timber.log.Timber
@@ -204,6 +206,60 @@ class ApiClient @Inject constructor(
suspend fun getUsage(): UsageDto = suspend fun getUsage(): UsageDto =
unwrap({ apiService.getUsage() }) unwrap({ apiService.getUsage() })
/**
* Export chiffré vers un fichier (V3 S7) — `POST /export`, streamé
* direct sur disque (jamais en RAM : un export peut peser des Go).
* 400 si mot de passe trop court, 401 → re-login.
*/
suspend fun exportToFile(password: String, dest: java.io.File) {
val response = try {
apiService.exportZip(ExportRequestDto(password))
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
Timber.d(e, "api: transport error (export)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} catch (e: Exception) {
if (e is CancellationException) throw e
Timber.d(e, "api: unexpected error (export)")
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 ?: "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())
try {
dest.parentFile?.mkdirs()
body.byteStream().use { input ->
dest.outputStream().use { out ->
input.copyTo(out)
}
}
} catch (e: CancellationException) {
runCatching { dest.delete() }
throw e
} catch (e: IOException) {
runCatching { dest.delete() }
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} finally {
body.close()
}
}
/** Recherche serveur paginée — `GET /files/search?q=…` (+ `meta`). */ /** Recherche serveur paginée — `GET /files/search?q=…` (+ `meta`). */
suspend fun searchFilesPaged( suspend fun searchFilesPaged(
query: String, query: String,
@@ -277,17 +333,39 @@ class ApiClient @Inject constructor(
suspend fun downloadContentBytes( suspend fun downloadContentBytes(
fileId: String, fileId: String,
maxBytes: Long = MAX_CONTENT_BYTES, maxBytes: Long = MAX_CONTENT_BYTES,
): ByteArray = downloadRawBytes(tag = "content", maxBytes = maxBytes) {
apiService.downloadContent(fileId)
}
/**
* Vignette JPEG 512 d'un fichier visible — `GET /files/:id/preview`
* (binaire brut, `inline`). 404 NOT_FOUND si invisible, 404 NO_PREVIEW
* si le type ne se prévisualise pas (code propagé tel quel pour que
* l'UI n'insiste pas).
*/
suspend fun downloadPreviewBytes(
fileId: String,
maxBytes: Long = MAX_PREVIEW_BYTES,
): ByteArray = downloadRawBytes(tag = "preview", maxBytes = maxBytes) {
apiService.downloadPreview(fileId)
}
/** Cœur streaming borné partagé par `content` et `preview` (V3 S7). */
private suspend fun downloadRawBytes(
tag: String,
maxBytes: Long,
call: suspend () -> Response<ResponseBody>,
): ByteArray { ): ByteArray {
val response = try { val response = try {
apiService.downloadContent(fileId) call()
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
} catch (e: IOException) { } catch (e: IOException) {
Timber.d(e, "api: transport error (content)") Timber.d(e, "api: transport error ($tag)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0) throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} catch (e: Exception) { } catch (e: Exception) {
if (e is CancellationException) throw e if (e is CancellationException) throw e
Timber.d(e, "api: unexpected error (content)") Timber.d(e, "api: unexpected error ($tag)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0) throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} }
if (!response.isSuccessful) { if (!response.isSuccessful) {
@@ -342,6 +420,8 @@ class ApiClient @Inject constructor(
companion object { companion object {
/** Borne streaming sans cache : 12 Mo (jamais en RAM au-delà). */ /** Borne streaming sans cache : 12 Mo (jamais en RAM au-delà). */
const val MAX_CONTENT_BYTES = 12 * 1024 * 1024L const val MAX_CONTENT_BYTES = 12 * 1024 * 1024L
/** Borne vignette distante : 1 Mo (JPEG 512 ≪ ça, garde-fou). */
const val MAX_PREVIEW_BYTES = 1024 * 1024L
} }
private suspend fun <T> unwrap( private suspend fun <T> unwrap(
@@ -25,6 +25,7 @@ import com.kazier.mobile.data.remote.dto.SyncOpsResult
import com.kazier.mobile.data.remote.dto.CorrectFactsDto import com.kazier.mobile.data.remote.dto.CorrectFactsDto
import com.kazier.mobile.data.remote.dto.DeviceDto import com.kazier.mobile.data.remote.dto.DeviceDto
import com.kazier.mobile.data.remote.dto.DuplicateGroupDto import com.kazier.mobile.data.remote.dto.DuplicateGroupDto
import com.kazier.mobile.data.remote.dto.ExportRequestDto
import com.kazier.mobile.data.remote.dto.FactDto import com.kazier.mobile.data.remote.dto.FactDto
import com.kazier.mobile.data.remote.dto.RelationDto import com.kazier.mobile.data.remote.dto.RelationDto
import com.kazier.mobile.data.remote.dto.RelationVerdictDto import com.kazier.mobile.data.remote.dto.RelationVerdictDto
@@ -148,6 +149,18 @@ interface ApiService {
@Path("id") fileId: String, @Path("id") fileId: String,
): Response<ResponseBody> ): Response<ResponseBody>
/**
* Vignette JPEG 512 d'un fichier visible (V3 S7) —
* `GET /files/:id/preview` (binaire brut, `inline`, cache 1 h).
* 404 NOT_FOUND si invisible/metadata-only, 404 NO_PREVIEW si le type
* ne se prévisualise pas (l'UI montre l'icône, sans réessai).
*/
@Streaming
@GET("files/{id}/preview")
suspend fun downloadPreview(
@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(
@@ -239,6 +252,17 @@ interface ApiService {
@GET("users/me/usage") @GET("users/me/usage")
suspend fun getUsage(): Response<ApiEnvelope<UsageDto>> suspend fun getUsage(): Response<ApiEnvelope<UsageDto>>
/**
* Export chiffré du compte (V3 S7) — `POST /export { password }`
* (mot de passe en corps, jamais en query). Zip AES-256 streamé
* (fichiers vifs possédés + manifest.json, tout chiffré).
*/
@Streaming
@POST("export")
suspend fun exportZip(
@Body body: ExportRequestDto,
): Response<ResponseBody>
/** /**
* Recherche serveur (`GET /files/search?q=…`, paginé `meta`). Non consommée * Recherche serveur (`GET /files/search?q=…`, paginé `meta`). Non consommée
* en V1 (recherche 100 % locale via Room) — exposée pour parité contrat. * en V1 (recherche 100 % locale via Room) — exposée pour parité contrat.
@@ -369,4 +369,9 @@ data class UsageDto(
@Json(name = "fileCount") val fileCount: Int = 0, @Json(name = "fileCount") val fileCount: Int = 0,
@Json(name = "trashCount") val trashCount: Int = 0, @Json(name = "trashCount") val trashCount: Int = 0,
@Json(name = "trashedBytes") val trashedBytes: Long = 0L, @Json(name = "trashedBytes") val trashedBytes: Long = 0L,
)
/** Body `POST /export` — mot de passe du zip AES (8+ caractères, V3 S7). */
data class ExportRequestDto(
@Json(name = "password") val password: String,
) )
@@ -0,0 +1,52 @@
package com.kazier.mobile.features.thumbnails
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.domain.FileCategory
import com.kazier.mobile.domain.computeCategory
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
import timber.log.Timber
/**
* Vignettes des fichiers cloud-only (V3 S7) : `GET /files/:id/preview`
* (JPEG 512 serveur) → cache WebP versionné ([ThumbnailStore.putRemote]).
*
* Garde-fou anti-matraquage : un `tried` process-wide (succès comme échec —
* 404 NO_PREVIEW inclus) garantit au plus UNE requête réseau par ressource et
* par session, même dans une grille de 500 items. Après succès, le cache
* disque prend le relais (zéro réseau) ; après un changement serveur, le
* versionnement `updatedAt + taille` invalide l'ancien fichier.
*/
@Singleton
class RemotePreviewFetcher @Inject constructor(
private val apiClient: ApiClient,
private val thumbnailStore: ThumbnailStore,
) {
private val tried = ConcurrentHashMap.newKeySet<String>()
/** Vignette distante mise en cache, ou `null` (icône de catégorie). */
suspend fun fetch(file: FileEntity): File? {
if (file.uri != null) return null
// computeCategory (domaine) plutôt que categoryValue (UI) : même
// règle, sans dépendance features → ui.
val category = computeCategory(file.mimeType, file.extension)
if (category != FileCategory.IMAGE && category != FileCategory.PDF) return null
// Cache disque d'abord (2e vue de la session, ou pré-rempli).
thumbnailStore.cachedRemote(file.resourceId, file.updatedAt, file.size)?.let { return it }
if (!tried.add(file.resourceId)) return null
return try {
val bytes = apiClient.downloadPreviewBytes(file.resourceId)
thumbnailStore.putRemote(file.resourceId, file.updatedAt, file.size, bytes)
} catch (e: Exception) {
Timber.d("remote preview %s: %s", file.resourceId, e.message)
null
}
}
/** Nombre de ressources tentées cette session (diagnostic/tests). */
internal fun triedCount(): Int = tried.size
}
@@ -111,6 +111,47 @@ class ThumbnailStore @Inject constructor(
} }
} }
/**
* Persiste des octets de vignette distants (`GET /files/:id/preview`,
* JPEG 512 déjà réduit serveur) en cache WebP versionné
* (`updatedAt + taille` — une source modifiée invalide l'ancien
* fichier, comme en local). Retourne le fichier, `null` si indécodable.
*/
suspend fun putRemote(
resourceId: String,
version: Long?,
sizeBytes: Long?,
bytes: ByteArray,
): File? = withContext(Dispatchers.IO) {
val bitmap = runCatching {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}.getOrNull() ?: return@withContext null
try {
val target = thumbnailFile(resourceId, version, sizeBytes)
if (isUpToDate(target, null)) return@withContext target
val tmp = File(target.parentFile, "${target.name}.tmp")
try {
dir().mkdirs()
val ok = tmp.outputStream().use { out ->
bitmap.compress(Bitmap.CompressFormat.WEBP, WEBP_QUALITY, out)
}
if (ok && tmp.renameTo(target)) {
pruneSiblings(resourceId, keep = target)
target
} else {
runCatching { tmp.delete() }
null
}
} catch (e: Exception) {
Timber.w(e, "remote thumbnail write failed")
runCatching { tmp.delete() }
null
}
} finally {
bitmap.recycle()
}
}
/** Fichier possédé par une resource : version courante, legacy ou tmp. */ /** Fichier possédé par une resource : version courante, legacy ou tmp. */
private fun isOwnedThumb(resourceId: String, name: String): Boolean { private fun isOwnedThumb(resourceId: String, name: String): Boolean {
if (name == "$resourceId.webp") return true if (name == "$resourceId.webp") return true
@@ -119,6 +160,19 @@ class ThumbnailStore @Inject constructor(
return false return false
} }
/**
* Cache disque d'une vignette distante (versionnée, puis legacy) — sans
* réseau. Le nom versionné (`updatedAt + taille`) porte la fraîcheur :
* une source modifiée ne matche plus et sera re-téléchargée.
*/
fun cachedRemote(resourceId: String, version: Long?, sizeBytes: Long?): File? {
val target = thumbnailFile(resourceId, version, sizeBytes)
if (isUpToDate(target, null)) return target
val legacy = thumbnailFile(resourceId)
if (legacy != target && isUpToDate(legacy, null)) return legacy
return null
}
/** Supprime les versions périmées et les `.tmp` orphelins (génération OK). */ /** Supprime les versions périmées et les `.tmp` orphelins (génération OK). */
private fun pruneSiblings(resourceId: String, keep: File) { private fun pruneSiblings(resourceId: String, keep: File) {
dir().listFiles { f -> f != keep && isOwnedThumb(resourceId, f.name) } dir().listFiles { f -> f != keep && isOwnedThumb(resourceId, f.name) }
@@ -16,6 +16,7 @@ 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.RemotePreviewFetcher
import com.kazier.mobile.features.thumbnails.ThumbnailStore import com.kazier.mobile.features.thumbnails.ThumbnailStore
import com.kazier.mobile.ui.theme.ThumbShape import com.kazier.mobile.ui.theme.ThumbShape
import dagger.hilt.EntryPoint import dagger.hilt.EntryPoint
@@ -32,8 +33,10 @@ import kotlinx.coroutines.withContext
* Images (JPEG/PNG/WebP) et PDF (page 1) n'affichent plus une simple icône : * Images (JPEG/PNG/WebP) et PDF (page 1) n'affichent plus une simple icône :
* la vignette est générée à la demande par [ThumbnailStore] (décodage borné * la vignette est générée à la demande par [ThumbnailStore] (décodage borné
* 512 px, single-flight, cache disque `filesDir/thumbnails`) puis rendue par * 512 px, single-flight, cache disque `filesDir/thumbnails`) puis rendue par
* Coil depuis le fichier local — zéro lecture SAF au scroll. Les autres * Coil depuis le fichier local — zéro lecture SAF au scroll. Les fichiers
* catégories et les fichiers cloud-only conservent l'icône de catégorie. * cloud-only (`uri == null`) tentent la preview serveur (`RemotePreviewFetcher`,
* une seule requête par session puis cache disque). Les autres catégories
* conservent l'icône de catégorie.
*/ */
@Composable @Composable
fun FileThumbnail( fun FileThumbnail(
@@ -50,9 +53,13 @@ fun FileThumbnail(
val context = LocalContext.current val context = LocalContext.current
val thumbnailStore = rememberThumbnailStore(context) val thumbnailStore = rememberThumbnailStore(context)
val remoteFetcher = rememberRemoteFetcher(context)
@Suppress("ProduceStateDoesNotAssignValue") @Suppress("ProduceStateDoesNotAssignValue")
val thumb by produceState<File?>(null, file.resourceId, file.lastModified) { val thumb by produceState<File?>(null, file.resourceId, file.lastModified, file.updatedAt) {
value = withContext(Dispatchers.IO) { thumbnailStore.ensure(file) } value = withContext(Dispatchers.IO) {
thumbnailStore.ensure(file)
?: remoteFetcher?.fetch(file)
}
} }
val thumbFile = thumb val thumbFile = thumb
@@ -84,8 +91,21 @@ private fun rememberThumbnailStore(context: Context): ThumbnailStore =
).thumbnailStore() ).thumbnailStore()
} }
/** Fetcher optionnel (hors Hilt direct en UI) — null si indisponible. */
@Composable
private fun rememberRemoteFetcher(context: Context): RemotePreviewFetcher? =
remember(context) {
runCatching {
EntryPointAccessors.fromApplication(
context.applicationContext,
ThumbnailStoreEntryPoint::class.java,
).remotePreviewFetcher()
}.getOrNull()
}
@EntryPoint @EntryPoint
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
internal interface ThumbnailStoreEntryPoint { internal interface ThumbnailStoreEntryPoint {
fun thumbnailStore(): ThumbnailStore fun thumbnailStore(): ThumbnailStore
fun remotePreviewFetcher(): RemotePreviewFetcher
} }
@@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.CloudOff import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DocumentScanner import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.FactCheck import androidx.compose.material.icons.filled.FactCheck
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
@@ -187,6 +188,31 @@ fun DocumentViewerScreen(
snackbarHostState.showSnackbar(context.getString(R.string.document_open_error)) snackbarHostState.showSnackbar(context.getString(R.string.document_open_error))
} }
} }
// B3 : partage système du fichier local (SAF content:// direct + grant).
// Cloud-only : pas de copie locale → pas de partage (télécharger d'abord).
val onShare: (() -> Unit)? = currentFile
?.takeIf { it.uri != null }
?.let { file ->
{
val uri = android.net.Uri.parse(file.uri)
val share = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
type = file.mimeType ?: "application/octet-stream"
putExtra(android.content.Intent.EXTRA_STREAM, uri)
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
clipData = android.content.ClipData.newUri(
context.contentResolver, file.name, uri,
)
}
runCatching {
context.startActivity(
android.content.Intent.createChooser(
share,
context.getString(R.string.document_share_title),
),
)
}.onFailure { onOpenExternalFailed() }
}
}
// Erreurs / succès transitoires (suppression, garder) → Snackbar puis effacés. // Erreurs / succès transitoires (suppression, garder) → Snackbar puis effacés.
LaunchedEffect(viewerState.deleteError) { LaunchedEffect(viewerState.deleteError) {
@@ -346,6 +372,7 @@ fun DocumentViewerScreen(
} else { } else {
null null
}, },
onShare = onShare,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) )
} }
@@ -660,6 +687,7 @@ private fun DocumentActionBar(
onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit, onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit,
onOcr: (() -> Unit)? = null, onOcr: (() -> Unit)? = null,
onFacts: (() -> Unit)? = null, onFacts: (() -> Unit)? = null,
onShare: (() -> Unit)? = null,
releasable: Boolean = false, releasable: Boolean = false,
onRelease: (() -> Unit)? = null, onRelease: (() -> Unit)? = null,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
@@ -736,6 +764,12 @@ private fun DocumentActionBar(
onClick = onFacts, onClick = onFacts,
) )
} }
if (onShare != null) {
DocumentShareButton(
enabled = !busy,
onClick = onShare,
)
}
DocumentDeleteMenu( DocumentDeleteMenu(
file = file, file = file,
enabled = !busy, enabled = !busy,
@@ -824,6 +858,31 @@ private fun DocumentOcrButton(
} }
} }
/** Bouton « Partager » B3 — ACTION_SEND du fichier local (SAF direct). */
@Composable
private fun DocumentShareButton(
enabled: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
FilledTonalButton(
onClick = onClick,
enabled = enabled,
modifier = modifier,
) {
Icon(
imageVector = Icons.Filled.Share,
contentDescription = null,
modifier = Modifier.size(20.dp),
)
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
Text(
text = stringResource(R.string.document_share),
maxLines = 1,
)
}
}
/** /**
* Fenêtre OCR : progression (upload → queued → processing), texte extrait * Fenêtre OCR : progression (upload → queued → processing), texte extrait
* (sélectionnable) ou erreur. Le bouton « Relancer » est proposé dès que le * (sélectionnable) ou erreur. Le bouton « Relancer » est proposé dès que le
@@ -0,0 +1,71 @@
package com.kazier.mobile.ui.settings
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kazier.mobile.data.remote.ApiClient
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import timber.log.Timber
/**
* Export chiffré du compte (V3 S7 C3) : `POST /export { password }` → zip
* AES-256 téléchargé dans le cache (`cache/exports/`) puis partagé via le
* sheet système (FileProvider, jamais d'URI `file://`). Le mot de passe
* n'est ni persisté ni journalisé (champ seul, 8+ caractères).
*/
@HiltViewModel
class ExportViewModel @Inject constructor(
private val apiClient: ApiClient,
@ApplicationContext private val appContext: Context,
) : ViewModel() {
data class ExportUiState(
val downloading: Boolean = false,
val file: File? = null,
val error: String? = null,
)
private val _uiState = MutableStateFlow(ExportUiState())
val uiState: StateFlow<ExportUiState> = _uiState.asStateFlow()
fun download(password: String) {
if (_uiState.value.downloading) return
viewModelScope.launch {
_uiState.update { it.copy(downloading = true, file = null, error = null) }
runCatching {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val dest = File(File(appContext.cacheDir, "exports"), "kazier-export-$stamp.zip")
// Nettoie les exports précédents (un seul fichier vivant).
dest.parentFile?.listFiles()?.forEach { runCatching { it.delete() } }
apiClient.exportToFile(password, dest)
dest
}.onSuccess { file ->
_uiState.update { it.copy(downloading = false, file = file) }
}.onFailure { e ->
Timber.w(e, "export failed")
_uiState.update {
it.copy(downloading = false, error = e.message ?: e.javaClass.simpleName)
}
}
}
}
fun consumeFile() {
_uiState.update { it.copy(file = null) }
}
fun clearError() {
_uiState.update { it.copy(error = null) }
}
}
@@ -23,6 +23,7 @@ import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Dns 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.material.icons.filled.Archive
import androidx.compose.material3.AlertDialog 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
@@ -44,10 +45,12 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.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
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.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
@@ -79,6 +82,7 @@ fun SettingsScreen(
connectionStatusViewModel: ConnectionStatusViewModel, connectionStatusViewModel: ConnectionStatusViewModel,
syncViewModel: SyncViewModel, syncViewModel: SyncViewModel,
viewModel: SettingsViewModel = hiltViewModel(), viewModel: SettingsViewModel = hiltViewModel(),
exportViewModel: ExportViewModel = hiltViewModel(),
) { ) {
val theme by viewModel.theme.collectAsStateWithLifecycle() val theme by viewModel.theme.collectAsStateWithLifecycle()
val serverUrl by viewModel.serverUrl.collectAsStateWithLifecycle() val serverUrl by viewModel.serverUrl.collectAsStateWithLifecycle()
@@ -95,6 +99,7 @@ fun SettingsScreen(
var showServerDialog by rememberSaveable { mutableStateOf(false) } var showServerDialog by rememberSaveable { mutableStateOf(false) }
var showAuthDialog by rememberSaveable { mutableStateOf(false) } var showAuthDialog by rememberSaveable { mutableStateOf(false) }
var showRetentionDialog by rememberSaveable { mutableStateOf(false) } var showRetentionDialog by rememberSaveable { mutableStateOf(false) }
var showExportDialog by rememberSaveable { mutableStateOf(false) }
// Stats de purge recalculées à l'ouverture du dialogue rétention. // Stats de purge recalculées à l'ouverture du dialogue rétention.
LaunchedEffect(showRetentionDialog) { LaunchedEffect(showRetentionDialog) {
@@ -201,6 +206,15 @@ fun SettingsScreen(
onClick = { showRetentionDialog = true }, onClick = { showRetentionDialog = true },
) )
// Export chiffré (V3 S7 C3) : connecté uniquement (données serveur).
if (authState is AuthState.SignedIn) {
HorizontalDivider()
ExportSettingsRow(
onExport = { showExportDialog = true },
exportViewModel = exportViewModel,
)
}
HorizontalDivider() HorizontalDivider()
val signedIn = authState as? AuthState.SignedIn val signedIn = authState as? AuthState.SignedIn
SettingsRow( SettingsRow(
@@ -257,6 +271,34 @@ fun SettingsScreen(
) )
} }
if (showExportDialog) {
val exportState by exportViewModel.uiState.collectAsStateWithLifecycle()
if (exportState.error != null) {
AlertDialog(
onDismissRequest = {
showExportDialog = false
exportViewModel.clearError()
},
title = { Text(stringResource(R.string.export_title)) },
text = { Text(exportState.error ?: "") },
confirmButton = {
TextButton(onClick = {
showExportDialog = false
exportViewModel.clearError()
}) { Text(stringResource(R.string.delete_cancel)) }
},
)
} else {
ExportPasswordDialog(
onDismiss = { showExportDialog = false },
onConfirm = { password ->
showExportDialog = false
exportViewModel.download(password)
},
)
}
}
if (showAuthDialog) { if (showAuthDialog) {
when (val state = authState) { when (val state = authState) {
is AuthState.SignedIn -> { is AuthState.SignedIn -> {
@@ -562,3 +604,117 @@ private fun SettingsRow(
trailing() trailing()
} }
} }
/**
* Ligne + dialogue d'export chiffré (V3 S7 C3) : mot de passe (8+, jamais
* persisté), téléchargement, puis partage via le sheet système (FileProvider).
*/
@Composable
private fun ExportSettingsRow(
onExport: () -> Unit,
exportViewModel: ExportViewModel,
) {
val exportState by exportViewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
// Fichier prêt → ouvre le sheet de partage une fois, puis consomme.
LaunchedEffect(exportState.file) {
val file = exportState.file ?: return@LaunchedEffect
val uri = androidx.core.content.FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
file,
)
val share = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
type = "application/zip"
putExtra(android.content.Intent.EXTRA_STREAM, uri)
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
runCatching {
context.startActivity(
android.content.Intent.createChooser(share, context.getString(R.string.export_share_title)),
)
}
exportViewModel.consumeFile()
}
LaunchedEffect(exportState.error) {
// L'erreur est affichée par le dialogue (champ dédié) — rien ici.
}
SettingsRow(
icon = { Icon(Icons.Filled.Archive, contentDescription = null) },
title = stringResource(R.string.export_title),
subtitle = stringResource(R.string.export_hint),
trailing = {
if (exportState.downloading) {
CircularProgressIndicator(modifier = Modifier.size(24.dp))
}
},
onClick = { if (!exportState.downloading) onExport() },
)
}
/** Dialogue mot de passe d'export (8+, champ sécurisé, erreur inline). */
@Composable
internal fun ExportPasswordDialog(
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
) {
var password by rememberSaveable { mutableStateOf("") }
var confirm by rememberSaveable { mutableStateOf("") }
val tooShort = password.isNotEmpty() && password.length < 8
val mismatch = confirm.isNotEmpty() && confirm != password
val canConfirm = password.length >= 8 && password == confirm
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.export_password_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(R.string.export_password_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text(stringResource(R.string.export_password)) },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
isError = tooShort,
)
OutlinedTextField(
value = confirm,
onValueChange = { confirm = it },
label = { Text(stringResource(R.string.export_password_confirm)) },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
isError = mismatch,
)
if (tooShort) {
Text(
text = stringResource(R.string.export_password_too_short),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
} else if (mismatch) {
Text(
text = stringResource(R.string.export_password_mismatch),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
}
},
confirmButton = {
TextButton(onClick = { onConfirm(password) }, enabled = canConfirm) {
Text(stringResource(R.string.export_download))
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.delete_cancel)) }
},
)
}
@@ -78,6 +78,8 @@
<string name="document_open_with">Open with</string> <string name="document_open_with">Open with</string>
<string name="document_open_with_hint">No built-in reader — open this file in an external app.</string> <string name="document_open_with_hint">No built-in reader — open this file in an external app.</string>
<string name="document_open_error">No app can open this file.</string> <string name="document_open_error">No app can open this file.</string>
<string name="document_share">Share</string>
<string name="document_share_title">Share document</string>
<string name="document_cloud_only">Cloud only</string> <string name="document_cloud_only">Cloud only</string>
<string name="document_cloud_only_hint">This file is not downloaded on this device. Sign in to your server to make it available.</string> <string name="document_cloud_only_hint">This file is not downloaded on this device. Sign in to your server to make it available.</string>
<string name="document_keep_done">Document kept and synced.</string> <string name="document_keep_done">Document kept and synced.</string>
@@ -476,4 +478,15 @@
<string name="family_name">Circle name</string> <string name="family_name">Circle name</string>
<string name="family_default_name">Family</string> <string name="family_default_name">Family</string>
<string name="family_create">Create</string> <string name="family_create">Create</string>
<!-- Encrypted export V3 S7 C3 -->
<string name="export_title">Export (encrypted zip)</string>
<string name="export_hint">Full backup: files + manifest, AES-256</string>
<string name="export_password_title">Export password</string>
<string name="export_password_hint">It protects the zip. Don\'t lose it: without it, the backup is unreadable.</string>
<string name="export_password">Password (8+ characters)</string>
<string name="export_password_confirm">Confirm</string>
<string name="export_password_too_short">8 characters minimum.</string>
<string name="export_password_mismatch">Passwords do not match.</string>
<string name="export_download">Download</string>
<string name="export_share_title">Share backup</string>
</resources> </resources>
@@ -78,6 +78,8 @@
<string name="document_open_with">Ouvrir avec</string> <string name="document_open_with">Ouvrir avec</string>
<string name="document_open_with_hint">Aucun lecteur intégré — ouvre ce fichier dans une application externe.</string> <string name="document_open_with_hint">Aucun lecteur intégré — ouvre ce fichier dans une application externe.</string>
<string name="document_open_error">Aucune application ne peut ouvrir ce fichier.</string> <string name="document_open_error">Aucune application ne peut ouvrir ce fichier.</string>
<string name="document_share">Partager</string>
<string name="document_share_title">Partager le document</string>
<string name="document_cloud_only">Disponible uniquement sur le cloud</string> <string name="document_cloud_only">Disponible uniquement sur le cloud</string>
<string name="document_cloud_only_hint">Ce fichier n\'est pas téléchargé sur cet appareil. Connecte-toi à ton serveur pour le rendre disponible.</string> <string name="document_cloud_only_hint">Ce fichier n\'est pas téléchargé sur cet appareil. Connecte-toi à ton serveur pour le rendre disponible.</string>
<string name="document_keep_done">Document gardé et synchronisé.</string> <string name="document_keep_done">Document gardé et synchronisé.</string>
@@ -477,4 +479,15 @@
<string name="family_name">Nom du cercle</string> <string name="family_name">Nom du cercle</string>
<string name="family_default_name">Famille</string> <string name="family_default_name">Famille</string>
<string name="family_create">Créer</string> <string name="family_create">Créer</string>
<!-- Export chiffré V3 S7 C3 -->
<string name="export_title">Exporter (zip chiffré)</string>
<string name="export_hint">Sauvegarde complète : fichiers + manifest, AES-256</string>
<string name="export_password_title">Mot de passe de l\'export</string>
<string name="export_password_hint">Il protège le zip. Ne le perdez pas : sans lui, la sauvegarde est illisible.</string>
<string name="export_password">Mot de passe (8+ caractères)</string>
<string name="export_password_confirm">Confirmer</string>
<string name="export_password_too_short">8 caractères minimum.</string>
<string name="export_password_mismatch">Les mots de passe diffèrent.</string>
<string name="export_download">Télécharger</string>
<string name="export_share_title">Partager la sauvegarde</string>
</resources> </resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- FileProvider V3 S7 : partage de l'export chiffré depuis le cache. -->
<paths>
<cache-path name="exports" path="exports/" />
</paths>
@@ -384,6 +384,14 @@ class Auth401Test {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -258,6 +258,14 @@ class PaginationTest {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -179,6 +179,10 @@ class RemoteContentTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = content() override suspend fun downloadContent(fileId: String): Response<ResponseBody> = content()
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> = content()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> = content()
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -386,6 +386,12 @@ class SessionReloginTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null)) Response.success(ByteArray(0).toResponseBody(null))
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> = override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
Response.success(ApiEnvelope(data = emptyList())) Response.success(ApiEnvelope(data = emptyList()))
@@ -223,6 +223,12 @@ class ShareManagementTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null)) Response.success(ByteArray(0).toResponseBody(null))
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> = override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
if (failShares) { if (failShares) {
Response.error(404, errBody("NOT_FOUND")) Response.error(404, errBody("NOT_FOUND"))
@@ -313,6 +313,12 @@ class BytesUploadTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null)) Response.success(ByteArray(0).toResponseBody(null))
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> = override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
Response.success(ApiEnvelope(data = emptyList())) Response.success(ApiEnvelope(data = emptyList()))
@@ -186,6 +186,8 @@ class FactsRepositoryTest {
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO() override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO()
override suspend fun getFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO() override suspend fun getFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun downloadContent(fileId: String): Response<okhttp3.ResponseBody> = TODO() override suspend fun downloadContent(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun downloadPreview(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<okhttp3.ResponseBody> = TODO()
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO() override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listTrash(page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.TrashDto>>> = TODO() override suspend fun listTrash(page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.TrashDto>>> = TODO()
override suspend fun restoreFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO() override suspend fun restoreFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
@@ -444,6 +444,14 @@ private class FolderMergeApiService : ApiService {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -147,6 +147,8 @@ class LinksRepositoryTest {
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO() override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO()
override suspend fun getFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO() override suspend fun getFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun downloadContent(fileId: String): Response<okhttp3.ResponseBody> = TODO() override suspend fun downloadContent(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun downloadPreview(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<okhttp3.ResponseBody> = TODO()
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO() override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listTrash(page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.TrashDto>>> = TODO() override suspend fun listTrash(page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.TrashDto>>> = TODO()
override suspend fun restoreFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO() override suspend fun restoreFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
@@ -533,6 +533,14 @@ private class MoveProtectionApiService : ApiService {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -451,6 +451,14 @@ private class OcrApiServiceFake : ApiService {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -327,6 +327,12 @@ class OfflineDownloadTest {
Mode.NETWORK -> throw com.kazier.mobile.data.remote.ApiException("NETWORK_ERROR", "down", 0) Mode.NETWORK -> throw com.kazier.mobile.data.remote.ApiException("NETWORK_ERROR", "down", 0)
} }
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> = override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
Response.success(ApiEnvelope(data = emptyList())) Response.success(ApiEnvelope(data = emptyList()))
@@ -300,6 +300,14 @@ private class RefreshVsMoveApiService : ApiService {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -554,6 +554,14 @@ private class FakeApiService : ApiService {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -171,6 +171,8 @@ class ReleaseLocalCopyTest {
override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO() override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun getShareLink(token: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO() override suspend fun getShareLink(token: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO()
override suspend fun downloadContent(fileId: String): retrofit2.Response<okhttp3.ResponseBody> = TODO() override suspend fun downloadContent(fileId: String): retrofit2.Response<okhttp3.ResponseBody> = TODO()
override suspend fun downloadPreview(fileId: String): retrofit2.Response<okhttp3.ResponseBody> = TODO()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): retrofit2.Response<okhttp3.ResponseBody> = TODO()
override suspend fun listShares(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareGrantDto>>> = TODO() override suspend fun listShares(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareGrantDto>>> = TODO()
override suspend fun listLinks(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareLinkDto>>> = TODO() override suspend fun listLinks(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareLinkDto>>> = TODO()
override suspend fun listPlacements(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.PlacementDto>>> = TODO() override suspend fun listPlacements(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.PlacementDto>>> = TODO()
@@ -579,6 +579,14 @@ class OutboxSyncWorkerTest {
fileId: String, fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0))) ): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares( override suspend fun listShares(
fileId: String, fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList())) ): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -0,0 +1,142 @@
package com.kazier.mobile.features.thumbnails
import android.content.Context
import android.graphics.Bitmap
import androidx.test.core.app.ApplicationProvider
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiService
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.test.runTest
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
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
import java.io.ByteArrayOutputStream
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
import java.util.concurrent.atomic.AtomicInteger
/**
* Previews distantes V3 (S7) : `GET /files/:id/preview` → cache WebP
* versionné, une seule requête par session (garde `tried`), 404 → icône.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class RemotePreviewFetcherTest {
private lateinit var context: Context
private lateinit var store: ThumbnailStore
private lateinit var calls: AtomicInteger
private lateinit var previewBytes: ByteArray
private var failWith404 = false
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
store = ThumbnailStore(context)
calls = AtomicInteger(0)
previewBytes = jpegBytes(640, 480)
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val handler = InvocationHandler { _, method, _ ->
when (method.name) {
"downloadPreview" -> {
calls.incrementAndGet()
if (failWith404) {
Response.error<okhttp3.ResponseBody>(
404,
"{\"error\":{\"code\":\"NO_PREVIEW\",\"message\":\"none\"}}"
.toResponseBody("application/json".toMediaType()),
)
} else {
Response.success(previewBytes.toResponseBody("image/jpeg".toMediaType()))
}
}
else -> throw UnsupportedOperationException(method.name)
} as Any
}
val apiService = Proxy.newProxyInstance(
javaClass.classLoader, arrayOf(ApiService::class.java), handler,
) as ApiService
val apiClient = ApiClient(apiService, moshi)
fetcher = RemotePreviewFetcher(apiClient, store)
}
private lateinit var fetcher: RemotePreviewFetcher
private fun cloudImage(id: String) = FileEntity(
resourceId = id, uri = null, name = "distant.jpg",
folderResourceId = "f", extension = "jpg", size = 1000,
mimeType = "image/jpeg", exists = 1, processed = true,
addedAt = 1L, updatedAt = 2L,
)
private fun jpegBytes(w: Int, h: Int): ByteArray {
val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
val out = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 80, out)
bmp.recycle()
return out.toByteArray()
}
@Test
fun fetch_met_en_cache_une_seule_requete() = runTest {
val first = fetcher.fetch(cloudImage("r1".padEnd(32, '1')))
assertNotNull(first)
assertTrue(first!!.isFile && first.length() > 0)
assertEquals(1, calls.get())
// Second appel : cache disque, zéro réseau (tried + fichier présent).
val second = fetcher.fetch(cloudImage("r1".padEnd(32, '1')))
assertEquals(1, calls.get())
assertNotNull(second)
assertEquals(1, fetcher.triedCount())
}
@Test
fun no_preview_ne_reessaie_pas() = runTest {
failWith404 = true
assertNull(fetcher.fetch(cloudImage("r2".padEnd(32, '2'))))
assertEquals(1, calls.get())
// Pas de retry en session (icône).
assertNull(fetcher.fetch(cloudImage("r2".padEnd(32, '2'))))
assertEquals(1, calls.get())
}
@Test
fun putRemote_decode_et_versionne() = runTest {
val cached = store.putRemote("r3".padEnd(32, '3'), 2L, 1000L, previewBytes)
assertNotNull(cached)
// Même version → même fichier (cache-hit).
val again = store.putRemote("r3".padEnd(32, '3'), 2L, 1000L, previewBytes)
assertEquals(cached!!.absolutePath, again!!.absolutePath)
// Source modifiée (updatedAt) → nouveau fichier versionné.
val newer = store.putRemote("r3".padEnd(32, '3'), 3L, 1000L, previewBytes)
assertNotNull(newer)
assertTrue(newer!!.absolutePath != cached.absolutePath)
}
@Test
fun putRemote_binaire_pourri_ne_plante_pas() = runTest {
// Note : sous Robolectric le décodeur est indulgent (jamais null) —
// sur device réel, `decodeByteArray` null → `putRemote` null. Ici on
// vérifie seulement l'absence de crash et le contrat de versionnement.
val id = "r4".padEnd(32, '4')
val cached = store.putRemote(id, 2L, 9L, byteArrayOf(1, 2, 3))
assertNotNull(cached)
// Fichier versionné par (updatedAt, taille), comme en production.
assertTrue(cached!!.name.contains("_2_9"))
}
}
@@ -0,0 +1,89 @@
package com.kazier.mobile.ui.settings
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiService
import com.kazier.mobile.data.remote.dto.ApiEnvelope
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
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
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
/**
* Export chiffré V3 (S7 C3) : téléchargement vers le cache, erreur remontée,
* mot de passe jamais persisté (champ seul du ViewModel).
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ExportViewModelTest {
private fun viewModel(zipBytes: ByteArray?, fail: Boolean = false): ExportViewModel {
val context = ApplicationProvider.getApplicationContext<Context>()
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val handler = InvocationHandler { _, method, _ ->
when (method.name) {
"exportZip" -> {
if (fail) throw com.kazier.mobile.data.remote.ApiException("NETWORK_ERROR", "down", 0)
Response.success(zipBytes!!.toResponseBody("application/zip".toMediaType()))
}
else -> throw UnsupportedOperationException(method.name)
} as Any
}
val apiService = Proxy.newProxyInstance(
javaClass.classLoader, arrayOf(ApiService::class.java), handler,
) as ApiService
return ExportViewModel(ApiClient(apiService, moshi), context)
}
@Test
fun download_ecrit_le_zip_en_cache() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
val vm = viewModel("PK-fake-zip".toByteArray())
vm.download("motdepasse-8")
testScheduler.advanceUntilIdle()
val file = vm.uiState.value.file
assertNotNull(file)
assertTrue(file!!.isFile && file.length() > 0)
assertTrue(file.name.startsWith("kazier-export-"))
vm.consumeFile()
assertNull(vm.uiState.value.file)
} finally {
Dispatchers.resetMain()
}
}
@Test
fun echec_reseau_remonte_en_erreur() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
val vm = viewModel(null, fail = true)
vm.download("motdepasse-8")
testScheduler.advanceUntilIdle()
// ApiClient normalise le transport (pas de fuite du message fake).
assertEquals("Serveur injoignable", vm.uiState.value.error)
assertNull(vm.uiState.value.file)
vm.clearError()
assertNull(vm.uiState.value.error)
} finally {
Dispatchers.resetMain()
}
}
}