Compare commits
6
Commits
c642adb85b
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
225f6e4b93 | ||
|
|
f97e0aed45 | ||
|
|
9dbd9d7a11 | ||
|
|
33ff9a6789 | ||
|
|
22286aa2b1 | ||
|
|
d89c0d03c9 |
@@ -0,0 +1,28 @@
|
|||||||
|
# Production — copier vers .env.prod (jamais commité) et adapter.
|
||||||
|
# Utilisé avec : docker compose -f docker-compose.prod.yml --env-file .env.prod [pull|up -d]
|
||||||
|
|
||||||
|
# Image (registre Gitea). VERSION=latest par défaut ; pincer pour figer, ex. :
|
||||||
|
# VERSION=v0.1.0 (le tag release inclut le "v", cf. release.yml)
|
||||||
|
REGISTRY_IMAGE=gitea.thirdshop.fr/thirdshop/kazier
|
||||||
|
VERSION=latest
|
||||||
|
|
||||||
|
# Port d'écoute exposé sur l'hôte (derrière Caddy/Nginx/TLS en prod publique)
|
||||||
|
PORT=8080
|
||||||
|
|
||||||
|
# Postgres (mots de passe forts, générés, uniques à la prod)
|
||||||
|
POSTGRES_DB=kazier
|
||||||
|
POSTGRES_USER=kazier
|
||||||
|
POSTGRES_PASSWORD=CHANGE_ME_GENERER_UN_SECRET_LONG
|
||||||
|
|
||||||
|
# Backend
|
||||||
|
MAX_FILE_SIZE_MB=50
|
||||||
|
OCR_LANG=fra+eng
|
||||||
|
|
||||||
|
# Sécurité — générer un secret long et aléatoire, ex. :
|
||||||
|
# openssl rand -base64 48
|
||||||
|
AUTH_SECRET=CHANGE_ME_GENERER_UN_SECRET_LONG
|
||||||
|
|
||||||
|
# Premier admin (créé UNIQUEMENT si la table users est vide au premier boot).
|
||||||
|
# L'env n'écrase jamais un compte existant.
|
||||||
|
ADMIN_USERNAME=admin
|
||||||
|
ADMIN_PASSWORD=CHANGE_ME_MOT_DE_PASSE_INITIAL_FORT
|
||||||
@@ -2,7 +2,8 @@
|
|||||||
#
|
#
|
||||||
# Construit l'APK signé (assembleRelease), crée la Release Gitea avec l'APK en
|
# Construit l'APK signé (assembleRelease), crée la Release Gitea avec l'APK en
|
||||||
# asset (API, équivalent de `glab release create`), puis pousse l'image
|
# asset (API, équivalent de `glab release create`), puis pousse l'image
|
||||||
# kazier-server sur le registre conteneur Gitea + Docker Hub (tag + latest).
|
# kazier-server sur le registre conteneur Gitea (tag + latest).
|
||||||
|
# Déploiement perso uniquement : pas de push Docker Hub.
|
||||||
#
|
#
|
||||||
# Prérequis act_runner : job `release-docker` s'exécute directement sur
|
# Prérequis act_runner : job `release-docker` s'exécute directement sur
|
||||||
# l'hôte et utilise le daemon Docker local (pas de conteneur `docker:27`,
|
# l'hôte et utilise le daemon Docker local (pas de conteneur `docker:27`,
|
||||||
@@ -17,7 +18,6 @@
|
|||||||
# - RELEASE_API_TOKEN PAT scope write:repository (API : création Release)
|
# - RELEASE_API_TOKEN PAT scope write:repository (API : création Release)
|
||||||
# - CONTAINER_REGISTRY_TOKEN PAT scope write:package (registre conteneur Gitea)
|
# - CONTAINER_REGISTRY_TOKEN PAT scope write:package (registre conteneur Gitea)
|
||||||
# - CONTAINER_REGISTRY_USER utilisateur propriétaire du PAT ci-dessus
|
# - CONTAINER_REGISTRY_USER utilisateur propriétaire du PAT ci-dessus
|
||||||
# - DOCKERHUB_USER DOCKERHUB_TOKEN PAT Docker Hub (push public)
|
|
||||||
|
|
||||||
name: Release
|
name: Release
|
||||||
|
|
||||||
@@ -30,7 +30,6 @@ permissions:
|
|||||||
|
|
||||||
env:
|
env:
|
||||||
ANDROID_IMAGE: cimg/android:2024.01-node
|
ANDROID_IMAGE: cimg/android:2024.01-node
|
||||||
DOCKERHUB_IMAGE: docker.io/thirdshop/kazier
|
|
||||||
# API Gitea (host de l'instance)
|
# API Gitea (host de l'instance)
|
||||||
API_HOST: gitea.thirdshop.fr
|
API_HOST: gitea.thirdshop.fr
|
||||||
|
|
||||||
@@ -53,6 +52,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Signer + assembler l'APK release
|
- name: Signer + assembler l'APK release
|
||||||
working-directory: mobile-kotlin
|
working-directory: mobile-kotlin
|
||||||
|
shell: bash
|
||||||
env:
|
env:
|
||||||
RELEASE_KEYSTORE_B64: ${{ secrets.RELEASE_KEYSTORE_B64 }}
|
RELEASE_KEYSTORE_B64: ${{ secrets.RELEASE_KEYSTORE_B64 }}
|
||||||
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
|
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
|
||||||
@@ -80,25 +80,41 @@ jobs:
|
|||||||
./gradlew :app:assembleRelease -q
|
./gradlew :app:assembleRelease -q
|
||||||
|
|
||||||
- name: Créer la Release Gitea + upload APK
|
- name: Créer la Release Gitea + upload APK
|
||||||
|
shell: bash
|
||||||
env:
|
env:
|
||||||
RELEASE_API_TOKEN: ${{ secrets.RELEASE_API_TOKEN }}
|
RELEASE_API_TOKEN: ${{ secrets.RELEASE_API_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
VERSION="$(cat VERSION)"
|
VERSION="$(cat VERSION)"
|
||||||
|
TAG="v${VERSION}"
|
||||||
API="https://${API_HOST}/api/v1"
|
API="https://${API_HOST}/api/v1"
|
||||||
AUTH="Authorization: token ${RELEASE_API_TOKEN:?RELEASE_API_TOKEN manquant (PAT scope write:repository)}"
|
AUTH="Authorization: token ${RELEASE_API_TOKEN:?RELEASE_API_TOKEN manquant (PAT scope write:repository)}"
|
||||||
NOTES_JSON="$(python3 -c 'import json;print(json.dumps(open("CHANGELOG.md", encoding="utf-8").read()))')"
|
NOTES_JSON="$(python3 -c 'import json;print(json.dumps(open("CHANGELOG.md", encoding="utf-8").read()))')"
|
||||||
PAYLOAD_JSON="$(TAG="v${VERSION}" BODY="$NOTES_JSON" python3 -c 'import json,os;print(json.dumps({"tag_name":os.environ["TAG"],"name":"Kazier "+os.environ["TAG"],"body":json.loads(os.environ["BODY"])}))')"
|
# Idempotent : si la release du tag existe déjà (re-tag, retry du job),
|
||||||
RELEASE_JSON="$(curl -sSf -X POST "${API}/repos/${GITHUB_REPOSITORY}/releases" \
|
# la réutiliser au lieu d'échouer en 409.
|
||||||
-H "${AUTH}" \
|
if RELEASE_JSON="$(curl -sSf -H "${AUTH}" "${API}/repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" 2>/dev/null)"; then
|
||||||
-H "Content-Type: application/json" \
|
echo "Release ${TAG} existante — réutilisation."
|
||||||
-d "${PAYLOAD_JSON}")"
|
else
|
||||||
|
PAYLOAD_JSON="$(TAG="${TAG}" BODY="$NOTES_JSON" python3 -c 'import json,os;print(json.dumps({"tag_name":os.environ["TAG"],"name":"Kazier "+os.environ["TAG"],"body":json.loads(os.environ["BODY"])}))')"
|
||||||
|
RELEASE_JSON="$(curl -sSf -X POST "${API}/repos/${GITHUB_REPOSITORY}/releases" \
|
||||||
|
-H "${AUTH}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "${PAYLOAD_JSON}")"
|
||||||
|
fi
|
||||||
RELEASE_ID="$(printf '%s' "${RELEASE_JSON}" | python3 -c 'import json,sys;print(json.load(sys.stdin)["id"])')"
|
RELEASE_ID="$(printf '%s' "${RELEASE_JSON}" | python3 -c 'import json,sys;print(json.load(sys.stdin)["id"])')"
|
||||||
: "${RELEASE_ID:?id de release introuvable dans la réponse API}"
|
: "${RELEASE_ID:?id de release introuvable dans la réponse API}"
|
||||||
|
# Asset idempotent : remplace l'APK existant de même nom s'il y en a un.
|
||||||
|
APK_PATH="mobile-kotlin/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
EXISTING_ASSET_ID="$(curl -sSf -H "${AUTH}" "${API}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets" \
|
||||||
|
| python3 -c 'import json,sys;assets=json.load(sys.stdin);print(next((str(a["id"]) for a in assets if a.get("name")=="app-release.apk"),""))')"
|
||||||
|
if [ -n "${EXISTING_ASSET_ID}" ]; then
|
||||||
|
echo "Asset existant ${EXISTING_ASSET_ID} — suppression avant re-upload."
|
||||||
|
curl -sSf -X DELETE -H "${AUTH}" "${API}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets/${EXISTING_ASSET_ID}" > /dev/null
|
||||||
|
fi
|
||||||
curl -sSf -X POST \
|
curl -sSf -X POST \
|
||||||
"${API}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=app-release.apk" \
|
"${API}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=app-release.apk" \
|
||||||
-H "${AUTH}" \
|
-H "${AUTH}" \
|
||||||
-F "attachment=@mobile-kotlin/app/build/outputs/apk/release/app-release.apk"
|
-F "attachment=@${APK_PATH}"
|
||||||
|
|
||||||
release-docker:
|
release-docker:
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
@@ -111,12 +127,14 @@ jobs:
|
|||||||
token: ${{ secrets.GITEA_TOKEN }}
|
token: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
|
||||||
- name: Sanity daemon Docker hôte
|
- name: Sanity daemon Docker hôte
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
docker info >/dev/null
|
docker info >/dev/null
|
||||||
echo "daemon Docker hôte joignable"
|
echo "daemon Docker hôte joignable"
|
||||||
|
|
||||||
- name: Login registre Gitea
|
- name: Login registre Gitea
|
||||||
|
shell: bash
|
||||||
env:
|
env:
|
||||||
CONTAINER_REGISTRY_TOKEN: ${{ secrets.CONTAINER_REGISTRY_TOKEN }}
|
CONTAINER_REGISTRY_TOKEN: ${{ secrets.CONTAINER_REGISTRY_TOKEN }}
|
||||||
CONTAINER_REGISTRY_USER: ${{ secrets.CONTAINER_REGISTRY_USER }}
|
CONTAINER_REGISTRY_USER: ${{ secrets.CONTAINER_REGISTRY_USER }}
|
||||||
@@ -129,6 +147,7 @@ jobs:
|
|||||||
echo "REGISTRY_IMAGE=${API_HOST}/${OWNER_LC}/kazier" >> "$GITHUB_ENV"
|
echo "REGISTRY_IMAGE=${API_HOST}/${OWNER_LC}/kazier" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
- name: "Build + push (registre Gitea : vX.Y.Z + latest)"
|
- name: "Build + push (registre Gitea : vX.Y.Z + latest)"
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
VERSION="$(cat VERSION)"
|
VERSION="$(cat VERSION)"
|
||||||
@@ -143,20 +162,4 @@ jobs:
|
|||||||
./backend
|
./backend
|
||||||
docker run --rm "$REGISTRY_IMAGE:v${VERSION}" --version
|
docker run --rm "$REGISTRY_IMAGE:v${VERSION}" --version
|
||||||
docker push "$REGISTRY_IMAGE:v${VERSION}"
|
docker push "$REGISTRY_IMAGE:v${VERSION}"
|
||||||
docker push "$REGISTRY_IMAGE:latest"
|
docker push "$REGISTRY_IMAGE:latest"
|
||||||
echo "TAG=v${VERSION}" >> "$GITHUB_ENV"
|
|
||||||
|
|
||||||
- name: Push Docker Hub (tag + latest)
|
|
||||||
env:
|
|
||||||
DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }}
|
|
||||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
: "${DOCKERHUB_USER:?DOCKERHUB_USER manquant}"
|
|
||||||
: "${DOCKERHUB_TOKEN:?DOCKERHUB_TOKEN manquant}"
|
|
||||||
IMAGE="$DOCKERHUB_IMAGE"
|
|
||||||
echo "$DOCKERHUB_TOKEN" | docker login -u "$DOCKERHUB_USER" --password-stdin docker.io
|
|
||||||
docker tag "$REGISTRY_IMAGE:$TAG" "$IMAGE:$TAG"
|
|
||||||
docker tag "$REGISTRY_IMAGE:$TAG" "$IMAGE:latest"
|
|
||||||
docker push "$IMAGE:$TAG"
|
|
||||||
docker push "$IMAGE:latest"
|
|
||||||
+174
-289
@@ -1,317 +1,202 @@
|
|||||||
# FEEDBACK — Audit backend Kazier
|
# FEEDBACK — Audit bugs mobile-kotlin (local-first)
|
||||||
|
|
||||||
Date : 2026-09-21
|
> Généré le 2026-09-22 par 5 agents d'exploration parallèles (scopes : Room/DB, sync/outbox/SAF, réseau/auth/repos, UI/navigation/VM, scan/pdf/review/thumbnails).
|
||||||
Scope : `backend/` (Go, Gin, Postgres, Paseto, Tesseract)
|
> Chaque finding est vérifié avec preuve `file:line`. Méthode : lecture intégrale des fichiers + croisement `docs/api-v1.md`, `AGENTS.md`, handlers Go.
|
||||||
Mode : lecture seule, vérifié dans le code.
|
> Scope : `mobile-kotlin/` uniquement. Pas de fix appliqué — diagnostic seul.
|
||||||
But : autre agent relit et complète ci-dessous (voir § À compléter).
|
> Légende : 🔴 Critique (data loss / crash / sync bloquée) · 🟠 Majeur (divergence silencieuse, contrat violé) · 🟡 Mineur (UX, perf, dette).
|
||||||
|
|
||||||
## Haute priorité
|
Base paths : `mobile-kotlin/app/src/main/java/com/kazier/mobile/…`
|
||||||
|
|
||||||
1. **Route `GET /files/folders` masquée** — `backend/handlers/router.go:29-32`
|
---
|
||||||
`GET /files/:id` déclaré avant `GET /files/folders`. Gin peut capter `folders` comme `id="folders"` → 404 au lieu de la liste.
|
|
||||||
|
|
||||||
2. **`move_resource` sans check de cycle** — `backend/service/sync.go:204-219`
|
## 🔴 Critiques (à corriger en priorité)
|
||||||
Seul `toFolder == resourceID` rejeté. Déplacer un parent dans son enfant crée un cycle, casse les CTE récursives (`depth<100`).
|
|
||||||
|
|
||||||
3. **`create_link` non-idempotent** — `backend/service/sync.go:337` → `backend/repository/shares.go` (`CreateLink` INSERT simple sur PK `token`)
|
### C1 — `domain/GenerateId.kt:19` — IDs 32-hex non conformes (sign-extension `Byte` → `%02x`)
|
||||||
Rejeu même `operation_id` (crash entre apply et `Record`) → violation PK classée `INVALID_REQUEST` terminale, bloque tout l'outbox. Prévoir `ON CONFLICT DO NOTHING` comme `Operations.Record`.
|
`bytes.joinToString("") { "%02x".format(it) }` promeut chaque `Byte` signé en `int` : tout octet négatif produit `ffffffxx` (8 chars). Longueur 32→128, P(32 exact) ≈ 1/65536.
|
||||||
|
Impact : `resource_id` / `operation_id` / `device_user_id` violent `^[0-9a-f]{32}$` (CHECK serveur) → `POST /sync/ops` rejetés, outbox bloquée, identités invalides.
|
||||||
|
Repro : boucler `newResourceId()` et tester `length == 32 && matches([0-9a-f]{32})` → échec quasi systématique.
|
||||||
|
|
||||||
4. **`AUTH_SECRET` défaut faible** — `backend/config/config.go:49` + `backend/pkg/auth/auth.go`
|
### C2 — `features/sync/OutboxSyncWorker.kt:101-106` — dead-letter abusive sur erreurs non-attribuables
|
||||||
Défaut `dev-secret-change-me`, juste `SHA256`, pas de check longueur/entropie → tokens paseto v4-local forgeables sur déploiements par défaut.
|
Le `else` dead-letter `pending.first()` pour toute `ApiException` non-`NETWORK_ERROR`/5xx/401. `INVALID_RESPONSE` (200 sans enveloppe `{data}`) et `HTTP_429`/`408` (transitoires) tombent dedans. La faute est imputée à la 1re op du batch quelle que soit l'op rejetée.
|
||||||
|
Impact : op saine → `failed` à vie sur erreur batch-level ou transitoire ; inclut le cas `429 RATE_LIMITED` (login/devices/sync) qui devrait suivre le chemin `retry()`.
|
||||||
|
Repro : serveur 200 sans `data` ou 429 → 1re op dead-lettrée.
|
||||||
|
|
||||||
5. **Upload : extension non sanitisée** — `backend/service/resources.go:148-154`
|
### C3 — `features/sync/OutboxSyncWorker.kt:83` + `data/local/dao/PendingOperationDao.kt:42-43` — purge >7j qui casse le gate `processed`/`hasCreateOperation`
|
||||||
`filepath.Ext(file.Filename)` client tel quel → `destPath = <user>/<id>.<ext>`. Cas `""` → fichier `id.`, cas `../../`, `/`, très long → traversal / orphelins / ambiguïté `Glob(id.*)` pour OCR.
|
`purgeSynced` efface les lignes `synced`, or `countCreateOperations` (`IN ('pending','synced')`) fonde les gates delete/create dessus.
|
||||||
|
Impact : (a) fichier poussé puis purgé → `SafFileDeleter`/`FileDeleter`/`treeMarkMissing` omettent le `delete_resource` → fantôme serveur indélébile ; (b) `markProcessed` ré-enqueue un `create_resource` dupliqué.
|
||||||
|
Repro : pousser un fichier, attendre 7j, le supprimer → aucun `delete_resource`, serveur garde la ressource.
|
||||||
|
|
||||||
6. **Orphelins + stale bytes au re-upload** — `backend/service/resources.go:161-162` + `backend/service/ocr.go`
|
### C4 — `features/saf/FolderDeleter.kt:106-124` + `features/saf/FileDeleter.kt:109-119` — suppression physique avant transaction, delete perdu sur crash
|
||||||
`UpdatePhysical` ne supprime pas l'ancien `<id>.<oldExt>`. `Glob` prend le premier match → OCR sur bytes périmés + fuite disque. Échec `GetFile` après `InsertFile` réussi laisse aussi le fichier.
|
`deleteTreePhysically` (SAF, irréversible) avant `withTransaction { treeMarkMissing }`.
|
||||||
|
Impact : kill/crash entre les deux → octets supprimés, aucun `delete_resource` journalisé, walk suivant marque `exists=0` sans outbox (aucun chemin walk→enqueue) → fantôme serveur + divergence définitive.
|
||||||
|
Repro : `deleteFull` puis kill avant commit Room → serveur jamais notifié.
|
||||||
|
|
||||||
7. **`ApplyBatch` non-atomique** — `backend/service/sync.go:103-125`
|
### C5 — `ui/auth/AuthViewModel.kt:112-121` — pas de vidage outbox au sign-out, replay cross-account
|
||||||
`Applied() → apply → Record()` sans transaction. TOCTOU sur batches concurrents même `(device_id,operation_id)`, replay après crash, `Record` en 500 avec `applied` inconnu.
|
`signOut`/`signOutToLocal` purgent session et mode local mais aucune suppression de `pending_operations`. Les ops du compte A survivent au login du compte B (même `device_id`, `UNIQUE(device_id, operation_id)` sans historique partagé).
|
||||||
|
Impact : ops de A appliquées dans le scope de B (`NOT_FOUND`/`NAME_CONFLICT`, voire créations croisées).
|
||||||
|
Repro : enqueue offline sous A → sign-out → login B → drain pousse les ops de A sous token B.
|
||||||
|
|
||||||
8. **Fuite d'erreurs internes** — `backend/handlers/store.go:20-33` + `backend/service/sync.go:87-98`
|
### C6 — `features/sync/OutboxSyncWorker.kt:118-133` — drain poursuivi après échec + cascade limitée au même `resource_id`
|
||||||
Défaut `500 err.Error()` / `INVALID_REQUEST err.Error()` expose SQL/FS/paths au client.
|
Après `markFailed`, `continue` envoie le batch suivant, et `failDescendants` (`PendingOperationDao.kt:38`) ne cible que `resource_id = :resourceId` alors que les enfants portent un autre `resource_id` (lien dans le payload).
|
||||||
|
Impact : viole « serveur stop à la 1re erreur, client reprend à cet index » — creates enfants poussés et rejetés `NOT_FOUND` un par un, head-of-line blocking + dead-letters en cascade.
|
||||||
|
Repro : `create` dossier-parent en échec → le run pousse quand même les creates enfants au tour suivant.
|
||||||
|
|
||||||
9. **`Count()` bloque le bootstrap** — `backend/repository/users.go` + `backend/service/bootstrap.go`
|
### C7 — `features/sync/OutboxSyncWorker.kt:112-131` — gardes absents sur réponse serveur (boucle infinie / crash)
|
||||||
Compte les soft-deleted. Tous users supprimés → plus jamais de nouvel admin, lock définitif. Devrait filtrer `WHERE deleted_at IS NULL`.
|
(a) `result.failed.operationId` absent du batch (`indexOfFirst < 0`) → silence + re-sélection du même batch → boucle serrée sans backoff ; (b) `result.applied > pending.size` → `pending[i]` lève `IndexOutOfBoundsException` → crash worker.
|
||||||
|
Impact : (a) drain CPU/batterie ; (b) batch jamais acquitté. Complété par `data/remote` : `while(true)` sans garde `applied==0 && failed==null` → busy-loop si serveur renvoie `{applied:0, failed:null}`.
|
||||||
|
Repro : mocker `syncOps → applied=0, failed=null` ou `operation_id` inconnu → boucle infinie ; `applied` incohérent → crash.
|
||||||
|
|
||||||
10. **Migrations destructives / irréversibles**
|
### C8 — Scan : perte de données à l'export
|
||||||
- `backend/db/migrations/000007_resources_user_ownership.up.sql:7` fait `DELETE FROM resources` à l'upgrade (wipe prod).
|
- `ui/scan/ScanViewModel.kt:387-389` (`exportPdf`) — pages en échec seulement loggées (`failedIds`), puis **toutes** marquées `EXPORTED` + session `DONE` → PDF incomplet, sources abandonnées.
|
||||||
- `backend/db/migrations/000008_operation_uuid.down.sql` fait `operation_id::bigint` → casse dès que des IDs 32-hex avec `a-f` existent.
|
- `ui/scan/ScanViewModel.kt:259-298` (`export`) — retry non idempotent : `getPages` retourne aussi les `EXPORTED`, chaque retry crée un nouvel URI SAF → documents + lignes Room + ops outbox dupliqués.
|
||||||
|
- `ui/scan/ScanViewModel.kt:263` — fichier temp manquant → page sautée sans marquage mais `finishSession` ferme la session → page `PENDING` dans session `DONE`, jamais reprise ni nettoyée.
|
||||||
|
- `ui/scan/ScanViewModel.kt:186-201` — nom page `page_$order.jpg` avec `order = pageCount+1` → collision après suppression (A,B → del A → C écrase B) → deux entités même `tempUri`, `deletePage` orpheline B.
|
||||||
|
Repro : cf. chaque item (export partiel, retry après perte permission SAF, temp supprimé, capture-suppression-capture).
|
||||||
|
|
||||||
11. **Stubs dangereux** — `backend/service/services.go`, `move.go`, `upload.go`, `folders.go`
|
### C9 — `features/scan/ScanImageProcessor.kt:87-88` + `ui/scan/ScanViewModel.kt:192` — `recycle()` du bitmap encore affiché quand OpenCV indisponible
|
||||||
`UserCan*` toujours `true`, no-ops. Si jamais câblés = bypass auth total. À supprimer.
|
`process()` retourne l'instance d'entrée si `!isAvailable()` ; l'appelant `recycle()` le `processed` qui alias le draft dessiné par `CropStage` → crash `recycled bitmap`.
|
||||||
|
Repro : device sans lib OpenCV → valider un crop → crash au retour caméra.
|
||||||
|
|
||||||
12. **Oracle `INVALID_DEVICE_ID` au login** — `backend/handlers/auth.go:55-81`
|
---
|
||||||
Check device après `VerifyTimedEqual`. Creds valides + device inconnu → 400 vs 401 → oracle + pas de rate-limit.
|
|
||||||
|
|
||||||
## Priorité moyenne (phase 2)
|
## 🟠 Majeurs
|
||||||
|
|
||||||
- `DeviceID` login non validé `^[0-9a-f]{32}$` (`backend/handlers/auth.go:50` vs `devices.go:23`), `folderId/fileId/token` jamais validés hex avant DB.
|
### Sync / Outbox / SAF
|
||||||
- `POST /sync/ops` non borné (`backend/handlers/sync.go`) : pas de `MaxBytesReader`, pas de cap batch (client=20) → DoS OOM.
|
- **M1 — `features/sync/DeviceSync.kt:85-91` + `data/repository/FolderRepository.kt:99-134`** : le walk écrase le parent des dossiers sans garde pending-move (`saveFolder` écrase toujours, `reparentSubFolders` métadonnée-seule sans déplacement SAF). Les fichiers ont `hasPendingMoveOperation` (`FileRepository.kt:190`), les dossiers rien → tout reparent/merge revert au tick 30s suivant, divergence disque/serveur permanente.
|
||||||
- `ParentResourceID/ToFolder` non validés hex → mal classés `NOT_FOUND`.
|
- **M2 — `data/repository/FileRepository.kt:238-250`** : `applyMove` enqueue `move_resource` sans gate `create` (contrairement aux deletes) → move d'un fichier jamais poussé = `NOT_FOUND`/no-op serveur + ligne figée par `hasPendingMoveOperation`. Même cause `reparentSubFolders` (`FolderRepository.kt:144-157`) pour dossier au `create` purgé (>7j).
|
||||||
- `UpdateNameByID`, `TouchResource` non scopés owner (reposent que sur l'appelant) — TOCTOU.
|
- **M3 — `features/saf/FileMover.kt:47-53`** : repli métadonnée-seule incohérent (nouveau parent + ancienne uri quand `moveDocument` refusé) → Room ment durablement, walk bloqué par le garde pending-move, divergence serveur/disque.
|
||||||
- `Revoke/RevokeLink` : erreurs swallow `_ =` → masque vraies pannes (`backend/service/sync.go:306-309,359-361`).
|
- **M4 — `features/sync/DeviceSync.kt:122-134`** : réconciliation `exists=0` asymétrique — fichiers exclus via `hasMoveOperation` (pending **ou** synced → à vie après un move syncé, fichier supprimé ensuite = fantôme `exists=1` éternel) ; dossiers sans exclusion (move en transition marqué `missing` à tort).
|
||||||
- OCR : `Create` owner-only mais `GetFileOcr` viewer+, `Get` job scopé `device_id` → 2e device du même user = 404. PDF ignore `ctx`, pas de cap taille/pages, stderr (avec paths) exposé (`backend/ocr/tesseract.go:47-66`).
|
- **M5 — `features/saf/FileDeleter.kt:88-100` + `features/saf/FolderDeleter.kt:91-103`** : `deleteInCloud` sans tombstone locale (`exists` reste 1) → ressource toujours affichée, walk la revoit, `refreshFromServer` ne supprime jamais de lignes → fantôme local vs serveur supprimé.
|
||||||
- `passwd.Verify` parse `m=` du hash stocké sans cap → ligne DB compromise = OOM Argon2 au login (`backend/pkg/passwd/passwd.go:74-88`).
|
- **M6 — `features/sync/DeviceSync.kt:84`** : `?: root.resourceId` masque toute violation parent-avant-enfant (parent absent de `resourceIdByUri` → enfant rattaché racine) → arbre serveur corrompu silencieusement.
|
||||||
- `POST /devices` public sans rate-limit → remplissage table. `MarkUser` permet à n'importe qui de claim n'importe quel `device_id` (`backend/repository/devices.go:36-42`).
|
- **M7 — `features/sync/SyncViewModel.kt:135-156`** : `importRoot` ne schedule jamais le drain (contraire `syncAll:110`, login `AuthViewModel:54,77`) → `create_resource` racine dort jusqu'au prochain tick, badge faussement à jour.
|
||||||
- `getInt` sans range check (PORT/WORKERS/MAX négatifs acceptés) (`backend/config/config.go:64-70`).
|
- **M8 — `features/sync/SafScanner.kt:146`** : `if (size == 0L) continue` → fichiers vides légitimes exclus du miroir, jamais reviewés ni poussés (perte silencieuse).
|
||||||
- `ChangePassword` ne révoque pas les tokens (fenêtre 7j) (`backend/handlers/auth.go:113-151`).
|
- **M9 — `features/saf/FolderMerger.kt:45-85`** : merge multi-transactions non-atomique, non-idempotent (`createMergedFolder` recrée un dossier à chaque appel) → crash à mi-fusion = état partiel poussé, relance = dossier dupliqué côté serveur.
|
||||||
- `expiresAt` passé accepté pour shares/links → grants instantanément expirés.
|
|
||||||
- `Snapshot/ListOwned` `LIMIT 10000` sans pagination → troncation silencieuse (`backend/repository/shares.go:199`, `resources.go:547`).
|
|
||||||
- Positif : pas d'injection SQL trouvée (tout en `$n`, `sortClause` whitelist).
|
|
||||||
|
|
||||||
## Plan proposé
|
### Room / DB / Domain
|
||||||
|
- **M10 — `domain/DeviceIdentity.kt:18-26`** : `getOrCreate()` non atomique (read/insert/re-read hors transaction) + fallback `newResourceId()` jamais persisté → deux identités concurrentes, `owner_id` incohérents, outbox sous identité fantôme (aggravé par C1).
|
||||||
|
- **M11 — `data/local/migration/Migrations.kt:90-96`** : `MIGRATION_5_6` fait `UPDATE files SET processed = 1` sans `create_resource` rétroactif → backlog jamais poussé, invisible de la review (`getUnprocessed`) et du serveur, à vie.
|
||||||
|
- **M12 — `data/local/dao/FolderDao.kt:50-54` + `data/local/dao/FileDao.kt:48-49`** : `@Upsert` résout sur PK (`id`) pas sur uniques `resource_id`/`uri` ; pattern read-then-upsert (`id=0`) → deux inserts concurrents même `uri` = `SQLiteConstraintException` (crash walk SAF / refresh serveur).
|
||||||
|
- **M13 — entités `exists: Int? = null` + filtres `= 1`** (`FolderEntity.kt:36`, `FileEntity.kt:45`, `FolderDao.kt:34,41`, `FileDao.kt:15,18,21,32,42,95,98,108,135`, `Migrations.kt:51-72` sans DEFAULT) : toute ligne sans `exists` explicite disparaît UI/recherche/review — perte fonctionnelle silencieuse.
|
||||||
|
- **M14 — `data/local/entity/PendingOperationEntity.kt:28-53` + `Migrations.kt:101-123`** : pas de colonne `device_id`, unicité locale sur `operation_id` seul vs contrat `UNIQUE(device_id, operation_id)` → après régénération `device_user_id`, rejeu = `create_resource` dupliqués serveur.
|
||||||
|
- **M15 — `data/local/dao/PendingOperationDao.kt:38`** : `failDescendants` ne cascade que sur le même `resource_id`, pas les enfants (cf. C6).
|
||||||
|
- **M16 — `data/local/dao/FileDao.kt:133-145` + `Migrations.kt:75-82`** : `category` ajoutée sans backfill, `getOcrAutoCandidates()` exige `category IN (…)` → tout PDF/image/texte pré-v4 exclu de l'OCR auto à vie.
|
||||||
|
- **M17 — `data/local/dao/FileDao.kt:151-152`** : `clearOcrQueued` reset `ocr_attempts = 0` inconditionnellement (contredit commentaire `:130-132`) → échec permanent rejoué indéfiniment.
|
||||||
|
- **M18 — pas de FK `files → folders`** (`FileEntity.kt:18-26`, `FolderEntity.kt:18-25`, `FolderDao.kt:95-96`, `FileDao.kt:92-93` deletes physiques) → `remove(dossier)` laisse orphelins, `moveToFolder` vers parent inexistant accepté, cycles possibles.
|
||||||
|
- **M19 — `FolderDao.kt:56-57` + `FileDao.kt:51-52`** : `markMissing` = `SET exists = 0` seul (ni `sync_status` ni annulation `create` pending) → ressource disparue quand même poussée (fantôme serveur), placement `local-cloud` mensonger.
|
||||||
|
- **M20 — `data/local/dao/ScanDao.kt:12-64` + `entity/ScanSessionEntity.kt:15-20`** : sessions `active` multiples possibles (aucun index unique/partiel), aucun `deleteSession` → doubles inserts concurrents = session orpheline + pages fuyantes.
|
||||||
|
|
||||||
1. **P0 robustesse** : ordre routes, cycle move, idempotence `CreateLink`, transaction `ApplyBatch`, secret requis en prod, sanit `extension` + cleanup orphelins.
|
### Réseau / Auth / Repos
|
||||||
2. **P1 data** : fix `Count()` soft-deleted, corriger migrations 000007/000008, supprimer stubs, mapper erreurs sans fuite.
|
- **M21 — `data/repository/FileRepository.kt:261-272` + `data/remote/ApiClient.kt:64-65`** : pagination jetée (`pageSize=50` sans `page`, `meta` ignoré) alors que le serveur pagine → dossiers > 50 fichiers ne convergent jamais, silencieusement.
|
||||||
3. **P2 durcissement** : validation hex systématique, cap `sync/ops`, rate-limit login/devices, cap Argon2 + PDF/OCR, scope `Touch/UpdateName`, pagination snapshot.
|
- **M22 — `data/remote/ApiClient.kt:119-125`** : `catch (Exception) → NETWORK_ERROR` attrape aussi `JsonDataException` (Moshi) et `InterruptedIOException` (annulation) → parsing cassé = `retry()` infini, coroutine annulée = `ApiException` au lieu de `CancellationException` (scope/WorkManager corrompus).
|
||||||
|
- **M23 — `data/repository/ShareRepository.kt:45,99-104` + `FolderRepository.kt:115`** : confusion `device_id` vs `user_id` — `syncSnapshot` compare `deviceIdentity.getOrCreate()` (device) à `perm.ownerId` (user serveur), `saveFolder` stocke le device dans `ownerId`, `ActiveUserStore` ignoré. Le snapshot serveur **exclut les ressources possédées** → toute ligne cloud-only au vrai `ownerId=user` est `markMissing` à chaque login/restore (ex. note `createNote(ownerId=userId)` disparaît).
|
||||||
|
- **M24 — `features/sync/OutboxSyncWorker.kt:159-170` + `data/repository/OutboxRepository.kt:29-31`** : round-trip `expiresAt` Long→Double (Moshi `Map<String,Any?>`) → `enqueueShare(expiresAt: Long)` réémis `1.7E12` → serveur `*int64` refuse → `400 INVALID_REQUEST` → **tout partage avec expiration dead-lettered**.
|
||||||
|
- **M25 — `ui/auth/AuthViewModel.kt:43,123-125`** : callback 401 singleton possédé par un ViewModel (`apiClient.onUnauthorized`, `ApiClient` `@Singleton` survit au VM, annulé dans `onCleared`) → après destruction, 401 ne purge plus la session → token expiré réutilisé, worker `success()` sur 401 fige l'outbox, utilisateur jamais déconnecté.
|
||||||
|
- **M26 — `domain/ServerConfigStore.kt:32-43` + `data/remote/ServerUrlInterceptor.kt:25-38`** : race `load()` — interceptor lit `current` (défaut `10.0.2.2`) sur thread OkHttp pendant que `load()` restaure l'URL ; `registerDevice()` part avant `load()` → cold start avec URL custom = premières requêtes (y compris `Authorization: Bearer` restauré) vers l'hôte par défaut (**fuite du bearer**).
|
||||||
|
- **M27 — `data/repository/ShareRepository.kt:44-93` + `data/remote/dto/Dtos.kt:120-132`** : snapshot permissions sans delta (`after` jamais passé), `sharedById`/`expiresAt` en `Any?` jamais lus, `cachedAt` jamais persisté, aucun downgrade 24h ni `canAccess` → grant révoqué/expiré reste visible et ouvrable (`404`) jusqu'au prochain login.
|
||||||
|
- **M28 — `domain/ServerConfigStore.kt:46-59`** : `set()` persiste URL non validée (`"http://"` → `"http:"`, `"foo bar"` → `"http://foo bar"`) → app semi-brickée jusqu'à correction manuelle (recoupé par 2 agents).
|
||||||
|
|
||||||
## À compléter (pour le relecteur)
|
### UI / Navigation / VM
|
||||||
|
- **M29 — `ui/folderlist/FolderListScreen.kt:202+220`** : onboarding racine bloqué après rotation — `pendingDefaultPick` en `remember` (non-saveable), `LaunchedEffect` polling annulé à la rotation, import SAF continu en fond mais `setDefaultRoot()` jamais rappelé → écran figé sur `DefaultRootOnboarding`, re-picker = doublon d'import.
|
||||||
|
- **M30 — `ui/document/DocumentViewerScreen.kt:130-137`** : position pager perdue à la rotation (`jumpPending = remember`), re-scroll vers `initialResourceId` → page N → retour page initiale. Fix : `rememberSaveable` / mémoriser index courant.
|
||||||
|
- **M31 — `ui/search/SearchScreen.kt:276-284` + `SearchViewModel.kt:55-72`** : `TextField` branché sur la valeur **debouncée** (300 ms) → frappe affichée par à-coups, IME/autocorrect écrasés. Correct : champ sur requête brute, debounce pour Room seule.
|
||||||
|
- **M32 — `ui/folderdetail/FolderDetailScreen.kt:196-202`** : Partager sans gate `isShareable` (contraire FolderList `canShare`, `:154-159`) → partage d'un dossier local-only/reçu = op `share` vouée au dead-letter `NOT_FOUND`.
|
||||||
|
- **M33 — `ui/folderlist/FolderListViewModel.kt:165-173`** : `canShare` stale au login/logout (combine `_defaultRootId`/`_browseFolderId` sans token/auth) → « Partager » reste désactivé jusqu'à navigation après connexion depuis Réglages.
|
||||||
|
- **M34 — `ui/folderlist/FolderListScreen.kt:333-375 vs 326-330`** : suppression multi-dossiers filtre les items **visibles** alors que `selection.ids` survit à `openBrowseFolder` (jamais clear) → sélection hors-vue abandonnée silencieusement avec snackbar succès. Même classe `ui/search/SearchScreen.kt:290-305` (chips actifs en mode sélection, delete par snapshot).
|
||||||
|
- **M35 — `ui/document/DocumentViewerScreen.kt:131-144`** : pas de clamp après suppression — supprimer le dernier doc (page 2/2) laisse `pagerState` hors bornes → viewer vide au lieu de retomber sur 1er ou `onBack`.
|
||||||
|
- **M36 — `ui/settings/SettingsScreen.kt:120-128`** : préférence `SYSTEM` inatteignable (Switch DARK/LIGHT depuis `darkNow`, store + thème supportent SYSTEM) → impossible de revenir à « suivre le système ».
|
||||||
|
- **M37 — `ui/settings/SettingsViewModel.kt:30-36`** : `load()` écrase une saisie serveur en cours (`_serverUrl` init défaut puis réassigné après `load()` en `init`).
|
||||||
|
|
||||||
- Ajouter nouveaux bugs ci-dessous avec `fichier:ligne`, sévérité, explication courte.
|
### Scan / PDF / Review / Thumbnails
|
||||||
- Ne pas supprimer les entrées existantes, juste append ou annoter.
|
- **M38 — `data/repository/ScanRepository.kt:63-78`** : `addPage` avec `sortOrder = pageCount` → doublons après suppression (`ORDER BY sort_order` instable, `swapOrder` ambigu). Cause : compteur au lieu de `MAX+1`.
|
||||||
- Idées à creuser : `handlers/files.go` (`intParam`, `q` non borné), `service/resources.go:164` (filename brut comme `name`, mime verbatim), `repository/resources.go` (parent check puis UPDATE non-atomique → FK 500), `cmd/server/main.go` (double pool, `conn` jamais `Close`, worker OCR non attendu), `pkg/auth` (TTL 7j sans refresh/révocation).
|
- **M39 — `ui/scan/ScanViewModel.kt:180/199`** : dimensions stockées (pré-scale) ≠ réelles (downscale 2400px dans `process()`) → fiche `W×H` fausse pour grands quads.
|
||||||
|
- **M40 — `ui/scan/ScanViewModel.kt:177-203`** : écriture JPEG hors transaction Room (orphelins si insert échoue) ; `deletePage` supprime le fichier **avant** la ligne DB (crash = ligne vers fichier absent → rejoint C8).
|
||||||
|
- **M41 — `data/repository/FileRepository.kt:206`** : `saveLocalFile` ne remonte jamais `cloud` → `local-cloud` (`existing?.syncStatus ?: …`) → fichier cloud-only réimporté en SAF reste badgé « cloud », ignoré vignette/OCR (`sync_status='local-cloud'` requis, `FileDao.kt:137`).
|
||||||
|
- **M42 — `ui/pdfbuilder/PdfBuilderViewModel.kt:227-237`** : PDF assemblé importé `processed=false` (défaut omis, contraire export scan `true`) → atterrit en review alors que l'utilisateur vient de le construire.
|
||||||
|
- **M43 — `ui/review/SwipeReviewViewModel.kt:68-74,94-100`** : retrait optimiste sans réinsertion sur échec (`keep`/`markAllProcessed`, contraire `delete` qui réinsère) → carte perdue jusqu'au prochain `load()` (init seule).
|
||||||
|
- **M44 — `ui/pdfbuilder/PdfBuilderScreen.kt:248`** : `remember(files)` réinitialise la sélection à chaque update Room → cases cochées effacées pendant un refresh serveur.
|
||||||
|
- **M45 — `ui/pdfbuilder/PdfBuilderEngine.kt:104-107`** : pages PDF sources plafonnées à 1200pt malgré commentaire « format conservé » (`min(1, 1200/max, 3000/max)`, le 1200 gagne toujours) → pixellisation A3/300dpi.
|
||||||
|
- **M46 — `features/scan/CornerGeometry.kt:19-26`** : `orderPoints` sans validation dégénérescence (doublons/quad aplati) → `outputSize = 0` → bitmap 1×1 validé (page blanche) au lieu d'erreur.
|
||||||
|
- **M47 — `ui/scan/CameraStage.kt:162-181`** : overlay calibré sur flux `ImageAnalysis` (hypothèse `FILL_CENTER`) alors que `PreviewView` affiche le flux `Preview` (ratio/crop différents) → quad décalé systématiquement quand les ratios diffèrent.
|
||||||
|
|
||||||
### Ajouts relecteur (2026-09-21, vérifié en lecture)
|
---
|
||||||
|
|
||||||
> Nota : entrées existantes conservées. Ci-dessous uniquement des ajouts.
|
## 🟡 Mineurs (UX, perf, dette)
|
||||||
> Annotation §1 : `GET /files/folders` vs `GET /files/:id` — Gin privilégie
|
|
||||||
> les segments statiques sur `:param` dans son arbre, donc l'ordre de
|
|
||||||
> déclaration (`router.go:29-32`) ne masque pas forcément `folders` en
|
|
||||||
> pratique. Reste fragile (dépend du routeur) : à verrouiller par un test
|
|
||||||
> `GET /files/folders → 200` + `GET /files/<32hex> → 200/404`, pas par l'ordre.
|
|
||||||
|
|
||||||
#### A1 — CRITIQUE : bypass dummy-password + panic nil-deref au login
|
### Sync / Worker / SAF
|
||||||
- `backend/pkg/passwd/passwd.go:37-43,98-103` + `backend/handlers/auth.go:55-83`
|
- **m1 — `features/sync/SyncViewModel.kt:103-121`** : `_walkInProgress` sans `finally` (reste `true` si scope annulé) → badge « syncing » collé ; la fenêtre inclut l'appel réseau partage.
|
||||||
- `VerifyTimedEqual("", dummy)` vérifie contre `Hash("kazier-constantime-dummy")`
|
- **m2 — `features/sync/SyncViewModel.kt:106-112`** : `OutboxSyncWorker.enqueue` + `OcrAutoWorker.enqueue` à chaque tick même sans changement → réveils WorkManager / 30s pour rien.
|
||||||
en dur. `username=<inconnu> + password="kazier-constantime-dummy"` → `Verify`
|
- **m3 — `features/sync/OutboxSyncWorker.kt:97-100`** : 401 → `success()` sans re-signal, ops pendantes figées jusqu'au prochain tick/login (bénin, `AuthViewModel` ré-enqueue au re-login).
|
||||||
retourne `nil` → suite du handler avec `user == nil` → `user.ID:83` panic
|
- **m4 — `features/sync/SafScanner.kt:132-139`** : `cursor.getString(iDoc)` sans garde `iDoc == -1`, `name` plateforme-nullable déréférencé → provider dégénéré = crash de tout `scanTree` à chaque tick.
|
||||||
(Gin recovery → 500). Effets : DoS à la demande + oracle 500 vs 401 qui casse
|
- **m5 — `features/sync/DeviceSync.kt:75-137`** : « transaction courte » en réalité géante (N upserts + `getAll()` dossiers **et** fichiers par racine, O(racines×DB) sous verrou écriture) → lecteurs Room bloqués, jank/ANR sur grosses arborescences.
|
||||||
l'indistinguabilité revendiquée + préimage hardcodée en source. Fix :
|
- **m6 — `features/saf/FolderDeleter.kt:74-88`** : `deleteLocally` multi-writes hors transaction (contraire `treeMarkMissing`) → kill à mi-chemin = `exists` partiel.
|
||||||
dummy aléatoire par boot (ou hash du mot fourni à sel fixe) + ne jamais
|
|
||||||
toucher `user` si `userErr != nil`.
|
|
||||||
|
|
||||||
#### A2 — Upload : `file.Size` fait confiance au header, `io.Copy` illimité
|
### Room / Domain / DI
|
||||||
- `backend/service/resources.go:135,178-195` (service) vs `backend/handlers/files.go:119-133` (handler)
|
- **m7 — `data/local/dao/FileDao.kt:30-37`** : `searchWithFilters` `LIKE` brut sans `ESCAPE`, casse ASCII-only → `%`/`_` = jokers (match-all), « ete » ne trouve pas « ÉTÉ ».
|
||||||
- Le handler protège le transport (`MaxBytesReader`), mais l'invariant
|
- **m8 — `data/local/FileOrdering.kt:5-11`** : tri mémoire (`referenceDate` seule) divergent du SQL (`name ASC` tiebreak, `FileDao.kt:21,43`) ; `lastModified = 0` SAF trié comme plus vieux → ordre incohérent + fichiers `0` enfouis.
|
||||||
service est absent : header menteur → écriture disque illimitée. Envelopper
|
- **m9 — `data/local/dao/PendingOperationDao.kt:30-32`** : commentaire `MAX_PENDING_ATTEMPTS` contredit le code (`markFailed()` = dead-letter immédiate, `attempts` diagnostique) — trompeur pour futurs appelants (cohérent avec worker, seul le commentaire est faux).
|
||||||
`src` dans `io.LimitReader` + re-contrôler les octets écrits.
|
- **m10 — `data/local/dao/FileDao.kt:89`** : `updateUri` ne touche pas `updated_at` → ordre de convergence faussé après move.
|
||||||
|
- **m11 — `domain/LocalModeStore.kt:24`** : `get()` teste `!= null` au lieu de `== "1"` → toute valeur parasite (`"0"`, `""`) = mode local actif à tort.
|
||||||
|
- **m12 — `domain/ServerConfigStore.kt:40-44` + `domain/ThemePreferenceStore.kt:28-32`** : `load()` once-only (`AtomicBoolean`, sans réarmement) → après wipe/logout, URL/thème périmés en mémoire.
|
||||||
|
- **m13 — `domain/ThemePreferenceStore.kt:34-39`** : `set()` publie le `StateFlow` avant succès DB → divergence UI/DB si upsert échoue.
|
||||||
|
- **m14 — `domain/PrefKeys.kt:8`** : clé `SYNC_MODE` morte (0 usage, grep vérifié) → dérive spec/impl.
|
||||||
|
- **m15 — `di/DatabaseModule.kt:25-28`** : aucune stratégie de downgrade → APK plus ancien sur DB v11 = crash `IllegalStateException` au lieu de dégradation contrôlée.
|
||||||
|
- **m16 — index composites manquants** (`PendingOperationEntity.kt:20-27`, `FileEntity.kt:18-26`, `PendingOperationDao.kt:13`, `FileDao.kt:133-145`) : `selectPending` et `getOcrAutoCandidates` = full-table scan → jank/batterie à 10k lignes.
|
||||||
|
- **m17 — `data/local/entity/FileEntity.kt:56-57` vs `Migrations.kt:92`** : `processed` sans `defaultValue` Room alors que la migration met `DEFAULT 0` (contraire `createdInApp`, `FolderEntity.kt:43`) → fresh-install ≠ migré.
|
||||||
|
- **m18 — `data/local/dao/ScanDao.kt:48-57`** : `swapOrder` sans contrôle d'appartenance ni transaction → swap inter-sessions corrompt `sort_order`, concurrence = doublons.
|
||||||
|
- **m19 — `data/local/AppDatabase.kt:27-34`** : `exportSchema = false`, migrations non snapshotées → dérives indétectables en CI.
|
||||||
|
- **m20 — `data/repository/OcrRepository.kt:66-73`** : `poll()` infini (`while(true)` + 3s, sans timeout) alors qu'un job peut rester `processing` 15 min (stale claim serveur) → coroutine tenue indéfiniment.
|
||||||
|
- **m21 — `data/repository/OutboxRepository.kt`** : ops contrat non émissibles (`update_metadata`, `update_share`, `create_link`, `revoke_link` — §6.1 = 9 ops, 5 helpers) → rename partagé, update share, liens publics inopérants.
|
||||||
|
- **m22 — `data/remote/ApiService.kt`** : endpoints contrat absents (`PATCH /users/me/password`, `GET/DELETE /files/:id`, `GET /files/search`, `GET /shares/links/:token`) → changement mot de passe impossible avec tokens 7j non révoqués.
|
||||||
|
- **m23 — `data/repository/AuthRepository.kt:21-35`** : `registerDevice` best-effort avale tout (y compris 400/429) → `INVALID_DEVICE_ID`/`RATE_LIMITED` invisibles, 401 trompeur plus tard.
|
||||||
|
- **m24 — `ui/auth/AuthViewModel.kt:52-55`** : `registerDevice()` émis même en mode local (pas de garde contrairement à `syncSnapshot`).
|
||||||
|
- **m25 — `di/NetworkModule.kt:37-43`** : logging `BASIC` en DEBUG loggue les query PII (`GET /users/resolve?username=…`) dans logcat.
|
||||||
|
- **m26 — `data/remote/AuthInterceptor.kt:20-26`** : `Bearer` joint aux routes publiques (`POST /devices`, `POST /auth/login`) — serveur l'ignore mais hygiène + amplification de la fuite M26.
|
||||||
|
- **m27 — `auth/SessionManager.kt:33-38`** : `expiresAt` du login jeté (paseto TTL 7j) → expiration découverte par 401 brutal, impossible de pré-relancer.
|
||||||
|
- **m28 — `auth/SecureTokenStore.kt:27-36`** : init Keystore/`EncryptedSharedPreferences` au construct Hilt + I/O synchrone possiblement Main (`MasterKeys` déprécié) → ANR au restore, crash Direct Boot avant déverrouillage.
|
||||||
|
|
||||||
#### A3 — Upload non-atomique, torn reads OCR
|
### UI
|
||||||
- `backend/service/resources.go:154-157,178-195`
|
- **m29 — `ui/navigation/NavGraph.kt:50`** : `pdfBuilder(listOf())` → `"pdfbuilder/"` ne matche pas `"pdfbuilder/{ids}"` (protégé aujourd'hui par `enabled = ids.isNotEmpty()` — contrat implicite fragile).
|
||||||
- `os.Create(dest)` + `io.Copy` direct, overwrite sur place pour
|
- **m30 — `ui/navigation/NavGraph.kt:53-59,165`** : `folder/…` sans `launchSingleTop` → double-tap = doublon de pile.
|
||||||
`targetExisting`. `service/ocr.go` (`Glob`) peut lire un fichier à moitié
|
- **m31 — `ui/navigation/KazierApp.kt:54-63`** : `rememberNavController()` par branche SignedIn↔Local → `signOutToLocal()` perd la position d'exploration (hoister le controller).
|
||||||
écrit. Fix : temp + `Rename` (+ `Fsync`).
|
- **m32 — `ui/folderdetail/FolderDetailScreen.kt:395-429`** : dossiers non sélectionnables dans le détail (vs FolderList) — incohérence partage/multi-suppression inter-écrans.
|
||||||
|
- **m33 — `ui/pdfbuilder/PdfBuilderScreen.kt:104-114`** : `LaunchedEffect(buildPhase)` rejoue side-effects à la recomposition racine (rotation → `Failed` re-snackbar, `Saved` re-`onOpenDocument` = double navigation possible).
|
||||||
|
- **m34 — dialogs `remember` perdus à la rotation** (`SyncStatusBadge.kt:129`, `showDeleteWarning/Confirm`, `showMoveDialog`, `showShareSheet`, `showNameDialog`) — sûr mais UX ; `showOcrDialog` en `rememberSaveable` = bon exemple.
|
||||||
|
- **m35 — `ui/components/WatchedFoldersBadge.kt:36-40` + `WatchedFoldersViewModel.kt:25-27`** : double instance VM + `SharingStarted.Eagerly` collecte Room en continu même sur autres onglets.
|
||||||
|
- **m36 — `ui/settings/SettingsViewModel.kt:43-48`** : `onServerUrlChange` écrit en prefs à chaque frappe (churn IO) ; commentaire `testConnection` obsolète.
|
||||||
|
- **m37 — `MainActivity.kt:27-33`** : `themePreferenceStore.load()` fire-and-forget → flash de thème aux premières frames.
|
||||||
|
- **m38 — `ui/navigation/NavGraph.kt:213-219`** : bandeau import global chevauchant la FloatingNavBar, doublon des indicateurs par-écran.
|
||||||
|
- **m39 — `ui/pdfbuilder/PdfBuilderViewModel.kt:236`** : `syncStatus="local"` en littéral au lieu de `FileStatus.LOCAL` — fonctionne mais casse silencieusement à toute renommée.
|
||||||
|
|
||||||
#### A4 — Fichiers world-readable
|
### Scan / PDF / Thumbnails
|
||||||
- `backend/service/resources.go:149-150` : `MkdirAll 0755`, `os.Create` → 0644
|
- **m40 — `ui/scan/CameraStage.kt:86-91`** : `ImageCapture` forcé 1920×1080 paysage → sur portrait, bitmap pleine-rés + copie tournée (×2 mémoire ~16 Mo) → OOM petits devices.
|
||||||
selon umask. Données user lisibles sur hôte partagé. Passer en `0700/0600`.
|
- **m41 — `ui/scan/CameraStage.kt:165-181`** : `toBitmap()` pleine-rés à chaque frame d'analyse (~30fps) puis downscale interne → churn GC + batterie.
|
||||||
- Positif vérifié : pas de traversal via `ownerID/resourceID` (32-hex issus
|
- **m42 — `ui/scan/CameraStage.kt:99-101`** : `addOnLayoutChangeListener` jamais retiré → fuite mineure du listener.
|
||||||
token/serveur), `UPLOAD_DIR` = config admin.
|
- **m43 — `ui/scan/CameraStage.kt:200-211`** : `when` rotation sans `else` → angle inattendu = copie silencieuse au lieu d'erreur.
|
||||||
|
- **m44 — `ui/scan/ScanGeometry.kt:42-69`** : division par zéro si `sourceRect` dégénérée (`Infinity/NaN` dans le quad ; inatteignable via `initialViewport` mais API publique exposée).
|
||||||
|
- **m45 — `ui/scan/CropStage.kt:188-193`** : arrondi `roundToInt` viewport indépendant de l'offset → dépassement 1px en bordure (frange noire sur images impaires).
|
||||||
|
- **m46 — `ui/scan/ScanViewModel.kt:111-122`** : `combine(pages, pageCount)` avec count ignoré → réassignations `_pages` redondantes.
|
||||||
|
- **m47 — `ui/scan/ScanViewModel.kt:409-418`** : `abandon()` laisse sessions vides `ABANDONED` jamais purgées + `sessionDir()` fait `mkdirs()` en getter (recrée ce qu'on supprime).
|
||||||
|
- **m48 — `data/repository/ScanRepository.kt:27-40`** : race `getOrCreateActiveSession` (double `active` possible, aucune unicité partielle ; fenêtre étroite).
|
||||||
|
- **m49 — `domain/FileCategory.kt:19-27`** : CSV classé `TEXT` (par MIME) ou `OFFICE` (par extension) selon le chemin → icône/filtres/OCR divergents pour le même fichier.
|
||||||
|
- **m50 — `features/thumbnails/ThumbnailStore.kt:51`** : map de `Mutex` jamais purgée → fuite lente par `resourceId`.
|
||||||
|
- **m51 — `features/thumbnails/ThumbnailStore.kt:104-112`** : `.tmp` orphelin si `renameTo` échoue → résidus `*.webp.tmp`.
|
||||||
|
- **m52 — `features/thumbnails/ThumbnailStore.kt:83-87`** : `isUpToDate` sur `mtime` seule (granularité seconde SAF) → vignette périmée après édition rapide (pas de taille/hash).
|
||||||
|
- **m53 — `ui/pdfbuilder/PdfBuilderEngine.kt:121-124`** : `renderer?.close()` non protégé (si `close()` lève, `pfd.close()` sautée → fd leak ; `ThumbnailStore.renderPdfPage` fait `runCatching`).
|
||||||
|
- **m54 — `features/scan/CornerGeometry.kt:40-45`** : commentaire « moyenne » mais code `max` → warp légèrement étiré vs réel.
|
||||||
|
- **m55 — `features/scan/ScanImageProcessor.kt:126-181`** : mats de contours non libérés sur exception (`c.release()` chemin nominal seul) → fuite native OpenCV.
|
||||||
|
- **m56 — `ui/review/SwipeReviewViewModel.kt:52-64`** : échec de reload écrase le deck (`update{cards=files}` même sur `emptyList` d'erreur) → deck vidé à tort.
|
||||||
|
|
||||||
#### A5 — `NewID()` panic sur échec entropie
|
---
|
||||||
- `backend/repository/resources.go:23-29` : `panic` si `crypto/rand` échoue →
|
|
||||||
crash serveur entier. Retourner `(string,error)`.
|
|
||||||
|
|
||||||
#### A6 — `ShareLinkGet` compare avec `==` au lieu de `errors.Is`
|
## ✅ Vérifié infondé (suspects écartés)
|
||||||
- `backend/handlers/share_links.go:23` (tous les autres handlers via
|
- Single-flight `Mutex` présent (`DeviceSync.kt:49`), `enqueueUniqueWork(KEEP)` + batch 20 + `ORDER BY id` conformes — non-bugs.
|
||||||
`writeError` utilisent `errors.Is`) : `ErrNotFound` wrappé → 500 au lieu de
|
- `checkHealth` construit bien `{base}/health` avec base incluant `/api/v1` = route backend `GET /api/v1/health` — OK.
|
||||||
404, sur endpoint public non-authentifié → oracle 500/404.
|
- Token **non** stocké en clair (`EncryptedSharedPreferences` AES256-SIV/GCM + Keystore) — seul `TokenProvider.current` en mémoire, normal.
|
||||||
|
- Ordre interceptors `serverUrl → auth → logging`, `BASIC` ne log ni headers ni bodies — OK.
|
||||||
#### A7 — Incohérences contrat / parsing silencieux (mineurs mais réels)
|
- Contrat HTTP conforme sur endpoints déclarés (query `folderId/page/pageSize`, `deviceId` camel vs `device_id` login, multipart `file`/`resourceId`/`folderId`, enveloppes `{data,meta}`/`{error:{code,message}}`, codes) — OK.
|
||||||
- `backend/handlers/auth.go:94-96` : `ExpiresAt = Now()+TTL` seconde lecture
|
- `device_id` claim jamais utilisé comme preuve, seul le `Bearer` parle — conforme middleware.
|
||||||
d'horloge, pas le `exp` du token (dérive ms).
|
- Worker no-op en mode local (`OutboxSyncWorker.kt:71`), batch 20 ≤ 100 serveur, statuts OCR, `resolveUser` trim compatible, password jamais trimé — OK.
|
||||||
- `backend/handlers/auth.go:90` : code `TOKEN_ERROR` non-standard.
|
- Deep-links : aucun défini (absence, pas de bug) ; args nav `folderResourceId`/`documentResourceId`/`ids` cohérents, 32-hex sans `/`.
|
||||||
- `backend/handlers/files.go:114-117,50-53` : 32-hex malformé → `404`, vs
|
- Hilt : `MainActivity @AndroidEntryPoint`, tous `hiltViewModel()` ↔ `@HiltViewModel`, scopes corrects — aucune injection manquante.
|
||||||
`backend/handlers/devices.go:23-26` → `400 INVALID_DEVICE_ID`.
|
- Pas de recomposition infinie trouvée ; `collectAsStateWithLifecycle` partout ; placeholder cloud-only correct (`DocumentContentViewer.kt:39-47`) ; recherche 100 % locale conforme V1 ; back stack onglets correct (`saveState`/`restoreState`) ; `SelectionState` volatile documenté volontaire.
|
||||||
- `backend/handlers/files.go:13-22` + `backend/handlers/sync.go:43-47` :
|
- Scan : pas de double-`recycle` draft, pas de double rotation EXIF (comportement correct, commentaire trompeur), `swapOrder` args corrects, FK `scan_pages→sessions CASCADE` actif.
|
||||||
`intParam` invalide/négatif → `fallback` silencieux ; `after` garbage →
|
|
||||||
`0` = full snapshot au lieu de 400. `Atoi` 32-bit overflow pour epoch-ms.
|
|
||||||
- `backend/handlers/middleware.go:29` : préfixe `Bearer ` case-sensitive.
|
|
||||||
|
|
||||||
#### A8 — Sémantiques silencieuses outbox (désync grantees + fuite d'existence)
|
|
||||||
- `backend/service/sync.go:180-202` : `update_metadata` cible absente → `nil`
|
|
||||||
marqué *applied* (client croit le rename fait) vs `<editor` → `ErrNotFound`
|
|
||||||
(batch halté). Incohérent.
|
|
||||||
- `backend/service/sync.go:204-222` : `move`/`delete` sur ressource partagée
|
|
||||||
non-owned → no-op silencieux marqué applied → client grantee désync.
|
|
||||||
- `backend/service/sync.go:152-178` : `ExistsOwner` (own seul) puis `Insert` ;
|
|
||||||
id d'autrui deviné → PK globale → `23505 → ErrNameConflict`
|
|
||||||
(`repository/resources.go:143-146`) = oracle d'existence cross-user. + TOCTOU
|
|
||||||
`Exists→Insert`.
|
|
||||||
|
|
||||||
#### A9 — Replay à payload muté avalé
|
|
||||||
- `backend/service/sync.go:109-115` + `backend/repository/operations.go:44-50`
|
|
||||||
(`ON CONFLICT DO NOTHING`) : même `(device,op)` avec payload différent =
|
|
||||||
skip « succès », nouvelle intention dropée sans comparaison de hash.
|
|
||||||
|
|
||||||
#### A10 — `UpdatePassword` / `MarkDeleted` sans garde
|
|
||||||
- `backend/repository/users.go:87-103` : pas de `AND deleted_at IS NULL`, pas
|
|
||||||
de check `RowsAffected` → re-hash d'un compte soft-deleted, succès
|
|
||||||
silencieux sur id inconnu / course avec `MarkDeleted`.
|
|
||||||
|
|
||||||
#### A11 — `OcrJobs` : transitions sans garde
|
|
||||||
- `backend/repository/ocr_jobs.go:60-67,112-128` : `TouchProcessing`,
|
|
||||||
`Complete`/`Fail` sans garde de statut ni `RowsAffected` → `queued→done`,
|
|
||||||
`done→failed`, double-complete silencieux. `ResetStaleProcessing:100-110`
|
|
||||||
sur horloge app (skew DB), lignes `processing` à `started_at NULL` jamais
|
|
||||||
requeued. `ClaimNext:72-95` correct atomiquement mais sans index composite
|
|
||||||
`(status,created_at)` → scan O(queue).
|
|
||||||
|
|
||||||
#### A12 — `physicalPath` via `Glob` sans vérification fichier
|
|
||||||
- `backend/service/ocr.go:142-153` : symlink/répertoire/`id.` acceptés ;
|
|
||||||
symlink hors `UPLOAD_DIR` suivi par tesseract. Faire `Lstat + IsRegular +
|
|
||||||
EvalSymlinks`-containment. `lang` (`ocr/tesseract.go:30`, depuis `OCR_LANG`)
|
|
||||||
non whitelisté (argv, pas de shell — worst case erreur tesseract).
|
|
||||||
|
|
||||||
#### A13 — OCR : causes avalées, `done` trompeur
|
|
||||||
- `backend/service/ocr.go:113-138` : `Fail("file not readable")` sans `err`,
|
|
||||||
`Complete`/`UpdateOcrText` partiellement log-only → job `done` alors que
|
|
||||||
`ocr_text` non persisté ; `GET /files/:id/ocr` renvoie `""` 200
|
|
||||||
indistinguable de « pas encore extrait ».
|
|
||||||
- `backend/ocr/tesseract.go:29-45,47-67` : pas de timeout par job (ctx = vie
|
|
||||||
serveur), stdout/stderr non bornés → OOM, pages PDF en erreur `continue`
|
|
||||||
silencieusement → texte partiel vu comme complet, pas de cap taille/pages.
|
|
||||||
|
|
||||||
#### A14 — `main.go` : lifecycle / concurrence boot
|
|
||||||
- `backend/cmd/server/main.go:44-51,59` : `db.Open` + `MigrateDatabase` (qui
|
|
||||||
ouvre son propre pool) = double pool ; `conn` jamais `Close` ; migrations
|
|
||||||
DDL à chaque boot (rôle runtime devrait être DML-only en prod).
|
|
||||||
- `backend/service/bootstrap.go:25-47` : double réplica sur DB vide →
|
|
||||||
duplicate `username_normalized` → un réplica `Fatal`, pas de retry.
|
|
||||||
|
|
||||||
#### A15 — Complément device/token (étend § moyenne existant)
|
|
||||||
- Vérifié : `pkg/auth/auth.go:54-67` `Verify` n'impose pas `^[0-9a-f]{32}$` ;
|
|
||||||
`handlers/middleware.go:46-62` vérifie que le user existe mais jamais le
|
|
||||||
device (hex ni `Exists`) → tokens à device supprimé/jamais-enregistré
|
|
||||||
passent l'auth, 500 plus tard (FK). `repository/operations.go:36-51`
|
|
||||||
valide `operation_id` mais pas `device_id` ; payloads vides/`"null"`/invalides
|
|
||||||
normalisés en `{}` (`60-68`) au lieu d'être rejetés → trace infidèle.
|
|
||||||
|
|
||||||
#### A16 — Idées à creuser : conclusions
|
|
||||||
- `handlers/files.go:q` : `TrimSpace` + `!= ""` ok, mais pas de longueur maxi
|
|
||||||
→ `ILIKE %…%` géant = full scan (index trigram manquant,
|
|
||||||
`repository/resources.go:297,327`). `page/pageSize` cappés à 200 côté
|
|
||||||
handler, mais `(page-1)*pageSize` non cappé + repo sans validation
|
|
||||||
(`repository/resources.go:170-227`, `LIMIT` négatif → 500).
|
|
||||||
- `service/resources.go:159,164` : confirmé — `file.Filename` brut comme `name`
|
|
||||||
(sauts de ligne, 255+ chars, unicode) + `Content-Type` verbatim comme mime,
|
|
||||||
sans whitelist/normalisation.
|
|
||||||
- `repository/resources.go:124-147,374-403` : confirmé — `folderExists(SELECT)`
|
|
||||||
puis `INSERT`/`UPDATE` non-atomique → parent supprimé entre les deux = 500
|
|
||||||
FK ou orphelin.
|
|
||||||
- `cmd/server/main.go` : confirmé ci-dessus (A14) + worker OCR non attendu au
|
|
||||||
shutdown (5s puis exit, jobs `processing` → requeue au prochain boot via
|
|
||||||
`ResetStaleProcessing`, ok mais à documenter).
|
|
||||||
- `pkg/auth` : TTL 7j sans refresh/révocation confirmé par design
|
|
||||||
(`auth.go:13`, `handlers/auth.go:110-112`) ; `iat=nbf=now`, `exp` vérifié via
|
|
||||||
`NewParserForValidNow` (`auth.go:55`) — correct, pas de bug ici au-delà du
|
|
||||||
secret (A-suite § haute prio n°4) et du format non validé (A15).
|
|
||||||
|
|
||||||
## Validation (2026-09-21, autre agent — suite verte)
|
|
||||||
|
|
||||||
`go build ./...` OK. `go test ./...` : 11 packages OK, 0 fail
|
|
||||||
(`cmd/server, config, db, handlers, ocr, pkg/api, pkg/auth, pkg/passwd,
|
|
||||||
repository, service`). Les 4 échecs transitoires vus pendant l'édition
|
|
||||||
concurrente (RecordNormalizes, MarkDeleted, UploadSanitizes,
|
|
||||||
UpdateMetadata/Move) ne se reproduisent plus — tests alignés sur la
|
|
||||||
nouvelle sémantique.
|
|
||||||
|
|
||||||
### Haute priorité : tout corrigé
|
|
||||||
- §1 route `folders` : réordonnée avant `:id` + tests d'ordre (durcissement,
|
|
||||||
Gin préférait déjà le statique).
|
|
||||||
- #2 cycle : `checkNoCycle` (walk `GetParentID` ≤128) + `MoveResource`
|
|
||||||
atomique. Manque : pas de test cycle dédié.
|
|
||||||
- #3 `CreateLink` : `ON CONFLICT DO NOTHING` + même ressource → no-op,
|
|
||||||
sinon `NAME_CONFLICT`. Tests rejeu/conflit OK.
|
|
||||||
- #4 secret : défaut allongé (≥32), refusé en prod (`APP_ENV/ENV`),
|
|
||||||
`len<32` rejeté. Reste : dev boot sur défaut public (assumé).
|
|
||||||
- #5/#6/A2/A3/A4 upload : ext whitelistée, `LimitReader` octets réels,
|
|
||||||
temp+`Rename`+`Fsync`, `0700/0600`, cleanup stale/orphelins. Tests OK.
|
|
||||||
- #7 batch : `Claim`/`MarkApplied` + `applied:i/INTERNAL` explicites.
|
|
||||||
Documenté non-transactionnel (vrai Tx reportée).
|
|
||||||
- #8 fuites : `classifySyncError` générique + log serveur. OK côté sync.
|
|
||||||
- #9 `Count` : `WHERE deleted_at IS NULL`, bootstrap recrée l'admin. OK.
|
|
||||||
- #10 migrations : `000007` sans `DELETE`, `000008 down` sans `::bigint`
|
|
||||||
crash, + `000011/12/13` saines. Up/down OK.
|
|
||||||
- #11 stubs : `folders/move/upload/move_test` supprimés, 0 réf. OK.
|
|
||||||
- #12 oracle : device inconnu → `401` identique + rate-limit 60/min/IP. OK.
|
|
||||||
- A1 dummy : random 32B/boot + guard `user==nil → 401` + caps Argon2. OK.
|
|
||||||
|
|
||||||
### Moyens : corrigé, 3 partiels assumés
|
|
||||||
- A6 `errors.Is`, A8 sémantiques (absent → no-op, étranger → `NOT_FOUND`
|
|
||||||
halt), A9 rejeu (`payload_hash` 000013 + `ErrInvalidPayload`), A10 users
|
|
||||||
guards, A11 jobs gardés, A12 path containment + lang whitelist, A13 OCR
|
|
||||||
(timeout 120s, 2MiB, 50 pages), A7/A16 contrat : tous OK.
|
|
||||||
- Partiels : `EnforceDeviceExists` opt-in **défaut `false`** (tokens à
|
|
||||||
device inconnu passent toujours par défaut) ; `NewID()` panic conservé
|
|
||||||
(migration appelants partielle) ; double pool `main.go` subsiste ;
|
|
||||||
`POST /devices` sans rate-limit (TODO assumé).
|
|
||||||
- Reste : `UpdateNameByID`/`TouchResource` non scopés encore appelés
|
|
||||||
(`TouchOwned`/`UpdateNameOwned` ajoutés, migration appelants reportée).
|
|
||||||
|
|
||||||
### Risques résiduels à trancher
|
|
||||||
1. Activer `EnforceDeviceExists` par défaut (casse tokens existants —
|
|
||||||
planifier rotation).
|
|
||||||
2. Vrai Tx `ApplyBatch` (fenêtre TOCTOU admise, couverte par idempotence).
|
|
||||||
3. Rate-limit `POST /devices` + test cycle dédié manquant.
|
|
||||||
|
|
||||||
### Addendum validation v2 (autres tâches finalisées)
|
|
||||||
`go build ./...` OK, `go test ./...` vert (12 packages, dont
|
|
||||||
`handlers 9.6s`, `repository 3.4s`, `service 9.9s`).
|
|
||||||
Nouveautés depuis v1, toutes validées :
|
|
||||||
- `handlers/store.go` : `writeError` défaut → `500 INTERNAL "internal error"`
|
|
||||||
générique + `log` serveur (plus de `err.Error()` brut) — clôt #8 côté
|
|
||||||
handlers.
|
|
||||||
- `handlers/sync.go` : `POST /sync/ops` borné (`MaxBytesReader` 1 MiB, max
|
|
||||||
100 ops/batch → 400 explicite) + `parseAfterMs` strict 64-bit
|
|
||||||
(garbage/négatif → 400, fini le repli silencieux vers full snapshot) —
|
|
||||||
clôt le gap « sync non borné ».
|
|
||||||
- `repository/devices.go` : `MarkUser` → `ErrNotFound` si 0 rows (fini le
|
|
||||||
no-op silencieux sur device fantôme ; la course `Exists→MarkUser` est
|
|
||||||
désormais distinguable). Résiduel mineur : `handlers/auth.go` mappe
|
|
||||||
encore cette erreur vers 500 au lieu de 401.
|
|
||||||
- Nouveaux tests : `handlers/ocr_test.go`, `handlers/sync_test.go`,
|
|
||||||
`repository/devices_test.go` — tous verts.
|
|
||||||
Restent ouverts : `EnforceDeviceExists=false` par défaut, vrai Tx
|
|
||||||
`ApplyBatch`, rate-limit `POST /devices`, test cycle dédié.
|
|
||||||
|
|
||||||
## Suite (2026-09-21, fin des restes — suite verte)
|
|
||||||
|
|
||||||
`go build ./...` OK, `go vet ./...` OK, `go test ./...` : 12 packages OK, 0 fail.
|
|
||||||
Nouveaux tests exécutés nominalement (`-run` ciblé) : `TestApplyBatchMoveIntoDescendantRejected`,
|
|
||||||
`TestDevicesRegisterRateLimited`, `TestSyncOpsBatchTooLargeRejected`,
|
|
||||||
`TestDevicesMarkUserUnknownDevice`, `TestIssueWithExpiryMatchesTokenExp`.
|
|
||||||
|
|
||||||
- **#8 fuite `writeError`** : défaut `500` → message générique `"internal error"`
|
|
||||||
+ `log.Printf` serveur (`handlers/store.go:20-33`). Plus aucun `err.Error()`
|
|
||||||
brut vers le client (sync déjà générique, `response.go` déjà enveloppe).
|
|
||||||
- **A7 `ExpiresAt`** : `pkg/auth.IssueWithExpiry` retourne le `exp` embarqué ;
|
|
||||||
`AuthLogin` l'expose tel quel (plus de `Now()+TTL` recalculé). `Issue`
|
|
||||||
conservée (délègue) → 0 appelant cassé. Test d'égalité à la seconde
|
|
||||||
(le token sérialise sans monotonique/sous-seconde).
|
|
||||||
- **`MarkUser`** : `RowsAffected == 0 → ErrNotFound`
|
|
||||||
(`repository/devices.go:36-42`) ; login mappe en **401 indistinguable**
|
|
||||||
(jamais de token pour device fantôme). Test repo ajouté.
|
|
||||||
- **`TouchOwned` migré** : les 4 `TouchResource` des paths share/revoke/link
|
|
||||||
→ `TouchOwned(ownerID, …)` (tous précédés de `ExistsOwner`). `UpdateNameByID`
|
|
||||||
**conservé volontairement** pour `update_metadata` (un editor non-owner peut
|
|
||||||
renommer — `UpdateNameOwned` rejetterait à tort ; garde d'accès juste avant
|
|
||||||
l'écriture). Commentaires `Deprecated`/inter-lots mis à jour.
|
|
||||||
- **Test cycle** : `TestApplyBatchMoveIntoDescendantRejected` (parent→enfant →
|
|
||||||
`INVALID_REQUEST`, parent toujours à la racine). Point 3 des risques soldé
|
|
||||||
côté cycle.
|
|
||||||
- **Rate-limit `POST /devices`** : 300/min/IP → 429 `RATE_LIMITED` + hook
|
|
||||||
`OnDevicesRateLimited` + `ResetDevicesRateLimit` (placé APRÈS validation :
|
|
||||||
l'invalide ne consomme pas le budget). Resets ajoutés aux helpers de test
|
|
||||||
(`files_test.go setup`, `auth_test.go setTestAuth`, `ocr_test.go setupOcr` —
|
|
||||||
ce dernier manquait et faisait échouer `TestOcrJobsScopedByOwner` en 429,
|
|
||||||
corrigé). Budget large assumé : anti-flood massif, WAF frontal en prod.
|
|
||||||
- **Cap `POST /sync/ops`** : `MaxBytesReader` 1 MiB + max 100 ops/batch → 400
|
|
||||||
`INVALID_REQUEST` (client = 20, test 25 ops existant compatible).
|
|
||||||
Test `TestSyncOpsBatchTooLargeRejected` (101 ops → 400).
|
|
||||||
|
|
||||||
### Reste assumé (inchangé, documenté)
|
|
||||||
- `EnforceDeviceExists` défaut `false` ; `NewID()` panic conservé
|
|
||||||
(`NewIDErr` dispo) ; double pool `main.go` (migrate-avant-open, un seul
|
|
||||||
vivant) ; vraie Tx `ApplyBatch` reportée (idempotence couvre la fenêtre).
|
|
||||||
|
|||||||
@@ -1,137 +0,0 @@
|
|||||||
# Découpage parallèle — Backend Kazier
|
|
||||||
|
|
||||||
Source : `FEEDBACK.md` (12 + A1-A16). But : 6 lots preneurs en parallèle, **zéro chevauchement de fichiers**.
|
|
||||||
Règle : chaque lot ne touche QUE ses fichiers. Si besoin transverse → note dans `Besoins inter-lots`, ne pas éditer hors lot.
|
|
||||||
|
|
||||||
Commande vérif par lot : `cd backend && go test ./...` (ou package ciblé). DB tests : `TEST_DATABASE_URL` si PG dispo, sinon skip OK.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## LOT 1 — AUTH critique (A1, #4, #12, A15-part)
|
|
||||||
**Fichiers exclusifs :**
|
|
||||||
- `backend/pkg/passwd/passwd.go`
|
|
||||||
- `backend/pkg/auth/auth.go`
|
|
||||||
- `backend/config/config.go`
|
|
||||||
- `backend/handlers/auth.go`
|
|
||||||
- `backend/handlers/middleware.go`
|
|
||||||
|
|
||||||
**Tâches :**
|
|
||||||
1. A1 : `dummyHash` aléatoire par boot (plus de `"kazier-constantime-dummy"` en dur). `AuthLogin` : early-return si `userErr != nil`, ne jamais toucher `user.ID` quand nil. Ajouter test : login user inconnu + password dummy → 401, pas 500.
|
|
||||||
2. #4 : `AUTH_SECRET` : refuser défaut `dev-secret-change-me` en prod (ex. `if ENV=prod && secret==défaut → Fatal`), exiger longueur ≥ 32, doc `.env.example`.
|
|
||||||
3. #12 : casser l'oracle : même code/délai que device existe ou non (vérifier device AVANT ou uniformiser 401). Ajouter rate-limit basique ou hook (même no-op + TODO).
|
|
||||||
4. A15-part : `Verify` : rejeter `userID/deviceID` non `^[0-9a-f]{32}$`. Middleware : option `EnforceDeviceExists` (défaut off, documenté) ou au moins log.
|
|
||||||
|
|
||||||
**Ne pas toucher :** `handlers/devices.go` (LOT 6), `repository/*` (LOT 4).
|
|
||||||
|
|
||||||
**Acceptance :** `go test ./pkg/passwd/... ./pkg/auth/... ./handlers/...` OK + test regression A1.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## LOT 2 — UPLOAD safe (A2, A3, A4, #5, #6, A16-part)
|
|
||||||
**Fichiers exclusifs :**
|
|
||||||
- `backend/service/resources.go`
|
|
||||||
- `backend/handlers/files.go`
|
|
||||||
|
|
||||||
**Tâches :**
|
|
||||||
1. #5 : sanit `extension` : `[a-z0-9]{1,10}` lowercase, sinon `""` ou `bin`. `destPath` sans `ext` si vide (pas de `id.`). Rejeter `/`, `..`, très long.
|
|
||||||
2. A2 : service : `io.LimitReader(src, MaxFileSize+1)` + vérifier octets écrits, retourner `ErrFileTooLarge` même si header ment.
|
|
||||||
3. A3 : écriture atomique : temp `destDir/.tmp-<id>` + `Fsync` + `Rename`. Pas d'overwrite direct.
|
|
||||||
4. #6 : au `UpdatePhysical` : lister `Glob(id.*)` ancien, `Remove` les autres ext. Sur `Insert` fail → `Remove(destPath)`. Sur `GetFile` fail après insert → tenter cleanup, au moins log.
|
|
||||||
5. A4 : `MkdirAll 0700`, fichier `0600` (`OpenFile` + `Chmod`). Vérifier umask.
|
|
||||||
6. A16-part : `file.Filename` → `name` : `TrimSpace`, cap 255, rejeter vide/`/`/`\n`. `Content-Type` : whitelist ou fallback `application/octet-stream`. `intParam/page/pageSize` : cap + 400 si négatif (pas fallback silencieux), `q` : `MaxLen 200`.
|
|
||||||
|
|
||||||
**Acceptance :** tests service upload : header menteur, ext vide/malicieuse, re-upload change ext → un seul fichier physique, perms 0600/0700.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## LOT 3 — SYNC core (#3, #7, A8, A9)
|
|
||||||
**Fichiers exclusifs :**
|
|
||||||
- `backend/service/sync.go`
|
|
||||||
- `backend/repository/operations.go`
|
|
||||||
- `backend/repository/shares.go`
|
|
||||||
|
|
||||||
**Tâches :**
|
|
||||||
1. #7 : rendre `ApplyBatch` atomique par op : `SELECT ... FOR UPDATE` ou transaction `Applied→apply→Record`. `Record` fail → retourner `applied:i` explicite, pas 500 nu.
|
|
||||||
2. #3 : `CreateLink` idempotent : `ON CONFLICT (id) DO NOTHING` + vérifier owner identique, sinon `NAME_CONFLICT`.
|
|
||||||
3. A9 : stocker `payload_hash (sha256)` dans `operations`, au replay même `(device,op)` comparer hash : différent → `INVALID_REQUEST` (pas skip silencieux). Migration `000011`.
|
|
||||||
4. A8 : uniformiser sémantiques : `update_metadata` absent → `NOT_FOUND` halt (pas no-op applied) ; `move/delete` non-owned → `NOT_FOUND` (pas applied silencieux) ; documenter choix. `create` : `ExistsOwner` + `Insert` en transaction ou `ON CONFLICT DO NOTHING` + check owner.
|
|
||||||
5. `classifySyncError` : ne plus fuir `err.Error()` brut (#8-part) : messages génériques + log interne.
|
|
||||||
|
|
||||||
**Ne pas toucher :** `repository/resources.go` (LOT 4) — si besoin, exposer interface, pas d'édit direct.
|
|
||||||
|
|
||||||
**Acceptance :** tests `service/sync_test.go` : replay même op, replay payload muté, create_link rejoué, move/delete grantee.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## LOT 4 — DATA ownership + migrations (#9, #10, A10, + parent-check)
|
|
||||||
**Fichiers exclusifs :**
|
|
||||||
- `backend/repository/users.go`
|
|
||||||
- `backend/repository/resources.go`
|
|
||||||
- `backend/repository/devices.go`
|
|
||||||
- `backend/service/bootstrap.go`
|
|
||||||
- `backend/db/migrations/*`
|
|
||||||
- `backend/db/db.go` (lecture seule sauf si besoin migration)
|
|
||||||
|
|
||||||
**Tâches :**
|
|
||||||
1. #9+A10 : `Count()` → `WHERE deleted_at IS NULL`. `UpdatePassword/MarkDeleted/GetByID` : ajouter `AND deleted_at IS NULL` + check `RowsAffected` → `ErrNotFound` si 0.
|
|
||||||
2. #10 : `000007` : supprimer `DELETE FROM resources` (backfill `owner_id` via user admin ou colonne nullable + migration douce). `000008 down` : down sans `::bigint` (ex. recréer colonne bigint + drop text, ou marquer irréversible avec message clair).
|
|
||||||
3. Parent-check atomique : `InsertFolder/InsertFile/MoveResource` : `INSERT ... SELECT` ou transaction `SELECT parent FOR SHARE → INSERT`, FK 500 → mapper `NOT_FOUND`.
|
|
||||||
4. `TouchResource/UpdateNameByID` : ajouter variantes scopées `TouchOwned(ownerID,...)`, `UpdateNameOwned(...)`, laisser anciennes en `deprecated` (LOT 3 migrera ensuite).
|
|
||||||
5. `NewID()` (A5) : retourner `(string,error)` OU `MustNewID` + `NewIDErr`. Choisir une signature, mettre à jour appelants **uniquement dans ces fichiers**.
|
|
||||||
|
|
||||||
**Acceptance :** `go test ./repository/... ./service/... ./db/...` + test soft-deleted login/bootstrap.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## LOT 5 — OCR + INFRA (A11, A12-part, A13, A14, #11)
|
|
||||||
**Fichiers exclusifs :**
|
|
||||||
- `backend/service/ocr.go`
|
|
||||||
- `backend/repository/ocr_jobs.go`
|
|
||||||
- `backend/ocr/*`
|
|
||||||
- `backend/cmd/server/main.go`
|
|
||||||
- `backend/service/services.go`, `move.go`, `upload.go`, `folders.go` (suppression)
|
|
||||||
|
|
||||||
**Tâches :**
|
|
||||||
1. #11 : supprimer les 4 stubs `UserCan*` toujours-true.
|
|
||||||
2. A11 : transitions gardées : `Complete/ Fail WHERE status='processing'`, `TouchProcessing WHERE status='queued'`, check `RowsAffected`. `ResetStaleProcessing` sur horloge DB (`now() - interval`), inclure `started_at IS NULL`. Ajouter index `(status,created_at)` (migration `000012` — coordonner nom avec LOT 4 pour éviter collision : LOT 5 prend `000012`, LOT 4 prend `000011`, LOT 3 payload_hash prend `000013`).
|
|
||||||
3. A13 : `Fail` avec `err`, `Complete` vérifie `UpdateOcrText RowsAffected`, sinon `Fail`. `tesseract.go` : `context.WithTimeout` par job (ex. 120s), `LimitReader` stdout/stderr (ex. 2MB), cap pages PDF (ex. 50) + erreur si tronqué, pas `continue` silencieux.
|
|
||||||
4. A12-part : `physicalPath` : `Lstat`, `IsRegular`, `EvalSymlinks` ∈ `UPLOAD_DIR`. `OCR_LANG` : whitelist `^[a-z+]{2,20}$`.
|
|
||||||
5. A14 : `main.go` : un seul pool (réutiliser `conn` pour migrate), `defer conn.Close()`, worker OCR avec `WaitGroup` + shutdown 5s documenté. Bootstrap : retry duplicate `username_normalized` ou `ON CONFLICT DO NOTHING`.
|
|
||||||
|
|
||||||
**Acceptance :** `go test ./ocr/... ./service/... ./repository/...` + test double-complete, stale requeue.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## LOT 6 — CONTRACT + DEVICE (A6, A7, §1 route, devices, secret-doc)
|
|
||||||
**Fichiers exclusifs :**
|
|
||||||
- `backend/handlers/router.go`
|
|
||||||
- `backend/handlers/share_links.go`
|
|
||||||
- `backend/handlers/sync.go`
|
|
||||||
- `backend/handlers/devices.go`
|
|
||||||
- `backend/handlers/health.go` (tests seulement si besoin)
|
|
||||||
- `backend/cmd/server/router_test.go`
|
|
||||||
- `backend/pkg/api/response.go` (messages génériques seulement)
|
|
||||||
|
|
||||||
**Tâches :**
|
|
||||||
1. §1 : réordonner `GET /files/folders` avant `GET /files/:id` + test `folders→200`, `:id=folders→404` (verrouille, même si Gin priorise statique).
|
|
||||||
2. A6 : `ShareLinkGet` : `errors.Is(err, ErrNotFound)`.
|
|
||||||
3. A7 : `ExpiresAt` : utiliser `exp` du token (retourner `Auth` ou parser), pas `Now()+TTL`. `TOKEN_ERROR` → `INTERNAL`. 32-hex malformé → `400 INVALID_REQUEST` partout (aligner `files.go` sur `devices.go`). `intParam/after` : 400 si garbage/négatif (pas fallback 0), `Atoi` 64-bit pour epoch-ms. `Bearer` : accepter `bearer` case-insensitive (option).
|
|
||||||
4. Devices : `POST /devices` : rate-limit/TODO + doc. `MarkUser` : check `RowsAffected` (device supprimé → 404).
|
|
||||||
5. `response.go` : messages génériques côté client, détail en log serveur (#8-part lot 6).
|
|
||||||
|
|
||||||
**Acceptance :** `router_test.go` étendu + tests handlers 400/404 cohérents.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Ordre et dépendances
|
|
||||||
|
|
||||||
- Démarrage immédiat possible : LOT 1, LOT 2, LOT 5, LOT 6 (aucune dépendance mutuelle).
|
|
||||||
- LOT 3 et LOT 4 se touchent via `repository/resources.go` : LOT 4 seul l'édite. LOT 3 utilise l'interface existante, migrera vers `*Owned` au tour suivant.
|
|
||||||
- Migrations : LOT 4 = `000011`, LOT 5 = `000012`, LOT 3 = `000013`. Ne pas réutiliser un numéro.
|
|
||||||
- `NewID()` signature (LOT 4) : prévenir LOT 2/LOT 3 après merge, pas avant.
|
|
||||||
|
|
||||||
## Besoins inter-lots (ne pas éditer, juste signaler)
|
|
||||||
|
|
||||||
- LOT 3 → LOT 4 : besoin `TouchOwned/UpdateNameOwned`, `INSERT ... SELECT` parent.
|
|
||||||
- LOT 5 → LOT 2 : `physicalPath` safe partagé après merge LOT 2.
|
|
||||||
- Tous → LOT 6 : après uniformisation 400/404, aligner messages d'erreur.
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Déploiement perso — pull l'image depuis le registre Gitea (pas de build local).
|
||||||
|
#
|
||||||
|
# Usage sur le serveur :
|
||||||
|
# 1. cp .env.prod.example .env.prod && adapter (mots de passe forts, jamais commité)
|
||||||
|
# 2. echo "<PAT read:package>" | docker login gitea.thirdshop.fr -u <user> --password-stdin
|
||||||
|
# 3. docker compose -f docker-compose.prod.yml --env-file .env.prod pull
|
||||||
|
# 4. docker compose -f docker-compose.prod.yml --env-file .env.prod up -d
|
||||||
|
# 5. curl http://localhost:${PORT:-8080}/api/v1/health
|
||||||
|
#
|
||||||
|
# MAJ : répéter pull + up -d (ou tag précis via VERSION=x.y.z).
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-kazier}
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-kazier}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD requis (.env.prod)}
|
||||||
|
volumes:
|
||||||
|
- postgres-data:/var/lib/postgresql/data
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-kazier}"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
backend:
|
||||||
|
# Image publiée par la release Gitea (tag vX.Y.Z + latest).
|
||||||
|
image: ${REGISTRY_IMAGE:-gitea.thirdshop.fr/thirdshop/kazier}:${VERSION:-latest}
|
||||||
|
ports:
|
||||||
|
- "${PORT:-8080}:8080"
|
||||||
|
environment:
|
||||||
|
PORT: 8080
|
||||||
|
DATABASE_URL: postgres://${POSTGRES_USER:-kazier}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD requis}@postgres:5432/${POSTGRES_DB:-kazier}?sslmode=disable
|
||||||
|
UPLOAD_DIR: /app/uploads
|
||||||
|
MAX_FILE_SIZE_MB: ${MAX_FILE_SIZE_MB:-50}
|
||||||
|
OCR_LANG: ${OCR_LANG:-fra+eng}
|
||||||
|
AUTH_SECRET: ${AUTH_SECRET:?AUTH_SECRET requis (.env.prod)}
|
||||||
|
ADMIN_USERNAME: ${ADMIN_USERNAME:?ADMIN_USERNAME requis au premier démarrage}
|
||||||
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD requis au premier démarrage}
|
||||||
|
volumes:
|
||||||
|
- backend-uploads:/app/uploads
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres-data:
|
||||||
|
backend-uploads:
|
||||||
@@ -24,12 +24,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
|
|
||||||
lifecycleScope.launch { themePreferenceStore.load() }
|
// m37 : le contenu n'est posé qu'une fois le thème persisté chargé —
|
||||||
|
// avant, le défaut SYSTEM flashait aux premières frames.
|
||||||
setContent {
|
lifecycleScope.launch {
|
||||||
val theme by themePreferenceStore.theme.collectAsStateWithLifecycle()
|
themePreferenceStore.load()
|
||||||
KazierTheme(theme = theme) {
|
setContent {
|
||||||
KazierApp()
|
val theme by themePreferenceStore.theme.collectAsStateWithLifecycle()
|
||||||
|
KazierTheme(theme = theme) {
|
||||||
|
KazierApp()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,16 +15,20 @@ import javax.inject.Singleton
|
|||||||
* Persistance chiffrée du token paseto et du profil compte (Keystore + AES).
|
* Persistance chiffrée du token paseto et du profil compte (Keystore + AES).
|
||||||
* Miroir de `services/secureStore.ts` (expo-secure-store). Le token n'est
|
* Miroir de `services/secureStore.ts` (expo-secure-store). Le token n'est
|
||||||
* JAMAIS écrit en clair dans SQLite.
|
* JAMAIS écrit en clair dans SQLite.
|
||||||
|
*
|
||||||
|
* L'init Keystore/`EncryptedSharedPreferences` est paresseuse (m28) : aucun
|
||||||
|
* I/O au construct Hilt — le premier accès a lieu sur le thread de l'appelant
|
||||||
|
* ([SessionManager] bascule sur `Dispatchers.IO`).
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class SecureTokenStore @Inject constructor(
|
class SecureTokenStore @Inject constructor(
|
||||||
@ApplicationContext context: Context,
|
@ApplicationContext private val context: Context,
|
||||||
moshi: Moshi,
|
moshi: Moshi,
|
||||||
) {
|
) : TokenStore {
|
||||||
|
|
||||||
private val userAdapter: JsonAdapter<UserDto> = moshi.adapter(UserDto::class.java)
|
private val userAdapter: JsonAdapter<UserDto> = moshi.adapter(UserDto::class.java)
|
||||||
|
|
||||||
private val prefs: SharedPreferences = run {
|
private val prefs: SharedPreferences by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
|
||||||
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
|
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
|
||||||
EncryptedSharedPreferences.create(
|
EncryptedSharedPreferences.create(
|
||||||
FILE_NAME,
|
FILE_NAME,
|
||||||
@@ -35,29 +39,36 @@ class SecureTokenStore @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getToken(): String? = prefs.getString(KEY_TOKEN, null)
|
override fun getToken(): String? = prefs.getString(KEY_TOKEN, null)
|
||||||
|
|
||||||
fun getUser(): UserDto? {
|
override fun getUser(): UserDto? {
|
||||||
val raw = prefs.getString(KEY_ACCOUNT, null) ?: return null
|
val raw = prefs.getString(KEY_ACCOUNT, null) ?: return null
|
||||||
return runCatching { userAdapter.fromJson(raw) }
|
return runCatching { userAdapter.fromJson(raw) }
|
||||||
.getOrNull()
|
.getOrNull()
|
||||||
?.takeIf { it.id.isNotEmpty() && it.username.isNotEmpty() }
|
?.takeIf { it.id.isNotEmpty() && it.username.isNotEmpty() }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun save(token: String, user: UserDto) {
|
override fun getExpiresAt(): Long? =
|
||||||
|
prefs.getLong(KEY_EXPIRES_AT, -1L).takeIf { it >= 0L }
|
||||||
|
|
||||||
|
override fun save(token: String, user: UserDto, expiresAt: Long?) {
|
||||||
prefs.edit()
|
prefs.edit()
|
||||||
.putString(KEY_TOKEN, token)
|
.putString(KEY_TOKEN, token)
|
||||||
.putString(KEY_ACCOUNT, userAdapter.toJson(user))
|
.putString(KEY_ACCOUNT, userAdapter.toJson(user))
|
||||||
|
.apply {
|
||||||
|
if (expiresAt != null) putLong(KEY_EXPIRES_AT, expiresAt) else remove(KEY_EXPIRES_AT)
|
||||||
|
}
|
||||||
.apply()
|
.apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clear() {
|
override fun clear() {
|
||||||
prefs.edit().remove(KEY_TOKEN).remove(KEY_ACCOUNT).apply()
|
prefs.edit().remove(KEY_TOKEN).remove(KEY_ACCOUNT).remove(KEY_EXPIRES_AT).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val FILE_NAME = "kazier_secure"
|
private const val FILE_NAME = "kazier_secure"
|
||||||
private const val KEY_TOKEN = "kazier.auth_token"
|
private const val KEY_TOKEN = "kazier.auth_token"
|
||||||
private const val KEY_ACCOUNT = "kazier.account"
|
private const val KEY_ACCOUNT = "kazier.account"
|
||||||
|
private const val KEY_EXPIRES_AT = "kazier.expires_at"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,48 +1,105 @@
|
|||||||
package com.kazier.mobile.auth
|
package com.kazier.mobile.auth
|
||||||
|
|
||||||
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
import com.kazier.mobile.data.remote.dto.UserDto
|
||||||
import com.kazier.mobile.domain.ActiveUserStore
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
|
||||||
import com.kazier.mobile.domain.LocalModeStore
|
import com.kazier.mobile.domain.LocalModeStore
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Orchestration de la session (restauration/sauvegarde/purge) : relie le store
|
* Orchestration de la session (restauration/sauvegarde/purge) : relie le store
|
||||||
* sécurisé, le miroir `active_user_id` et le token en mémoire lu par
|
* sécurisé, le miroir `active_user_id` et le token en mémoire lu par
|
||||||
* `AuthInterceptor`. Le drapeau « mode local » est persisté à part
|
* `AuthInterceptor`. Le drapeau « mode local » est persisté à part
|
||||||
* ([LocalModeStore]) pour survivre aux redémarrages.
|
* ([LocalModeStore]) pour survivre aux redémarrages.
|
||||||
|
*
|
||||||
|
* Le callback 401 est possédé ici (singleton, M25) — jamais par un ViewModel :
|
||||||
|
* après `onCleared`, un token expiré/révoqué continue de purger la session
|
||||||
|
* (le worker cesse alors de rejouer l'outbox sous un token mort).
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class SessionManager @Inject constructor(
|
class SessionManager @Inject constructor(
|
||||||
private val secureTokenStore: SecureTokenStore,
|
private val tokenStore: TokenStore,
|
||||||
private val activeUserStore: ActiveUserStore,
|
private val activeUserStore: ActiveUserStore,
|
||||||
private val tokenProvider: TokenProvider,
|
private val tokenProvider: TokenProvider,
|
||||||
private val localModeStore: LocalModeStore,
|
private val localModeStore: LocalModeStore,
|
||||||
|
private val pendingOperationDao: PendingOperationDao,
|
||||||
|
private val apiClient: ApiClient,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
|
||||||
|
init {
|
||||||
|
// 401 sur un endpoint protégé (token expiré/révoqué, compte supprimé)
|
||||||
|
// → purge de la session. Le 401 du login et des routes publiques est
|
||||||
|
// exonéré côté ApiClient (skipUnauthorizedHandling).
|
||||||
|
apiClient.onUnauthorized = { handleUnauthorized() }
|
||||||
|
}
|
||||||
|
|
||||||
/** Restaure la session persistée (si présente), sinon null. */
|
/** Restaure la session persistée (si présente), sinon null. */
|
||||||
suspend fun restore(): AuthSession? {
|
suspend fun restore(): AuthSession? = withContext(Dispatchers.IO) {
|
||||||
val token = secureTokenStore.getToken() ?: return null
|
val token = tokenStore.getToken() ?: return@withContext null
|
||||||
val user = secureTokenStore.getUser() ?: return null
|
val user = tokenStore.getUser() ?: return@withContext null
|
||||||
tokenProvider.current = token
|
tokenProvider.current = token
|
||||||
return AuthSession(token = token, user = user)
|
AuthSession(token = token, user = user, expiresAt = tokenStore.getExpiresAt())
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun save(token: String, user: com.kazier.mobile.data.remote.dto.UserDto) {
|
suspend fun save(token: String, user: UserDto, expiresAt: Long? = null) =
|
||||||
secureTokenStore.save(token, user)
|
withContext(Dispatchers.IO) {
|
||||||
activeUserStore.set(user.id)
|
val previousUserId = activeUserStore.get()
|
||||||
localModeStore.clear()
|
tokenStore.save(token, user, expiresAt)
|
||||||
tokenProvider.current = token
|
activeUserStore.set(user.id)
|
||||||
}
|
localModeStore.clear()
|
||||||
|
tokenProvider.current = token
|
||||||
|
// Changement de compte sans sign-out explicite (login de B par
|
||||||
|
// dessus la session de A) : même purge que `clear()` — la file de
|
||||||
|
// A ne doit pas partir sous le token de B. Premier login
|
||||||
|
// (`previousUserId == null`, éventuel travail du mode local) et
|
||||||
|
// re-login du même compte : file conservée.
|
||||||
|
if (previousUserId != null && previousUserId != user.id) {
|
||||||
|
pendingOperationDao.deleteUnpushed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun clear() {
|
suspend fun clear() = withContext(Dispatchers.IO) {
|
||||||
secureTokenStore.clear()
|
tokenStore.clear()
|
||||||
activeUserStore.clear()
|
activeUserStore.clear()
|
||||||
tokenProvider.current = null
|
tokenProvider.current = null
|
||||||
|
// Sign-out explicite : la file non poussée est abandonnée (C5, voir
|
||||||
|
// `deleteUnpushed`). Les ops `synced` survivent comme tombstones.
|
||||||
|
pendingOperationDao.deleteUnpushed()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Purge fire-and-forget sur 401 (appelée depuis le thread OkHttp via
|
||||||
|
* `ApiClient`) : le token en mémoire tombe synchronement pour ne plus
|
||||||
|
* émettre de requêtes authentifiées, la persistance suit en IO.
|
||||||
|
*/
|
||||||
|
fun handleUnauthorized() {
|
||||||
|
tokenProvider.current = null
|
||||||
|
scope.launch {
|
||||||
|
runCatching { tokenStore.clear() }
|
||||||
|
runCatching { activeUserStore.clear() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pré-relogin : vrai si l'`expires_at` persistée du login est atteinte
|
||||||
|
* (marge anti-course d'1 min par défaut). L'appelant peut alors reloginer
|
||||||
|
* avant de subir le 401 brutal (tokens 7 j, m27).
|
||||||
|
*/
|
||||||
|
suspend fun isTokenExpired(nowMs: Long = System.currentTimeMillis(), marginMs: Long = 60_000L): Boolean =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
val expiresAt = tokenStore.getExpiresAt() ?: return@withContext false
|
||||||
|
nowMs + marginMs >= expiresAt
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun isLocalMode(): Boolean = localModeStore.get()
|
suspend fun isLocalMode(): Boolean = localModeStore.get()
|
||||||
|
|
||||||
suspend fun setLocalMode() = localModeStore.set()
|
suspend fun setLocalMode() = localModeStore.set()
|
||||||
@@ -52,5 +109,7 @@ class SessionManager @Inject constructor(
|
|||||||
|
|
||||||
data class AuthSession(
|
data class AuthSession(
|
||||||
val token: String,
|
val token: String,
|
||||||
val user: com.kazier.mobile.data.remote.dto.UserDto,
|
val user: UserDto,
|
||||||
)
|
/** Expiration persistée du token (ms epoch) — null si inconnue. */
|
||||||
|
val expiresAt: Long? = null,
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.kazier.mobile.auth
|
||||||
|
|
||||||
|
import com.kazier.mobile.data.remote.dto.UserDto
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persistance du token paseto, du profil compte et de l'expiration du token
|
||||||
|
* (claim `expires_at` du login, TTL 7 j). Implémentation : [SecureTokenStore]
|
||||||
|
* (Keystore + AES, jamais en clair dans SQLite).
|
||||||
|
*/
|
||||||
|
interface TokenStore {
|
||||||
|
|
||||||
|
fun getToken(): String?
|
||||||
|
|
||||||
|
fun getUser(): UserDto?
|
||||||
|
|
||||||
|
/** Expiration du token (ms epoch, `expires_at` du login) — null si inconnue. */
|
||||||
|
fun getExpiresAt(): Long?
|
||||||
|
|
||||||
|
fun save(token: String, user: UserDto, expiresAt: Long?)
|
||||||
|
|
||||||
|
fun clear()
|
||||||
|
}
|
||||||
@@ -23,13 +23,17 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
|||||||
* v10: ocr_text sur files (extrait OCR serveur persisté localement) ;
|
* v10: ocr_text sur files (extrait OCR serveur persisté localement) ;
|
||||||
* v11: ocr_attempts + ocr_queued_at sur files (driver OCR auto côté client —
|
* v11: ocr_attempts + ocr_queued_at sur files (driver OCR auto côté client —
|
||||||
* compteur d'échecs terminaux ≤ 3, marqueur « en cours » de l'upload).
|
* compteur d'échecs terminaux ≤ 3, marqueur « en cours » de l'upload).
|
||||||
|
* v12: device_id sur pending_operations + unicité UNIQUE(device_id,
|
||||||
|
* operation_id) (contrat outbox docs/api-v1.md §6.1).
|
||||||
|
* v13: index composites files(exists, processed, sync_status) et
|
||||||
|
* pending_operations(resource_id, operation, status) (requêtes review/OCR/gates).
|
||||||
*/
|
*/
|
||||||
@Database(
|
@Database(
|
||||||
entities = [
|
entities = [
|
||||||
FolderEntity::class, UserPreferenceEntity::class, FileEntity::class,
|
FolderEntity::class, UserPreferenceEntity::class, FileEntity::class,
|
||||||
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
|
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
|
||||||
],
|
],
|
||||||
version = 11,
|
version = 14,
|
||||||
exportSchema = false,
|
exportSchema = false,
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
|
|||||||
@@ -4,8 +4,11 @@ import com.kazier.mobile.data.local.entity.FileEntity
|
|||||||
|
|
||||||
/** Date de référence d'un fichier : modification SAF quand dispo, sinon ajout local. */
|
/** Date de référence d'un fichier : modification SAF quand dispo, sinon ajout local. */
|
||||||
val FileEntity.referenceDate: Long
|
val FileEntity.referenceDate: Long
|
||||||
get() = lastModified ?: addedAt
|
get() {
|
||||||
|
val modified = lastModified
|
||||||
|
return if (modified != null && modified > 0L) modified else addedAt
|
||||||
|
}
|
||||||
|
|
||||||
/** Tri documents : même ordre que la grille d'accueil, du plus récent au plus vieux. */
|
/** Tri documents : même ordre que la grille d'accueil, du plus récent au plus vieux. */
|
||||||
fun List<FileEntity>.orderedByReferenceDateDesc(): List<FileEntity> =
|
fun List<FileEntity>.orderedByReferenceDateDesc(): List<FileEntity> =
|
||||||
sortedByDescending { it.referenceDate }
|
sortedWith(compareByDescending<FileEntity> { it.referenceDate }.thenBy { it.name })
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
package com.kazier.mobile.data.local.dao
|
package com.kazier.mobile.data.local.dao
|
||||||
|
|
||||||
import androidx.room.Dao
|
import androidx.room.Dao
|
||||||
|
import androidx.room.Insert
|
||||||
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
|
import androidx.room.Update
|
||||||
import androidx.room.Upsert
|
import androidx.room.Upsert
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -12,6 +15,15 @@ interface FileDao {
|
|||||||
@Query("SELECT * FROM files ORDER BY name ASC")
|
@Query("SELECT * FROM files ORDER BY name ASC")
|
||||||
suspend fun getAll(): List<FileEntity>
|
suspend fun getAll(): List<FileEntity>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repasse C4 : lignes déjà journalisées (`exists = 0`) dont les octets
|
||||||
|
* sont peut-être encore sur le disque (journal-first, crash ou refus SAF
|
||||||
|
* entre la transaction et la suppression physique). Borné pour ne jamais
|
||||||
|
* bloquer un tick de sync.
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM files WHERE \"exists\" = 0 AND uri IS NOT NULL ORDER BY updated_at ASC LIMIT :limit")
|
||||||
|
suspend fun getMissingWithUri(limit: Int): List<FileEntity>
|
||||||
|
|
||||||
@Query("SELECT * FROM files WHERE folder_resource_id = :folderResourceId AND \"exists\" = 1 ORDER BY name ASC")
|
@Query("SELECT * FROM files WHERE folder_resource_id = :folderResourceId AND \"exists\" = 1 ORDER BY name ASC")
|
||||||
fun observeByFolder(folderResourceId: String): Flow<List<FileEntity>>
|
fun observeByFolder(folderResourceId: String): Flow<List<FileEntity>>
|
||||||
|
|
||||||
@@ -48,6 +60,19 @@ interface FileDao {
|
|||||||
@Upsert
|
@Upsert
|
||||||
suspend fun upsert(file: FileEntity)
|
suspend fun upsert(file: FileEntity)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert sans écrasement, résolu sur TOUTES les contraintes uniques
|
||||||
|
* (`resource_id`, `uri`) — pas seulement la PK. Retourne le rowId, ou -1
|
||||||
|
* si une ligne existe déjà : le repository relit alors le gagnant et
|
||||||
|
* applique [update]. Deux walks/refresh concurrents ne lèvent jamais
|
||||||
|
* `SQLiteConstraintException`.
|
||||||
|
*/
|
||||||
|
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
||||||
|
suspend fun insertIgnore(file: FileEntity): Long
|
||||||
|
|
||||||
|
@Update
|
||||||
|
suspend fun update(file: FileEntity)
|
||||||
|
|
||||||
@Query("UPDATE files SET \"exists\" = 0, updated_at = :updatedAt WHERE resource_id = :resourceId")
|
@Query("UPDATE files SET \"exists\" = 0, updated_at = :updatedAt WHERE resource_id = :resourceId")
|
||||||
suspend fun markMissing(resourceId: String, updatedAt: Long)
|
suspend fun markMissing(resourceId: String, updatedAt: Long)
|
||||||
|
|
||||||
@@ -86,8 +111,8 @@ interface FileDao {
|
|||||||
@Query("UPDATE files SET folder_resource_id = :folderId, updated_at = :updatedAt WHERE resource_id IN (:resourceIds)")
|
@Query("UPDATE files SET folder_resource_id = :folderId, updated_at = :updatedAt WHERE resource_id IN (:resourceIds)")
|
||||||
suspend fun moveToFolder(resourceIds: List<String>, folderId: String, updatedAt: Long)
|
suspend fun moveToFolder(resourceIds: List<String>, folderId: String, updatedAt: Long)
|
||||||
|
|
||||||
@Query("UPDATE files SET uri = :uri WHERE resource_id = :resourceId")
|
@Query("UPDATE files SET uri = :uri, updated_at = :updatedAt WHERE resource_id = :resourceId")
|
||||||
suspend fun updateUri(resourceId: String, uri: String?)
|
suspend fun updateUri(resourceId: String, uri: String?, updatedAt: Long)
|
||||||
|
|
||||||
@Query("DELETE FROM files WHERE resource_id = :resourceId")
|
@Query("DELETE FROM files WHERE resource_id = :resourceId")
|
||||||
suspend fun remove(resourceId: String)
|
suspend fun remove(resourceId: String)
|
||||||
@@ -129,7 +154,10 @@ interface FileDao {
|
|||||||
|
|
||||||
/** Candidate OCR auto : fichier `processed`, `local-cloud`, avec copie
|
/** Candidate OCR auto : fichier `processed`, `local-cloud`, avec copie
|
||||||
* locale, format potentiellement extractible, jamais extrait, pas en cours
|
* locale, format potentiellement extractible, jamais extrait, pas en cours
|
||||||
* et pas épuisé (< 3 échecs terminaux). Trié par dernier upload. */
|
* et pas épuisé (< 3 échecs terminaux). Trié par dernier upload.
|
||||||
|
*
|
||||||
|
* Les lignes pré-v4 sans `category` (NULL) restent éligibles sur la base
|
||||||
|
* de leur `mime_type`/`extension` (backfill logique, sans migration). */
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT * FROM files
|
SELECT * FROM files
|
||||||
WHERE "exists" = 1
|
WHERE "exists" = 1
|
||||||
@@ -139,7 +167,16 @@ interface FileDao {
|
|||||||
AND ocr_text IS NULL
|
AND ocr_text IS NULL
|
||||||
AND ocr_attempts < 3
|
AND ocr_attempts < 3
|
||||||
AND ocr_queued_at IS NULL
|
AND ocr_queued_at IS NULL
|
||||||
AND category IN ('PDF', 'IMAGE', 'TEXT')
|
AND (
|
||||||
|
category IN ('PDF', 'IMAGE', 'TEXT')
|
||||||
|
OR (category IS NULL AND (
|
||||||
|
mime_type = 'application/pdf'
|
||||||
|
OR mime_type LIKE 'image/%'
|
||||||
|
OR mime_type LIKE 'text/%'
|
||||||
|
OR extension IN ('pdf', 'png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp',
|
||||||
|
'txt', 'md', 'html', 'xml', 'json')
|
||||||
|
))
|
||||||
|
)
|
||||||
ORDER BY COALESCE(last_modified, added_at) DESC, name ASC
|
ORDER BY COALESCE(last_modified, added_at) DESC, name ASC
|
||||||
""")
|
""")
|
||||||
suspend fun getOcrAutoCandidates(): List<FileEntity>
|
suspend fun getOcrAutoCandidates(): List<FileEntity>
|
||||||
@@ -148,8 +185,10 @@ interface FileDao {
|
|||||||
@Query("UPDATE files SET ocr_queued_at = :queuedAt, updated_at = :now WHERE resource_id = :resourceId")
|
@Query("UPDATE files SET ocr_queued_at = :queuedAt, updated_at = :now WHERE resource_id = :resourceId")
|
||||||
suspend fun markOcrQueued(resourceId: String, queuedAt: Long, now: Long)
|
suspend fun markOcrQueued(resourceId: String, queuedAt: Long, now: Long)
|
||||||
|
|
||||||
/** Levé du marqueur + reset du compteur d'échecs (succès / erreur transitoire). */
|
/** Levé du marqueur « en cours » (succès / erreur transitoire). Le
|
||||||
@Query("UPDATE files SET ocr_queued_at = NULL, ocr_attempts = 0, updated_at = :now WHERE resource_id = :resourceId")
|
* compteur d'échecs est préservé : seul [markOcrFailure] l'incrémente,
|
||||||
|
* un succès durable passe par `updateOcrText` + `markOcrQueued` réarmé. */
|
||||||
|
@Query("UPDATE files SET ocr_queued_at = NULL, updated_at = :now WHERE resource_id = :resourceId")
|
||||||
suspend fun clearOcrQueued(resourceId: String, now: Long)
|
suspend fun clearOcrQueued(resourceId: String, now: Long)
|
||||||
|
|
||||||
/** Échec terminal : +1 tentative, marqueur levé (ne rejoue pas à l'infini). */
|
/** Échec terminal : +1 tentative, marqueur levé (ne rejoue pas à l'infini). */
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import androidx.room.Dao
|
|||||||
import androidx.room.Insert
|
import androidx.room.Insert
|
||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
|
import androidx.room.Update
|
||||||
import androidx.room.Upsert
|
import androidx.room.Upsert
|
||||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -17,6 +18,14 @@ interface FolderDao {
|
|||||||
@Query("SELECT * FROM folders ORDER BY name ASC")
|
@Query("SELECT * FROM folders ORDER BY name ASC")
|
||||||
suspend fun getAll(): List<FolderEntity>
|
suspend fun getAll(): List<FolderEntity>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repasse C4 (dossiers) : voir `FileDao.getMissingWithUri`. Un dossier
|
||||||
|
* n'est re-supprimé physiquement que si toute sa descendance Room est
|
||||||
|
* aussi `exists = 0` (jamais de suppression d'un arbre encore vivant).
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM folders WHERE \"exists\" = 0 AND uri IS NOT NULL ORDER BY updated_at ASC LIMIT :limit")
|
||||||
|
suspend fun getMissingWithUri(limit: Int): List<FolderEntity>
|
||||||
|
|
||||||
/** Dossiers créés dans l'app (`created_in_app = 1`) — cibles du picker de déplacement. */
|
/** Dossiers créés dans l'app (`created_in_app = 1`) — cibles du picker de déplacement. */
|
||||||
@Query("SELECT * FROM folders WHERE \"created_in_app\" = 1 ORDER BY name ASC")
|
@Query("SELECT * FROM folders WHERE \"created_in_app\" = 1 ORDER BY name ASC")
|
||||||
suspend fun getCreatedInApp(): List<FolderEntity>
|
suspend fun getCreatedInApp(): List<FolderEntity>
|
||||||
@@ -50,6 +59,19 @@ interface FolderDao {
|
|||||||
@Upsert
|
@Upsert
|
||||||
suspend fun upsert(folder: FolderEntity)
|
suspend fun upsert(folder: FolderEntity)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert sans écrasement, résolu sur TOUTES les contraintes uniques
|
||||||
|
* (`resource_id`, `uri`) — pas seulement la PK. Retourne le rowId, ou -1
|
||||||
|
* si une ligne existe déjà : le repository relit alors le gagnant et
|
||||||
|
* applique [update]. Deux walks concurrents ne lèvent jamais
|
||||||
|
* `SQLiteConstraintException`.
|
||||||
|
*/
|
||||||
|
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
||||||
|
suspend fun insertIgnore(folder: FolderEntity): Long
|
||||||
|
|
||||||
|
@Update
|
||||||
|
suspend fun update(folder: FolderEntity)
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun upsertAll(folders: List<FolderEntity>)
|
suspend fun upsertAll(folders: List<FolderEntity>)
|
||||||
|
|
||||||
|
|||||||
+109
-9
@@ -27,19 +27,48 @@ interface PendingOperationDao {
|
|||||||
@Query("UPDATE pending_operations SET status = 'synced', updated_at = :now WHERE id = :id")
|
@Query("UPDATE pending_operations SET status = 'synced', updated_at = :now WHERE id = :id")
|
||||||
suspend fun markSynced(id: Long, now: Long)
|
suspend fun markSynced(id: Long, now: Long)
|
||||||
|
|
||||||
/** Échec avec bump du compteur de tentatives (dead-letter après MAX_PENDING_ATTEMPTS). */
|
/**
|
||||||
|
* Échec définitif (dead-letter immédiate) ; `attempts` est un compteur
|
||||||
|
* diagnostic (bump), pas un seuil — il n'y a aucun `MAX_PENDING_ATTEMPTS` :
|
||||||
|
* une op `failed` n'est plus resélectionnée.
|
||||||
|
*/
|
||||||
@Query("UPDATE pending_operations SET status = 'failed', attempts = attempts + 1, updated_at = :now WHERE id = :id")
|
@Query("UPDATE pending_operations SET status = 'failed', attempts = attempts + 1, updated_at = :now WHERE id = :id")
|
||||||
suspend fun markFailed(id: Long, now: Long)
|
suspend fun markFailed(id: Long, now: Long)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Invalidation en cascade : un `create_resource` définitivement échoué rend
|
* Invalidation en cascade : un `create_resource` définitivement échoué rend
|
||||||
* fautives toutes les ops en attente qui ciblent la même ressource (filles).
|
* fautives toutes les ops en attente qui ciblent la même ressource, ainsi
|
||||||
|
* que les creates enfants (autre `resource_id`, liés via la colonne
|
||||||
|
* `parent_resource_id` — le walk émet parent avant enfant, cf. C6).
|
||||||
|
* Le repli `LIKE` sur le payload ne sert que les lignes pré-v14 sans
|
||||||
|
* colonne renseignée.
|
||||||
*/
|
*/
|
||||||
@Query("UPDATE pending_operations SET status = 'failed', updated_at = :now WHERE resource_id = :resourceId AND status = 'pending'")
|
@Query("""
|
||||||
|
UPDATE pending_operations SET status = 'failed', updated_at = :now
|
||||||
|
WHERE status = 'pending' AND (
|
||||||
|
resource_id = :resourceId
|
||||||
|
OR parent_resource_id = :resourceId
|
||||||
|
OR (parent_resource_id IS NULL AND payload LIKE '%"parentResourceId":"' || :resourceId || '"%')
|
||||||
|
)
|
||||||
|
""")
|
||||||
suspend fun failDescendants(resourceId: String, now: Long)
|
suspend fun failDescendants(resourceId: String, now: Long)
|
||||||
|
|
||||||
/** Rétention : purge des ops synchronisées plus anciennes que `cutoff`. */
|
/**
|
||||||
@Query("DELETE FROM pending_operations WHERE status = 'synced' AND updated_at < :cutoff")
|
* Rétention : purge des ops synchronisées plus anciennes que `cutoff`.
|
||||||
|
*
|
||||||
|
* Décision C3 — les `create_resource` synced ne sont JAMAIS purgés
|
||||||
|
* (tombstones) : les gates delete/create (`hasCreateOperation`,
|
||||||
|
* `countCreateOperations…`) et le backfill de placement sont fondés sur
|
||||||
|
* `pending+synced`. Purger un create casserait le gate delete (fantôme
|
||||||
|
* serveur indélébile) et ré-enqueue un create dupliqué au prochain
|
||||||
|
* `markProcessed`. Les autres ops synced (> 7j) sont purgées normalement.
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
DELETE FROM pending_operations
|
||||||
|
WHERE status = 'synced'
|
||||||
|
AND updated_at < :cutoff
|
||||||
|
AND operation != 'create_resource'
|
||||||
|
""")
|
||||||
suspend fun purgeSynced(cutoff: Long)
|
suspend fun purgeSynced(cutoff: Long)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,14 +98,85 @@ interface PendingOperationDao {
|
|||||||
""")
|
""")
|
||||||
suspend fun countCreateOperationsAnyType(resourceId: String): Int
|
suspend fun countCreateOperationsAnyType(resourceId: String): Int
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annulation (M19) : supprime les `create_resource` encore `pending` pour
|
||||||
|
* cette ressource. Appelé quand la ressource disparaît localement
|
||||||
|
* (suppression, réconciliation du walk) AVANT que le serveur l'ait connue :
|
||||||
|
* pousser un create puis un delete serait du bruit — le serveur n'a rien
|
||||||
|
* à oublier. Les creates `synced` sont conservés (tombstones C3) : le gate
|
||||||
|
* delete reste fondé dessus.
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
DELETE FROM pending_operations
|
||||||
|
WHERE resource_id = :resourceId
|
||||||
|
AND operation = 'create_resource'
|
||||||
|
AND status = 'pending'
|
||||||
|
""")
|
||||||
|
suspend fun deletePendingCreates(resourceId: String): Int
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un `create_resource` a-t-il déjà été POUSSÉ (synced) pour ce fichier ?
|
||||||
|
* Gate delete précis : après [deletePendingCreates], `hasCreateOperation`
|
||||||
|
* (pending+synced) y est équivalent — ce compteur l'exprime directement.
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
SELECT COUNT(*) FROM pending_operations
|
||||||
|
WHERE resource_id = :resourceId
|
||||||
|
AND operation = 'create_resource'
|
||||||
|
AND resource_type = 'file'
|
||||||
|
AND status = 'synced'
|
||||||
|
""")
|
||||||
|
suspend fun countSyncedCreateOperations(resourceId: String): Int
|
||||||
|
|
||||||
|
/** Variante sans filtre `resource_type` (dossiers) de [countSyncedCreateOperations]. */
|
||||||
|
@Query("""
|
||||||
|
SELECT COUNT(*) FROM pending_operations
|
||||||
|
WHERE resource_id = :resourceId
|
||||||
|
AND operation = 'create_resource'
|
||||||
|
AND status = 'synced'
|
||||||
|
""")
|
||||||
|
suspend fun countSyncedCreateOperationsAnyType(resourceId: String): Int
|
||||||
|
|
||||||
@Query("SELECT COUNT(*) FROM pending_operations WHERE status = 'pending'")
|
@Query("SELECT COUNT(*) FROM pending_operations WHERE status = 'pending'")
|
||||||
suspend fun countPending(): Int
|
suspend fun countPending(): Int
|
||||||
|
|
||||||
|
/** Compteur diagnostique par statut (tests, badge « liste des sync »). */
|
||||||
|
@Query("SELECT COUNT(*) FROM pending_operations WHERE status = :status")
|
||||||
|
suspend fun countByStatus(status: String): Int
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Une op `move_resource` encore en attente de push existe-t-elle pour cette
|
* Abandon de la file non poussée (C5) : supprime les ops `pending` et
|
||||||
* ressource ? L'antichambre outbox est alors la source de vérité du
|
* `failed` — jamais les `synced`. Au changement de compte (sign-out, ou
|
||||||
* placement : ni le refresh serveur ni le walk SAF ne doivent écraser le
|
* login d'un autre user), rejouer la file de A sous le token de B
|
||||||
* `folder_resource_id` local avant que le serveur ait accusé le move.
|
* appliquerait ses mutations dans le scope de B (`NOT_FOUND`,
|
||||||
|
* `NAME_CONFLICT`, voire créations croisées). Les ops `synced` sont
|
||||||
|
* conservées : ce sont des tombstones (C3) fondant les gates
|
||||||
|
* delete/create et le backfill — elles ne sont plus jamais sélectionnées
|
||||||
|
* (`selectPending` ne lit que `pending`) donc sans risque de rejeu.
|
||||||
|
*/
|
||||||
|
@Query("DELETE FROM pending_operations WHERE status IN ('pending', 'failed')")
|
||||||
|
suspend fun deleteUnpushed(): Int
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un `delete_resource` est-il encore en attente de push pour cette
|
||||||
|
* ressource ? Le walk SAF ne doit alors jamais la ressusciter (`exists =
|
||||||
|
* 1`) : l'intention de suppression est déjà journalisée (ordre
|
||||||
|
* journal-first, C4) et la repasse physique va suivre. Sans ce garde, le
|
||||||
|
* walk réimporterait une ressource que le serveur s'apprête à supprimer.
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
SELECT COUNT(*) FROM pending_operations
|
||||||
|
WHERE resource_id = :resourceId
|
||||||
|
AND operation = 'delete_resource'
|
||||||
|
AND status = 'pending'
|
||||||
|
""")
|
||||||
|
suspend fun countPendingDeleteOperations(resourceId: String): Int
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un `move_resource` est-il encore en attente de push ? Tant que l'op est
|
||||||
|
* pendante, le `folder_resource_id` local reflète la cible future : ni le
|
||||||
|
* refresh serveur (qui renvoie l'ancien dossier) ni le walk SAF (snapshot
|
||||||
|
* périmé) ne doivent l'écraser.
|
||||||
*/
|
*/
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT COUNT(*) FROM pending_operations
|
SELECT COUNT(*) FROM pending_operations
|
||||||
|
|||||||
@@ -45,6 +45,9 @@ interface ScanDao {
|
|||||||
@Query("DELETE FROM scan_pages WHERE id = :pageId AND session_id = :sessionId")
|
@Query("DELETE FROM scan_pages WHERE id = :pageId AND session_id = :sessionId")
|
||||||
suspend fun deletePage(pageId: Long, sessionId: Long)
|
suspend fun deletePage(pageId: Long, sessionId: Long)
|
||||||
|
|
||||||
|
@Query("DELETE FROM scan_sessions WHERE id = :sessionId")
|
||||||
|
suspend fun deleteSession(sessionId: Long)
|
||||||
|
|
||||||
@Query(
|
@Query(
|
||||||
"""
|
"""
|
||||||
UPDATE scan_pages SET sort_order = CASE id
|
UPDATE scan_pages SET sort_order = CASE id
|
||||||
@@ -61,4 +64,12 @@ interface ScanDao {
|
|||||||
|
|
||||||
@Query("SELECT COUNT(*) FROM scan_pages WHERE session_id = :sessionId")
|
@Query("SELECT COUNT(*) FROM scan_pages WHERE session_id = :sessionId")
|
||||||
suspend fun pageCount(sessionId: Long): Int
|
suspend fun pageCount(sessionId: Long): Int
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plus grand `sort_order` de la session (NULL si vide) : l'ordre d'une
|
||||||
|
* nouvelle page est `MAX + 1`, jamais `COUNT` (qui collisionne après
|
||||||
|
* suppression : A,B → del A → C réutiliserait l'ordre de B).
|
||||||
|
*/
|
||||||
|
@Query("SELECT MAX(sort_order) FROM scan_pages WHERE session_id = :sessionId")
|
||||||
|
suspend fun maxSortOrder(sessionId: Long): Int?
|
||||||
}
|
}
|
||||||
@@ -22,6 +22,7 @@ import androidx.room.PrimaryKey
|
|||||||
Index(value = ["uri"], unique = true),
|
Index(value = ["uri"], unique = true),
|
||||||
Index(value = ["folder_resource_id"]),
|
Index(value = ["folder_resource_id"]),
|
||||||
Index(value = ["category"]),
|
Index(value = ["category"]),
|
||||||
|
Index(value = ["exists", "processed", "sync_status"]),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
data class FileEntity(
|
data class FileEntity(
|
||||||
|
|||||||
+14
-1
@@ -20,14 +20,18 @@ import androidx.room.PrimaryKey
|
|||||||
@Entity(
|
@Entity(
|
||||||
tableName = "pending_operations",
|
tableName = "pending_operations",
|
||||||
indices = [
|
indices = [
|
||||||
Index(value = ["operation_id"], unique = true),
|
Index(value = ["device_id", "operation_id"], unique = true),
|
||||||
Index(value = ["status"]),
|
Index(value = ["status"]),
|
||||||
Index(value = ["resource_id"]),
|
Index(value = ["resource_id"]),
|
||||||
|
Index(value = ["resource_id", "operation", "status"]),
|
||||||
|
Index(value = ["parent_resource_id"]),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
data class PendingOperationEntity(
|
data class PendingOperationEntity(
|
||||||
@PrimaryKey(autoGenerate = true)
|
@PrimaryKey(autoGenerate = true)
|
||||||
val id: Long = 0L,
|
val id: Long = 0L,
|
||||||
|
@ColumnInfo(name = "device_id")
|
||||||
|
val deviceId: String? = null,
|
||||||
@ColumnInfo(name = "operation_id")
|
@ColumnInfo(name = "operation_id")
|
||||||
val operationId: String,
|
val operationId: String,
|
||||||
@ColumnInfo(name = "ref_type")
|
@ColumnInfo(name = "ref_type")
|
||||||
@@ -42,6 +46,15 @@ data class PendingOperationEntity(
|
|||||||
val operation: String,
|
val operation: String,
|
||||||
@ColumnInfo(name = "payload")
|
@ColumnInfo(name = "payload")
|
||||||
val payload: String,
|
val payload: String,
|
||||||
|
/**
|
||||||
|
* Lien parent→enfant dénormalisé (P8) : `resource_id` du dossier parent
|
||||||
|
* pour un `create_resource` avec parent (les enfants portent un autre
|
||||||
|
* `resource_id`). Évite de parser le JSON du payload (`LIKE`) pour la
|
||||||
|
* cascade d'invalidation — robuste au format de sérialisation Moshi.
|
||||||
|
* NULL pour les ops sans parent et les lignes pré-v14 (repli LIKE).
|
||||||
|
*/
|
||||||
|
@ColumnInfo(name = "parent_resource_id")
|
||||||
|
val parentResourceId: String? = null,
|
||||||
@ColumnInfo(name = "status")
|
@ColumnInfo(name = "status")
|
||||||
val status: String = PendingOpStatus.PENDING,
|
val status: String = PendingOpStatus.PENDING,
|
||||||
@ColumnInfo(name = "attempts")
|
@ColumnInfo(name = "attempts")
|
||||||
|
|||||||
+66
-1
@@ -26,6 +26,13 @@ import androidx.sqlite.db.SupportSQLiteDatabase
|
|||||||
* l'app (fichier cloud-only, uri = NULL). Null pour les fichiers importés.
|
* l'app (fichier cloud-only, uri = NULL). Null pour les fichiers importés.
|
||||||
* v10 : ajout colonne `ocr_text` sur `files` — extrait OCR serveur persisté
|
* v10 : ajout colonne `ocr_text` sur `files` — extrait OCR serveur persisté
|
||||||
* localement (résultat d'un job `POST /ocr/jobs`, réaffichable sans relance).
|
* localement (résultat d'un job `POST /ocr/jobs`, réaffichable sans relance).
|
||||||
|
* v11 : `ocr_attempts` + `ocr_queued_at` sur `files` (driver OCR auto).
|
||||||
|
* v12 : ajout colonne `device_id` sur `pending_operations` + unicité
|
||||||
|
* composite `UNIQUE(device_id, operation_id)` (contrat docs/api-v1.md §6.1) ;
|
||||||
|
* backfill depuis `user_preferences.device_user_id` pour les lignes existantes.
|
||||||
|
* v13 : index composites `files(exists, processed, sync_status)` (review +
|
||||||
|
* candidats OCR auto) et `pending_operations(resource_id, operation, status)`
|
||||||
|
* (gates outbox create/move) — requêtes à chaud sans full-table scan.
|
||||||
*/
|
*/
|
||||||
object Migrations {
|
object Migrations {
|
||||||
|
|
||||||
@@ -92,6 +99,14 @@ object Migrations {
|
|||||||
db.execSQL("ALTER TABLE `files` ADD COLUMN `processed` INTEGER NOT NULL DEFAULT 0")
|
db.execSQL("ALTER TABLE `files` ADD COLUMN `processed` INTEGER NOT NULL DEFAULT 0")
|
||||||
// Backlog = déjà traité : la file de review ne contient que les
|
// Backlog = déjà traité : la file de review ne contient que les
|
||||||
// fichiers découverts après l'activation de la fonctionnalité.
|
// fichiers découverts après l'activation de la fonctionnalité.
|
||||||
|
//
|
||||||
|
// Décision M11 (documentée, assumée) : aucun `create_resource`
|
||||||
|
// rétroactif n'est journalisé pour ce backlog — ces fichiers ne
|
||||||
|
// seront jamais poussés vers le serveur (ni vizibles en review).
|
||||||
|
// Un backfill applicatif créerait des doublons serveur pour les
|
||||||
|
// ressources déjà connues par d'autres chemins (scan, second
|
||||||
|
// device) sans moyen fiable de les distinguer : la perte silencieuse
|
||||||
|
// du backlog pré-v6 est préférée à une résurrection massive.
|
||||||
db.execSQL("UPDATE `files` SET `processed` = 1")
|
db.execSQL("UPDATE `files` SET `processed` = 1")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -181,7 +196,57 @@ object Migrations {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val MIGRATION_11_12 = object : Migration(11, 12) {
|
||||||
|
override fun migrate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL("ALTER TABLE `pending_operations` ADD COLUMN `device_id` TEXT")
|
||||||
|
// Backfill : les ops pré-v12 héritent du device courant (une seule
|
||||||
|
// identité device par base en pratique).
|
||||||
|
db.execSQL(
|
||||||
|
"""
|
||||||
|
UPDATE `pending_operations` SET `device_id` =
|
||||||
|
(SELECT `value` FROM `user_preferences` WHERE `key` = 'device_user_id')
|
||||||
|
WHERE `device_id` IS NULL
|
||||||
|
""".trimIndent(),
|
||||||
|
)
|
||||||
|
db.execSQL("DROP INDEX IF EXISTS `index_pending_operations_operation_id`")
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE UNIQUE INDEX IF NOT EXISTS " +
|
||||||
|
"`index_pending_operations_device_id_operation_id` " +
|
||||||
|
"ON `pending_operations` (`device_id`, `operation_id`)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val MIGRATION_12_13 = object : Migration(12, 13) {
|
||||||
|
override fun migrate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` " +
|
||||||
|
"ON `files` (`exists`, `processed`, `sync_status`)",
|
||||||
|
)
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` " +
|
||||||
|
"ON `pending_operations` (`resource_id`, `operation`, `status`)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P8 : colonne `parent_resource_id` dénormalisée (cascade sans parsing
|
||||||
|
* JSON). Les lignes pré-v14 gardent NULL et restent couvertes par le repli
|
||||||
|
* `LIKE` de `failDescendants` — pas de backfill (le `json_extract`
|
||||||
|
* SQLite n'est pas garanti sur tous les niveaux d'API).
|
||||||
|
*/
|
||||||
|
private val MIGRATION_13_14 = object : Migration(13, 14) {
|
||||||
|
override fun migrate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL("ALTER TABLE `pending_operations` ADD COLUMN `parent_resource_id` TEXT")
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` " +
|
||||||
|
"ON `pending_operations` (`parent_resource_id`)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val ALL: Array<Migration> = arrayOf(
|
val ALL: Array<Migration> = arrayOf(
|
||||||
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11,
|
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,22 +1,29 @@
|
|||||||
package com.kazier.mobile.data.remote
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
import com.squareup.moshi.JsonAdapter
|
import com.squareup.moshi.JsonAdapter
|
||||||
|
import com.squareup.moshi.JsonDataException
|
||||||
|
import com.squareup.moshi.JsonEncodingException
|
||||||
import com.squareup.moshi.Moshi
|
import com.squareup.moshi.Moshi
|
||||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
import com.kazier.mobile.data.remote.dto.ApiErrorEnvelope
|
import com.kazier.mobile.data.remote.dto.ApiErrorEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiMeta
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileDto
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpDto
|
import com.kazier.mobile.data.remote.dto.SyncOpDto
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import kotlin.coroutines.cancellation.CancellationException
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
@@ -44,7 +51,12 @@ class ApiException(
|
|||||||
* - non-2xx → `ApiException` (code du body si présent, sinon `HTTP_<status>`),
|
* - non-2xx → `ApiException` (code du body si présent, sinon `HTTP_<status>`),
|
||||||
* et un 401 sur un endpoint protégé déclenche `onUnauthorized` (sauf si
|
* et un 401 sur un endpoint protégé déclenche `onUnauthorized` (sauf si
|
||||||
* `skipUnauthorizedHandling` — cas du login, où 401 = identifiants erronés) ;
|
* `skipUnauthorizedHandling` — cas du login, où 401 = identifiants erronés) ;
|
||||||
* - 2xx sans `data` (ou corps illisible) → `INVALID_RESPONSE`.
|
* - 2xx sans `data` (ou corps illisible) → `INVALID_RESPONSE` ;
|
||||||
|
* - un corps non parsable (Moshi) → `INVALID_RESPONSE`, jamais
|
||||||
|
* `NETWORK_ERROR` (pas de `retry()` infini sur contrat cassé) ;
|
||||||
|
* - `CancellationException` n'est jamais avalée (scopes/Worker sains).
|
||||||
|
* Les routes publiques (`/devices`, `/auth/login`, `/shares/links/:token`)
|
||||||
|
* désactivent le handling 401 : y purger la session serait faux.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ApiClient @Inject constructor(
|
class ApiClient @Inject constructor(
|
||||||
@@ -55,7 +67,7 @@ class ApiClient @Inject constructor(
|
|||||||
private val errorEnvelopeAdapter: JsonAdapter<ApiErrorEnvelope> =
|
private val errorEnvelopeAdapter: JsonAdapter<ApiErrorEnvelope> =
|
||||||
moshi.adapter(ApiErrorEnvelope::class.java)
|
moshi.adapter(ApiErrorEnvelope::class.java)
|
||||||
|
|
||||||
/** Callback 401 (expiration/révocation) — branché par AuthViewModel. */
|
/** Callback 401 (expiration/révocation) — branché par SessionManager. */
|
||||||
@Volatile
|
@Volatile
|
||||||
var onUnauthorized: (() -> Unit)? = null
|
var onUnauthorized: (() -> Unit)? = null
|
||||||
|
|
||||||
@@ -64,8 +76,20 @@ class ApiClient @Inject constructor(
|
|||||||
suspend fun listFiles(folderId: String? = null, page: Int? = null, pageSize: Int? = null): List<FileDto> =
|
suspend fun listFiles(folderId: String? = null, page: Int? = null, pageSize: Int? = null): List<FileDto> =
|
||||||
unwrap({ apiService.listFiles(folderId, page, pageSize) })
|
unwrap({ apiService.listFiles(folderId, page, pageSize) })
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Variante paginée exposant `meta` (page/pageSize/total) — seule base
|
||||||
|
* saine pour drainer un dossier au-delà de la 1re page (M21).
|
||||||
|
*/
|
||||||
|
suspend fun listFilesPaged(
|
||||||
|
folderId: String? = null,
|
||||||
|
page: Int? = null,
|
||||||
|
pageSize: Int? = null,
|
||||||
|
): Pair<List<FileDto>, ApiMeta?> =
|
||||||
|
unwrapWithMeta({ apiService.listFiles(folderId, page, pageSize) })
|
||||||
|
|
||||||
suspend fun registerDevice(deviceId: String): String =
|
suspend fun registerDevice(deviceId: String): String =
|
||||||
unwrap({ apiService.registerDevice(DeviceRegistrationDto(deviceId)) }).deviceId
|
unwrap({ apiService.registerDevice(DeviceRegistrationDto(deviceId)) },
|
||||||
|
skipUnauthorizedHandling = true).deviceId
|
||||||
|
|
||||||
suspend fun login(username: String, password: String, deviceId: String): LoginResponseDto =
|
suspend fun login(username: String, password: String, deviceId: String): LoginResponseDto =
|
||||||
unwrap({ apiService.login(LoginRequestDto(username, password, deviceId)) },
|
unwrap({ apiService.login(LoginRequestDto(username, password, deviceId)) },
|
||||||
@@ -110,16 +134,59 @@ class ApiClient @Inject constructor(
|
|||||||
suspend fun getFileOcr(fileId: String): FileOcrDto =
|
suspend fun getFileOcr(fileId: String): FileOcrDto =
|
||||||
unwrap({ apiService.getFileOcr(fileId) })
|
unwrap({ apiService.getFileOcr(fileId) })
|
||||||
|
|
||||||
|
/** Détail serveur d'un fichier visible — `GET /files/:id`. */
|
||||||
|
suspend fun getFile(fileId: String): FileDto =
|
||||||
|
unwrap({ apiService.getFile(fileId) })
|
||||||
|
|
||||||
|
/** Suppression serveur — `DELETE /files/:id`, retourne l'id supprimé. */
|
||||||
|
suspend fun deleteFile(fileId: String): String =
|
||||||
|
unwrap({ apiService.deleteFile(fileId) }).id
|
||||||
|
|
||||||
|
/** Recherche serveur paginée — `GET /files/search?q=…` (+ `meta`). */
|
||||||
|
suspend fun searchFilesPaged(
|
||||||
|
query: String,
|
||||||
|
page: Int? = null,
|
||||||
|
pageSize: Int? = null,
|
||||||
|
): Pair<List<FileDto>, ApiMeta?> =
|
||||||
|
unwrapWithMeta({ apiService.searchFiles(query, page, pageSize) })
|
||||||
|
|
||||||
|
/** Rotation du mot de passe — `PATCH /users/me/password`. */
|
||||||
|
suspend fun changePassword(currentPassword: String, newPassword: String): String =
|
||||||
|
unwrap({ apiService.changePassword(ChangePasswordDto(currentPassword, newPassword)) }).id
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résolution anonyme d'un lien de partage — `GET /shares/links/:token`
|
||||||
|
* (route publique : le 401 n'a aucun sens ici, handling désactivé).
|
||||||
|
*/
|
||||||
|
suspend fun getShareLink(token: String): ShareLinkDto =
|
||||||
|
unwrap({ apiService.getShareLink(token) }, skipUnauthorizedHandling = true)
|
||||||
|
|
||||||
private suspend fun <T> unwrap(
|
private suspend fun <T> unwrap(
|
||||||
call: suspend () -> Response<ApiEnvelope<T>>,
|
call: suspend () -> Response<ApiEnvelope<T>>,
|
||||||
skipUnauthorizedHandling: Boolean = false,
|
skipUnauthorizedHandling: Boolean = false,
|
||||||
): T {
|
): T = unwrapWithMeta(call, skipUnauthorizedHandling).first
|
||||||
|
|
||||||
|
private suspend fun <T> unwrapWithMeta(
|
||||||
|
call: suspend () -> Response<ApiEnvelope<T>>,
|
||||||
|
skipUnauthorizedHandling: Boolean = false,
|
||||||
|
): Pair<T, ApiMeta?> {
|
||||||
val response = try {
|
val response = try {
|
||||||
call()
|
call()
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
// Ne jamais avaler l'annulation : la convertir en ApiException
|
||||||
|
// corromprait les scopes et le WorkManager (M22).
|
||||||
|
throw e
|
||||||
|
} catch (e: JsonDataException) {
|
||||||
|
Timber.w(e, "api: corps inattendu (parsing)")
|
||||||
|
throw ApiException("INVALID_RESPONSE", "Réponse serveur invalide", 0)
|
||||||
|
} catch (e: JsonEncodingException) {
|
||||||
|
Timber.w(e, "api: corps inencodable (parsing)")
|
||||||
|
throw ApiException("INVALID_RESPONSE", "Réponse serveur invalide", 0)
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
Timber.d(e, "api: transport error")
|
Timber.d(e, "api: transport error")
|
||||||
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
|
||||||
Timber.d(e, "api: unexpected error")
|
Timber.d(e, "api: unexpected error")
|
||||||
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
|
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
|
||||||
}
|
}
|
||||||
@@ -151,6 +218,6 @@ class ApiClient @Inject constructor(
|
|||||||
httpCode = response.code(),
|
httpCode = response.code(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return data
|
return data to envelope.meta
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,29 @@
|
|||||||
package com.kazier.mobile.data.remote
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileDto
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
import retrofit2.Response
|
import retrofit2.Response
|
||||||
import retrofit2.http.Body
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.DELETE
|
||||||
import retrofit2.http.GET
|
import retrofit2.http.GET
|
||||||
import retrofit2.http.Multipart
|
import retrofit2.http.Multipart
|
||||||
|
import retrofit2.http.PATCH
|
||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
import retrofit2.http.Part
|
import retrofit2.http.Part
|
||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
@@ -107,4 +112,46 @@ interface ApiService {
|
|||||||
suspend fun getFileOcr(
|
suspend fun getFileOcr(
|
||||||
@Path("id") fileId: String,
|
@Path("id") fileId: String,
|
||||||
): Response<ApiEnvelope<FileOcrDto>>
|
): Response<ApiEnvelope<FileOcrDto>>
|
||||||
|
|
||||||
|
/** Détail d'un fichier visible (own ou shared) — `GET /files/:id`. */
|
||||||
|
@GET("files/{id}")
|
||||||
|
suspend fun getFile(
|
||||||
|
@Path("id") fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>>
|
||||||
|
|
||||||
|
/** Suppression serveur d'un fichier possédé — `DELETE /files/:id`. */
|
||||||
|
@DELETE("files/{id}")
|
||||||
|
suspend fun deleteFile(
|
||||||
|
@Path("id") fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recherche serveur (`GET /files/search?q=…`, paginé `meta`). Non consommée
|
||||||
|
* en V1 (recherche 100 % locale via Room) — exposée pour parité contrat.
|
||||||
|
*/
|
||||||
|
@GET("files/search")
|
||||||
|
suspend fun searchFiles(
|
||||||
|
@Query("q") query: String,
|
||||||
|
@Query("page") page: Int?,
|
||||||
|
@Query("pageSize") pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rotation du mot de passe du compte connecté (`PATCH /users/me/password`,
|
||||||
|
* `current_password` requis). Limite V1 : les tokens déjà émis restent
|
||||||
|
* valides jusqu'à expiration (7 j, pas de révocation).
|
||||||
|
*/
|
||||||
|
@PATCH("users/me/password")
|
||||||
|
suspend fun changePassword(
|
||||||
|
@Body body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résolution anonyme d'un lien de partage (`GET /shares/links/:token`,
|
||||||
|
* route publique — jamais de `Bearer`, cf. `AuthInterceptor`).
|
||||||
|
*/
|
||||||
|
@GET("shares/links/{token}")
|
||||||
|
suspend fun getShareLink(
|
||||||
|
@Path("token") token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>>
|
||||||
}
|
}
|
||||||
@@ -7,9 +7,12 @@ import javax.inject.Singleton
|
|||||||
import com.kazier.mobile.auth.TokenProvider
|
import com.kazier.mobile.auth.TokenProvider
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Injecte `Authorization: Bearer <token>` sur chaque requête si un token est
|
* Injecte `Authorization: Bearer <token>` sur chaque requête protégée si un
|
||||||
* disponible. Sans token (mode local / non connecté), aucune entête n'est posée
|
* token est disponible. Les routes publiques (`POST /devices`,
|
||||||
* — le serveur répondra 401, géré proprement par `ApiClient`.
|
* `POST /auth/login`, `GET /shares/links/:token`, `/health`) ne reçoivent
|
||||||
|
* jamais de `Bearer` (hygiène + pas d'amplification de fuite, cf. M26/m26).
|
||||||
|
* Sans token (mode local / non connecté), aucune entête n'est posée — le
|
||||||
|
* serveur répondra 401, géré proprement par `ApiClient`.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class AuthInterceptor @Inject constructor(
|
class AuthInterceptor @Inject constructor(
|
||||||
@@ -17,11 +20,31 @@ class AuthInterceptor @Inject constructor(
|
|||||||
) : Interceptor {
|
) : Interceptor {
|
||||||
|
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val request = chain.request()
|
||||||
|
val requestBuilder = request.newBuilder()
|
||||||
val token = tokenProvider.current
|
val token = tokenProvider.current
|
||||||
val requestBuilder = chain.request().newBuilder()
|
if (token != null && !isPublic(request.url.encodedPath)) {
|
||||||
if (token != null) {
|
|
||||||
requestBuilder.header("Authorization", "Bearer $token")
|
requestBuilder.header("Authorization", "Bearer $token")
|
||||||
}
|
}
|
||||||
return chain.proceed(requestBuilder.build())
|
return chain.proceed(requestBuilder.build())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/**
|
||||||
|
* Segments terminaux des routes publiques V1 (après réécriture par
|
||||||
|
* `ServerUrlInterceptor`, la base inclut `/api/v1` — on matche en
|
||||||
|
* suffixe pour rester indépendant du préfixe configuré).
|
||||||
|
*/
|
||||||
|
private val PUBLIC_SUFFIXES = listOf(
|
||||||
|
"/devices",
|
||||||
|
"/auth/login",
|
||||||
|
"/health",
|
||||||
|
)
|
||||||
|
|
||||||
|
fun isPublic(encodedPath: String): Boolean {
|
||||||
|
if (PUBLIC_SUFFIXES.any { encodedPath.endsWith(it) }) return true
|
||||||
|
// Lien de partage anonyme : /api/v1/shares/links/:token.
|
||||||
|
return encodedPath.contains("/shares/links/")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+20
-1
@@ -3,6 +3,7 @@ package com.kazier.mobile.data.remote
|
|||||||
import com.kazier.mobile.domain.ServerConfigStore
|
import com.kazier.mobile.domain.ServerConfigStore
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||||
import okhttp3.Interceptor
|
import okhttp3.Interceptor
|
||||||
import okhttp3.Response
|
import okhttp3.Response
|
||||||
@@ -13,6 +14,11 @@ import timber.log.Timber
|
|||||||
* La base Retrofit n'est qu'un placeholder ; c'est cet interceptor qui décide
|
* La base Retrofit n'est qu'un placeholder ; c'est cet interceptor qui décide
|
||||||
* du schéma/host/port réels, en préservant le préfixe de chemin de la base
|
* du schéma/host/port réels, en préservant le préfixe de chemin de la base
|
||||||
* configurée (ex. `/api/v1`) ainsi que la query d'origine.
|
* configurée (ex. `/api/v1`) ainsi que la query d'origine.
|
||||||
|
*
|
||||||
|
* Garde M26 : si le `load()` du cold start n'a pas encore restauré l'URL
|
||||||
|
* persistée, l'interceptor le fait lui-même (bloquant, thread OkHttp — jamais
|
||||||
|
* le Main) au lieu de laisser partir la requête vers l'hôte par défaut
|
||||||
|
* (avec le `Bearer` restauré — fuite).
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ServerUrlInterceptor @Inject constructor(
|
class ServerUrlInterceptor @Inject constructor(
|
||||||
@@ -22,6 +28,10 @@ class ServerUrlInterceptor @Inject constructor(
|
|||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
val request = chain.request()
|
val request = chain.request()
|
||||||
|
|
||||||
|
if (!serverConfigStore.isLoaded) {
|
||||||
|
runBlocking { serverConfigStore.load() }
|
||||||
|
}
|
||||||
|
|
||||||
val targetUrl = runCatching {
|
val targetUrl = runCatching {
|
||||||
(serverConfigStore.current.trimEnd('/') + "/").toHttpUrl()
|
(serverConfigStore.current.trimEnd('/') + "/").toHttpUrl()
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
@@ -32,8 +42,17 @@ class ServerUrlInterceptor @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val original = request.url
|
val original = request.url
|
||||||
|
// La base Retrofit placeholder contient déjà le préfixe de chemin
|
||||||
|
// (`/api/v1`) : ne pas le dupliquer quand le chemin d'origine le porte.
|
||||||
|
val basePath = targetUrl.encodedPath.trimEnd('/')
|
||||||
|
val origPath = original.encodedPath
|
||||||
|
val mergedPath = if (basePath.isNotEmpty() && (origPath == basePath || origPath.startsWith("$basePath/"))) {
|
||||||
|
origPath
|
||||||
|
} else {
|
||||||
|
basePath + "/" + origPath.trimStart('/')
|
||||||
|
}
|
||||||
val rewritten = targetUrl.newBuilder()
|
val rewritten = targetUrl.newBuilder()
|
||||||
.encodedPath(targetUrl.encodedPath.trimEnd('/') + "/" + original.encodedPath.trimStart('/'))
|
.encodedPath(mergedPath)
|
||||||
.encodedQuery(original.encodedQuery)
|
.encodedQuery(original.encodedQuery)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
|
|||||||
@@ -88,6 +88,30 @@ data class LoginResponseDto(
|
|||||||
@Json(name = "user") val user: UserDto,
|
@Json(name = "user") val user: UserDto,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** Requête `PATCH /users/me/password` — `{ current_password, new_password }`. */
|
||||||
|
data class ChangePasswordDto(
|
||||||
|
@Json(name = "current_password") val currentPassword: String,
|
||||||
|
@Json(name = "new_password") val newPassword: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Réponse `PATCH /users/me/password` et `DELETE /files/:id` — `{ id }`. */
|
||||||
|
data class IdResultDto(
|
||||||
|
@Json(name = "id") val id: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Réponse `GET /shares/links/:token` — métadonnées publiques du lien
|
||||||
|
* (jamais d'identité du propriétaire au-delà du contrat).
|
||||||
|
*/
|
||||||
|
data class ShareLinkDto(
|
||||||
|
@Json(name = "token") val token: String,
|
||||||
|
@Json(name = "resource_id") val resourceId: String,
|
||||||
|
@Json(name = "resourceType") val resourceType: String,
|
||||||
|
@Json(name = "name") val name: String,
|
||||||
|
@Json(name = "access") val access: String,
|
||||||
|
@Json(name = "expiresAt") val expiresAt: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
/** Outbox — une op du batch `POST /sync/ops` (docs/api-v1.md §6.1). */
|
/** Outbox — une op du batch `POST /sync/ops` (docs/api-v1.md §6.1). */
|
||||||
data class SyncOpDto(
|
data class SyncOpDto(
|
||||||
@Json(name = "operation_id") val operationId: String,
|
@Json(name = "operation_id") val operationId: String,
|
||||||
|
|||||||
+32
-6
@@ -1,8 +1,10 @@
|
|||||||
package com.kazier.mobile.data.repository
|
package com.kazier.mobile.data.repository
|
||||||
|
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
|
import com.kazier.mobile.data.remote.ApiException
|
||||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
|
import kotlin.coroutines.cancellation.CancellationException
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -17,11 +19,25 @@ class AuthRepository @Inject constructor(
|
|||||||
private val deviceIdentity: DeviceIdentity,
|
private val deviceIdentity: DeviceIdentity,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
/** Enregistrement best-effort du device (offline → ignoré). */
|
/**
|
||||||
|
* Enregistrement best-effort du device : seules les erreurs réseau et 5xx
|
||||||
|
* sont ignorées (offline → retry au prochain tick/login). Une 4xx
|
||||||
|
* (400 `INVALID_DEVICE_ID`, 429 `RATE_LIMITED`, …) est remontée — l'avaler
|
||||||
|
* rendrait le 401 du login incompréhensible (m23).
|
||||||
|
*/
|
||||||
suspend fun registerDevice(): String {
|
suspend fun registerDevice(): String {
|
||||||
val deviceId = deviceIdentity.getOrCreate()
|
val deviceId = deviceIdentity.getOrCreate()
|
||||||
runCatching { apiClient.registerDevice(deviceId) }
|
try {
|
||||||
.onFailure { Timber.d(it, "auth: device registration failed (offline?)") }
|
apiClient.registerDevice(deviceId)
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: ApiException) {
|
||||||
|
if (e.httpCode == 0 || e.httpCode >= 500) {
|
||||||
|
Timber.d(e, "auth: device registration failed (offline?)")
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
return deviceId
|
return deviceId
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,8 +45,18 @@ class AuthRepository @Inject constructor(
|
|||||||
val deviceId = deviceIdentity.getOrCreate()
|
val deviceId = deviceIdentity.getOrCreate()
|
||||||
// Re-registration idempotente juste avant le login : un device inconnu
|
// Re-registration idempotente juste avant le login : un device inconnu
|
||||||
// du serveur (ex. restart de la base) répondrait INVALID_DEVICE_ID.
|
// du serveur (ex. restart de la base) répondrait INVALID_DEVICE_ID.
|
||||||
runCatching { apiClient.registerDevice(deviceId) }
|
// Même politique que registerDevice : 4xx remontée, réseau/5xx ignorés.
|
||||||
.onFailure { Timber.d(it, "auth: pre-login registration failed") }
|
try {
|
||||||
|
apiClient.registerDevice(deviceId)
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: ApiException) {
|
||||||
|
if (e.httpCode == 0 || e.httpCode >= 500) {
|
||||||
|
Timber.d(e, "auth: pre-login registration failed")
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
return apiClient.login(username.trim(), password, deviceId)
|
return apiClient.login(username.trim(), password, deviceId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+87
-19
@@ -3,6 +3,7 @@ package com.kazier.mobile.data.repository
|
|||||||
import androidx.room.withTransaction
|
import androidx.room.withTransaction
|
||||||
import com.kazier.mobile.data.local.AppDatabase
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
import com.kazier.mobile.data.local.dao.FileDao
|
import com.kazier.mobile.data.local.dao.FileDao
|
||||||
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.data.local.entity.FileStatus
|
import com.kazier.mobile.data.local.entity.FileStatus
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
@@ -27,6 +28,7 @@ import javax.inject.Singleton
|
|||||||
@Singleton
|
@Singleton
|
||||||
class FileRepository @Inject constructor(
|
class FileRepository @Inject constructor(
|
||||||
private val fileDao: FileDao,
|
private val fileDao: FileDao,
|
||||||
|
private val folderDao: FolderDao,
|
||||||
private val apiClient: ApiClient,
|
private val apiClient: ApiClient,
|
||||||
private val generateId: GenerateId,
|
private val generateId: GenerateId,
|
||||||
private val appDatabase: AppDatabase,
|
private val appDatabase: AppDatabase,
|
||||||
@@ -154,7 +156,7 @@ class FileRepository @Inject constructor(
|
|||||||
updatedAt = now,
|
updatedAt = now,
|
||||||
)
|
)
|
||||||
appDatabase.withTransaction {
|
appDatabase.withTransaction {
|
||||||
fileDao.upsert(entity)
|
upsertTolerant(entity)
|
||||||
outboxRepository.enqueueCreateResource(
|
outboxRepository.enqueueCreateResource(
|
||||||
resourceId = entity.resourceId,
|
resourceId = entity.resourceId,
|
||||||
resourceType = "file",
|
resourceType = "file",
|
||||||
@@ -184,11 +186,32 @@ class FileRepository @Inject constructor(
|
|||||||
|
|
||||||
val category = computeCategory(input.mimeType, input.extension).dbValue
|
val category = computeCategory(input.mimeType, input.extension).dbValue
|
||||||
|
|
||||||
|
// Garde anti-résurrection (C4) : un `delete_resource` déjà journalisé
|
||||||
|
// (ordre journal-first) interdit de réimporter la ressource — le
|
||||||
|
// serveur s'apprête à la supprimer et la repasse physique va suivre.
|
||||||
|
if (existing != null && outboxRepository.hasPendingDeleteOperation(existing.resourceId)) {
|
||||||
|
if (existing.exists != 0) fileDao.markMissing(existing.resourceId, now)
|
||||||
|
return existing.copy(exists = 0, updatedAt = now)
|
||||||
|
}
|
||||||
|
|
||||||
// Un `move_resource` encore en attente fait de la cible outbox la
|
// Un `move_resource` encore en attente fait de la cible outbox la
|
||||||
// source de vérité du placement : un snapshot SAF périmé (walk lancé
|
// source de vérité du placement : un snapshot SAF périmé (walk lancé
|
||||||
// avant le move) ne doit pas ré-attribuer le dossier à l'ancien parent.
|
// avant le move) ne doit pas ré-attribuer le dossier à l'ancien parent.
|
||||||
val movePending = existing != null && outboxRepository.hasPendingMoveOperation(existing.resourceId)
|
val movePending = existing != null && outboxRepository.hasPendingMoveOperation(existing.resourceId)
|
||||||
val effectiveFolder = if (movePending) existing.folderResourceId else folderResourceId
|
val effectiveFolder = if (movePending) existing.folderResourceId else folderResourceId
|
||||||
|
// Pas de FK `files → folders` : le parent est validé ici (orphelin
|
||||||
|
// refusé au lieu d'une ligne fantôme jamais affichable).
|
||||||
|
require(folderDao.getByResourceId(effectiveFolder) != null) {
|
||||||
|
"unknown parent folder: $effectiveFolder"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Un fichier cloud-only (snapshot serveur) réimporté en SAF devient
|
||||||
|
// `local-cloud` : le serveur le connaît déjà, la copie physique aussi.
|
||||||
|
val placement = if (existing != null && existing.uri == null && existing.syncStatus == FileStatus.CLOUD) {
|
||||||
|
SyncPlacement.confirmed(hasLocalUri = true)
|
||||||
|
} else {
|
||||||
|
existing?.syncStatus ?: input.syncStatus ?: FileStatus.LOCAL
|
||||||
|
}
|
||||||
|
|
||||||
val entity = FileEntity(
|
val entity = FileEntity(
|
||||||
id = existing?.id ?: 0L,
|
id = existing?.id ?: 0L,
|
||||||
@@ -203,7 +226,7 @@ class FileRepository @Inject constructor(
|
|||||||
exists = if (input.exists) 1 else 0,
|
exists = if (input.exists) 1 else 0,
|
||||||
lastModified = input.lastModified,
|
lastModified = input.lastModified,
|
||||||
ownerId = ownerId ?: existing?.ownerId,
|
ownerId = ownerId ?: existing?.ownerId,
|
||||||
syncStatus = existing?.syncStatus ?: input.syncStatus ?: FileStatus.LOCAL,
|
syncStatus = placement,
|
||||||
// Une ligne existante liée reste à son état ; une nouvelle ligne est
|
// Une ligne existante liée reste à son état ; une nouvelle ligne est
|
||||||
// « traitée » si la source l'a demandé (ex. scan), sinon à traiter.
|
// « traitée » si la source l'a demandé (ex. scan), sinon à traiter.
|
||||||
processed = existing?.processed ?: input.processed,
|
processed = existing?.processed ?: input.processed,
|
||||||
@@ -211,7 +234,7 @@ class FileRepository @Inject constructor(
|
|||||||
updatedAt = now,
|
updatedAt = now,
|
||||||
)
|
)
|
||||||
appDatabase.withTransaction {
|
appDatabase.withTransaction {
|
||||||
fileDao.upsert(entity)
|
upsertTolerant(entity)
|
||||||
if (existing == null && entity.processed) {
|
if (existing == null && entity.processed) {
|
||||||
// Nouveau fichier physique déjà « traité » (ex. scan export) :
|
// Nouveau fichier physique déjà « traité » (ex. scan export) :
|
||||||
// poussé immédiatement. Un fichier SAF tout juste découvert
|
// poussé immédiatement. Un fichier SAF tout juste découvert
|
||||||
@@ -234,24 +257,35 @@ class FileRepository @Inject constructor(
|
|||||||
suspend fun markMissing(resourceId: String, updatedAt: Long) =
|
suspend fun markMissing(resourceId: String, updatedAt: Long) =
|
||||||
fileDao.markMissing(resourceId, updatedAt)
|
fileDao.markMissing(resourceId, updatedAt)
|
||||||
|
|
||||||
/** Met à jour la cible dossier d'un fichier (déplacement local / cloud-only). */
|
/** Met à jour la cible dossier d'un fichier (déplacement local / cloud-only).
|
||||||
|
*
|
||||||
|
* Le `move_resource` n'est journalisé que si le serveur connaît déjà la
|
||||||
|
* ressource (gate `create`) : déplacer un fichier jamais poussé est une
|
||||||
|
* opération purement locale, un move serveur serait `NOT_FOUND`/no-op et
|
||||||
|
* figerait la ligne derrière `hasPendingMoveOperation`. */
|
||||||
suspend fun applyMove(resourceId: String, folderId: String, newUri: String?) {
|
suspend fun applyMove(resourceId: String, folderId: String, newUri: String?) {
|
||||||
|
require(folderDao.getByResourceId(folderId) != null) {
|
||||||
|
"unknown target folder: $folderId"
|
||||||
|
}
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
appDatabase.withTransaction {
|
appDatabase.withTransaction {
|
||||||
fileDao.moveToFolder(listOf(resourceId), folderId, now)
|
fileDao.moveToFolder(listOf(resourceId), folderId, now)
|
||||||
if (newUri != null) fileDao.updateUri(resourceId, newUri)
|
if (newUri != null) fileDao.updateUri(resourceId, newUri, now)
|
||||||
// Déplacement reflété localement ←→ poussé vers le serveur.
|
// Déplacement reflété localement ←→ poussé vers le serveur.
|
||||||
outboxRepository.enqueueMoveResource(
|
if (outboxRepository.hasCreateOperation(resourceId)) {
|
||||||
resourceId = resourceId,
|
outboxRepository.enqueueMoveResource(
|
||||||
resourceType = "file",
|
resourceId = resourceId,
|
||||||
toFolderResourceId = folderId,
|
resourceType = "file",
|
||||||
)
|
toFolderResourceId = folderId,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `GET /files?folderId=...` (1re page, tri serveur) puis upsert cloud de
|
* `GET /files?folderId=...` drainé page par page en suivant `meta`
|
||||||
* chaque fichier. Ne supprime jamais de lignes locales.
|
* (page/pageSize/total), puis upsert cloud de chaque fichier. Ne supprime
|
||||||
|
* jamais de lignes locales.
|
||||||
*
|
*
|
||||||
* Garde-fou outbox : un fichier dont le `move_resource` n'a pas encore été
|
* Garde-fou outbox : un fichier dont le `move_resource` n'a pas encore été
|
||||||
* poussé garde son placement local. Le serveur renvoie encore l'ancien
|
* poussé garde son placement local. Le serveur renvoie encore l'ancien
|
||||||
@@ -259,15 +293,47 @@ class FileRepository @Inject constructor(
|
|||||||
* du dossier cible (et réapparaître dans l'ancien).
|
* du dossier cible (et réapparaître dans l'ancien).
|
||||||
*/
|
*/
|
||||||
suspend fun refreshFromServer(folderResourceId: String) {
|
suspend fun refreshFromServer(folderResourceId: String) {
|
||||||
val files = apiClient.listFiles(folderId = folderResourceId, pageSize = PAGE_SIZE)
|
|
||||||
if (files.isEmpty()) return
|
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
files.forEach { dto ->
|
var page = 1
|
||||||
if (outboxRepository.hasPendingMoveOperation(dto.id)) {
|
while (page <= MAX_PAGES) {
|
||||||
// L'antichambre outbox fait foi tant que le move n'est pas synced.
|
val (files, meta) = apiClient.listFilesPaged(
|
||||||
return@forEach
|
folderId = folderResourceId,
|
||||||
|
page = page,
|
||||||
|
pageSize = PAGE_SIZE,
|
||||||
|
)
|
||||||
|
files.forEach { dto ->
|
||||||
|
if (outboxRepository.hasPendingMoveOperation(dto.id)) {
|
||||||
|
// L'antichambre outbox fait foi tant que le move n'est pas synced.
|
||||||
|
return@forEach
|
||||||
|
}
|
||||||
|
upsertTolerant(toEntity(dto, folderResourceId, now))
|
||||||
}
|
}
|
||||||
fileDao.upsert(toEntity(dto, folderResourceId, now))
|
if (files.isEmpty()) break
|
||||||
|
val total = meta?.total
|
||||||
|
if (total != null) {
|
||||||
|
// `total` contractuel : arrêter dès la couverture atteinte.
|
||||||
|
if (page * PAGE_SIZE >= total) break
|
||||||
|
} else if (files.size < PAGE_SIZE) {
|
||||||
|
// Sans `meta` (vieux serveur) : dernière page partielle.
|
||||||
|
break
|
||||||
|
}
|
||||||
|
page++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upsert résolu sur les contraintes uniques (`resource_id`, `uri`), pas
|
||||||
|
* sur la PK : insert-or-ignore puis update du gagnant en cas de conflit.
|
||||||
|
* Les courses walk/refresh ne lèvent jamais `SQLiteConstraintException`.
|
||||||
|
*/
|
||||||
|
private suspend fun upsertTolerant(entity: FileEntity) {
|
||||||
|
if (fileDao.insertIgnore(entity) != -1L) return
|
||||||
|
val winner = entity.uri?.let { fileDao.getByUri(it) }
|
||||||
|
?: fileDao.getByResourceId(entity.resourceId)
|
||||||
|
if (winner != null) {
|
||||||
|
fileDao.update(entity.copy(id = winner.id, resourceId = winner.resourceId))
|
||||||
|
} else {
|
||||||
|
fileDao.upsert(entity)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,6 +367,8 @@ class FileRepository @Inject constructor(
|
|||||||
companion object {
|
companion object {
|
||||||
private const val PAGE_SIZE = 50
|
private const val PAGE_SIZE = 50
|
||||||
private const val RECENT_LIMIT = 5
|
private const val RECENT_LIMIT = 5
|
||||||
|
/** Garde anti-boucle si le serveur renvoie un `total` incohérent. */
|
||||||
|
private const val MAX_PAGES = 2000
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+73
-14
@@ -7,7 +7,7 @@ import com.kazier.mobile.data.local.entity.FolderEntity
|
|||||||
import com.kazier.mobile.data.local.entity.FolderStatus
|
import com.kazier.mobile.data.local.entity.FolderStatus
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.domain.GenerateId
|
import com.kazier.mobile.domain.GenerateId
|
||||||
import com.kazier.mobile.domain.SyncPlacement
|
import com.kazier.mobile.domain.SyncPlacement
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -26,7 +26,7 @@ class FolderRepository @Inject constructor(
|
|||||||
private val folderDao: FolderDao,
|
private val folderDao: FolderDao,
|
||||||
private val apiClient: ApiClient,
|
private val apiClient: ApiClient,
|
||||||
private val generateId: GenerateId,
|
private val generateId: GenerateId,
|
||||||
private val deviceIdentity: DeviceIdentity,
|
private val activeUserStore: ActiveUserStore,
|
||||||
private val appDatabase: AppDatabase,
|
private val appDatabase: AppDatabase,
|
||||||
private val outboxRepository: OutboxRepository,
|
private val outboxRepository: OutboxRepository,
|
||||||
) {
|
) {
|
||||||
@@ -66,7 +66,14 @@ class FolderRepository @Inject constructor(
|
|||||||
val folders = apiClient.listFolders()
|
val folders = apiClient.listFolders()
|
||||||
if (folders.isEmpty()) return
|
if (folders.isEmpty()) return
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
folderDao.upsertAll(folders.map { toEntity(it, now) })
|
val rows = folders
|
||||||
|
.filterNot { dto ->
|
||||||
|
// L'antichambre outbox fait foi tant que le move n'est pas
|
||||||
|
// synced : le serveur renvoie encore l'ancien parent.
|
||||||
|
outboxRepository.hasPendingMoveOperation(dto.id)
|
||||||
|
}
|
||||||
|
.map { toEntity(it, now) }
|
||||||
|
if (rows.isNotEmpty()) folderDao.upsertAll(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun toEntity(dto: FolderDto, now: Long): FolderEntity {
|
private suspend fun toEntity(dto: FolderDto, now: Long): FolderEntity {
|
||||||
@@ -93,8 +100,10 @@ class FolderRepository @Inject constructor(
|
|||||||
* ajoute une ligne avec sa `uri` si absente, ou met à jour ses champs.
|
* ajoute une ligne avec sa `uri` si absente, ou met à jour ses champs.
|
||||||
*
|
*
|
||||||
* `parentResourceId` non-null écrase le parent existant (un déplacement dans
|
* `parentResourceId` non-null écrase le parent existant (un déplacement dans
|
||||||
* l'arborescence SAF est reflété) ; null préserve le parent courant. `ownerId`
|
* l'arborescence SAF est reflété) ; null préserve le parent courant — sauf
|
||||||
* optionnel évite de relire l'identité device à chaque ligne d'un walk.
|
* `move_resource` en attente, qui fait de la cible outbox la source de
|
||||||
|
* vérité du placement (miroir du garde fichiers). `ownerId`
|
||||||
|
* optionnel évite de relire le compte actif à chaque ligne d'un walk.
|
||||||
*/
|
*/
|
||||||
suspend fun saveFolder(
|
suspend fun saveFolder(
|
||||||
input: SaveFolderInput,
|
input: SaveFolderInput,
|
||||||
@@ -105,21 +114,47 @@ class FolderRepository @Inject constructor(
|
|||||||
val existing = input.resourceId?.let { folderDao.getByResourceId(it) }
|
val existing = input.resourceId?.let { folderDao.getByResourceId(it) }
|
||||||
?: input.uri?.let { folderDao.getByUri(it) }
|
?: input.uri?.let { folderDao.getByUri(it) }
|
||||||
|
|
||||||
|
// Garde anti-résurrection (C4) : voir `FileRepository.saveLocalFile`.
|
||||||
|
if (existing != null && outboxRepository.hasPendingDeleteOperation(existing.resourceId)) {
|
||||||
|
if (existing.exists != 0) folderDao.markMissing(existing.resourceId, now)
|
||||||
|
return existing.copy(exists = 0, updatedAt = now)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Garde pending-move (M1) : un snapshot SAF périmé ne revert jamais un
|
||||||
|
// reparent/merge en cours de push.
|
||||||
|
val movePending = existing != null && outboxRepository.hasPendingMoveOperation(existing.resourceId)
|
||||||
|
val effectiveParent = if (movePending) existing.parentResourceId else (parentResourceId ?: existing?.parentResourceId)
|
||||||
|
// Pas de FK `files → folders` : le parent est validé ici (orphelin
|
||||||
|
// refusé au lieu d'une ligne fantôme jamais affichable).
|
||||||
|
if (effectiveParent != null && folderDao.getByResourceId(effectiveParent) == null) {
|
||||||
|
throw IllegalArgumentException("unknown parent folder: $effectiveParent")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Un dossier cloud-only réimporté en SAF devient `local-cloud`.
|
||||||
|
val placement = if (existing != null && existing.uri == null && input.uri != null &&
|
||||||
|
existing.syncStatus == FolderStatus.CLOUD
|
||||||
|
) {
|
||||||
|
SyncPlacement.confirmed(hasLocalUri = true)
|
||||||
|
} else {
|
||||||
|
existing?.syncStatus ?: FolderStatus.LOCAL
|
||||||
|
}
|
||||||
|
|
||||||
val entity = FolderEntity(
|
val entity = FolderEntity(
|
||||||
id = existing?.id ?: 0L,
|
id = existing?.id ?: 0L,
|
||||||
resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(),
|
resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(),
|
||||||
uri = input.uri,
|
uri = input.uri,
|
||||||
name = input.name,
|
name = input.name,
|
||||||
exists = input.exists?.let { if (it) 1 else 0 },
|
exists = input.exists?.let { if (it) 1 else 0 },
|
||||||
parentResourceId = parentResourceId ?: existing?.parentResourceId,
|
parentResourceId = effectiveParent,
|
||||||
ownerId = ownerId ?: existing?.ownerId ?: deviceIdentity.getOrCreate(),
|
// `owner_id` Room = user_id du compte actif, jamais l'identité device.
|
||||||
syncStatus = existing?.syncStatus ?: FolderStatus.LOCAL,
|
ownerId = ownerId ?: existing?.ownerId ?: activeUserStore.get(),
|
||||||
|
syncStatus = placement,
|
||||||
createdInApp = existing?.createdInApp ?: input.createdInApp,
|
createdInApp = existing?.createdInApp ?: input.createdInApp,
|
||||||
addedAt = existing?.addedAt ?: now,
|
addedAt = existing?.addedAt ?: now,
|
||||||
updatedAt = now,
|
updatedAt = now,
|
||||||
)
|
)
|
||||||
appDatabase.withTransaction {
|
appDatabase.withTransaction {
|
||||||
folderDao.upsert(entity)
|
upsertTolerant(entity)
|
||||||
if (existing == null) {
|
if (existing == null) {
|
||||||
// Nouvelle ressource physique → la pousser vers le serveur.
|
// Nouvelle ressource physique → la pousser vers le serveur.
|
||||||
outboxRepository.enqueueCreateResource(
|
outboxRepository.enqueueCreateResource(
|
||||||
@@ -140,21 +175,45 @@ class FolderRepository @Inject constructor(
|
|||||||
/**
|
/**
|
||||||
* Re-parente des sous-dossiers vers un nouveau parent (fusion de dossiers).
|
* Re-parente des sous-dossiers vers un nouveau parent (fusion de dossiers).
|
||||||
* Transaction atomique : reparent Room + outbox `move_resource` par dossier.
|
* Transaction atomique : reparent Room + outbox `move_resource` par dossier.
|
||||||
|
*
|
||||||
|
* Le `move_resource` n'est journalisé que si le serveur connaît déjà le
|
||||||
|
* dossier (gate `create`, miroir fichiers) : sinon le move serait
|
||||||
|
* `NOT_FOUND` et figerait la ligne derrière `hasPendingMoveOperation`.
|
||||||
*/
|
*/
|
||||||
suspend fun reparentSubFolders(resourceIds: List<String>, newParentId: String) {
|
suspend fun reparentSubFolders(resourceIds: List<String>, newParentId: String) {
|
||||||
if (resourceIds.isEmpty()) return
|
if (resourceIds.isEmpty()) return
|
||||||
|
require(folderDao.getByResourceId(newParentId) != null) {
|
||||||
|
"unknown target folder: $newParentId"
|
||||||
|
}
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
appDatabase.withTransaction {
|
appDatabase.withTransaction {
|
||||||
folderDao.reparent(resourceIds, newParentId, now)
|
folderDao.reparent(resourceIds, newParentId, now)
|
||||||
for (resourceId in resourceIds) {
|
for (resourceId in resourceIds) {
|
||||||
outboxRepository.enqueueMoveResource(
|
if (outboxRepository.hasCreateOperationAnyType(resourceId)) {
|
||||||
resourceId = resourceId,
|
outboxRepository.enqueueMoveResource(
|
||||||
resourceType = "folder",
|
resourceId = resourceId,
|
||||||
toFolderResourceId = newParentId,
|
resourceType = "folder",
|
||||||
)
|
toFolderResourceId = newParentId,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upsert résolu sur les contraintes uniques (`resource_id`, `uri`), pas
|
||||||
|
* sur la PK : insert-or-ignore puis update du gagnant en cas de conflit.
|
||||||
|
*/
|
||||||
|
private suspend fun upsertTolerant(entity: FolderEntity) {
|
||||||
|
if (folderDao.insertIgnore(entity) != -1L) return
|
||||||
|
val winner = entity.uri?.let { folderDao.getByUri(it) }
|
||||||
|
?: folderDao.getByResourceId(entity.resourceId)
|
||||||
|
if (winner != null) {
|
||||||
|
folderDao.update(entity.copy(id = winner.id, resourceId = winner.resourceId))
|
||||||
|
} else {
|
||||||
|
folderDao.upsert(entity)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
data class SaveFolderInput(
|
data class SaveFolderInput(
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import com.kazier.mobile.data.local.dao.PendingOperationDao
|
|||||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
import com.kazier.mobile.domain.GenerateId
|
import com.kazier.mobile.domain.GenerateId
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -23,6 +24,7 @@ import javax.inject.Singleton
|
|||||||
class OutboxRepository @Inject constructor(
|
class OutboxRepository @Inject constructor(
|
||||||
private val pendingOperationDao: PendingOperationDao,
|
private val pendingOperationDao: PendingOperationDao,
|
||||||
private val generateId: GenerateId,
|
private val generateId: GenerateId,
|
||||||
|
private val deviceIdentity: DeviceIdentity,
|
||||||
moshi: Moshi,
|
moshi: Moshi,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
@@ -46,6 +48,9 @@ class OutboxRepository @Inject constructor(
|
|||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
pendingOperationDao.insert(
|
pendingOperationDao.insert(
|
||||||
PendingOperationEntity(
|
PendingOperationEntity(
|
||||||
|
// Clé d'idempotence locale UNIQUE(device_id, operation_id)
|
||||||
|
// (contrat docs/api-v1.md §6.1).
|
||||||
|
deviceId = deviceIdentity.getOrCreate(),
|
||||||
operationId = operationId,
|
operationId = operationId,
|
||||||
refType = refType,
|
refType = refType,
|
||||||
refId = refId,
|
refId = refId,
|
||||||
@@ -53,6 +58,9 @@ class OutboxRepository @Inject constructor(
|
|||||||
resourceType = resourceType,
|
resourceType = resourceType,
|
||||||
operation = operation,
|
operation = operation,
|
||||||
payload = payloadAdapter.toJson(payload),
|
payload = payloadAdapter.toJson(payload),
|
||||||
|
// Lien parent→enfant dénormalisé pour la cascade (P8) —
|
||||||
|
// même clé que le payload JSON ci-dessous.
|
||||||
|
parentResourceId = payload[PARENT_PAYLOAD_KEY] as? String,
|
||||||
status = PendingOpStatus.PENDING,
|
status = PendingOpStatus.PENDING,
|
||||||
createdAt = now,
|
createdAt = now,
|
||||||
updatedAt = now,
|
updatedAt = now,
|
||||||
@@ -158,6 +166,27 @@ class OutboxRepository @Inject constructor(
|
|||||||
suspend fun hasCreateOperationAnyType(resourceId: String): Boolean =
|
suspend fun hasCreateOperationAnyType(resourceId: String): Boolean =
|
||||||
pendingOperationDao.countCreateOperationsAnyType(resourceId) > 0
|
pendingOperationDao.countCreateOperationsAnyType(resourceId) > 0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Le serveur connaît-il déjà ce fichier (create `synced`) ? Gate delete
|
||||||
|
* précis (M19) : après [cancelPendingCreates], un `delete_resource` n'est
|
||||||
|
* émis que dans ce cas — jamais pour une ressource que le serveur n'a
|
||||||
|
* jamais vue (ni bruit create-puis-delete, ni `NOT_FOUND`).
|
||||||
|
*/
|
||||||
|
suspend fun hasSyncedCreateOperation(resourceId: String): Boolean =
|
||||||
|
pendingOperationDao.countSyncedCreateOperations(resourceId) > 0
|
||||||
|
|
||||||
|
/** Variante dossiers de [hasSyncedCreateOperation]. */
|
||||||
|
suspend fun hasSyncedCreateOperationAnyType(resourceId: String): Boolean =
|
||||||
|
pendingOperationDao.countSyncedCreateOperationsAnyType(resourceId) > 0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annulation (M19) : supprime les `create_resource` encore `pending` pour
|
||||||
|
* cette ressource qui disparaît localement avant que le serveur l'ait
|
||||||
|
* connue. Retourne le nombre d'ops annulées.
|
||||||
|
*/
|
||||||
|
suspend fun cancelPendingCreates(resourceId: String): Int =
|
||||||
|
pendingOperationDao.deletePendingCreates(resourceId)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Un `move_resource` est-il encore en attente de push ? Tant que l'op est
|
* Un `move_resource` est-il encore en attente de push ? Tant que l'op est
|
||||||
* pendante, le `folder_resource_id` local reflète la cible future : ni le
|
* pendante, le `folder_resource_id` local reflète la cible future : ni le
|
||||||
@@ -167,6 +196,23 @@ class OutboxRepository @Inject constructor(
|
|||||||
suspend fun hasPendingMoveOperation(resourceId: String): Boolean =
|
suspend fun hasPendingMoveOperation(resourceId: String): Boolean =
|
||||||
pendingOperationDao.countPendingMoveOperations(resourceId) > 0
|
pendingOperationDao.countPendingMoveOperations(resourceId) > 0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un `delete_resource` est-il encore en attente de push ? Garde
|
||||||
|
* anti-résurrection du walk (C4, voir DAO) : une ressource dont la
|
||||||
|
* suppression est journalisée ne doit plus être réimportée.
|
||||||
|
*/
|
||||||
|
suspend fun hasPendingDeleteOperation(resourceId: String): Boolean =
|
||||||
|
pendingOperationDao.countPendingDeleteOperations(resourceId) > 0
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/**
|
||||||
|
* Clé du lien parent→enfant, à la fois dans le payload JSON
|
||||||
|
* `create_resource` (protocole, lu par `OutboxSyncWorker`) et dans la
|
||||||
|
* colonne dénormalisée `parent_resource_id` (cascade SQL).
|
||||||
|
*/
|
||||||
|
const val PARENT_PAYLOAD_KEY = "parentResourceId"
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Un `move_resource` (pending ou synced) a-t-il jamais été journalisé ?
|
* Un `move_resource` (pending ou synced) a-t-il jamais été journalisé ?
|
||||||
* Utilisé par la réconciliation du walk : une ligne en transition physique
|
* Utilisé par la réconciliation du walk : une ligne en transition physique
|
||||||
|
|||||||
+39
-17
@@ -9,6 +9,8 @@ import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
|||||||
import com.kazier.mobile.data.local.entity.ScanSessionStatus
|
import com.kazier.mobile.data.local.entity.ScanSessionStatus
|
||||||
import com.kazier.mobile.domain.GenerateId
|
import com.kazier.mobile.domain.GenerateId
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -24,20 +26,28 @@ class ScanRepository @Inject constructor(
|
|||||||
private val generateId: GenerateId,
|
private val generateId: GenerateId,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
suspend fun getOrCreateActiveSession(rootFolderId: String?): ScanSessionEntity {
|
/**
|
||||||
scanDao.getActiveSession()?.let { return it }
|
* Single-flight de création de session : sans garde, deux appels
|
||||||
val now = System.currentTimeMillis()
|
* concurrents créent deux sessions `active` (aucune unicité partielle
|
||||||
val sessionId = scanDao.insertSession(
|
* côté Room) et orphelinent les pages de l'une d'elles.
|
||||||
ScanSessionEntity(
|
*/
|
||||||
resourceId = generateId.newResourceId(),
|
private val sessionMutex = Mutex()
|
||||||
rootFolderId = rootFolderId,
|
|
||||||
status = ScanSessionStatus.ACTIVE,
|
suspend fun getOrCreateActiveSession(rootFolderId: String?): ScanSessionEntity =
|
||||||
createdAt = now,
|
sessionMutex.withLock {
|
||||||
updatedAt = now,
|
scanDao.getActiveSession()?.let { return@withLock it }
|
||||||
),
|
val now = System.currentTimeMillis()
|
||||||
)
|
val sessionId = scanDao.insertSession(
|
||||||
return checkNotNull(scanDao.getSession(sessionId))
|
ScanSessionEntity(
|
||||||
}
|
resourceId = generateId.newResourceId(),
|
||||||
|
rootFolderId = rootFolderId,
|
||||||
|
status = ScanSessionStatus.ACTIVE,
|
||||||
|
createdAt = now,
|
||||||
|
updatedAt = now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
checkNotNull(scanDao.getSession(sessionId))
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun setRootFolder(sessionId: Long, rootFolderId: String) {
|
suspend fun setRootFolder(sessionId: Long, rootFolderId: String) {
|
||||||
appDatabase.withTransaction {
|
appDatabase.withTransaction {
|
||||||
@@ -61,7 +71,10 @@ class ScanRepository @Inject constructor(
|
|||||||
height: Int,
|
height: Int,
|
||||||
): ScanPageEntity {
|
): ScanPageEntity {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
val order = scanDao.pageCount(session.id)
|
// MAX + 1, jamais COUNT : après suppression, COUNT réutilise un ordre
|
||||||
|
// existant (doublons → `ORDER BY sort_order` instable, `swapOrder`
|
||||||
|
// ambigu), MAX + 1 reste strictement unique et croissant.
|
||||||
|
val order = (scanDao.maxSortOrder(session.id) ?: -1) + 1
|
||||||
val page = ScanPageEntity(
|
val page = ScanPageEntity(
|
||||||
resourceId = generateId.newResourceId(),
|
resourceId = generateId.newResourceId(),
|
||||||
sessionId = session.id,
|
sessionId = session.id,
|
||||||
@@ -73,8 +86,10 @@ class ScanRepository @Inject constructor(
|
|||||||
status = ScanPageStatus.PENDING,
|
status = ScanPageStatus.PENDING,
|
||||||
createdAt = now,
|
createdAt = now,
|
||||||
)
|
)
|
||||||
scanDao.insertPage(page)
|
// L'id auto-généré est indispensable : sans lui, deletePage/movePage
|
||||||
return page
|
// ciblent l'id 0 et ne touchent aucune ligne.
|
||||||
|
val rowId = scanDao.insertPage(page)
|
||||||
|
return page.copy(id = rowId)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun deletePage(pageId: Long, sessionId: Long) {
|
suspend fun deletePage(pageId: Long, sessionId: Long) {
|
||||||
@@ -83,6 +98,13 @@ class ScanRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Supprime une session abandonnée vide (jamais de session orpheline). */
|
||||||
|
suspend fun deleteSession(sessionId: Long) {
|
||||||
|
appDatabase.withTransaction {
|
||||||
|
scanDao.deleteSession(sessionId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun movePage(sessionId: Long, pages: List<ScanPageEntity>, pageId: Long, delta: Int) {
|
suspend fun movePage(sessionId: Long, pages: List<ScanPageEntity>, pageId: Long, delta: Int) {
|
||||||
val index = pages.indexOfFirst { it.id == pageId }
|
val index = pages.indexOfFirst { it.id == pageId }
|
||||||
val target = index + delta
|
val target = index + delta
|
||||||
|
|||||||
+17
-11
@@ -8,7 +8,7 @@ import com.kazier.mobile.data.local.entity.FileEntity
|
|||||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.domain.SyncPlacement
|
import com.kazier.mobile.domain.SyncPlacement
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -28,7 +28,7 @@ import javax.inject.Singleton
|
|||||||
class ShareRepository @Inject constructor(
|
class ShareRepository @Inject constructor(
|
||||||
private val apiClient: ApiClient,
|
private val apiClient: ApiClient,
|
||||||
private val appDatabase: AppDatabase,
|
private val appDatabase: AppDatabase,
|
||||||
private val deviceIdentity: DeviceIdentity,
|
private val activeUserStore: ActiveUserStore,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -42,7 +42,8 @@ class ShareRepository @Inject constructor(
|
|||||||
* marquées `exists = 0`.
|
* marquées `exists = 0`.
|
||||||
*/
|
*/
|
||||||
suspend fun syncSnapshot() {
|
suspend fun syncSnapshot() {
|
||||||
val currentUserId = deviceIdentity.getOrCreate()
|
// `ownerId` serveur = user_id : comparer au compte actif, jamais au device.
|
||||||
|
val currentUserId = activeUserStore.get()
|
||||||
val permissions = apiClient.syncPermissions()
|
val permissions = apiClient.syncPermissions()
|
||||||
|
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
@@ -67,18 +68,23 @@ class ShareRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convergence : marquer les lignes cloud-only absentes du snapshot
|
// Convergence : marquer les lignes cloud-only d'autrui absentes du
|
||||||
// comme disparues (révocation / expiration côté serveur).
|
// snapshot comme disparues (révocation / expiration côté serveur).
|
||||||
|
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le
|
||||||
|
// snapshot exclut les ressources possédées → une ligne cloud-only
|
||||||
|
// au vrai ownerId=user ne doit jamais être markMissing.
|
||||||
for (folder in folderDao.getAll()) {
|
for (folder in folderDao.getAll()) {
|
||||||
if (isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists)
|
if (currentUserId != null &&
|
||||||
&& folder.resourceId !in snapshotFolderIds
|
isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists) &&
|
||||||
|
folder.resourceId !in snapshotFolderIds
|
||||||
) {
|
) {
|
||||||
folderDao.markMissing(folder.resourceId, now)
|
folderDao.markMissing(folder.resourceId, now)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (file in fileDao.getAll()) {
|
for (file in fileDao.getAll()) {
|
||||||
if (isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists)
|
if (currentUserId != null &&
|
||||||
&& file.resourceId !in snapshotFileIds
|
isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists) &&
|
||||||
|
file.resourceId !in snapshotFileIds
|
||||||
) {
|
) {
|
||||||
fileDao.markMissing(file.resourceId, now)
|
fileDao.markMissing(file.resourceId, now)
|
||||||
}
|
}
|
||||||
@@ -99,9 +105,9 @@ class ShareRepository @Inject constructor(
|
|||||||
private fun isCloudOnlyForOtherUser(
|
private fun isCloudOnlyForOtherUser(
|
||||||
uri: String?,
|
uri: String?,
|
||||||
ownerId: String?,
|
ownerId: String?,
|
||||||
currentNodeId: String,
|
currentUserId: String,
|
||||||
exists: Int?,
|
exists: Int?,
|
||||||
): Boolean = uri == null && ownerId != null && ownerId != currentNodeId && exists != 0
|
): Boolean = uri == null && ownerId != null && ownerId != currentUserId && exists != 0
|
||||||
|
|
||||||
private suspend fun upsertSharedFolder(
|
private suspend fun upsertSharedFolder(
|
||||||
perm: ResourcePermissionDto,
|
perm: ResourcePermissionDto,
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package com.kazier.mobile.di
|
package com.kazier.mobile.di
|
||||||
|
|
||||||
|
import com.kazier.mobile.auth.SecureTokenStore
|
||||||
|
import com.kazier.mobile.auth.TokenStore
|
||||||
|
import dagger.Binds
|
||||||
import dagger.Module
|
import dagger.Module
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
import dagger.hilt.components.SingletonComponent
|
import dagger.hilt.components.SingletonComponent
|
||||||
@@ -9,4 +12,8 @@ import dagger.hilt.components.SingletonComponent
|
|||||||
*/
|
*/
|
||||||
@Module
|
@Module
|
||||||
@InstallIn(SingletonComponent::class)
|
@InstallIn(SingletonComponent::class)
|
||||||
object AppModule
|
abstract class AppModule {
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
abstract fun bindTokenStore(impl: SecureTokenStore): TokenStore
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ package com.kazier.mobile.di
|
|||||||
|
|
||||||
import com.squareup.moshi.Moshi
|
import com.squareup.moshi.Moshi
|
||||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
import com.kazier.mobile.BuildConfig
|
|
||||||
import com.kazier.mobile.data.remote.ApiService
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
import com.kazier.mobile.data.remote.AuthInterceptor
|
import com.kazier.mobile.data.remote.AuthInterceptor
|
||||||
import com.kazier.mobile.data.remote.ServerUrlInterceptor
|
import com.kazier.mobile.data.remote.ServerUrlInterceptor
|
||||||
@@ -34,12 +33,10 @@ object NetworkModule {
|
|||||||
serverUrlInterceptor: ServerUrlInterceptor,
|
serverUrlInterceptor: ServerUrlInterceptor,
|
||||||
authInterceptor: AuthInterceptor,
|
authInterceptor: AuthInterceptor,
|
||||||
): OkHttpClient {
|
): OkHttpClient {
|
||||||
|
// Logging désactivé même en DEBUG : BASIC loggue les lignes de requête
|
||||||
|
// avec query PII (`GET /users/resolve?username=…`) dans logcat (m25).
|
||||||
val logging = HttpLoggingInterceptor().apply {
|
val logging = HttpLoggingInterceptor().apply {
|
||||||
level = if (BuildConfig.DEBUG) {
|
level = HttpLoggingInterceptor.Level.NONE
|
||||||
HttpLoggingInterceptor.Level.BASIC
|
|
||||||
} else {
|
|
||||||
HttpLoggingInterceptor.Level.NONE
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return OkHttpClient.Builder()
|
return OkHttpClient.Builder()
|
||||||
.addInterceptor(serverUrlInterceptor)
|
.addInterceptor(serverUrlInterceptor)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
|||||||
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Identité locale du device : 32-hex généré une seule fois à la première
|
* Identité locale du device : 32-hex généré une seule fois à la première
|
||||||
@@ -15,13 +17,22 @@ class DeviceIdentity @Inject constructor(
|
|||||||
private val generateId: GenerateId,
|
private val generateId: GenerateId,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
suspend fun getOrCreate(): String {
|
/**
|
||||||
|
* Single-flight intra-processus : deux `getOrCreate()` concurrents ne
|
||||||
|
* génèrent/inserent qu'une seule fois (`insertIgnore` tranche, le perdant
|
||||||
|
* relit la valeur gagnante).
|
||||||
|
*/
|
||||||
|
private val mutex = Mutex()
|
||||||
|
|
||||||
|
suspend fun getOrCreate(): String = mutex.withLock {
|
||||||
userPreferenceDao.getValue(PrefKeys.DEVICE_USER_ID)?.let { return it }
|
userPreferenceDao.getValue(PrefKeys.DEVICE_USER_ID)?.let { return it }
|
||||||
val id = generateId.newResourceId()
|
val id = generateId.newResourceId()
|
||||||
userPreferenceDao.insertIgnore(
|
userPreferenceDao.insertIgnore(
|
||||||
UserPreferenceEntity(PrefKeys.DEVICE_USER_ID, id, System.currentTimeMillis()),
|
UserPreferenceEntity(PrefKeys.DEVICE_USER_ID, id, System.currentTimeMillis()),
|
||||||
)
|
)
|
||||||
return userPreferenceDao.getValue(PrefKeys.DEVICE_USER_ID)
|
// Jamais de fallback fantôme : si la rellecture échoue, échouer
|
||||||
?: generateId.newResourceId()
|
// proprement plutôt que de renvoyer un ID non persisté.
|
||||||
|
userPreferenceDao.getValue(PrefKeys.DEVICE_USER_ID)
|
||||||
|
?: error("device identity not persisted")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,8 @@ enum class FileCategory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun computeCategory(mimeType: String?, extension: String?): FileCategory {
|
fun computeCategory(mimeType: String?, extension: String?): FileCategory {
|
||||||
|
// Le CSV est toujours TEXT (MIME `text/csv` comme extension `csv`) :
|
||||||
|
// un même fichier ne change jamais de catégorie selon le chemin d'entrée.
|
||||||
val mime = mimeType?.lowercase().orEmpty()
|
val mime = mimeType?.lowercase().orEmpty()
|
||||||
val ext = extension?.lowercase().orEmpty()
|
val ext = extension?.lowercase().orEmpty()
|
||||||
|
|
||||||
@@ -41,11 +43,11 @@ private val OFFICE_MIMES = setOf(
|
|||||||
|
|
||||||
private val OFFICE_EXTENSIONS = setOf(
|
private val OFFICE_EXTENSIONS = setOf(
|
||||||
"doc", "docx", "odt", "rtf",
|
"doc", "docx", "odt", "rtf",
|
||||||
"xls", "xlsx", "ods", "csv",
|
"xls", "xlsx", "ods",
|
||||||
"ppt", "pptx", "odp",
|
"ppt", "pptx", "odp",
|
||||||
)
|
)
|
||||||
|
|
||||||
private val TEXT_EXTENSIONS = setOf(
|
private val TEXT_EXTENSIONS = setOf(
|
||||||
"txt", "md", "html", "xml", "json", "css", "js", "kt", "py", "java",
|
"txt", "md", "html", "xml", "json", "css", "js", "kt", "py", "java",
|
||||||
"log", "ini", "cfg", "yaml", "yml", "toml",
|
"log", "ini", "cfg", "yaml", "yml", "toml", "csv",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -16,6 +16,6 @@ class GenerateId @Inject constructor() {
|
|||||||
fun newResourceId(): String {
|
fun newResourceId(): String {
|
||||||
val bytes = ByteArray(16)
|
val bytes = ByteArray(16)
|
||||||
random.nextBytes(bytes)
|
random.nextBytes(bytes)
|
||||||
return bytes.joinToString("") { "%02x".format(it) }
|
return bytes.joinToString("") { "%02x".format(it.toInt() and 0xFF) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ class LocalModeStore @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun get(): Boolean = userPreferenceDao.getValue(PrefKeys.LOCAL_MODE) != null
|
suspend fun get(): Boolean = userPreferenceDao.getValue(PrefKeys.LOCAL_MODE) == "1"
|
||||||
|
|
||||||
suspend fun clear() = userPreferenceDao.delete(PrefKeys.LOCAL_MODE)
|
suspend fun clear() = userPreferenceDao.delete(PrefKeys.LOCAL_MODE)
|
||||||
}
|
}
|
||||||
@@ -32,6 +32,10 @@ class ServerConfigStore @Inject constructor(
|
|||||||
private val _baseUrl = MutableStateFlow(DEFAULT_BASE_URL)
|
private val _baseUrl = MutableStateFlow(DEFAULT_BASE_URL)
|
||||||
val baseUrl: StateFlow<String> = _baseUrl.asStateFlow()
|
val baseUrl: StateFlow<String> = _baseUrl.asStateFlow()
|
||||||
|
|
||||||
|
/** Vrai une fois [load] passé — lu par `ServerUrlInterceptor` (garde M26). */
|
||||||
|
val isLoaded: Boolean
|
||||||
|
get() = loaded.get()
|
||||||
|
|
||||||
/** Dernière base effective — lu par `ServerUrlInterceptor` (filaire, volatile). */
|
/** Dernière base effective — lu par `ServerUrlInterceptor` (filaire, volatile). */
|
||||||
val current: String
|
val current: String
|
||||||
get() = _baseUrl.value
|
get() = _baseUrl.value
|
||||||
@@ -43,12 +47,48 @@ class ServerConfigStore @Inject constructor(
|
|||||||
_baseUrl.value = stored?.takeIf { it.isNotBlank() }?.let(::normalize) ?: DEFAULT_BASE_URL
|
_baseUrl.value = stored?.takeIf { it.isNotBlank() }?.let(::normalize) ?: DEFAULT_BASE_URL
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun set(url: String) {
|
/**
|
||||||
val normalized = normalize(url).ifEmpty { DEFAULT_BASE_URL }
|
* Réarme le garde once-only pour permettre un rechargement (ex. après
|
||||||
_baseUrl.value = normalized
|
* wipe/logout où la valeur en mémoire est périmée).
|
||||||
|
*/
|
||||||
|
fun invalidate() {
|
||||||
|
loaded.set(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recharge depuis la DB même si déjà chargé (ex. après wipe/logout). */
|
||||||
|
suspend fun reload() {
|
||||||
|
loaded.set(false)
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persiste la base serveur après validation (M28). Retourne `false` —
|
||||||
|
* sans rien persister ni publier — si l'URL est invalide (schéma non
|
||||||
|
* http/https, host vide, illisible par OkHttp) : l'appelant par frappe
|
||||||
|
* ([com.kazier.mobile.ui.settings.SettingsViewModel.onServerUrlChange])
|
||||||
|
* ne brique jamais l'app sur une saisie intermédiaire.
|
||||||
|
*/
|
||||||
|
suspend fun set(url: String): Boolean {
|
||||||
|
val normalized = validate(url) ?: return false
|
||||||
userPreferenceDao.upsert(
|
userPreferenceDao.upsert(
|
||||||
UserPreferenceEntity(PrefKeys.SERVER_URL, normalized, System.currentTimeMillis()),
|
UserPreferenceEntity(PrefKeys.SERVER_URL, normalized, System.currentTimeMillis()),
|
||||||
)
|
)
|
||||||
|
// Publier après succès DB pour ne jamais diverger UI/DB si l'upsert échoue.
|
||||||
|
_baseUrl.value = normalized
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalise puis valide : schéma http/https et host non vide exigés.
|
||||||
|
* Retourne la base normalisée, ou `null` si invalide.
|
||||||
|
*/
|
||||||
|
fun validate(url: String): String? {
|
||||||
|
val normalized = normalize(url)
|
||||||
|
if (normalized.isEmpty()) return null
|
||||||
|
val parsed = runCatching { normalized.toHttpUrl() }.getOrNull() ?: return null
|
||||||
|
if (parsed.scheme != "http" && parsed.scheme != "https") return null
|
||||||
|
if (parsed.host.isBlank()) return null
|
||||||
|
return normalized
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Trim, ajoute `http://` si le schéma est absent, retire les `/` finaux. */
|
/** Trim, ajoute `http://` si le schéma est absent, retire les `/` finaux. */
|
||||||
|
|||||||
@@ -31,10 +31,25 @@ class ThemePreferenceStore @Inject constructor(
|
|||||||
_theme.value = ThemePreference.fromStored(stored)
|
_theme.value = ThemePreference.fromStored(stored)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Réarme le garde once-only pour permettre un rechargement (ex. après
|
||||||
|
* wipe/logout où la valeur en mémoire est périmée).
|
||||||
|
*/
|
||||||
|
fun invalidate() {
|
||||||
|
loaded.set(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recharge depuis la DB même si déjà chargé (ex. après wipe/logout). */
|
||||||
|
suspend fun reload() {
|
||||||
|
loaded.set(false)
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun set(theme: ThemePreference) {
|
suspend fun set(theme: ThemePreference) {
|
||||||
_theme.value = theme
|
|
||||||
userPreferenceDao.upsert(
|
userPreferenceDao.upsert(
|
||||||
UserPreferenceEntity(PrefKeys.THEME, theme.storedValue, System.currentTimeMillis()),
|
UserPreferenceEntity(PrefKeys.THEME, theme.storedValue, System.currentTimeMillis()),
|
||||||
)
|
)
|
||||||
|
// Publier après succès DB pour ne jamais diverger UI/DB si l'upsert échoue.
|
||||||
|
_theme.value = theme
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,11 @@ class FileDeleter @Inject constructor(
|
|||||||
private suspend fun deleteInCloud(file: FileEntity): Boolean {
|
private suspend fun deleteInCloud(file: FileEntity): Boolean {
|
||||||
var ok = false
|
var ok = false
|
||||||
runCatching {
|
runCatching {
|
||||||
if (outboxRepository.hasCreateOperation(file.resourceId)) {
|
// Jamais poussé (create encore pending) : annulation (M19), pas
|
||||||
|
// de delete — le serveur n'a rien à oublier. Poussé (synced) :
|
||||||
|
// `delete_resource`, le serveur connaît la ressource.
|
||||||
|
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||||
|
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||||
}
|
}
|
||||||
ok = true
|
ok = true
|
||||||
@@ -100,34 +104,75 @@ class FileDeleter @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Suppression complète : physique + cloud.
|
* Suppression complète : journal d'abord, physique ensuite (C4).
|
||||||
* Transaction atomique : SAF delete + markMissing + outbox.
|
*
|
||||||
|
* Ordre crash-safe : la transaction Room (`exists = 0` + annulation du
|
||||||
|
* create pending + éventuel `delete_resource`) est committée AVANT la
|
||||||
|
* suppression SAF — un kill entre les deux ne perd plus le journal, le
|
||||||
|
* serveur est toujours notifié. Si la suppression physique échoue (ou si
|
||||||
|
* le kill survient juste après), la ligne reste `exists = 0` avec son
|
||||||
|
* `uri` : la repasse [sweepPendingPhysicalDeletes] retentera le
|
||||||
|
* `deleteDocument` au prochain tick (le walk peut la ressusciter
|
||||||
|
* entre-temps, elle sera re-marquée sans nouveau journal — convergence).
|
||||||
*/
|
*/
|
||||||
private suspend fun deleteFull(file: FileEntity): Boolean {
|
private suspend fun deleteFull(file: FileEntity): Boolean {
|
||||||
val uri = file.uri
|
val uri = file.uri
|
||||||
return if (uri != null) {
|
return if (uri != null) {
|
||||||
runCatching {
|
val now = System.currentTimeMillis()
|
||||||
DocumentsContract.deleteDocument(resolver, Uri.parse(uri))
|
appDatabase.withTransaction {
|
||||||
}.onSuccess { deleted ->
|
fileRepository.markMissing(file.resourceId, now)
|
||||||
if (deleted) {
|
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||||
val now = System.currentTimeMillis()
|
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||||
appDatabase.withTransaction {
|
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||||
fileRepository.markMissing(file.resourceId, now)
|
|
||||||
if (outboxRepository.hasCreateOperation(file.resourceId)) {
|
|
||||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Timber.d("deleted full %s", uri)
|
|
||||||
thumbnailStore.delete(file.resourceId)
|
|
||||||
} else {
|
|
||||||
Timber.w("deleteDocument returned false for %s", uri)
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
val deleted = runCatching {
|
||||||
|
DocumentsContract.deleteDocument(resolver, Uri.parse(uri))
|
||||||
}.onFailure { e ->
|
}.onFailure { e ->
|
||||||
Timber.w(e, "deleteDocument failed for %s", uri)
|
Timber.w(e, "deleteDocument failed for %s (sweep will retry)", uri)
|
||||||
}.getOrDefault(false)
|
}.getOrDefault(false)
|
||||||
|
if (deleted) {
|
||||||
|
Timber.d("deleted full %s", uri)
|
||||||
|
thumbnailStore.delete(file.resourceId)
|
||||||
|
} else {
|
||||||
|
Timber.w("deleteDocument returned false for %s (sweep will retry)", uri)
|
||||||
|
}
|
||||||
|
deleted
|
||||||
} else {
|
} else {
|
||||||
// Cloud-only : outbox uniquement.
|
// Cloud-only : outbox uniquement.
|
||||||
deleteInCloud(file)
|
deleteInCloud(file)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repasse C4 : retente la suppression physique des lignes déjà
|
||||||
|
* journalisées (`exists = 0`, `uri` présente) dont les octets ont survécu
|
||||||
|
* (kill entre journal et SAF, refus du provider). Bornée ([SWEEP_LIMIT])
|
||||||
|
* et best-effort — appelée à chaque tick de sync et après chaque import.
|
||||||
|
* Retourne le nombre d'octets effectivement supprimés.
|
||||||
|
*/
|
||||||
|
suspend fun sweepPendingPhysicalDeletes(limit: Int = SWEEP_LIMIT): Int {
|
||||||
|
var swept = 0
|
||||||
|
val stale = try {
|
||||||
|
appDatabase.fileDao().getMissingWithUri(limit)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Timber.w(e, "sweep: lecture impossible")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
for (file in stale) {
|
||||||
|
val uri = file.uri ?: continue
|
||||||
|
val deleted = runCatching {
|
||||||
|
DocumentsContract.deleteDocument(resolver, Uri.parse(uri))
|
||||||
|
}.getOrDefault(false)
|
||||||
|
if (deleted) {
|
||||||
|
thumbnailStore.delete(file.resourceId)
|
||||||
|
swept++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return swept
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val SWEEP_LIMIT = 50
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,13 @@ import javax.inject.Singleton
|
|||||||
*
|
*
|
||||||
* - fichier physique (uri ≠ null) + dossier cible physique → relocation SAF
|
* - fichier physique (uri ≠ null) + dossier cible physique → relocation SAF
|
||||||
* réelle via `DocumentsContract.moveDocument` (l'arborescence locale reste
|
* réelle via `DocumentsContract.moveDocument` (l'arborescence locale reste
|
||||||
* cohérente avec Room) ; en cas d'échec (permission/edge provider), repli
|
* cohérente avec Room) ; en cas d'échec (permission/edge provider), Room
|
||||||
* bas de gamme : métadonnée seule (`folderResourceId`), la marche suivante
|
* est laissée INCHANGÉE — le repli « métadonnée seule » mentirait
|
||||||
* re-réconciliera.
|
* durablement (nouveau parent + ancienne uri), et le garde pending-move
|
||||||
|
* bloquerait le walk. L'utilisateur peut réessayer, le walk réconciliera.
|
||||||
* - fichier cloud-only → mise à jour de la métadonnée de dossier uniquement
|
* - fichier cloud-only → mise à jour de la métadonnée de dossier uniquement
|
||||||
* (`applyMove` journalise aussi un `move_resource` dans l'outbox).
|
* (`applyMove` journalise aussi un `move_resource` dans l'outbox, sous gate
|
||||||
|
* `create`).
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class FileMover @Inject constructor(
|
class FileMover @Inject constructor(
|
||||||
@@ -42,21 +44,24 @@ class FileMover @Inject constructor(
|
|||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
for (resourceId in resourceIds) {
|
for (resourceId in resourceIds) {
|
||||||
val file = fileRepository.getFile(resourceId) ?: continue
|
val file = fileRepository.getFile(resourceId) ?: continue
|
||||||
val physicalTarget = file.uri != null && targetDoc != null
|
if (file.uri != null && targetDoc != null) {
|
||||||
|
// Refus du provider → on ne touche pas à Room (cohérence
|
||||||
val newUri = if (physicalTarget) {
|
// disque/Room/serveur préservée, nouvel essai possible).
|
||||||
tryMove(file.uri, file.folderResourceId, targetDoc)
|
val movedUri = tryMove(file.uri, file.folderResourceId, targetDoc)
|
||||||
|
?: continue
|
||||||
|
fileRepository.applyMove(resourceId, targetFolderId, movedUri)
|
||||||
} else {
|
} else {
|
||||||
null
|
fileRepository.applyMove(resourceId, targetFolderId, file.uri)
|
||||||
}
|
}
|
||||||
fileRepository.applyMove(resourceId, targetFolderId, newUri ?: file.uri)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tente la relocation SAF. Retourne le nouvel uri du document (peut être
|
* Tente la relocation SAF. Retourne le nouvel uri du document, ou null en
|
||||||
* identique à l'ancien), ou null en échec → repli métadonnée seule.
|
* échec (exception, retour null, ou uri identique à la source — certains
|
||||||
|
* providers renvoient la source quand ils refusent ou déplacent sur place :
|
||||||
|
* sans preuve d'un nouvel emplacement, on ne touche pas à Room).
|
||||||
*/
|
*/
|
||||||
private suspend fun tryMove(fileUri: String?, sourceFolderId: String, targetDoc: Uri): String? {
|
private suspend fun tryMove(fileUri: String?, sourceFolderId: String, targetDoc: Uri): String? {
|
||||||
if (fileUri == null) return null
|
if (fileUri == null) return null
|
||||||
@@ -71,7 +76,8 @@ class FileMover @Inject constructor(
|
|||||||
targetDoc,
|
targetDoc,
|
||||||
)
|
)
|
||||||
}.onSuccess { moved -> Timber.d("moved %s -> %s (%s)", fileUri, targetDoc, moved) }
|
}.onSuccess { moved -> Timber.d("moved %s -> %s (%s)", fileUri, targetDoc, moved) }
|
||||||
.onFailure { Timber.w(it, "physical move failed for %s (metadata-only)", fileUri) }
|
.onFailure { Timber.w(it, "physical move failed for %s (Room unchanged)", fileUri) }
|
||||||
.getOrNull()?.toString()
|
.getOrNull()?.toString()
|
||||||
|
.takeIf { it != fileUri }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,7 +91,8 @@ class FolderDeleter @Inject constructor(
|
|||||||
private suspend fun deleteInCloud(folder: FolderEntity): Boolean {
|
private suspend fun deleteInCloud(folder: FolderEntity): Boolean {
|
||||||
var ok = false
|
var ok = false
|
||||||
runCatching {
|
runCatching {
|
||||||
if (outboxRepository.hasCreateOperationAnyType(folder.resourceId)) {
|
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||||
|
if (outboxRepository.hasSyncedCreateOperationAnyType(folder.resourceId)) {
|
||||||
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder")
|
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder")
|
||||||
}
|
}
|
||||||
ok = true
|
ok = true
|
||||||
@@ -102,43 +103,88 @@ class FolderDeleter @Inject constructor(
|
|||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Suppression complète : physique + cloud. Transaction atomique Room. */
|
/**
|
||||||
|
* Suppression complète : journal d'abord, physique ensuite (C4).
|
||||||
|
*
|
||||||
|
* Même contrat crash-safe que `FileDeleter.deleteFull` : la transaction
|
||||||
|
* Room (`exists = 0` sur tout l'arbre + annulation des creates pending +
|
||||||
|
* `delete_resource` là où le serveur connaît déjà la ressource) est
|
||||||
|
* committée AVANT la suppression SAF. Un kill entre les deux ne perd plus
|
||||||
|
* le journal ; si le physique échoue, [sweepPendingPhysicalDeletes]
|
||||||
|
* retentera au prochain tick (le walk ne ressuscite plus les lignes sous
|
||||||
|
* `delete_resource` pending — garde anti-résurrection).
|
||||||
|
*/
|
||||||
private suspend fun deleteFull(folder: FolderEntity): Boolean {
|
private suspend fun deleteFull(folder: FolderEntity): Boolean {
|
||||||
val uri = folder.uri
|
val uri = folder.uri
|
||||||
if (uri != null) {
|
if (uri != null) {
|
||||||
val tree = collectDescendants(folder.resourceId)
|
val tree = collectDescendants(folder.resourceId)
|
||||||
if (deleteTreePhysically(folder, tree)) {
|
val now = System.currentTimeMillis()
|
||||||
val now = System.currentTimeMillis()
|
appDatabase.withTransaction {
|
||||||
appDatabase.withTransaction {
|
treeMarkMissing(folder, tree, now)
|
||||||
treeMarkMissing(folder, tree, now)
|
}
|
||||||
}
|
return if (deleteTreePhysically(folder, tree)) {
|
||||||
tree.files.forEach { thumbnailStore.delete(it.resourceId) }
|
tree.files.forEach { thumbnailStore.delete(it.resourceId) }
|
||||||
Timber.d("deleted folder full %s", uri)
|
Timber.d("deleted folder full %s", uri)
|
||||||
return true
|
true
|
||||||
|
} else {
|
||||||
|
Timber.w("deleteDocument returned false for %s (sweep will retry)", uri)
|
||||||
|
false
|
||||||
}
|
}
|
||||||
Timber.w("deleteDocument returned false for %s", uri)
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
// Cloud-only : outbox uniquement.
|
// Cloud-only : outbox uniquement.
|
||||||
return deleteInCloud(folder)
|
return deleteInCloud(folder)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repasse C4 (dossiers) : retente la suppression physique des arbres déjà
|
||||||
|
* journalisés (`exists = 0`, `uri` présente). Un dossier n'est retenté que
|
||||||
|
* si toute sa descendance Room est aussi `exists = 0` — jamais de
|
||||||
|
* suppression d'un arbre encore vivant. Bornée ([SWEEP_LIMIT]).
|
||||||
|
* Retourne le nombre d'arbres effectivement supprimés.
|
||||||
|
*/
|
||||||
|
suspend fun sweepPendingPhysicalDeletes(limit: Int = SWEEP_LIMIT): Int {
|
||||||
|
var swept = 0
|
||||||
|
val stale = try {
|
||||||
|
appDatabase.folderDao().getMissingWithUri(limit)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Timber.w(e, "sweep folders: lecture impossible")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
for (folder in stale) {
|
||||||
|
val tree = collectDescendants(folder.resourceId)
|
||||||
|
val alive = tree.files.any { it.exists != 0 } || tree.folders.any { it.exists != 0 }
|
||||||
|
if (alive) continue
|
||||||
|
if (deleteTreePhysically(folder, tree)) {
|
||||||
|
tree.files.forEach { thumbnailStore.delete(it.resourceId) }
|
||||||
|
swept++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return swept
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val SWEEP_LIMIT = 50
|
||||||
|
}
|
||||||
|
|
||||||
/** Marque missing + outbox `delete_resource` pour toute la descendance, atomique. */
|
/** Marque missing + outbox `delete_resource` pour toute la descendance, atomique. */
|
||||||
private suspend fun treeMarkMissing(folder: FolderEntity, tree: FolderTree, now: Long) {
|
private suspend fun treeMarkMissing(folder: FolderEntity, tree: FolderTree, now: Long) {
|
||||||
for (file in tree.files) {
|
for (file in tree.files) {
|
||||||
fileRepository.markMissing(file.resourceId, now)
|
fileRepository.markMissing(file.resourceId, now)
|
||||||
if (outboxRepository.hasCreateOperation(file.resourceId)) {
|
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||||
|
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (desc in tree.folders) {
|
for (desc in tree.folders) {
|
||||||
folderRepository.markMissing(desc.resourceId, now)
|
folderRepository.markMissing(desc.resourceId, now)
|
||||||
if (outboxRepository.hasCreateOperationAnyType(desc.resourceId)) {
|
outboxRepository.cancelPendingCreates(desc.resourceId)
|
||||||
|
if (outboxRepository.hasSyncedCreateOperationAnyType(desc.resourceId)) {
|
||||||
outboxRepository.enqueueDeleteResource(desc.resourceId, "folder")
|
outboxRepository.enqueueDeleteResource(desc.resourceId, "folder")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
folderRepository.markMissing(folder.resourceId, now)
|
folderRepository.markMissing(folder.resourceId, now)
|
||||||
if (outboxRepository.hasCreateOperationAnyType(folder.resourceId)) {
|
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||||
|
if (outboxRepository.hasSyncedCreateOperationAnyType(folder.resourceId)) {
|
||||||
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder")
|
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package com.kazier.mobile.features.saf
|
package com.kazier.mobile.features.saf
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.provider.DocumentsContract
|
||||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
import com.kazier.mobile.data.repository.FileRepository
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
import com.kazier.mobile.data.repository.FolderRepository
|
import com.kazier.mobile.data.repository.FolderRepository
|
||||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
@@ -14,17 +17,22 @@ import javax.inject.Singleton
|
|||||||
* Fusion de dossiers en mode multi-sélection.
|
* Fusion de dossiers en mode multi-sélection.
|
||||||
*
|
*
|
||||||
* 1. Crée un nouveau dossier nommé `newName` au même niveau que les dossiers
|
* 1. Crée un nouveau dossier nommé `newName` au même niveau que les dossiers
|
||||||
* sélectionnés (même parent).
|
* sélectionnés (même parent) — ou réutilise celui d'une tentative
|
||||||
|
* précédente (idempotence : un crash à mi-fusion ne duplique jamais le
|
||||||
|
* dossier fusionné à la relance).
|
||||||
* 2. Déplace tout le contenu de chaque dossier source (fichiers + sous-dossiers)
|
* 2. Déplace tout le contenu de chaque dossier source (fichiers + sous-dossiers)
|
||||||
* vers le dossier fusionné — relocation SAF quand les deux côtés sont
|
* vers le dossier fusionné — relocation SAF quand les deux côtés sont
|
||||||
* physiques, repli métadonnée seule sinon (`move_resource` outbox quand même).
|
* physiques (fichiers via [FileMover], sous-dossiers via `moveDocument`),
|
||||||
* 3. Supprime les dossiers sources désormais vides (physique + outbox).
|
* métadonnée seule sinon (`move_resource` outbox sous gate `create`).
|
||||||
|
* Un refus SAF laisse la source en place (ni reparent ni suppression).
|
||||||
|
* 3. Supprime les dossiers sources vidés avec succès (physique + outbox).
|
||||||
*
|
*
|
||||||
* L'ordre outbox est garanti par l'insertion séquentielle : `create_resource`
|
* L'ordre outbox est garanti par l'insertion séquentielle : `create_resource`
|
||||||
* du dossier fusionné avant les `move_resource`, avant les `delete_resource`.
|
* du dossier fusionné avant les `move_resource`, avant les `delete_resource`.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class FolderMerger @Inject constructor(
|
class FolderMerger @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
private val folderRepository: FolderRepository,
|
private val folderRepository: FolderRepository,
|
||||||
private val fileRepository: FileRepository,
|
private val fileRepository: FileRepository,
|
||||||
private val fileMover: FileMover,
|
private val fileMover: FileMover,
|
||||||
@@ -45,13 +53,15 @@ class FolderMerger @Inject constructor(
|
|||||||
suspend fun mergeSelectedFolders(folders: List<FolderEntity>, newName: String): MergeReport {
|
suspend fun mergeSelectedFolders(folders: List<FolderEntity>, newName: String): MergeReport {
|
||||||
require(folders.size >= 2) { "merge requires at least 2 folders" }
|
require(folders.size >= 2) { "merge requires at least 2 folders" }
|
||||||
|
|
||||||
// 1. Dossier fusionné au même niveau que les sources.
|
// 1. Dossier fusionné au même niveau que les sources (réutilisé si une
|
||||||
|
// tentative précédente l'a déjà créé — relance idempotente).
|
||||||
val parentId = folders.first().parentResourceId
|
val parentId = folders.first().parentResourceId
|
||||||
val merged = createMergedFolder(parentId, newName)
|
val merged = createMergedFolder(parentId, newName)
|
||||||
|
|
||||||
// 2. Déplacement du contenu de chaque dossier source.
|
// 2. Déplacement du contenu de chaque dossier source.
|
||||||
var movedFiles = 0
|
var movedFiles = 0
|
||||||
var stepFailures = 0
|
var stepFailures = 0
|
||||||
|
val readyToDelete = ArrayList<FolderEntity>()
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
for (src in folders) {
|
for (src in folders) {
|
||||||
val ok = runCatching {
|
val ok = runCatching {
|
||||||
@@ -62,18 +72,29 @@ class FolderMerger @Inject constructor(
|
|||||||
}
|
}
|
||||||
val subFolders = folderRepository.getChildren(src.resourceId)
|
val subFolders = folderRepository.getChildren(src.resourceId)
|
||||||
if (subFolders.isNotEmpty()) {
|
if (subFolders.isNotEmpty()) {
|
||||||
folderRepository.reparentSubFolders(subFolders.map { it.resourceId }, merged.resourceId)
|
val movable = subFolders.filter { moveSubFolderPhysically(it, src, merged) }
|
||||||
|
if (movable.size < subFolders.size) {
|
||||||
|
error("refus SAF : ${subFolders.size - movable.size} sous-dossier(s) non déplaçables")
|
||||||
|
}
|
||||||
|
if (movable.isNotEmpty()) {
|
||||||
|
folderRepository.reparentSubFolders(movable.map { it.resourceId }, merged.resourceId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}.isSuccess
|
}.isSuccess
|
||||||
if (!ok) stepFailures++
|
if (ok) {
|
||||||
|
readyToDelete += src
|
||||||
|
} else {
|
||||||
|
stepFailures++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Suppression des dossiers sources (désormais sans contenu).
|
// 3. Suppression des dossiers sources vidés avec succès (jamais ceux
|
||||||
|
// dont le contenu n'a pas pu être déplacé).
|
||||||
var deletedFolders = 0
|
var deletedFolders = 0
|
||||||
var failed = 0
|
var failed = 0
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
for (src in folders) {
|
for (src in readyToDelete) {
|
||||||
val report = folderDeleter.deleteFolders(listOf(src), FileDeleter.DeleteMode.FULL)
|
val report = folderDeleter.deleteFolders(listOf(src), FileDeleter.DeleteMode.FULL)
|
||||||
if (report.failed == 0) deletedFolders++ else failed++
|
if (report.failed == 0) deletedFolders++ else failed++
|
||||||
}
|
}
|
||||||
@@ -84,12 +105,38 @@ class FolderMerger @Inject constructor(
|
|||||||
return MergeReport(movedFiles = movedFiles, deletedFolders = deletedFolders, failed = failed)
|
return MergeReport(movedFiles = movedFiles, deletedFolders = deletedFolders, failed = failed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Déplace physiquement un sous-dossier vers le dossier fusionné.
|
||||||
|
* Retourne `true` si le reparent Room peut suivre : rien à déplacer
|
||||||
|
* (cloud-only) ou `moveDocument` accepté. `false` (refus SAF) → la source
|
||||||
|
* reste en place, ni reparentée ni supprimée (cohérence disque/Room).
|
||||||
|
*/
|
||||||
|
private fun moveSubFolderPhysically(sub: FolderEntity, src: FolderEntity, merged: FolderEntity): Boolean {
|
||||||
|
val subUri = SafUris.toDocumentUri(sub.uri) ?: return true
|
||||||
|
val mergedDoc = SafUris.toDocumentUri(merged.uri) ?: return true
|
||||||
|
val srcDoc = SafUris.toDocumentUri(src.uri) ?: return false
|
||||||
|
return runCatching {
|
||||||
|
DocumentsContract.moveDocument(
|
||||||
|
context.contentResolver,
|
||||||
|
subUri,
|
||||||
|
srcDoc,
|
||||||
|
mergedDoc,
|
||||||
|
)
|
||||||
|
}.onSuccess { moved -> Timber.d("moved folder %s -> %s (%s)", subUri, mergedDoc, moved) }
|
||||||
|
.onFailure { Timber.w(it, "physical folder move failed for %s", subUri) }
|
||||||
|
.getOrNull() != null
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Crée (physique si le parent l'est, cloud-only sinon) et enregistre en Room
|
* Crée (physique si le parent l'est, cloud-only sinon) et enregistre en Room
|
||||||
* le dossier fusionné. Retourne l'entité Room. La sauvegarde enqueue le
|
* le dossier fusionné. Retourne l'entité Room. La sauvegarde enqueue le
|
||||||
* `create_resource` dans la même transaction.
|
* `create_resource` dans la même transaction.
|
||||||
|
*
|
||||||
|
* Idempotence : si un frère du même nom existe déjà (crash à mi-fusion puis
|
||||||
|
* relance), il est réutilisé — aucun doublon, aucun `create_resource` bis.
|
||||||
*/
|
*/
|
||||||
private suspend fun createMergedFolder(parentId: String?, newName: String): FolderEntity {
|
private suspend fun createMergedFolder(parentId: String?, newName: String): FolderEntity {
|
||||||
|
findExistingMerged(parentId, newName)?.let { return it }
|
||||||
val parent = parentId?.let { folderRepository.getFolder(it) }
|
val parent = parentId?.let { folderRepository.getFolder(it) }
|
||||||
val createdUri = parent?.uri?.let { safFolderCreator.createFolder(it, newName) }?.toString()
|
val createdUri = parent?.uri?.let { safFolderCreator.createFolder(it, newName) }?.toString()
|
||||||
return folderRepository.saveFolder(
|
return folderRepository.saveFolder(
|
||||||
@@ -102,4 +149,14 @@ class FolderMerger @Inject constructor(
|
|||||||
parentResourceId = parentId,
|
parentResourceId = parentId,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Frère existant du même nom (visible), ou null si première tentative. */
|
||||||
|
private suspend fun findExistingMerged(parentId: String?, newName: String): FolderEntity? {
|
||||||
|
val siblings = if (parentId == null) {
|
||||||
|
folderRepository.getRootFolders().filter { it.exists != 0 }
|
||||||
|
} else {
|
||||||
|
folderRepository.getChildren(parentId)
|
||||||
|
}
|
||||||
|
return siblings.firstOrNull { it.name == newName }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -41,32 +41,39 @@ class SafFileDeleter @Inject constructor(
|
|||||||
|
|
||||||
private val resolver: ContentResolver get() = context.contentResolver
|
private val resolver: ContentResolver get() = context.contentResolver
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Suppression review (swipe ✗) : journal d'abord, physique ensuite (C4 —
|
||||||
|
* même contrat que `FileDeleter.deleteFull`, la repasse
|
||||||
|
* `FileDeleter.sweepPendingPhysicalDeletes` couvrant aussi ces lignes).
|
||||||
|
*/
|
||||||
suspend fun delete(file: FileEntity): Boolean {
|
suspend fun delete(file: FileEntity): Boolean {
|
||||||
val uri = file.uri ?: return false
|
val uri = file.uri ?: return false
|
||||||
return withContext(Dispatchers.IO) {
|
return withContext(Dispatchers.IO) {
|
||||||
runCatching {
|
val now = System.currentTimeMillis()
|
||||||
DocumentsContract.deleteDocument(resolver, Uri.parse(uri))
|
appDatabase.withTransaction {
|
||||||
}.onSuccess { deleted ->
|
fileRepository.markMissing(file.resourceId, now)
|
||||||
if (deleted) {
|
// Gate « processed » + annulation (M19) : si le fichier
|
||||||
val now = System.currentTimeMillis()
|
// n'a jamais été poussé (create encore pending), on
|
||||||
appDatabase.withTransaction {
|
// annule le create au lieu d'un delete bruit ; le
|
||||||
fileRepository.markMissing(file.resourceId, now)
|
// delete n'est journalisé que si le serveur connaît
|
||||||
// Gate « processed » : si le fichier n'a jamais été poussé
|
// déjà la ressource (create synced).
|
||||||
// (create_resource absent), le serveur n'en sait rien —
|
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||||
// un delete_resource serait du bruit. On ne le journalise
|
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||||
// que pour les ressources déjà synchronisées.
|
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||||
if (outboxRepository.hasCreateOperation(file.resourceId)) {
|
|
||||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Timber.d("deleted %s", uri)
|
|
||||||
thumbnailStore.delete(file.resourceId)
|
|
||||||
} else {
|
|
||||||
Timber.w("deleteDocument returned false for %s", uri)
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
val deleted = runCatching {
|
||||||
|
DocumentsContract.deleteDocument(resolver, Uri.parse(uri))
|
||||||
}.onFailure { e ->
|
}.onFailure { e ->
|
||||||
Timber.w(e, "deleteDocument failed for %s", uri)
|
Timber.w(e, "deleteDocument failed for %s (sweep will retry)", uri)
|
||||||
}.getOrDefault(false)
|
}.getOrDefault(false)
|
||||||
|
if (deleted) {
|
||||||
|
Timber.d("deleted %s", uri)
|
||||||
|
thumbnailStore.delete(file.resourceId)
|
||||||
|
} else {
|
||||||
|
Timber.w("deleteDocument returned false for %s (sweep will retry)", uri)
|
||||||
|
}
|
||||||
|
deleted
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -36,11 +36,28 @@ object CornerGeometry {
|
|||||||
return abs(sum) / 2f
|
return abs(sum) / 2f
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Dimensions du document redressé (moyenne des côtés opposés). */
|
/** Dimensions du document redressé (plus grand des côtés opposés). */
|
||||||
fun outputSize(points: List<PointF>): Pair<Int, Int> {
|
fun outputSize(points: List<PointF>): Pair<Int, Int> {
|
||||||
val (tl, tr, br, bl) = orderPoints(points)
|
val (tl, tr, br, bl) = orderPoints(points)
|
||||||
val w = max(distance(tl, tr), distance(bl, br))
|
val w = max(distance(tl, tr), distance(bl, br))
|
||||||
val h = max(distance(tl, bl), distance(tr, br))
|
val h = max(distance(tl, bl), distance(tr, br))
|
||||||
return w.roundToInt() to h.roundToInt()
|
return w.roundToInt() to h.roundToInt()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quad inexploitable (coins dupliqués, aire nulle, aplati) : le warp
|
||||||
|
* produirait une page blanche 1×1 validée par erreur — l'appelant doit
|
||||||
|
* refuser la page au lieu de la persister.
|
||||||
|
*/
|
||||||
|
fun isDegenerate(points: List<PointF>, epsilon: Float = 0.5f): Boolean {
|
||||||
|
if (points.size != 4) return true
|
||||||
|
for (i in points.indices) {
|
||||||
|
for (j in i + 1 until points.size) {
|
||||||
|
if (distance(points[i], points[j]) <= epsilon) return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (area(points) <= epsilon) return true
|
||||||
|
val (w, h) = outputSize(points)
|
||||||
|
return w <= 0 || h <= 0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.kazier.mobile.features.scan
|
||||||
|
|
||||||
|
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.ScanPageStatus
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Décisions pures de l'export d'une session de scan (aucune IO) :
|
||||||
|
* - **retry idempotent** : seul le `PENDING` est (ré)exporté, jamais le
|
||||||
|
* `EXPORTED` (chaque retry créait sinon un nouvel URI SAF + ligne Room +
|
||||||
|
* op outbox en double) ;
|
||||||
|
* - **pas de DONE partiel** : la session ne passe `DONE` que si tout a
|
||||||
|
* réussi ; un temp manquant ou une page en échec reste `PENDING` pour
|
||||||
|
* reprise, la session reste active avec un message d'erreur.
|
||||||
|
*/
|
||||||
|
object ScanExport {
|
||||||
|
|
||||||
|
/** Pages à (ré)exporter : les `PENDING` dans l'ordre de la session. */
|
||||||
|
fun pendingForExport(pages: List<ScanPageEntity>): List<ScanPageEntity> =
|
||||||
|
pages.filter { it.status == ScanPageStatus.PENDING }
|
||||||
|
|
||||||
|
/** Pages effectivement embarquées (succès seuls, jamais les échecs). */
|
||||||
|
fun succeeded(
|
||||||
|
pages: List<ScanPageEntity>,
|
||||||
|
failedIds: Set<String>,
|
||||||
|
): List<ScanPageEntity> =
|
||||||
|
pages.filterNot { it.resourceId in failedIds }
|
||||||
|
|
||||||
|
/** La session ne se termine que si aucune page n'a échoué. */
|
||||||
|
fun shouldFinishSession(failedCount: Int): Boolean = failedCount == 0
|
||||||
|
}
|
||||||
+9
-1
@@ -39,7 +39,7 @@ class ScanImageProcessor @Inject constructor() {
|
|||||||
|
|
||||||
fun isAvailable(): Boolean {
|
fun isAvailable(): Boolean {
|
||||||
if (!loaded) {
|
if (!loaded) {
|
||||||
loaded = OpenCVLoader.initLocal()
|
loaded = runCatching { OpenCVLoader.initLocal() }.getOrDefault(false)
|
||||||
}
|
}
|
||||||
return loaded
|
return loaded
|
||||||
}
|
}
|
||||||
@@ -83,9 +83,14 @@ class ScanImageProcessor @Inject constructor() {
|
|||||||
/**
|
/**
|
||||||
* Redresse (`warpPerspective`) selon `quad` puis applique le mode de rendu.
|
* Redresse (`warpPerspective`) selon `quad` puis applique le mode de rendu.
|
||||||
* Sortie plafonnée à [MAX_OUTPUT_SIDE] px sur le grand côté.
|
* Sortie plafonnée à [MAX_OUTPUT_SIDE] px sur le grand côté.
|
||||||
|
*
|
||||||
|
* Contrat alias : si OpenCV est indisponible, retourne l'instance d'entrée
|
||||||
|
* elle-même — l'appelant ne doit la recycler que s'il a reçu une nouvelle
|
||||||
|
* instance (`processed !== input`), jamais un alias du bitmap affiché.
|
||||||
*/
|
*/
|
||||||
fun process(bitmap: Bitmap, quad: ScanQuad, mode: ScanRenderMode): Bitmap {
|
fun process(bitmap: Bitmap, quad: ScanQuad, mode: ScanRenderMode): Bitmap {
|
||||||
if (!isAvailable()) return bitmap
|
if (!isAvailable()) return bitmap
|
||||||
|
require(!CornerGeometry.isDegenerate(quad.points)) { "degenerate quad" }
|
||||||
val (targetW, targetH) = CornerGeometry.outputSize(quad.points)
|
val (targetW, targetH) = CornerGeometry.outputSize(quad.points)
|
||||||
val maxSide = max(targetW, targetH)
|
val maxSide = max(targetW, targetH)
|
||||||
val outScale = min(1f, MAX_OUTPUT_SIDE.toFloat() / maxSide)
|
val outScale = min(1f, MAX_OUTPUT_SIDE.toFloat() / maxSide)
|
||||||
@@ -177,6 +182,9 @@ class ScanImageProcessor @Inject constructor() {
|
|||||||
blur.release()
|
blur.release()
|
||||||
edges.release()
|
edges.release()
|
||||||
hierarchy.release()
|
hierarchy.release()
|
||||||
|
// Contours non consommés (exception à mi-boucle) : `release()` est
|
||||||
|
// idempotent côté OpenCV, les déjà-libérés sont des no-ops.
|
||||||
|
contours.forEach { runCatching { it.release() } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import com.kazier.mobile.data.repository.FolderRepository
|
|||||||
import com.kazier.mobile.data.repository.OutboxRepository
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
import com.kazier.mobile.data.repository.SaveFileInput
|
import com.kazier.mobile.data.repository.SaveFileInput
|
||||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
@@ -36,7 +36,7 @@ class DeviceSync @Inject constructor(
|
|||||||
private val folderRepository: FolderRepository,
|
private val folderRepository: FolderRepository,
|
||||||
private val fileRepository: FileRepository,
|
private val fileRepository: FileRepository,
|
||||||
private val outboxRepository: OutboxRepository,
|
private val outboxRepository: OutboxRepository,
|
||||||
private val deviceIdentity: DeviceIdentity,
|
private val activeUserStore: ActiveUserStore,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
data class SyncResult(
|
data class SyncResult(
|
||||||
@@ -66,7 +66,8 @@ class DeviceSync @Inject constructor(
|
|||||||
|
|
||||||
private suspend fun doSyncRoot(root: FolderEntity): SyncResult {
|
private suspend fun doSyncRoot(root: FolderEntity): SyncResult {
|
||||||
val rootUri = checkNotNull(root.uri) { "root '${root.name}' has no physical uri" }
|
val rootUri = checkNotNull(root.uri) { "root '${root.name}' has no physical uri" }
|
||||||
val ownerId = deviceIdentity.getOrCreate()
|
// `owner_id` Room = user_id du compte actif, jamais l'identité device.
|
||||||
|
val ownerId = activeUserStore.get()
|
||||||
|
|
||||||
// Phase 1 — listing SAF (I/O disque, HORS transaction).
|
// Phase 1 — listing SAF (I/O disque, HORS transaction).
|
||||||
val folders = scanner.scanTree(Uri.parse(rootUri))
|
val folders = scanner.scanTree(Uri.parse(rootUri))
|
||||||
@@ -79,9 +80,22 @@ class DeviceSync @Inject constructor(
|
|||||||
|
|
||||||
for (folder in folders) {
|
for (folder in folders) {
|
||||||
seen += folder.uri
|
seen += folder.uri
|
||||||
val parentResourceId =
|
val parentResourceId = if (folder.parentUri == null) {
|
||||||
if (folder.parentUri == null) null
|
null
|
||||||
else resourceIdByUri[folder.parentUri] ?: root.resourceId
|
} else {
|
||||||
|
resourceIdByUri[folder.parentUri]
|
||||||
|
}
|
||||||
|
if (folder.parentUri != null && parentResourceId == null) {
|
||||||
|
// Violation parent-avant-enfant (snapshot incohérent) : on
|
||||||
|
// n'attache JAMAIS à la racine par défaut — le dossier est
|
||||||
|
// ignoré et journalisé, le prochain walk convergera.
|
||||||
|
Timber.w(
|
||||||
|
"walk: parent SAF inconnu, dossier ignoré (uri=%s parent=%s)",
|
||||||
|
folder.uri,
|
||||||
|
folder.parentUri,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
val saved = folderRepository.saveFolder(
|
val saved = folderRepository.saveFolder(
|
||||||
SaveFolderInput(uri = folder.uri, name = folder.name, exists = true),
|
SaveFolderInput(uri = folder.uri, name = folder.name, exists = true),
|
||||||
parentResourceId = parentResourceId,
|
parentResourceId = parentResourceId,
|
||||||
@@ -91,7 +105,9 @@ class DeviceSync @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (folder in folders) {
|
for (folder in folders) {
|
||||||
val folderResourceId = resourceIdByUri[folder.uri] ?: root.resourceId
|
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne
|
||||||
|
// sont pas rattachés à la racine, ils attendent le walk suivant.
|
||||||
|
val folderResourceId = resourceIdByUri[folder.uri] ?: continue
|
||||||
for (file in folder.files) {
|
for (file in folder.files) {
|
||||||
seen += file.uri
|
seen += file.uri
|
||||||
fileRepository.saveLocalFile(
|
fileRepository.saveLocalFile(
|
||||||
@@ -114,21 +130,30 @@ class DeviceSync @Inject constructor(
|
|||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
for (folder in folderRepository.getAll()) {
|
for (folder in folderRepository.getAll()) {
|
||||||
val folderUri = folder.uri
|
val folderUri = folder.uri
|
||||||
if (folder.exists != 0 && folderUri != null && isChildOf(folderUri, rootUri) && folderUri !in seen) {
|
if (folder.exists != 0 && folderUri != null && isChildOf(folderUri, rootUri) && folderUri !in seen &&
|
||||||
|
!outboxRepository.hasPendingMoveOperation(folder.resourceId)
|
||||||
|
) {
|
||||||
folderRepository.markMissing(folder.resourceId, now)
|
folderRepository.markMissing(folder.resourceId, now)
|
||||||
|
// Disparu avant push : annule le create pending (M19) —
|
||||||
|
// le serveur ne doit ni le créer ni l'oublier.
|
||||||
|
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||||
missing++
|
missing++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (file in fileRepository.getAll()) {
|
for (file in fileRepository.getAll()) {
|
||||||
val fileUri = file.uri
|
val fileUri = file.uri
|
||||||
// Un `move_resource` (pending ou synced) fait de l'outbox la
|
// Un `move_resource` encore `pending` fait de l'outbox la
|
||||||
// source de vérité du placement : on ne masque jamais une ligne
|
// source de vérité du placement : on ne masque jamais une ligne
|
||||||
// en transition vers une autre arborescence physique (le
|
// en transition vers une autre arborescence physique (le
|
||||||
// snapshot peut être périmé par rapport au move en cours).
|
// snapshot peut être périmé par rapport au move en cours).
|
||||||
|
// Un move déjà `synced` ne protège plus : si le fichier a
|
||||||
|
// ensuite disparu du disque, c'est une vraie suppression
|
||||||
|
// (sinon fantôme `exists = 1` éternel, M4).
|
||||||
if (file.exists != 0 && fileUri != null && isChildOf(fileUri, rootUri) && fileUri !in seen &&
|
if (file.exists != 0 && fileUri != null && isChildOf(fileUri, rootUri) && fileUri !in seen &&
|
||||||
!outboxRepository.hasMoveOperation(file.resourceId)
|
!outboxRepository.hasPendingMoveOperation(file.resourceId)
|
||||||
) {
|
) {
|
||||||
fileRepository.markMissing(file.resourceId, now)
|
fileRepository.markMissing(file.resourceId, now)
|
||||||
|
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||||
missing++
|
missing++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+130
-24
@@ -17,17 +17,53 @@ import com.kazier.mobile.auth.TokenProvider
|
|||||||
import com.kazier.mobile.data.local.dao.FileDao
|
import com.kazier.mobile.data.local.dao.FileDao
|
||||||
import com.kazier.mobile.data.local.dao.FolderDao
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.ApiException
|
import com.kazier.mobile.data.remote.ApiException
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpDto
|
import com.kazier.mobile.data.remote.dto.SyncOpDto
|
||||||
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
import com.kazier.mobile.features.ocr.OcrAutoWorker
|
import com.kazier.mobile.features.ocr.OcrAutoWorker
|
||||||
import dagger.assisted.Assisted
|
import dagger.assisted.Assisted
|
||||||
import dagger.assisted.AssistedInject
|
import dagger.assisted.AssistedInject
|
||||||
|
import java.util.ArrayDeque
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalise les nombres d'un payload décodé : Moshi parse tout nombre JSON
|
||||||
|
* en `Double` dans un `Map<String, Any?>` — les entiers (ex. `expiresAt` en
|
||||||
|
* ms) doivent repartir comme entiers exacts, sinon le serveur refuse
|
||||||
|
* `1.7E12` (M24). Récursif (maps/listes imbriquées).
|
||||||
|
*/
|
||||||
|
internal fun normalizePayloadNumbers(payload: Map<String, Any?>): Map<String, Any?> =
|
||||||
|
payload.mapValues { (_, value) -> normalizePayloadValue(value) }
|
||||||
|
|
||||||
|
private fun normalizePayloadValue(value: Any?): Any? = when (value) {
|
||||||
|
is Double ->
|
||||||
|
if (value % 1.0 == 0.0 && value >= Long.MIN_VALUE.toDouble() &&
|
||||||
|
value <= Long.MAX_VALUE.toDouble()
|
||||||
|
) {
|
||||||
|
value.toLong()
|
||||||
|
} else {
|
||||||
|
value
|
||||||
|
}
|
||||||
|
is Float ->
|
||||||
|
if (value % 1f == 0f && value >= Long.MIN_VALUE.toFloat() &&
|
||||||
|
value <= Long.MAX_VALUE.toFloat()
|
||||||
|
) {
|
||||||
|
value.toLong()
|
||||||
|
} else {
|
||||||
|
value
|
||||||
|
}
|
||||||
|
is Map<*, *> ->
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
normalizePayloadNumbers(value as Map<String, Any?>)
|
||||||
|
is List<*> -> value.map { normalizePayloadValue(it) }
|
||||||
|
else -> value
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Worker de push de l'outbox : applique les batchs `pending_operations` vers
|
* Worker de push de l'outbox : applique les batchs `pending_operations` vers
|
||||||
* `POST /sync/ops`, séquentiellement et dans l'ordre d'entrée en file.
|
* `POST /sync/ops`, séquentiellement et dans l'ordre d'entrée en file.
|
||||||
@@ -36,12 +72,16 @@ import timber.log.Timber
|
|||||||
* - **single-flight** : enregistré via `enqueueUniqueWork(KEEP)` — jamais deux
|
* - **single-flight** : enregistré via `enqueueUniqueWork(KEEP)` — jamais deux
|
||||||
* workers parallèles (ordonnancement chronologique préservé) ;
|
* workers parallèles (ordonnancement chronologique préservé) ;
|
||||||
* - **no-op sans token** : mode local, rien à pousser (contrat syncOutbox) ;
|
* - **no-op sans token** : mode local, rien à pousser (contrat syncOutbox) ;
|
||||||
* - **retry transient** : `NETWORK_ERROR`/5xx/timeout → `Result.retry()`
|
* - **retry transient ou non-attribuable** : `NETWORK_ERROR`/5xx/429/408,
|
||||||
* (backoff exponentiel) sans bump du compteur d'attempts ;
|
* `INVALID_RESPONSE` et toute erreur batch-level non-401 → `Result.retry()`
|
||||||
* - **dead-letter permanent** : erreur 4xx non-idempotente → op passée en
|
* (backoff exponentiel) sans toucher aux ops — la faute ne peut pas être
|
||||||
* `failed` immédiatement (évite d'affamer la queue : le serveur s'arrête à
|
* imputée à une op du batch, le rejeu est sûr (idempotence serveur) ;
|
||||||
* la 1re erreur), et cascade si `create_resource` a échoué (toutes les ops
|
* - **dead-letter permanente** : seule l'erreur par-op (`failed` dans le
|
||||||
* filles en attente sur la même resource passent `failed`) ;
|
* `200`) passe l'op en `failed` immédiatement (évite d'affamer la queue :
|
||||||
|
* le serveur s'arrête à la 1re erreur) puis **stoppe le run** — jamais de
|
||||||
|
* batch suivant dans le même run ; si un `create_resource` a échoué, les
|
||||||
|
* ops filles en attente (même ressource + enfants via
|
||||||
|
* `payload.parentResourceId`, transitif) passent `failed` ;
|
||||||
* - `attempts` est un compteur diagnostic (incrémenté à chaque dead-letter),
|
* - `attempts` est un compteur diagnostic (incrémenté à chaque dead-letter),
|
||||||
* pas un seuil : une op `failed` n'est plus resélectionnée.
|
* pas un seuil : une op `failed` n'est plus resélectionnée.
|
||||||
* - push **avant** pull : le pull `GET /sync/permissions` (V2) s'appliquera
|
* - push **avant** pull : le pull `GET /sync/permissions` (V2) s'appliquera
|
||||||
@@ -90,26 +130,35 @@ class OutboxSyncWorker @AssistedInject constructor(
|
|||||||
apiClient.syncOps(ops)
|
apiClient.syncOps(ops)
|
||||||
} catch (e: ApiException) {
|
} catch (e: ApiException) {
|
||||||
when {
|
when {
|
||||||
e.code == "NETWORK_ERROR" || e.httpCode >= 500 -> {
|
|
||||||
// Transitoire : on retentera avec backoff, sans bump d'attempts.
|
|
||||||
return Result.retry()
|
|
||||||
}
|
|
||||||
e.httpCode == 401 -> {
|
e.httpCode == 401 -> {
|
||||||
// Token expiré/révoqué : le re-login se fera via l'UI.
|
// Token expiré/révoqué : `onUnauthorized` (scope
|
||||||
|
// applicatif) a purgé la session. Succès : le re-login
|
||||||
|
// ré-enqueue le drain (m3).
|
||||||
return Result.success()
|
return Result.success()
|
||||||
}
|
}
|
||||||
else -> {
|
else -> {
|
||||||
// Erreur permanente : dead-letter la 1re op du batch.
|
// Transitoire (NETWORK_ERROR/5xx/429/408) ou
|
||||||
val now = System.currentTimeMillis()
|
// non-attribuable (INVALID_RESPONSE, 4xx batch-level) :
|
||||||
pendingOperationDao.markFailed(pending.first().id, now)
|
// rejouer avec backoff SANS toucher aux ops. La faute
|
||||||
continue
|
// ne peut pas être imputée à la 1re op du batch (C2) —
|
||||||
|
// le rejeu est sûr (idempotence serveur).
|
||||||
|
return Result.retry()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
|
// Garde C7 : `applied` incohérent → clamp, jamais de crash.
|
||||||
|
val appliedCount = result.applied.coerceIn(0, pending.size)
|
||||||
|
if (appliedCount != result.applied) {
|
||||||
|
Timber.w(
|
||||||
|
"outbox applied incohérent (%d pour %d ops), clamp",
|
||||||
|
result.applied,
|
||||||
|
pending.size,
|
||||||
|
)
|
||||||
|
}
|
||||||
// Ops appliquées par le serveur (indices < applied).
|
// Ops appliquées par le serveur (indices < applied).
|
||||||
for (i in 0 until result.applied) {
|
for (i in 0 until appliedCount) {
|
||||||
pendingOperationDao.markSynced(pending[i].id, now)
|
pendingOperationDao.markSynced(pending[i].id, now)
|
||||||
promotePlacement(pending[i])
|
promotePlacement(pending[i])
|
||||||
Timber.d("outbox synced %s", pending[i].operationId)
|
Timber.d("outbox synced %s", pending[i].operationId)
|
||||||
@@ -118,16 +167,32 @@ class OutboxSyncWorker @AssistedInject constructor(
|
|||||||
// Première erreur non-idempotente → dead-letter + cascade éventuelle.
|
// Première erreur non-idempotente → dead-letter + cascade éventuelle.
|
||||||
result.failed?.let { fail ->
|
result.failed?.let { fail ->
|
||||||
val failedIndex = pending.indexOfFirst { it.operationId == fail.operationId }
|
val failedIndex = pending.indexOfFirst { it.operationId == fail.operationId }
|
||||||
if (failedIndex >= 0) {
|
if (failedIndex < 0) {
|
||||||
val failedOp = pending[failedIndex]
|
// Garde C7 : `operation_id` inconnu → stop, pas de boucle
|
||||||
pendingOperationDao.markFailed(failedOp.id, now)
|
// serrée sur le même batch.
|
||||||
Timber.w("outbox failed %s (%s: %s)", fail.operationId, fail.code, fail.message)
|
Timber.w("outbox failed inconnu %s, arrêt du run", fail.operationId)
|
||||||
if (failedOp.operation == PendingOperationType.CREATE_RESOURCE) {
|
return Result.success()
|
||||||
failedOp.resourceId?.let { resourceId ->
|
}
|
||||||
pendingOperationDao.failDescendants(resourceId, now)
|
val failedOp = pending[failedIndex]
|
||||||
}
|
pendingOperationDao.markFailed(failedOp.id, now)
|
||||||
|
Timber.w("outbox failed %s (%s: %s)", fail.operationId, fail.code, fail.message)
|
||||||
|
if (failedOp.operation == PendingOperationType.CREATE_RESOURCE) {
|
||||||
|
failedOp.resourceId?.let { resourceId ->
|
||||||
|
pendingOperationDao.failDescendants(resourceId, now)
|
||||||
|
cascadeCreateFailure(resourceId, now)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// C6 : stop au 1er échec — le serveur s'est arrêté là, tout ce
|
||||||
|
// qui suit reste pending pour le prochain run (jamais de
|
||||||
|
// `continue` vers le batch suivant).
|
||||||
|
return Result.success()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Garde C7 : aucun progrès (`applied == 0`, `failed == null`) →
|
||||||
|
// sortie, sinon busy-loop sans backoff.
|
||||||
|
if (appliedCount == 0) {
|
||||||
|
Timber.w("outbox aucun progrès (applied=0, failed=null), arrêt du run")
|
||||||
|
return Result.success()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Boucle : d'autres batchs attendent → traité dans le même run.
|
// Boucle : d'autres batchs attendent → traité dans le même run.
|
||||||
@@ -158,6 +223,7 @@ class OutboxSyncWorker @AssistedInject constructor(
|
|||||||
|
|
||||||
private fun PendingOperationEntity.toSyncOpDto(): SyncOpDto {
|
private fun PendingOperationEntity.toSyncOpDto(): SyncOpDto {
|
||||||
val payloadMap = runCatching { payloadAdapter.fromJson(payload) }.getOrNull()
|
val payloadMap = runCatching { payloadAdapter.fromJson(payload) }.getOrNull()
|
||||||
|
?.let { normalizePayloadNumbers(it) }
|
||||||
return SyncOpDto(
|
return SyncOpDto(
|
||||||
operationId = operationId,
|
operationId = operationId,
|
||||||
refType = refType,
|
refType = refType,
|
||||||
@@ -169,10 +235,50 @@ class OutboxSyncWorker @AssistedInject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invalidation transitive après l'échec d'un `create_resource` : les
|
||||||
|
* enfants portent un autre `resource_id`, liés via
|
||||||
|
* `payload.parentResourceId` (le walk émet parent avant enfant). Parcours
|
||||||
|
* en largeur depuis la ressource fautive sur l'ensemble des ops en
|
||||||
|
* attente — chaque niveau est invalidé via `failDescendants`.
|
||||||
|
*/
|
||||||
|
private suspend fun cascadeCreateFailure(failedResourceId: String, now: Long) {
|
||||||
|
val visited = mutableSetOf(failedResourceId)
|
||||||
|
val frontier = ArrayDeque<String>().apply { add(failedResourceId) }
|
||||||
|
while (frontier.isNotEmpty()) {
|
||||||
|
val current = frontier.removeFirst()
|
||||||
|
val children = pendingOperationDao.selectPending(CASCADE_SCAN_LIMIT)
|
||||||
|
.mapNotNull { op ->
|
||||||
|
val childId = op.resourceId
|
||||||
|
if (op.status == PendingOpStatus.PENDING && childId != null &&
|
||||||
|
childId !in visited && parentResourceIdOf(op) == current
|
||||||
|
) {
|
||||||
|
childId
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.distinct()
|
||||||
|
for (child in children) {
|
||||||
|
if (visited.add(child)) {
|
||||||
|
pendingOperationDao.failDescendants(child, now)
|
||||||
|
frontier.add(child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lien parent→enfant : colonne dénormalisée, repli parsing JSON (lignes pré-v14). */
|
||||||
|
private fun parentResourceIdOf(op: PendingOperationEntity): String? =
|
||||||
|
op.parentResourceId ?: runCatching { payloadAdapter.fromJson(op.payload) }
|
||||||
|
.getOrNull()?.get(OutboxRepository.PARENT_PAYLOAD_KEY) as? String
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val NAME = "outbox_sync"
|
const val NAME = "outbox_sync"
|
||||||
private const val BATCH_SIZE = 20
|
private const val BATCH_SIZE = 20
|
||||||
private const val PURGE_AGE_MS = 7 * 24 * 60 * 60 * 1000L
|
private const val PURGE_AGE_MS = 7 * 24 * 60 * 60 * 1000L
|
||||||
|
/** Fenêtre de balayage de la cascade (au-delà, convergence au run suivant). */
|
||||||
|
private const val CASCADE_SCAN_LIMIT = 10_000
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enregistre (idempotent) le worker avec contrainte réseau + backoff.
|
* Enregistre (idempotent) le worker avec contrainte réseau + backoff.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.ensureActive
|
import kotlinx.coroutines.ensureActive
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import kotlinx.coroutines.yield
|
import kotlinx.coroutines.yield
|
||||||
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -51,7 +52,9 @@ class SafScanner @Inject constructor(
|
|||||||
|
|
||||||
/** Marche la racine `treeUri` ; renvoie tous les dossiers en ordre préfixe (DFS). */
|
/** Marche la racine `treeUri` ; renvoie tous les dossiers en ordre préfixe (DFS). */
|
||||||
suspend fun scanTree(treeUri: Uri): List<FolderNode> = withContext(Dispatchers.IO) {
|
suspend fun scanTree(treeUri: Uri): List<FolderNode> = withContext(Dispatchers.IO) {
|
||||||
val rootDocId = DocumentsContract.getTreeDocumentId(treeUri)
|
val rootDocId = runCatching { DocumentsContract.getTreeDocumentId(treeUri) }
|
||||||
|
.onFailure { Timber.w(it, "scanTree: treeUri illisible %s", treeUri) }
|
||||||
|
.getOrNull() ?: return@withContext emptyList()
|
||||||
val root = ScanFolder(
|
val root = ScanFolder(
|
||||||
uri = treeUri.toString(),
|
uri = treeUri.toString(),
|
||||||
docId = rootDocId,
|
docId = rootDocId,
|
||||||
@@ -110,52 +113,64 @@ class SafScanner @Inject constructor(
|
|||||||
val folders = ArrayList<ChildDir>()
|
val folders = ArrayList<ChildDir>()
|
||||||
val files = ArrayList<FileNode>()
|
val files = ArrayList<FileNode>()
|
||||||
|
|
||||||
resolver.query(
|
// Permission révoquée / provider KO : dossier vu vide, jamais de crash
|
||||||
childrenUri,
|
// (le walk réessaiera au prochain tick, la réconciliation ne supprime rien).
|
||||||
arrayOf(
|
runCatching {
|
||||||
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
resolver.query(
|
||||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
childrenUri,
|
||||||
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
arrayOf(
|
||||||
DocumentsContract.Document.COLUMN_SIZE,
|
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||||
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
|
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||||
),
|
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
||||||
null,
|
DocumentsContract.Document.COLUMN_SIZE,
|
||||||
null,
|
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
|
||||||
"${DocumentsContract.Document.COLUMN_DISPLAY_NAME} ASC",
|
),
|
||||||
)?.use { cursor ->
|
null,
|
||||||
val iDoc = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
|
null,
|
||||||
val iName = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
"${DocumentsContract.Document.COLUMN_DISPLAY_NAME} ASC",
|
||||||
val iMime = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE)
|
)?.use { cursor ->
|
||||||
val iSize = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_SIZE)
|
val iDoc = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
|
||||||
val iLast = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
// Curseur dégénéré (colonne DOCUMENT_ID absente) : dossier vu
|
||||||
|
// vide plutôt que crash de tout le walk.
|
||||||
|
if (iDoc < 0) return@use
|
||||||
|
val iName = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
||||||
|
val iMime = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE)
|
||||||
|
val iSize = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_SIZE)
|
||||||
|
val iLast = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
||||||
|
|
||||||
while (cursor.moveToNext()) {
|
while (cursor.moveToNext()) {
|
||||||
val docId = cursor.getString(iDoc)
|
val docId = if (!cursor.isNull(iDoc)) cursor.getString(iDoc) else null
|
||||||
if (docId == dirDocId) continue // certains providers renvoient le dossier lui-même
|
if (docId.isNullOrEmpty()) continue
|
||||||
val name = if (iName >= 0) cursor.getString(iName)
|
if (docId == dirDocId) continue // certains providers renvoient le dossier lui-même
|
||||||
else docId.substringAfterLast('/')
|
var name = if (iName >= 0 && !cursor.isNull(iName)) cursor.getString(iName) else null
|
||||||
val mime = if (iMime >= 0) cursor.getString(iMime) else null
|
if (name.isNullOrEmpty()) name = docId.substringAfterLast('/')
|
||||||
|
if (name.isNullOrEmpty()) continue
|
||||||
|
val mime = if (iMime >= 0 && !cursor.isNull(iMime)) cursor.getString(iMime) else null
|
||||||
|
|
||||||
if (name.startsWith(".")) continue
|
if (name.startsWith(".")) continue
|
||||||
|
|
||||||
if (mime == DocumentsContract.Document.MIME_TYPE_DIR) {
|
if (mime == DocumentsContract.Document.MIME_TYPE_DIR) {
|
||||||
val uri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId).toString()
|
val uri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId).toString()
|
||||||
folders += ChildDir(docId, uri, name)
|
folders += ChildDir(docId, uri, name)
|
||||||
} else {
|
} else {
|
||||||
val size = if (iSize >= 0 && !cursor.isNull(iSize)) cursor.getLong(iSize) else 0L
|
val size = if (iSize >= 0 && !cursor.isNull(iSize)) cursor.getLong(iSize) else 0L
|
||||||
if (size == 0L) continue
|
// Les fichiers 0-octet sont des documents légitimes
|
||||||
if (KNOWN_NOISE_EXTENSIONS.any { name.endsWith(it, ignoreCase = true) }) continue
|
// (notes vides, exports) : importés et reviewés comme les autres.
|
||||||
|
if (KNOWN_NOISE_EXTENSIONS.any { name.endsWith(it, ignoreCase = true) }) continue
|
||||||
|
|
||||||
val uri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId).toString()
|
val uri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId).toString()
|
||||||
files += FileNode(
|
files += FileNode(
|
||||||
uri = uri,
|
uri = uri,
|
||||||
name = name,
|
name = name,
|
||||||
size = size,
|
size = size,
|
||||||
mimeType = mime,
|
mimeType = mime,
|
||||||
lastModified = if (iLast >= 0 && !cursor.isNull(iLast)) cursor.getLong(iLast) else null,
|
lastModified = if (iLast >= 0 && !cursor.isNull(iLast)) cursor.getLong(iLast) else null,
|
||||||
)
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}.onFailure { e ->
|
||||||
|
Timber.w(e, "scanTree: listing impossible pour %s", dirDocId)
|
||||||
}
|
}
|
||||||
return DirContents(folders, files)
|
return DirContents(folders, files)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import com.kazier.mobile.data.repository.FolderRepository
|
|||||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||||
import com.kazier.mobile.data.repository.ShareRepository
|
import com.kazier.mobile.data.repository.ShareRepository
|
||||||
import com.kazier.mobile.features.ocr.OcrAutoWorker
|
import com.kazier.mobile.features.ocr.OcrAutoWorker
|
||||||
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
|
import com.kazier.mobile.features.saf.FolderDeleter
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
@@ -49,6 +51,8 @@ class SyncViewModel @Inject constructor(
|
|||||||
private val folderRepository: FolderRepository,
|
private val folderRepository: FolderRepository,
|
||||||
private val pendingOperationDao: PendingOperationDao,
|
private val pendingOperationDao: PendingOperationDao,
|
||||||
private val shareRepository: ShareRepository,
|
private val shareRepository: ShareRepository,
|
||||||
|
private val fileDeleter: FileDeleter,
|
||||||
|
private val folderDeleter: FolderDeleter,
|
||||||
@ApplicationContext private val appContext: Context,
|
@ApplicationContext private val appContext: Context,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
@@ -110,6 +114,16 @@ class SyncViewModel @Inject constructor(
|
|||||||
OutboxSyncWorker.enqueue(appContext)
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
// OCR auto : uploader les octets des fichiers récemment promus (local-cloud).
|
// OCR auto : uploader les octets des fichiers récemment promus (local-cloud).
|
||||||
OcrAutoWorker.enqueue(appContext)
|
OcrAutoWorker.enqueue(appContext)
|
||||||
|
// Repasse C4 : les suppressions journalisées dont les
|
||||||
|
// octets ont survécu (crash entre journal et SAF).
|
||||||
|
runCatching {
|
||||||
|
fileDeleter.sweepPendingPhysicalDeletes() +
|
||||||
|
folderDeleter.sweepPendingPhysicalDeletes()
|
||||||
|
}.onSuccess { swept ->
|
||||||
|
if (swept > 0) Timber.d("sweep: %d suppressions physiques rattrapées", swept)
|
||||||
|
}.onFailure { e ->
|
||||||
|
Timber.w(e, "sweep failed, retrying later")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.onFailure { e -> Timber.w(e, "syncAll failed, retrying later") }
|
.onFailure { e -> Timber.w(e, "syncAll failed, retrying later") }
|
||||||
// Hydrate les ressources partagées depuis le snapshot serveur.
|
// Hydrate les ressources partagées depuis le snapshot serveur.
|
||||||
@@ -143,6 +157,14 @@ class SyncViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
val result = deviceSync.syncRoot(saved.resourceId)
|
val result = deviceSync.syncRoot(saved.resourceId)
|
||||||
Timber.d("syncRoot %s", result)
|
Timber.d("syncRoot %s", result)
|
||||||
|
// Même drain qu'après `syncAll` (M7) : le `create_resource` de
|
||||||
|
// la racine ne doit pas dormir jusqu'au prochain tick.
|
||||||
|
OutboxSyncWorker.enqueue(appContext)
|
||||||
|
OcrAutoWorker.enqueue(appContext)
|
||||||
|
runCatching {
|
||||||
|
fileDeleter.sweepPendingPhysicalDeletes() +
|
||||||
|
folderDeleter.sweepPendingPhysicalDeletes()
|
||||||
|
}.onFailure { e -> Timber.w(e, "sweep failed, retrying later") }
|
||||||
} catch (e: CancellationException) {
|
} catch (e: CancellationException) {
|
||||||
throw e
|
throw e
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
|||||||
+67
-12
@@ -54,6 +54,19 @@ class ThumbnailStore @Inject constructor(
|
|||||||
internal fun thumbnailFile(resourceId: String): File =
|
internal fun thumbnailFile(resourceId: String): File =
|
||||||
File(dir(), "$resourceId.webp")
|
File(dir(), "$resourceId.webp")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fichier cible versionné `mtime + taille` de la source : après une
|
||||||
|
* édition rapide (mtime SAF à la seconde près), la taille différente
|
||||||
|
* invalide l'ancien fichier même si les mtime coïncident.
|
||||||
|
*/
|
||||||
|
internal fun thumbnailFile(resourceId: String, lastModified: Long?, size: Long?): File {
|
||||||
|
if (lastModified == null || size == null) return thumbnailFile(resourceId)
|
||||||
|
return File(dir(), "${resourceId}_${lastModified}_${size}.webp")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombre de verrous single-flight en cours (diagnostic/tests). */
|
||||||
|
internal fun lockCount(): Int = locks.size
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Vignette du fichier, générée si absente ou périmée. `null` si le fichier
|
* Vignette du fichier, générée si absente ou périmée. `null` si le fichier
|
||||||
* n'est ni image ni PDF, n'a pas d'uri, ou si la génération échoue
|
* n'est ni image ni PDF, n'a pas d'uri, ou si la génération échoue
|
||||||
@@ -64,24 +77,57 @@ class ThumbnailStore @Inject constructor(
|
|||||||
val category = file.categoryValue()
|
val category = file.categoryValue()
|
||||||
if (category != FileCategory.IMAGE && category != FileCategory.PDF) return null
|
if (category != FileCategory.IMAGE && category != FileCategory.PDF) return null
|
||||||
|
|
||||||
val target = thumbnailFile(file.resourceId)
|
val target = thumbnailFile(file.resourceId, file.lastModified, file.size)
|
||||||
if (isUpToDate(target, file.lastModified)) return target
|
if (isUpToDate(target, file.lastModified)) return target
|
||||||
|
// Ancienne version (legacy ou mtime/taille précédents) encore fraîche.
|
||||||
|
val legacy = thumbnailFile(file.resourceId)
|
||||||
|
if (legacy != target && isUpToDate(legacy, file.lastModified)) return legacy
|
||||||
|
|
||||||
val lock = locks.getOrPut(file.resourceId) { Mutex() }
|
val lock = locks.getOrPut(file.resourceId) { Mutex() }
|
||||||
return lock.withLock {
|
try {
|
||||||
if (isUpToDate(target, file.lastModified)) target
|
return lock.withLock {
|
||||||
else generateInto(context.contentResolver, uri, category, target)
|
if (isUpToDate(target, file.lastModified)) {
|
||||||
|
target
|
||||||
|
} else if (legacy != target && isUpToDate(legacy, file.lastModified)) {
|
||||||
|
legacy
|
||||||
|
} else {
|
||||||
|
generateInto(context.contentResolver, uri, category, target)?.also { generated ->
|
||||||
|
pruneSiblings(file.resourceId, keep = generated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
// Pas de fuite lente : le Mutex est retiré dès la fin (un appelant
|
||||||
|
// arrivé entre-temps garde sa propre référence, toujours valide).
|
||||||
|
locks.remove(file.resourceId, lock)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Purge la vignette d'une resource (delete physique) — best-effort. */
|
/** Purge toutes les vignettes d'une resource (toutes versions + tmp). */
|
||||||
fun delete(resourceId: String) {
|
fun delete(resourceId: String) {
|
||||||
runCatching { thumbnailFile(resourceId).delete() }
|
runCatching {
|
||||||
|
dir().listFiles { f -> isOwnedThumb(resourceId, f.name) }
|
||||||
|
?.forEach { it.delete() }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cache-hit : fichier présent et au moins aussi récent que la source. */
|
/** Fichier possédé par une resource : version courante, legacy ou tmp. */
|
||||||
|
private fun isOwnedThumb(resourceId: String, name: String): Boolean {
|
||||||
|
if (name == "$resourceId.webp") return true
|
||||||
|
if (name.startsWith(resourceId + "_") && name.endsWith(".webp")) return true
|
||||||
|
if (name.startsWith(resourceId) && name.endsWith(".tmp")) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Supprime les versions périmées et les `.tmp` orphelins (génération OK). */
|
||||||
|
private fun pruneSiblings(resourceId: String, keep: File) {
|
||||||
|
dir().listFiles { f -> f != keep && isOwnedThumb(resourceId, f.name) }
|
||||||
|
?.forEach { runCatching { it.delete() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cache-hit : fichier présent, non vide, et au moins aussi récent que la source. */
|
||||||
internal fun isUpToDate(target: File, lastModified: Long?): Boolean {
|
internal fun isUpToDate(target: File, lastModified: Long?): Boolean {
|
||||||
if (!target.isFile) return false
|
if (!target.isFile || target.length() == 0L) return false
|
||||||
if (lastModified == null) return true
|
if (lastModified == null) return true
|
||||||
return target.lastModified() >= lastModified
|
return target.lastModified() >= lastModified
|
||||||
}
|
}
|
||||||
@@ -99,9 +145,9 @@ class ThumbnailStore @Inject constructor(
|
|||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
bitmap ?: return@withContext null
|
bitmap ?: return@withContext null
|
||||||
|
val tmp = File(target.parentFile, "${target.name}.tmp")
|
||||||
try {
|
try {
|
||||||
dir().mkdirs()
|
dir().mkdirs()
|
||||||
val tmp = File(target.parentFile, "${target.name}.tmp")
|
|
||||||
val ok = tmp.outputStream().use { out ->
|
val ok = tmp.outputStream().use { out ->
|
||||||
bitmap.compress(Bitmap.CompressFormat.WEBP, WEBP_QUALITY, out)
|
bitmap.compress(Bitmap.CompressFormat.WEBP, WEBP_QUALITY, out)
|
||||||
}
|
}
|
||||||
@@ -109,10 +155,15 @@ class ThumbnailStore @Inject constructor(
|
|||||||
// La source a bougé pendant notre génération : on garde la dernière.
|
// La source a bougé pendant notre génération : on garde la dernière.
|
||||||
target.delete()
|
target.delete()
|
||||||
}
|
}
|
||||||
if (ok && tmp.renameTo(target)) target else null
|
// Échec de renommage : pas de `.tmp` orphelin, pas de cible
|
||||||
|
// touchée (une version concurrente fraîche reste en place).
|
||||||
|
if (ok && tmp.renameTo(target)) target else {
|
||||||
|
runCatching { tmp.delete() }
|
||||||
|
null
|
||||||
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Timber.w(e, "thumbnail write failed for $uri")
|
Timber.w(e, "thumbnail write failed for $uri")
|
||||||
runCatching { target.delete() }
|
runCatching { tmp.delete() }
|
||||||
null
|
null
|
||||||
} finally {
|
} finally {
|
||||||
bitmap.recycle()
|
bitmap.recycle()
|
||||||
@@ -121,7 +172,11 @@ class ThumbnailStore @Inject constructor(
|
|||||||
|
|
||||||
/** Image : décodage en `inSampleSize` pour ne jamais matérialiser le full-res. */
|
/** Image : décodage en `inSampleSize` pour ne jamais matérialiser le full-res. */
|
||||||
private fun decodeImage(resolver: ContentResolver, uri: String): Bitmap? {
|
private fun decodeImage(resolver: ContentResolver, uri: String): Bitmap? {
|
||||||
val stream = DocumentContent.openInputStream(resolver, uri) ?: return null
|
// Le provider peut lever à l'ouverture (permission révoquée, fichier
|
||||||
|
// absent) : échec de génération, jamais de crash (même contrat que le
|
||||||
|
// walk SAF face aux providers dégénérés).
|
||||||
|
val stream = runCatching { DocumentContent.openInputStream(resolver, uri) }.getOrNull()
|
||||||
|
?: return null
|
||||||
return try {
|
return try {
|
||||||
// Première passe : dimensions seulement, sans décodage pixels.
|
// Première passe : dimensions seulement, sans décodage pixels.
|
||||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import android.content.Context
|
|||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.kazier.mobile.auth.SessionManager
|
import com.kazier.mobile.auth.SessionManager
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
|
||||||
import com.kazier.mobile.data.remote.ApiException
|
import com.kazier.mobile.data.remote.ApiException
|
||||||
import com.kazier.mobile.data.repository.AuthRepository
|
import com.kazier.mobile.data.repository.AuthRepository
|
||||||
import com.kazier.mobile.data.repository.ShareRepository
|
import com.kazier.mobile.data.repository.ShareRepository
|
||||||
@@ -26,7 +25,6 @@ import javax.inject.Inject
|
|||||||
class AuthViewModel @Inject constructor(
|
class AuthViewModel @Inject constructor(
|
||||||
private val authRepository: AuthRepository,
|
private val authRepository: AuthRepository,
|
||||||
private val sessionManager: SessionManager,
|
private val sessionManager: SessionManager,
|
||||||
private val apiClient: ApiClient,
|
|
||||||
private val shareRepository: ShareRepository,
|
private val shareRepository: ShareRepository,
|
||||||
@ApplicationContext private val appContext: Context,
|
@ApplicationContext private val appContext: Context,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
@@ -38,10 +36,8 @@ class AuthViewModel @Inject constructor(
|
|||||||
val loginUiState: StateFlow<LoginUiState> = _loginUiState.asStateFlow()
|
val loginUiState: StateFlow<LoginUiState> = _loginUiState.asStateFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
// 401 sur un endpoint protégé (token expiré/révoqué, compte supprimé)
|
// Le 401 est géré par SessionManager (singleton) — jamais ici (M25) :
|
||||||
// → purge de la session. Le 401 du login est exonéré (skip dans ApiClient).
|
// ce callback survivrait sinon à onCleared et figerait l'outbox.
|
||||||
apiClient.onUnauthorized = { signOut() }
|
|
||||||
|
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val session = sessionManager.restore()
|
val session = sessionManager.restore()
|
||||||
_authState.value = when {
|
_authState.value = when {
|
||||||
@@ -70,7 +66,7 @@ class AuthViewModel @Inject constructor(
|
|||||||
_loginUiState.update { LoginUiState(isSubmitting = true) }
|
_loginUiState.update { LoginUiState(isSubmitting = true) }
|
||||||
runCatching { authRepository.login(username, password) }
|
runCatching { authRepository.login(username, password) }
|
||||||
.onSuccess { response ->
|
.onSuccess { response ->
|
||||||
sessionManager.save(response.token, response.user)
|
sessionManager.save(response.token, response.user, response.expiresAt)
|
||||||
_loginUiState.value = LoginUiState()
|
_loginUiState.value = LoginUiState()
|
||||||
_authState.value = AuthState.SignedIn(response.user)
|
_authState.value = AuthState.SignedIn(response.user)
|
||||||
// Connexion réussie → pousser les mutations locales en attente.
|
// Connexion réussie → pousser les mutations locales en attente.
|
||||||
@@ -119,8 +115,4 @@ class AuthViewModel @Inject constructor(
|
|||||||
_authState.value = AuthState.SignedOut
|
_authState.value = AuthState.SignedOut
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onCleared() {
|
|
||||||
apiClient.onUnauthorized = null
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -18,7 +18,7 @@ import androidx.compose.material3.Text
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -126,7 +126,7 @@ fun SyncStatusAction(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
val status by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
val status by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
||||||
var showList by remember { mutableStateOf(false) }
|
var showList by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
SyncStatusBadge(
|
SyncStatusBadge(
|
||||||
status = status,
|
status = status,
|
||||||
|
|||||||
+45
-4
@@ -126,20 +126,38 @@ fun DocumentViewerScreen(
|
|||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||||
val pagerState = rememberPagerState(pageCount = { documents.size })
|
val pagerState = rememberPagerState(pageCount = { documents.size })
|
||||||
|
|
||||||
// Démarre une seule fois sur le document demandé, dès que la liste est chargée.
|
// M30 : survit à la rotation (`rememberSaveable`) — `savedPage` mémorise
|
||||||
var jumpPending by remember { mutableStateOf(true) }
|
// l'index courant pour y revenir au lieu de retomber sur le document initial.
|
||||||
|
var jumpPending by rememberSaveable { mutableStateOf(true) }
|
||||||
|
var savedPage by rememberSaveable { mutableIntStateOf(-1) }
|
||||||
|
// Vrai dès qu'une liste non vide a été vue dans cette composition : garde
|
||||||
|
// contre un `onBack` intempestif pendant le (re)chargement initial.
|
||||||
|
var hadDocuments by remember { mutableStateOf(false) }
|
||||||
LaunchedEffect(documents) {
|
LaunchedEffect(documents) {
|
||||||
|
if (documents.isNotEmpty()) hadDocuments = true
|
||||||
if (jumpPending) {
|
if (jumpPending) {
|
||||||
|
// Démarre une seule fois sur le document demandé, dès que la liste est chargée.
|
||||||
val index = documents.indexOfFirst { it.resourceId == initialResourceId }
|
val index = documents.indexOfFirst { it.resourceId == initialResourceId }
|
||||||
if (index >= 0) {
|
if (index >= 0) {
|
||||||
pagerState.scrollToPage(index)
|
pagerState.scrollToPage(index)
|
||||||
|
savedPage = index
|
||||||
jumpPending = false
|
jumpPending = false
|
||||||
}
|
}
|
||||||
} else if (documents.isEmpty()) {
|
} else if (documents.isEmpty()) {
|
||||||
// Dernier document supprimé : plus rien à afficher → retour.
|
// Dernier document supprimé : plus rien à afficher → retour.
|
||||||
onBack()
|
if (shouldExitViewer(jumpPending, hadDocuments, documents.isEmpty())) onBack()
|
||||||
|
} else {
|
||||||
|
// M35 : clamp après suppression (ex. page 2/2 supprimée) +
|
||||||
|
// restauration de la page mémorisée après rotation.
|
||||||
|
val target = resolveViewerPage(pagerState.currentPage, savedPage, documents.size)
|
||||||
|
savedPage = target
|
||||||
|
if (target != pagerState.currentPage) pagerState.scrollToPage(target)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Suit le swipe utilisateur pour mémoriser la page courante (rotation).
|
||||||
|
LaunchedEffect(pagerState.currentPage) {
|
||||||
|
if (!jumpPending) savedPage = pagerState.currentPage
|
||||||
|
}
|
||||||
|
|
||||||
val currentFile = documents.getOrNull(pagerState.currentPage)
|
val currentFile = documents.getOrNull(pagerState.currentPage)
|
||||||
|
|
||||||
@@ -180,7 +198,7 @@ fun DocumentViewerScreen(
|
|||||||
|
|
||||||
// Confirmation avant suppression d'un document déjà traité.
|
// Confirmation avant suppression d'un document déjà traité.
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var showDeleteConfirm by remember { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
var fullscreen by rememberSaveable { mutableStateOf(false) }
|
var fullscreen by rememberSaveable { mutableStateOf(false) }
|
||||||
val canFullscreen = currentFile?.canFocus() == true
|
val canFullscreen = currentFile?.canFocus() == true
|
||||||
@@ -894,6 +912,29 @@ private fun fileTypeLabel(file: FileEntity): String =
|
|||||||
?: file.mimeType?.uppercase(Locale.getDefault())
|
?: file.mimeType?.uppercase(Locale.getDefault())
|
||||||
?: "—"
|
?: "—"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Page cible du pager après évolution de la liste (rotation, suppression).
|
||||||
|
*
|
||||||
|
* - `restoredPage` (mémorisée, `rememberSaveable`) prime si elle reste valide
|
||||||
|
* → retour à la page lue avant rotation (M30) ;
|
||||||
|
* - sinon la page courante est clampée aux bornes (M35 : suppression du
|
||||||
|
* dernier document → retombe sur le précédent au lieu d'une page vide).
|
||||||
|
*/
|
||||||
|
internal fun resolveViewerPage(currentPage: Int, restoredPage: Int, itemCount: Int): Int {
|
||||||
|
if (itemCount <= 0) return 0
|
||||||
|
val lastIndex = itemCount - 1
|
||||||
|
if (restoredPage in 0..lastIndex) return restoredPage
|
||||||
|
return currentPage.coerceIn(0, lastIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retour arrière uniquement quand une liste a déjà été vue dans cette
|
||||||
|
* composition puis vidée hors saut initial : le vide transitoire du
|
||||||
|
* (re)chargement — y compris après rotation — ne quitte jamais l'écran.
|
||||||
|
*/
|
||||||
|
internal fun shouldExitViewer(jumpPending: Boolean, hadDocuments: Boolean, isEmpty: Boolean): Boolean =
|
||||||
|
!jumpPending && hadDocuments && isEmpty
|
||||||
|
|
||||||
/** Vrai si le fichier est local et appartient à une catégorie consultable en mode focus. */
|
/** Vrai si le fichier est local et appartient à une catégorie consultable en mode focus. */
|
||||||
private fun FileEntity.canFocus(): Boolean =
|
private fun FileEntity.canFocus(): Boolean =
|
||||||
uri != null && categoryValue() in FOCUS_CATEGORIES
|
uri != null && categoryValue() in FOCUS_CATEGORIES
|
||||||
|
|||||||
+20
-6
@@ -39,6 +39,7 @@ import androidx.compose.runtime.LaunchedEffect
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -69,6 +70,8 @@ import com.kazier.mobile.ui.components.DeleteReview
|
|||||||
import com.kazier.mobile.ui.components.DeleteWarningDialog
|
import com.kazier.mobile.ui.components.DeleteWarningDialog
|
||||||
import com.kazier.mobile.ui.components.reviewDelete
|
import com.kazier.mobile.ui.components.reviewDelete
|
||||||
import com.kazier.mobile.ui.navigation.SelectionNavBar
|
import com.kazier.mobile.ui.navigation.SelectionNavBar
|
||||||
|
import com.kazier.mobile.ui.auth.AuthState
|
||||||
|
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||||
import com.kazier.mobile.ui.share.ShareBottomSheet
|
import com.kazier.mobile.ui.share.ShareBottomSheet
|
||||||
import com.kazier.mobile.ui.share.ShareViewModel
|
import com.kazier.mobile.ui.share.ShareViewModel
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
@@ -83,24 +86,31 @@ fun FolderDetailScreen(
|
|||||||
onBuildPdf: (List<String>) -> Unit,
|
onBuildPdf: (List<String>) -> Unit,
|
||||||
connectionStatusViewModel: ConnectionStatusViewModel,
|
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||||
syncViewModel: SyncViewModel,
|
syncViewModel: SyncViewModel,
|
||||||
|
authViewModel: AuthViewModel,
|
||||||
viewModel: FolderDetailViewModel = hiltViewModel(),
|
viewModel: FolderDetailViewModel = hiltViewModel(),
|
||||||
shareViewModel: ShareViewModel = hiltViewModel(),
|
shareViewModel: ShareViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
|
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||||
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val selection = rememberSelectionState()
|
val selection = rememberSelectionState()
|
||||||
var showCreateDialog by remember { mutableStateOf(false) }
|
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var showMoveDialog by remember { mutableStateOf(false) }
|
var showMoveDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteWarning by remember { mutableStateOf(false) }
|
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteConfirm by remember { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
var showShareSheet by remember { mutableStateOf(false) }
|
var showShareSheet by rememberSaveable { mutableStateOf(false) }
|
||||||
var showMoreMenu by remember { mutableStateOf(false) }
|
var showMoreMenu by rememberSaveable { mutableStateOf(false) }
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
val deletedLabel = stringResource(R.string.delete)
|
val deletedLabel = stringResource(R.string.delete)
|
||||||
|
|
||||||
|
// M33 : le gate `canShare` dépend du token — recalculé au login/logout.
|
||||||
|
LaunchedEffect(authState) {
|
||||||
|
if (authState != AuthState.Loading) viewModel.refreshShareGate()
|
||||||
|
}
|
||||||
|
|
||||||
LaunchedEffect(uiState.folderMissing) {
|
LaunchedEffect(uiState.folderMissing) {
|
||||||
if (uiState.folderMissing) onBack()
|
if (uiState.folderMissing) onBack()
|
||||||
}
|
}
|
||||||
@@ -195,6 +205,10 @@ fun FolderDetailScreen(
|
|||||||
) {
|
) {
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(stringResource(R.string.share_action)) },
|
text = { Text(stringResource(R.string.share_action)) },
|
||||||
|
// M32 : même gate que FolderList — un dossier
|
||||||
|
// local-only/reçu partage sans ce gate voue
|
||||||
|
// l'op `share` au dead-letter NOT_FOUND.
|
||||||
|
enabled = uiState.canShare,
|
||||||
onClick = {
|
onClick = {
|
||||||
showMoreMenu = false
|
showMoreMenu = false
|
||||||
showShareSheet = true
|
showShareSheet = true
|
||||||
|
|||||||
+20
@@ -11,6 +11,7 @@ import com.kazier.mobile.data.local.entity.FolderEntity
|
|||||||
import com.kazier.mobile.data.repository.FileRepository
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
import com.kazier.mobile.data.repository.FolderRepository
|
import com.kazier.mobile.data.repository.FolderRepository
|
||||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||||
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.features.saf.FileDeleter
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
import com.kazier.mobile.features.saf.FileMover
|
import com.kazier.mobile.features.saf.FileMover
|
||||||
import com.kazier.mobile.features.saf.SafFolderCreator
|
import com.kazier.mobile.features.saf.SafFolderCreator
|
||||||
@@ -40,6 +41,8 @@ data class FolderDetailUiState(
|
|||||||
val deleteError: String? = null,
|
val deleteError: String? = null,
|
||||||
/** Succès transitoire de suppression — affiché en Snackbar puis effacé. */
|
/** Succès transitoire de suppression — affiché en Snackbar puis effacé. */
|
||||||
val deleteSuccess: Boolean = false,
|
val deleteSuccess: Boolean = false,
|
||||||
|
/** Le dossier courant peut être partagé (connecté + possédé, cf. FolderList). */
|
||||||
|
val canShare: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
@@ -51,6 +54,7 @@ class FolderDetailViewModel @Inject constructor(
|
|||||||
private val safFolderCreator: SafFolderCreator,
|
private val safFolderCreator: SafFolderCreator,
|
||||||
private val fileMover: FileMover,
|
private val fileMover: FileMover,
|
||||||
private val fileDeleter: FileDeleter,
|
private val fileDeleter: FileDeleter,
|
||||||
|
private val activeUserStore: ActiveUserStore,
|
||||||
@ApplicationContext private val context: Context,
|
@ApplicationContext private val context: Context,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
@@ -70,6 +74,7 @@ class FolderDetailViewModel @Inject constructor(
|
|||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
_uiState.value = _uiState.value.copy(folder = folder)
|
_uiState.value = _uiState.value.copy(folder = folder)
|
||||||
|
refreshShareGate()
|
||||||
}
|
}
|
||||||
|
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
@@ -141,6 +146,21 @@ class FolderDetailViewModel @Inject constructor(
|
|||||||
_uiState.update { it.copy(createError = null) }
|
_uiState.update { it.copy(createError = null) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gate de partage du dossier courant (M32, même règle que FolderList) :
|
||||||
|
* connecté et dossier possédé (pas une ressource reçue en partage), sinon
|
||||||
|
* l'op `share` serait dead-letter `NOT_FOUND` côté serveur.
|
||||||
|
*/
|
||||||
|
fun refreshShareGate() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val folder = _uiState.value.folder
|
||||||
|
val shareable = folder != null &&
|
||||||
|
tokenProvider.current != null &&
|
||||||
|
(folder.ownerId == null || folder.ownerId == activeUserStore.get())
|
||||||
|
_uiState.update { it.copy(canShare = shareable) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Charge les dossiers éligibles à recevoir les fichiers sélectionnés. */
|
/** Charge les dossiers éligibles à recevoir les fichiers sélectionnés. */
|
||||||
fun loadMoveFolders() {
|
fun loadMoveFolders() {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
|||||||
+34
-13
@@ -62,6 +62,7 @@ import androidx.compose.runtime.LaunchedEffect
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -105,6 +106,8 @@ import com.kazier.mobile.ui.navigation.FolderSelectionNavBar
|
|||||||
import com.kazier.mobile.ui.navigation.MoveTargetBar
|
import com.kazier.mobile.ui.navigation.MoveTargetBar
|
||||||
import com.kazier.mobile.ui.navigation.NavTab
|
import com.kazier.mobile.ui.navigation.NavTab
|
||||||
import com.kazier.mobile.ui.navigation.SelectionNavBar
|
import com.kazier.mobile.ui.navigation.SelectionNavBar
|
||||||
|
import com.kazier.mobile.ui.auth.AuthState
|
||||||
|
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||||
import com.kazier.mobile.ui.share.ShareBottomSheet
|
import com.kazier.mobile.ui.share.ShareBottomSheet
|
||||||
import com.kazier.mobile.ui.share.ShareViewModel
|
import com.kazier.mobile.ui.share.ShareViewModel
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
@@ -127,9 +130,11 @@ fun FolderListScreen(
|
|||||||
onOpenScan: () -> Unit,
|
onOpenScan: () -> Unit,
|
||||||
syncViewModel: SyncViewModel,
|
syncViewModel: SyncViewModel,
|
||||||
connectionStatusViewModel: ConnectionStatusViewModel,
|
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||||
|
authViewModel: AuthViewModel,
|
||||||
viewModel: FolderListViewModel = hiltViewModel(),
|
viewModel: FolderListViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
|
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||||
val shareViewModel: ShareViewModel = hiltViewModel()
|
val shareViewModel: ShareViewModel = hiltViewModel()
|
||||||
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val importState by syncViewModel.importState.collectAsStateWithLifecycle()
|
val importState by syncViewModel.importState.collectAsStateWithLifecycle()
|
||||||
@@ -137,20 +142,27 @@ fun FolderListScreen(
|
|||||||
val defaultRootId by viewModel.defaultRootId.collectAsStateWithLifecycle()
|
val defaultRootId by viewModel.defaultRootId.collectAsStateWithLifecycle()
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val selection = rememberSelectionState()
|
val selection = rememberSelectionState()
|
||||||
var showCreateDialog by remember { mutableStateOf(false) }
|
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteWarning by remember { mutableStateOf(false) }
|
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteConfirm by remember { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
||||||
var pendingFolderIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
var pendingFolderIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||||
var pendingFileIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
var pendingFileIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||||
var shareTarget by remember { mutableStateOf<ShareTarget?>(null) }
|
var shareTarget by remember { mutableStateOf<ShareTarget?>(null) }
|
||||||
var showShareMenu by remember { mutableStateOf(false) }
|
var showShareMenu by rememberSaveable { mutableStateOf(false) }
|
||||||
var shareEnabled by remember { mutableStateOf(false) }
|
var shareEnabled by remember { mutableStateOf(false) }
|
||||||
var showCreateMenu by remember { mutableStateOf(false) }
|
var showCreateMenu by rememberSaveable { mutableStateOf(false) }
|
||||||
var showNoteDialog by remember { mutableStateOf(false) }
|
var showNoteDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
|
|
||||||
|
// Le gate `canShare` est calculé côté VM sur la cible courante ; le token
|
||||||
|
// n'y est lu qu'à ce moment-là (M33) : le login/logout depuis les Réglages
|
||||||
|
// doit donc le recalculer explicitement.
|
||||||
|
LaunchedEffect(authState) {
|
||||||
|
if (authState != AuthState.Loading) viewModel.refreshShareGate()
|
||||||
|
}
|
||||||
|
|
||||||
// Le partage multi-sélection ne vaut que pour un dossier unique sélectionné,
|
// Le partage multi-sélection ne vaut que pour un dossier unique sélectionné,
|
||||||
// possédé et déjà poussé au serveur (sinon dead-letter NOT_FOUND côté serveur).
|
// possédé et déjà poussé au serveur (sinon dead-letter NOT_FOUND côté serveur).
|
||||||
LaunchedEffect(uiState.browseSubFolders, selection.ids) {
|
LaunchedEffect(uiState.browseSubFolders, selection.ids) {
|
||||||
@@ -197,9 +209,11 @@ fun FolderListScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Racine par défaut : dossier Kazier choisi au premier lancement.
|
// Racine par défaut : dossier Kazier choisi au premier lancement.
|
||||||
|
// `rememberSaveable` (M29) : après rotation, le polling reprend au lieu de
|
||||||
|
// rester figé sur l'onboarding pendant que l'import continue en fond.
|
||||||
val defaultRootLabel = stringResource(R.string.default_root_folder_label)
|
val defaultRootLabel = stringResource(R.string.default_root_folder_label)
|
||||||
val folderLabel = stringResource(R.string.folder)
|
val folderLabel = stringResource(R.string.folder)
|
||||||
var pendingDefaultPick by remember { mutableStateOf<Uri?>(null) }
|
var pendingDefaultPick by rememberSaveable { mutableStateOf<Uri?>(null) }
|
||||||
val pickDefaultRootLauncher = rememberLauncherForActivityResult(
|
val pickDefaultRootLauncher = rememberLauncherForActivityResult(
|
||||||
ActivityResultContracts.OpenDocumentTree(),
|
ActivityResultContracts.OpenDocumentTree(),
|
||||||
) { uri: Uri? ->
|
) { uri: Uri? ->
|
||||||
@@ -387,6 +401,8 @@ fun FolderListScreen(
|
|||||||
val allFiles = uiState.sections.flatMap { section ->
|
val allFiles = uiState.sections.flatMap { section ->
|
||||||
section.rows.flatMap { row -> listOfNotNull(row.left, row.right) }
|
section.rows.flatMap { row -> listOfNotNull(row.left, row.right) }
|
||||||
}
|
}
|
||||||
|
// M34 : on ne supprime que les fichiers visibles —
|
||||||
|
// la sélection ne survit pas à la navigation.
|
||||||
val selectedFiles = allFiles.filter { it.resourceId in selection.ids }
|
val selectedFiles = allFiles.filter { it.resourceId in selection.ids }
|
||||||
pendingFolderIds = emptyList()
|
pendingFolderIds = emptyList()
|
||||||
pendingFileIds = selectedFiles.map { it.resourceId }
|
pendingFileIds = selectedFiles.map { it.resourceId }
|
||||||
@@ -467,8 +483,14 @@ fun FolderListScreen(
|
|||||||
isImporting = importState.isImporting,
|
isImporting = importState.isImporting,
|
||||||
error = uiState.error ?: importState.error,
|
error = uiState.error ?: importState.error,
|
||||||
selection = selection,
|
selection = selection,
|
||||||
onBrowseUp = viewModel::browseUp,
|
// M34 : la sélection ne suit pas la navigation — changer de
|
||||||
onOpenBrowseFolder = viewModel::openBrowseFolder,
|
// dossier l'abandonne (sauf en mode déplacement où la sélection
|
||||||
|
// est justement ce qu'on déplace).
|
||||||
|
onBrowseUp = { if (!uiState.moveMode) selection.clear(); viewModel.browseUp() },
|
||||||
|
onOpenBrowseFolder = { id ->
|
||||||
|
if (!uiState.moveMode) selection.clear()
|
||||||
|
viewModel.openBrowseFolder(id)
|
||||||
|
},
|
||||||
onCreateFolder = { showCreateDialog = true },
|
onCreateFolder = { showCreateDialog = true },
|
||||||
onOpenDocument = onOpenDocument,
|
onOpenDocument = onOpenDocument,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
@@ -519,7 +541,6 @@ fun FolderListScreen(
|
|||||||
count = pendingFolderIds.size + pendingFileIds.size,
|
count = pendingFolderIds.size + pendingFileIds.size,
|
||||||
onConfirm = {
|
onConfirm = {
|
||||||
val mode = pendingDeleteMode!!
|
val mode = pendingDeleteMode!!
|
||||||
val fileIds = selection.ids.toList()
|
|
||||||
selection.clear()
|
selection.clear()
|
||||||
showDeleteConfirm = false
|
showDeleteConfirm = false
|
||||||
pendingDeleteMode = null
|
pendingDeleteMode = null
|
||||||
@@ -527,7 +548,7 @@ fun FolderListScreen(
|
|||||||
if (uiState.view == HomeView.FOLDERS) {
|
if (uiState.view == HomeView.FOLDERS) {
|
||||||
viewModel.deleteFolderSelection(pendingFolderIds, pendingFileIds, mode)
|
viewModel.deleteFolderSelection(pendingFolderIds, pendingFileIds, mode)
|
||||||
} else {
|
} else {
|
||||||
viewModel.deleteSelectedFiles(fileIds, mode)
|
viewModel.deleteSelectedFiles(pendingFileIds, mode)
|
||||||
}
|
}
|
||||||
pendingFolderIds = emptyList()
|
pendingFolderIds = emptyList()
|
||||||
pendingFileIds = emptyList()
|
pendingFileIds = emptyList()
|
||||||
@@ -1172,8 +1193,8 @@ private fun NoteDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onConfirm: (title: String, body: String) -> Unit,
|
onConfirm: (title: String, body: String) -> Unit,
|
||||||
) {
|
) {
|
||||||
var title by remember { mutableStateOf("") }
|
var title by rememberSaveable { mutableStateOf("") }
|
||||||
var body by remember { mutableStateOf("") }
|
var body by rememberSaveable { mutableStateOf("") }
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
title = { Text(stringResource(R.string.note_dialog_title)) },
|
title = { Text(stringResource(R.string.note_dialog_title)) },
|
||||||
|
|||||||
+26
-10
@@ -15,7 +15,7 @@ import com.kazier.mobile.data.remote.ApiException
|
|||||||
import com.kazier.mobile.data.repository.FileRepository
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
import com.kazier.mobile.data.repository.FolderRepository
|
import com.kazier.mobile.data.repository.FolderRepository
|
||||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.features.saf.FileMover
|
import com.kazier.mobile.features.saf.FileMover
|
||||||
import com.kazier.mobile.features.saf.FileDeleter
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
import com.kazier.mobile.features.saf.FolderDeleter
|
import com.kazier.mobile.features.saf.FolderDeleter
|
||||||
@@ -49,7 +49,7 @@ class FolderListViewModel @Inject constructor(
|
|||||||
private val fileMover: FileMover,
|
private val fileMover: FileMover,
|
||||||
private val fileDeleter: FileDeleter,
|
private val fileDeleter: FileDeleter,
|
||||||
private val folderDeleter: FolderDeleter,
|
private val folderDeleter: FolderDeleter,
|
||||||
private val deviceIdentity: DeviceIdentity,
|
private val activeUserStore: ActiveUserStore,
|
||||||
@ApplicationContext private val context: Context,
|
@ApplicationContext private val context: Context,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
@@ -165,18 +165,34 @@ class FolderListViewModel @Inject constructor(
|
|||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_defaultRootId.combine(_browseFolderId) { root, browse -> browse ?: root }
|
_defaultRootId.combine(_browseFolderId) { root, browse -> browse ?: root }
|
||||||
.collect { targetId ->
|
.collect { targetId ->
|
||||||
val shareable = targetId != null &&
|
_uiState.update { it.copy(canShare = isShareableTarget(targetId)) }
|
||||||
tokenProvider.current != null &&
|
|
||||||
folderRepository.getFolder(targetId)?.let { isShareable(it) } == true
|
|
||||||
_uiState.update { it.copy(canShare = shareable) }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recalcule le gate de partage du dossier courant (M33) : le token est lu
|
||||||
|
* à l'appel, mais le collect ci-dessus ne se réveille qu'au changement de
|
||||||
|
* cible — le login/logout depuis les Réglages doit donc déclencher ce
|
||||||
|
* rafraîchissement explicite (appelé par l'écran sur changement d'auth).
|
||||||
|
*/
|
||||||
|
fun refreshShareGate() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val targetId = _browseFolderId.value ?: _defaultRootId.value
|
||||||
|
_uiState.update { it.copy(canShare = isShareableTarget(targetId)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun isShareableTarget(targetId: String?): Boolean =
|
||||||
|
targetId != null &&
|
||||||
|
tokenProvider.current != null &&
|
||||||
|
folderRepository.getFolder(targetId)?.let { isShareable(it) } == true
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Un dossier est partageable quand l'utilisateur est connecté et que ce
|
* Un dossier est partageable quand l'utilisateur est connecté et que ce
|
||||||
* n'est pas une ressource reçue en partage : `ownerId` absent ou égal à
|
* n'est pas une ressource reçue en partage : `ownerId` absent ou égal à
|
||||||
* l'identité du device (les lignes hydratées portent l'utilisateur réel).
|
* l'utilisateur connecté (`owner_id` Room = `user_id`, jamais le device —
|
||||||
|
* les lignes hydratées du snapshot portent le vrai propriétaire).
|
||||||
*
|
*
|
||||||
* Pas de gate `syncStatus` : un dossier `local` a son `create_resource`
|
* Pas de gate `syncStatus` : un dossier `local` a son `create_resource`
|
||||||
* enqueued avant le `share` dans le même outbox — le serveur applique la
|
* enqueued avant le `share` dans le même outbox — le serveur applique la
|
||||||
@@ -184,8 +200,8 @@ class FolderListViewModel @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
private suspend fun isShareable(folder: FolderEntity): Boolean {
|
private suspend fun isShareable(folder: FolderEntity): Boolean {
|
||||||
if (tokenProvider.current == null) return false
|
if (tokenProvider.current == null) return false
|
||||||
val deviceUserId = deviceIdentity.getOrCreate()
|
val currentUserId = activeUserStore.get()
|
||||||
return folder.ownerId == null || folder.ownerId == deviceUserId
|
return folder.ownerId == null || folder.ownerId == currentUserId
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun isShareableFolder(folder: FolderEntity): Boolean = isShareable(folder)
|
suspend fun isShareableFolder(folder: FolderEntity): Boolean = isShareable(folder)
|
||||||
@@ -273,7 +289,7 @@ class FolderListViewModel @Inject constructor(
|
|||||||
title = trimmed,
|
title = trimmed,
|
||||||
body = body,
|
body = body,
|
||||||
folderResourceId = targetId,
|
folderResourceId = targetId,
|
||||||
ownerId = deviceIdentity.getOrCreate(),
|
ownerId = activeUserStore.get(),
|
||||||
)
|
)
|
||||||
}.onFailure {
|
}.onFailure {
|
||||||
_uiState.update { it.copy(createError = context.getString(R.string.new_folder_error)) }
|
_uiState.update { it.copy(createError = context.getString(R.string.new_folder_error)) }
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import androidx.navigation.compose.rememberNavController
|
||||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||||
import com.kazier.mobile.features.sync.SyncViewModel
|
import com.kazier.mobile.features.sync.SyncViewModel
|
||||||
import com.kazier.mobile.ui.auth.AuthState
|
import com.kazier.mobile.ui.auth.AuthState
|
||||||
@@ -40,6 +41,10 @@ fun KazierApp(
|
|||||||
) {
|
) {
|
||||||
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
// m31 : un seul controller pour les deux branches — `signOutToLocal()`
|
||||||
|
// ne perd plus la position d'exploration.
|
||||||
|
val navController = rememberNavController()
|
||||||
|
|
||||||
// Une fois la session résolue, lancer les boucles de fond (idempotentes).
|
// Une fois la session résolue, lancer les boucles de fond (idempotentes).
|
||||||
LaunchedEffect(authState) {
|
LaunchedEffect(authState) {
|
||||||
if (authState != AuthState.Loading) {
|
if (authState != AuthState.Loading) {
|
||||||
@@ -55,11 +60,13 @@ fun KazierApp(
|
|||||||
authViewModel = authViewModel,
|
authViewModel = authViewModel,
|
||||||
syncViewModel = syncViewModel,
|
syncViewModel = syncViewModel,
|
||||||
connectionStatusViewModel = connectionStatusViewModel,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
|
navController = navController,
|
||||||
)
|
)
|
||||||
is AuthState.SignedIn -> NavGraph(
|
is AuthState.SignedIn -> NavGraph(
|
||||||
authViewModel = authViewModel,
|
authViewModel = authViewModel,
|
||||||
syncViewModel = syncViewModel,
|
syncViewModel = syncViewModel,
|
||||||
connectionStatusViewModel = connectionStatusViewModel,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
|
navController = navController,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,20 +2,17 @@ package com.kazier.mobile.ui.navigation
|
|||||||
|
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.navigation.NavGraph.Companion.findStartDestination
|
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||||
|
import androidx.navigation.NavHostController
|
||||||
import androidx.navigation.NavType
|
import androidx.navigation.NavType
|
||||||
import androidx.navigation.compose.NavHost
|
import androidx.navigation.compose.NavHost
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.compose.rememberNavController
|
||||||
import androidx.navigation.navArgument
|
import androidx.navigation.navArgument
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|
||||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||||
import com.kazier.mobile.features.sync.SyncViewModel
|
import com.kazier.mobile.features.sync.SyncViewModel
|
||||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||||
@@ -47,7 +44,25 @@ object Routes {
|
|||||||
|
|
||||||
fun folder(folderResourceId: String): String = "folder/$folderResourceId"
|
fun folder(folderResourceId: String): String = "folder/$folderResourceId"
|
||||||
fun document(documentResourceId: String): String = "document/$documentResourceId"
|
fun document(documentResourceId: String): String = "document/$documentResourceId"
|
||||||
fun pdfBuilder(resourceIds: List<String>): String = "pdfbuilder/${resourceIds.joinToString(",")}"
|
|
||||||
|
/**
|
||||||
|
* m29 : jamais de route `"pdfbuilder/"` vide (ne matche pas
|
||||||
|
* `"pdfbuilder/{ids}"`) — une sélection vide donne le sentinelle
|
||||||
|
* `"empty"`, re-parsé en liste vide par [parseBuilderIds].
|
||||||
|
*/
|
||||||
|
fun pdfBuilder(resourceIds: List<String>): String {
|
||||||
|
val ids = resourceIds.filter { it.isNotBlank() }
|
||||||
|
if (ids.isEmpty()) return "pdfbuilder/$BUILDER_EMPTY"
|
||||||
|
return "pdfbuilder/${ids.joinToString(",")}"
|
||||||
|
}
|
||||||
|
|
||||||
|
internal const val BUILDER_EMPTY = "empty"
|
||||||
|
|
||||||
|
/** Inverse de [pdfBuilder] : sentinelle et blancs → liste vide. */
|
||||||
|
fun parseBuilderIds(arg: String?): List<String> {
|
||||||
|
if (arg.isNullOrBlank() || arg == BUILDER_EMPTY) return emptyList()
|
||||||
|
return arg.split(",").filter { it.isNotBlank() }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun String?.toNavTab(): NavTab = when (this) {
|
private fun String?.toNavTab(): NavTab = when (this) {
|
||||||
@@ -63,14 +78,13 @@ fun NavGraph(
|
|||||||
authViewModel: AuthViewModel,
|
authViewModel: AuthViewModel,
|
||||||
syncViewModel: SyncViewModel,
|
syncViewModel: SyncViewModel,
|
||||||
connectionStatusViewModel: ConnectionStatusViewModel,
|
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||||
|
// m31 : controller hoisté par KazierApp — une seule instance pour les
|
||||||
|
// branches SignedIn↔Local, la position d'exploration survit au sign-out.
|
||||||
|
navController: NavHostController = rememberNavController(),
|
||||||
) {
|
) {
|
||||||
val navController = rememberNavController()
|
|
||||||
|
|
||||||
val backStackEntry by navController.currentBackStackEntryAsState()
|
val backStackEntry by navController.currentBackStackEntryAsState()
|
||||||
val selectedTab = backStackEntry?.destination?.route.toNavTab()
|
val selectedTab = backStackEntry?.destination?.route.toNavTab()
|
||||||
|
|
||||||
val importState by syncViewModel.importState.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
val onOpenWatchedFolders = { navController.navigate(Routes.WATCHED_FOLDERS) }
|
val onOpenWatchedFolders = { navController.navigate(Routes.WATCHED_FOLDERS) }
|
||||||
|
|
||||||
val onTabSelected: (NavTab) -> Unit = { tab ->
|
val onTabSelected: (NavTab) -> Unit = { tab ->
|
||||||
@@ -100,6 +114,7 @@ fun NavGraph(
|
|||||||
onOpenScan = { navController.navigate(Routes.SCAN) },
|
onOpenScan = { navController.navigate(Routes.SCAN) },
|
||||||
syncViewModel = syncViewModel,
|
syncViewModel = syncViewModel,
|
||||||
connectionStatusViewModel = connectionStatusViewModel,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
|
authViewModel = authViewModel,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(Routes.SEARCH) {
|
composable(Routes.SEARCH) {
|
||||||
@@ -162,11 +177,17 @@ fun NavGraph(
|
|||||||
FolderDetailScreen(
|
FolderDetailScreen(
|
||||||
folderResourceId = folderId,
|
folderResourceId = folderId,
|
||||||
onBack = { navController.popBackStack() },
|
onBack = { navController.popBackStack() },
|
||||||
onOpenFolder = { id -> navController.navigate(Routes.folder(id)) },
|
// m30 : launchSingleTop — un double-tap ne duplique plus la pile.
|
||||||
|
onOpenFolder = { id ->
|
||||||
|
navController.navigate(Routes.folder(id)) {
|
||||||
|
launchSingleTop = true
|
||||||
|
}
|
||||||
|
},
|
||||||
onOpenDocument = { id -> navController.navigate(Routes.document(id)) },
|
onOpenDocument = { id -> navController.navigate(Routes.document(id)) },
|
||||||
onBuildPdf = { ids -> navController.navigate(Routes.pdfBuilder(ids)) },
|
onBuildPdf = { ids -> navController.navigate(Routes.pdfBuilder(ids)) },
|
||||||
connectionStatusViewModel = connectionStatusViewModel,
|
connectionStatusViewModel = connectionStatusViewModel,
|
||||||
syncViewModel = syncViewModel,
|
syncViewModel = syncViewModel,
|
||||||
|
authViewModel = authViewModel,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(
|
composable(
|
||||||
@@ -191,11 +212,9 @@ fun NavGraph(
|
|||||||
navArgument(Routes.ARG_BUILDER_IDS) { type = NavType.StringType },
|
navArgument(Routes.ARG_BUILDER_IDS) { type = NavType.StringType },
|
||||||
),
|
),
|
||||||
) { backStackEntry ->
|
) { backStackEntry ->
|
||||||
val ids = backStackEntry.arguments
|
val ids = Routes.parseBuilderIds(
|
||||||
?.getString(Routes.ARG_BUILDER_IDS)
|
backStackEntry.arguments?.getString(Routes.ARG_BUILDER_IDS),
|
||||||
.orEmpty()
|
)
|
||||||
.split(",")
|
|
||||||
.filter { it.isNotBlank() }
|
|
||||||
PdfBuilderScreen(
|
PdfBuilderScreen(
|
||||||
initialResourceIds = ids,
|
initialResourceIds = ids,
|
||||||
onBack = { navController.popBackStack() },
|
onBack = { navController.popBackStack() },
|
||||||
@@ -207,15 +226,5 @@ fun NavGraph(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bandeau global : visible sur tous les onglets tant qu'un import SAF
|
|
||||||
// est en cours (indique que la marche continue hors écran Fichiers).
|
|
||||||
if (importState.isImporting) {
|
|
||||||
LinearProgressIndicator(
|
|
||||||
modifier = Modifier
|
|
||||||
.align(Alignment.BottomCenter)
|
|
||||||
.fillMaxWidth(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -101,8 +101,11 @@ class PdfBuilderEngine @Inject constructor() {
|
|||||||
val srcH = page.height.toFloat()
|
val srcH = page.height.toFloat()
|
||||||
if (srcW <= 0f || srcH <= 0f) return@repeat
|
if (srcW <= 0f || srcH <= 0f) return@repeat
|
||||||
|
|
||||||
|
// Format source conservé, borné mémoire à MAX_IMAGE_PX
|
||||||
|
// (pas de plafond en points : une page A3 restait
|
||||||
|
// pixellisée par l'ancien cap à 1200 pt).
|
||||||
val maxDim = maxOf(srcW, srcH)
|
val maxDim = maxOf(srcW, srcH)
|
||||||
val scale = minOf(1f, MAX_PAGE_POINTS / maxDim, MAX_IMAGE_PX / maxDim)
|
val scale = minOf(1f, MAX_IMAGE_PX / maxDim)
|
||||||
val pageW = (srcW * scale).toInt().coerceAtLeast(1)
|
val pageW = (srcW * scale).toInt().coerceAtLeast(1)
|
||||||
val pageH = (srcH * scale).toInt().coerceAtLeast(1)
|
val pageH = (srcH * scale).toInt().coerceAtLeast(1)
|
||||||
|
|
||||||
@@ -119,8 +122,10 @@ class PdfBuilderEngine @Inject constructor() {
|
|||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
return appended
|
return appended
|
||||||
} finally {
|
} finally {
|
||||||
renderer?.close()
|
// `close()` protégés séparément : si le renderer lève, le fd doit
|
||||||
pfd.close()
|
// quand même être refermé (sinon fd leak).
|
||||||
|
runCatching { renderer?.close() }
|
||||||
|
runCatching { pfd.close() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,7 +338,6 @@ class PdfBuilderEngine @Inject constructor() {
|
|||||||
private const val IMAGE_MARGIN = 40f
|
private const val IMAGE_MARGIN = 40f
|
||||||
|
|
||||||
/** Bornes mémoire : pages et bitmaps jamais au-delà. */
|
/** Bornes mémoire : pages et bitmaps jamais au-delà. */
|
||||||
private const val MAX_PAGE_POINTS = 1200f
|
|
||||||
private const val MAX_IMAGE_PX = 3000
|
private const val MAX_IMAGE_PX = 3000
|
||||||
private const val MAX_NOTE_CHARS = 100_000
|
private const val MAX_NOTE_CHARS = 100_000
|
||||||
private const val MAX_NOTE_PAGES = 30
|
private const val MAX_NOTE_PAGES = 30
|
||||||
|
|||||||
+24
-13
@@ -51,6 +51,7 @@ import androidx.compose.runtime.getValue
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -87,9 +88,9 @@ fun PdfBuilderScreen(
|
|||||||
|
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
|
|
||||||
var showNoteDialog by remember { mutableStateOf(false) }
|
var showNoteDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var showFileSheet by remember { mutableStateOf(false) }
|
var showFileSheet by rememberSaveable { mutableStateOf(false) }
|
||||||
var showNameDialog by remember { mutableStateOf(false) }
|
var showNameDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var previewFile by remember { mutableStateOf<FileEntity?>(null) }
|
var previewFile by remember { mutableStateOf<FileEntity?>(null) }
|
||||||
|
|
||||||
// Nom suggéré par défaut : date du jour au format jour-mois-année.
|
// Nom suggéré par défaut : date du jour au format jour-mois-année.
|
||||||
@@ -101,15 +102,22 @@ fun PdfBuilderScreen(
|
|||||||
viewModel.loadInitial(initialResourceIds)
|
viewModel.loadInitial(initialResourceIds)
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(buildPhase) {
|
// m33 : clés précises — `LaunchedEffect(buildPhase)` rejouait les
|
||||||
when (buildPhase) {
|
// side-effects à chaque recomposition racine (rotation → Failed
|
||||||
is BuildPhase.Ready -> showNameDialog = true
|
// re-snackbar, Saved re-`onOpenDocument` = double navigation possible).
|
||||||
is BuildPhase.Saved -> onOpenDocument((buildPhase as BuildPhase.Saved).resourceId)
|
val isReady = buildPhase is BuildPhase.Ready
|
||||||
is BuildPhase.Failed -> {
|
val savedResourceId = (buildPhase as? BuildPhase.Saved)?.resourceId
|
||||||
snackbarHostState.showSnackbar((buildPhase as BuildPhase.Failed).message)
|
val failureMessage = (buildPhase as? BuildPhase.Failed)?.message
|
||||||
viewModel.acknowledgeFailure()
|
LaunchedEffect(isReady) {
|
||||||
}
|
if (isReady) showNameDialog = true
|
||||||
else -> Unit
|
}
|
||||||
|
LaunchedEffect(savedResourceId) {
|
||||||
|
if (savedResourceId != null) onOpenDocument(savedResourceId)
|
||||||
|
}
|
||||||
|
LaunchedEffect(failureMessage) {
|
||||||
|
if (failureMessage != null) {
|
||||||
|
snackbarHostState.showSnackbar(failureMessage)
|
||||||
|
viewModel.acknowledgeFailure()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,7 +253,10 @@ private fun SelectFilesSheet(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onConfirm: (Set<String>) -> Unit,
|
onConfirm: (Set<String>) -> Unit,
|
||||||
) {
|
) {
|
||||||
var selected by remember(files) { mutableStateOf(existingIds.toMutableSet()) }
|
// Clé stable (items du panier), jamais la liste Room des fichiers : avec
|
||||||
|
// `remember(files)`, chaque update Room recréait la sélection et effaçait
|
||||||
|
// les cases cochées en cours.
|
||||||
|
var selected by remember(existingIds) { mutableStateOf(existingIds.toMutableSet()) }
|
||||||
val sheetState = rememberModalBottomSheetState()
|
val sheetState = rememberModalBottomSheetState()
|
||||||
|
|
||||||
ModalBottomSheet(
|
ModalBottomSheet(
|
||||||
|
|||||||
+27
-8
@@ -10,6 +10,7 @@ import androidx.lifecycle.ViewModel
|
|||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.FileStatus
|
||||||
import com.kazier.mobile.data.preferences.DefaultRootStore
|
import com.kazier.mobile.data.preferences.DefaultRootStore
|
||||||
import com.kazier.mobile.data.repository.FileRepository
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
import com.kazier.mobile.data.repository.FolderRepository
|
import com.kazier.mobile.data.repository.FolderRepository
|
||||||
@@ -225,15 +226,11 @@ class PdfBuilderViewModel @Inject constructor(
|
|||||||
val actualName = displayName(createdUri) ?: fileName
|
val actualName = displayName(createdUri) ?: fileName
|
||||||
val bytes = cacheFile.length()
|
val bytes = cacheFile.length()
|
||||||
val inserted = fileRepository.saveLocalFile(
|
val inserted = fileRepository.saveLocalFile(
|
||||||
input = SaveFileInput(
|
input = pdfSaveFileInput(
|
||||||
uri = createdUri.toString(),
|
uri = createdUri.toString(),
|
||||||
name = actualName,
|
name = actualName,
|
||||||
extension = "pdf",
|
bytes = bytes,
|
||||||
size = bytes,
|
now = System.currentTimeMillis(),
|
||||||
mimeType = "application/pdf",
|
|
||||||
lastModified = System.currentTimeMillis(),
|
|
||||||
exists = true,
|
|
||||||
syncStatus = "local",
|
|
||||||
),
|
),
|
||||||
folderResourceId = folderId,
|
folderResourceId = folderId,
|
||||||
)
|
)
|
||||||
@@ -358,4 +355,26 @@ sealed interface BuildPhase {
|
|||||||
data class Ready(val file: File) : BuildPhase
|
data class Ready(val file: File) : BuildPhase
|
||||||
data class Saved(val resourceId: String) : BuildPhase
|
data class Saved(val resourceId: String) : BuildPhase
|
||||||
data class Failed(val message: String) : BuildPhase
|
data class Failed(val message: String) : BuildPhase
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ligne Room d'un PDF assemblé : déjà « traité » (l'utilisateur vient de le
|
||||||
|
* construire — pas de review) et `syncStatus` via la constante, pas un
|
||||||
|
* littéral.
|
||||||
|
*/
|
||||||
|
internal fun pdfSaveFileInput(
|
||||||
|
uri: String,
|
||||||
|
name: String,
|
||||||
|
bytes: Long,
|
||||||
|
now: Long,
|
||||||
|
): SaveFileInput = SaveFileInput(
|
||||||
|
uri = uri,
|
||||||
|
name = name,
|
||||||
|
extension = "pdf",
|
||||||
|
size = bytes,
|
||||||
|
mimeType = "application/pdf",
|
||||||
|
lastModified = now,
|
||||||
|
exists = true,
|
||||||
|
syncStatus = FileStatus.LOCAL,
|
||||||
|
processed = true,
|
||||||
|
)
|
||||||
+47
-12
@@ -52,24 +52,40 @@ class SwipeReviewViewModel @Inject constructor(
|
|||||||
fun load() {
|
fun load() {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_uiState.update { it.copy(isLoading = true) }
|
_uiState.update { it.copy(isLoading = true) }
|
||||||
val files = runCatching { fileRepository.getUnprocessed() }
|
runCatching { fileRepository.getUnprocessed() }
|
||||||
.getOrElse { e ->
|
.onSuccess { files ->
|
||||||
|
_uiState.update { it.copy(isLoading = false, cards = files, total = files.size) }
|
||||||
|
}
|
||||||
|
.onFailure { e ->
|
||||||
Timber.w(e, "review: cannot load unprocessed files")
|
Timber.w(e, "review: cannot load unprocessed files")
|
||||||
|
// Échec de reload : le deck existant est conservé (jamais
|
||||||
|
// vidé à tort), seule l'erreur est signalée.
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(error = context.getString(R.string.review_load_error))
|
it.copy(
|
||||||
|
isLoading = false,
|
||||||
|
error = context.getString(R.string.review_load_error),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
emptyList()
|
|
||||||
}
|
}
|
||||||
_uiState.update { it.copy(isLoading = false, cards = files, total = files.size) }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Swipe droite (ou bouton ✓) : garder le document, le voilà traité. */
|
/** Swipe droite (ou bouton ✓) : garder le document, le voilà traité. */
|
||||||
fun keep(file: FileEntity) {
|
fun keep(file: FileEntity) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
runCatching { fileRepository.markProcessed(file.resourceId) }
|
val ok = runCatching { fileRepository.markProcessed(file.resourceId) }.isSuccess
|
||||||
.onFailure { Timber.w(it, "review: mark processed failed for %s", file.resourceId) }
|
if (ok) {
|
||||||
removeOptimistically(file.resourceId)
|
removeOptimistically(file.resourceId)
|
||||||
|
} else {
|
||||||
|
// Échec : la carte est réinsérée en tête (jamais perdue).
|
||||||
|
Timber.w("review: mark processed failed for %s — card kept", file.resourceId)
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(
|
||||||
|
error = context.getString(R.string.review_keep_error),
|
||||||
|
cards = reinsertHead(it.cards, file),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,7 +99,7 @@ class SwipeReviewViewModel @Inject constructor(
|
|||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
error = context.getString(R.string.review_delete_error),
|
error = context.getString(R.string.review_delete_error),
|
||||||
cards = listOf(file) + it.cards.filterNot { c -> c.resourceId == file.resourceId },
|
cards = reinsertHead(it.cards, file),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,9 +109,19 @@ class SwipeReviewViewModel @Inject constructor(
|
|||||||
/** Échappatoire : tout marquer traité d'un coup (premier lancement massif). */
|
/** Échappatoire : tout marquer traité d'un coup (premier lancement massif). */
|
||||||
fun markAllProcessed() {
|
fun markAllProcessed() {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
runCatching { fileRepository.markAllProcessed() }
|
val snapshot = _uiState.value.cards
|
||||||
.onFailure { Timber.w(it, "review: mark all failed") }
|
|
||||||
_uiState.update { it.copy(cards = emptyList()) }
|
_uiState.update { it.copy(cards = emptyList()) }
|
||||||
|
val ok = runCatching { fileRepository.markAllProcessed() }.isSuccess
|
||||||
|
if (!ok) {
|
||||||
|
// Échec : le deck est restauré (jamais vidé à tort).
|
||||||
|
Timber.w("review: mark all failed — deck restored")
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(
|
||||||
|
error = context.getString(R.string.review_keep_error),
|
||||||
|
cards = snapshot,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,4 +132,13 @@ class SwipeReviewViewModel @Inject constructor(
|
|||||||
private fun removeOptimistically(resourceId: String) {
|
private fun removeOptimistically(resourceId: String) {
|
||||||
_uiState.update { it.copy(cards = it.cards.filterNot { c -> c.resourceId == resourceId }) }
|
_uiState.update { it.copy(cards = it.cards.filterNot { c -> c.resourceId == resourceId }) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Réinsère une carte en tête du deck (échec d'une action optimiste) sans
|
||||||
|
* doublon : la carte n'est jamais perdue, jamais dupliquée.
|
||||||
|
*/
|
||||||
|
internal fun reinsertHead(
|
||||||
|
cards: List<FileEntity>,
|
||||||
|
file: FileEntity,
|
||||||
|
): List<FileEntity> = listOf(file) + cards.filterNot { it.resourceId == file.resourceId }
|
||||||
@@ -5,6 +5,7 @@ import android.graphics.Bitmap
|
|||||||
import android.graphics.Matrix
|
import android.graphics.Matrix
|
||||||
import android.graphics.PointF
|
import android.graphics.PointF
|
||||||
import android.util.Size
|
import android.util.Size
|
||||||
|
import android.view.View
|
||||||
import androidx.camera.core.CameraSelector
|
import androidx.camera.core.CameraSelector
|
||||||
import androidx.camera.core.ImageAnalysis
|
import androidx.camera.core.ImageAnalysis
|
||||||
import androidx.camera.core.ImageCapture
|
import androidx.camera.core.ImageCapture
|
||||||
@@ -84,10 +85,16 @@ fun CameraStage(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var previewView by remember { mutableStateOf<PreviewView?>(null) }
|
var previewView by remember { mutableStateOf<PreviewView?>(null) }
|
||||||
val imageCapture = remember {
|
// Pas de résolution forcée : la capture suit le défaut du device (une
|
||||||
ImageCapture.Builder()
|
// cible 1920×1080 paysage imposait pleine-rés + copie tournée en portrait,
|
||||||
.setTargetResolution(Size(1920, 1080))
|
// ~×2 mémoire → OOM sur petits devices).
|
||||||
.build()
|
val imageCapture = remember { ImageCapture.Builder().build() }
|
||||||
|
|
||||||
|
// Listener nommé pour pouvoir le retirer (`onRelease`) : pas de fuite.
|
||||||
|
val layoutListener = remember {
|
||||||
|
View.OnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ ->
|
||||||
|
viewSize = IntSize(right - left, bottom - top)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Box(modifier = modifier) {
|
Box(modifier = modifier) {
|
||||||
@@ -96,12 +103,11 @@ fun CameraStage(
|
|||||||
PreviewView(ctx).apply {
|
PreviewView(ctx).apply {
|
||||||
implementationMode = PreviewView.ImplementationMode.PERFORMANCE
|
implementationMode = PreviewView.ImplementationMode.PERFORMANCE
|
||||||
}.also { view ->
|
}.also { view ->
|
||||||
view.addOnLayoutChangeListener { v, left, top, right, bottom, _, _, _, _ ->
|
view.addOnLayoutChangeListener(layoutListener)
|
||||||
viewSize = IntSize(right - left, bottom - top)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
update = { previewView = it },
|
update = { previewView = it },
|
||||||
|
onRelease = { it.removeOnLayoutChangeListener(layoutListener) },
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -158,24 +164,35 @@ fun CameraStage(
|
|||||||
val bindingListener = Runnable {
|
val bindingListener = Runnable {
|
||||||
if (disposed.get()) return@Runnable
|
if (disposed.get()) return@Runnable
|
||||||
val provider = providerFuture.get()
|
val provider = providerFuture.get()
|
||||||
val preview = Preview.Builder().build().also { it.setSurfaceProvider(pv.surfaceProvider) }
|
// Preview et analyse partagent la même résolution cible : les deux
|
||||||
|
// flux subissent le même crop, et l'overlay calibré sur l'image
|
||||||
|
// d'analyse coïncide avec ce que PreviewView affiche (FILL_CENTER).
|
||||||
|
// Avant, l'overlay suivait le flux ImageAnalysis seul alors que
|
||||||
|
// l'écran montrait le flux Preview (ratio/crop différents → quad
|
||||||
|
// décalé dès que les ratios divergeaient).
|
||||||
|
val preview = Preview.Builder().setTargetResolution(SCAN_STREAM_SIZE)
|
||||||
|
.build().also { it.setSurfaceProvider(pv.surfaceProvider) }
|
||||||
val analysis = ImageAnalysis.Builder()
|
val analysis = ImageAnalysis.Builder()
|
||||||
|
.setTargetResolution(SCAN_STREAM_SIZE)
|
||||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||||
.build()
|
.build()
|
||||||
analysis.setAnalyzer(analysisExecutor) { proxy ->
|
analysis.setAnalyzer(analysisExecutor) { proxy ->
|
||||||
|
var frame: Bitmap? = null
|
||||||
|
var scaled: Bitmap? = null
|
||||||
try {
|
try {
|
||||||
val unrotated = proxy.toBitmap()
|
val unrotated = proxy.toBitmap()
|
||||||
val degrees = proxy.imageInfo.rotationDegrees
|
val degrees = proxy.imageInfo.rotationDegrees
|
||||||
val bitmap = if (degrees != 0) rotate(unrotated, degrees) else unrotated
|
frame = if (degrees != 0) rotate(unrotated, degrees) else unrotated
|
||||||
try {
|
if (frame !== unrotated) unrotated.recycle()
|
||||||
viewModel.processAnalysisFrame(bitmap.width, bitmap.height, bitmap)
|
// Jamais de pleine-rés vers le détecteur (churn GC +
|
||||||
} finally {
|
// batterie à ~30 fps) : downscale vers le côté de détection.
|
||||||
if (bitmap !== unrotated) unrotated.recycle()
|
scaled = downscaleForAnalysis(frame)
|
||||||
bitmap.recycle()
|
viewModel.processAnalysisFrame(scaled.width, scaled.height, scaled)
|
||||||
}
|
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
// Une frame illisible ne doit pas stopper l'analyse.
|
// Une frame illisible ne doit pas stopper l'analyse.
|
||||||
} finally {
|
} finally {
|
||||||
|
if (frame !== scaled) frame?.recycle()
|
||||||
|
scaled?.recycle()
|
||||||
proxy.close()
|
proxy.close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -198,11 +215,14 @@ fun CameraStage(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun rotate(bitmap: Bitmap, degrees: Int): Bitmap {
|
private fun rotate(bitmap: Bitmap, degrees: Int): Bitmap {
|
||||||
|
if (degrees == 0) return bitmap
|
||||||
val matrix = Matrix().apply {
|
val matrix = Matrix().apply {
|
||||||
when (degrees) {
|
when (degrees) {
|
||||||
90 -> setRotate(90f)
|
90 -> setRotate(90f)
|
||||||
180 -> setRotate(180f)
|
180 -> setRotate(180f)
|
||||||
270 -> setRotate(270f)
|
270 -> setRotate(270f)
|
||||||
|
// Angle inattendu : pas de copie silencieuse, on garde l'original.
|
||||||
|
else -> return bitmap
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return bitmap.run {
|
return bitmap.run {
|
||||||
@@ -210,6 +230,19 @@ private fun rotate(bitmap: Bitmap, degrees: Int): Bitmap {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Downscale d'une frame d'analyse vers [ANALYSIS_MAX_SIDE] (alias si déjà petit). */
|
||||||
|
private fun downscaleForAnalysis(frame: Bitmap): Bitmap {
|
||||||
|
val maxSide = maxOf(frame.width, frame.height)
|
||||||
|
if (maxSide <= ANALYSIS_MAX_SIDE) return frame
|
||||||
|
val scale = ANALYSIS_MAX_SIDE.toFloat() / maxSide
|
||||||
|
return Bitmap.createScaledBitmap(
|
||||||
|
frame,
|
||||||
|
(frame.width * scale).toInt().coerceAtLeast(1),
|
||||||
|
(frame.height * scale).toInt().coerceAtLeast(1),
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
private fun capture(context: Context, imageCapture: ImageCapture, viewModel: ScanViewModel) {
|
private fun capture(context: Context, imageCapture: ImageCapture, viewModel: ScanViewModel) {
|
||||||
val file = File(context.cacheDir, "scan_capture_${System.currentTimeMillis()}.jpg")
|
val file = File(context.cacheDir, "scan_capture_${System.currentTimeMillis()}.jpg")
|
||||||
imageCapture.takePicture(
|
imageCapture.takePicture(
|
||||||
@@ -247,4 +280,10 @@ private fun capture(context: Context, imageCapture: ImageCapture, viewModel: Sca
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val SCAN_JPEG_QUALITY = 92
|
private const val SCAN_JPEG_QUALITY = 92
|
||||||
|
|
||||||
|
/** Résolution commune Preview/analyse (même crop → overlay aligné). */
|
||||||
|
private val SCAN_STREAM_SIZE = Size(1280, 720)
|
||||||
|
|
||||||
|
/** Côté max des frames envoyées au détecteur (GC/batterie bornés). */
|
||||||
|
private const val ANALYSIS_MAX_SIDE = 900
|
||||||
@@ -185,10 +185,17 @@ fun CropStage(
|
|||||||
|
|
||||||
Canvas(modifier = Modifier.fillMaxSize()) {
|
Canvas(modifier = Modifier.fillMaxSize()) {
|
||||||
val dst = ScanGeometry.viewportFit(viewport, boxSize.width, boxSize.height)
|
val dst = ScanGeometry.viewportFit(viewport, boxSize.width, boxSize.height)
|
||||||
|
// Offset et taille arrondis indépendamment → dépassement 1 px
|
||||||
|
// en bordure (frange noire sur images impaires) : on clampe
|
||||||
|
// la source dans l'image.
|
||||||
|
val srcLeft = viewport.left.roundToInt().coerceIn(0, imageWidth)
|
||||||
|
val srcTop = viewport.top.roundToInt().coerceIn(0, imageHeight)
|
||||||
|
val srcRight = viewport.right.roundToInt().coerceIn(srcLeft + 1, imageWidth)
|
||||||
|
val srcBottom = viewport.bottom.roundToInt().coerceIn(srcTop + 1, imageHeight)
|
||||||
drawImage(
|
drawImage(
|
||||||
image = bitmap.asImageBitmap(),
|
image = bitmap.asImageBitmap(),
|
||||||
srcOffset = IntOffset(viewport.left.roundToInt(), viewport.top.roundToInt()),
|
srcOffset = IntOffset(srcLeft, srcTop),
|
||||||
srcSize = IntSize(viewport.width().roundToInt(), viewport.height().roundToInt()),
|
srcSize = IntSize(srcRight - srcLeft, srcBottom - srcTop),
|
||||||
dstOffset = IntOffset(dst.left.roundToInt(), dst.top.roundToInt()),
|
dstOffset = IntOffset(dst.left.roundToInt(), dst.top.roundToInt()),
|
||||||
dstSize = IntSize(dst.width().roundToInt(), dst.height().roundToInt()),
|
dstSize = IntSize(dst.width().roundToInt(), dst.height().roundToInt()),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ object ScanGeometry {
|
|||||||
viewWidth: Int,
|
viewWidth: Int,
|
||||||
viewHeight: Int,
|
viewHeight: Int,
|
||||||
): PointF {
|
): PointF {
|
||||||
|
if (sourceRect.width() <= 0f || sourceRect.height() <= 0f) return PointF(point.x, point.y)
|
||||||
val dst = viewportFit(sourceRect, viewWidth, viewHeight)
|
val dst = viewportFit(sourceRect, viewWidth, viewHeight)
|
||||||
if (dst.width() <= 0f || dst.height() <= 0f) return point
|
if (dst.width() <= 0f || dst.height() <= 0f) return point
|
||||||
return PointF(
|
return PointF(
|
||||||
@@ -60,6 +61,7 @@ object ScanGeometry {
|
|||||||
viewWidth: Int,
|
viewWidth: Int,
|
||||||
viewHeight: Int,
|
viewHeight: Int,
|
||||||
): PointF {
|
): PointF {
|
||||||
|
if (sourceRect.width() <= 0f || sourceRect.height() <= 0f) return PointF(point.x, point.y)
|
||||||
val dst = viewportFit(sourceRect, viewWidth, viewHeight)
|
val dst = viewportFit(sourceRect, viewWidth, viewHeight)
|
||||||
if (dst.width() <= 0f || dst.height() <= 0f) return point
|
if (dst.width() <= 0f || dst.height() <= 0f) return point
|
||||||
return PointF(
|
return PointF(
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import androidx.lifecycle.ViewModel
|
|||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.kazier.mobile.R
|
import com.kazier.mobile.R
|
||||||
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||||
import com.kazier.mobile.data.local.entity.ScanPageStatus
|
|
||||||
import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
||||||
import com.kazier.mobile.data.preferences.DefaultRootStore
|
import com.kazier.mobile.data.preferences.DefaultRootStore
|
||||||
import com.kazier.mobile.data.repository.FileRepository
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
@@ -21,6 +20,7 @@ import com.kazier.mobile.data.repository.ScanRepository
|
|||||||
import com.kazier.mobile.features.saf.SafUris
|
import com.kazier.mobile.features.saf.SafUris
|
||||||
import com.kazier.mobile.features.saf.SafWriter
|
import com.kazier.mobile.features.saf.SafWriter
|
||||||
import com.kazier.mobile.features.scan.CornerGeometry
|
import com.kazier.mobile.features.scan.CornerGeometry
|
||||||
|
import com.kazier.mobile.features.scan.ScanExport
|
||||||
import com.kazier.mobile.features.scan.ScanImageProcessor
|
import com.kazier.mobile.features.scan.ScanImageProcessor
|
||||||
import com.kazier.mobile.features.scan.ScanQuad
|
import com.kazier.mobile.features.scan.ScanQuad
|
||||||
import com.kazier.mobile.features.scan.ScanRenderMode
|
import com.kazier.mobile.features.scan.ScanRenderMode
|
||||||
@@ -34,7 +34,6 @@ import kotlinx.coroutines.SupervisorJob
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.combine
|
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
@@ -44,6 +43,7 @@ import java.io.FileOutputStream
|
|||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import java.util.UUID
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import kotlin.math.max
|
import kotlin.math.max
|
||||||
import kotlin.math.min
|
import kotlin.math.min
|
||||||
@@ -113,11 +113,7 @@ class ScanViewModel @Inject constructor(
|
|||||||
val rootId = defaultRootStore.get()
|
val rootId = defaultRootStore.get()
|
||||||
val session = scanRepository.getOrCreateActiveSession(rootId)
|
val session = scanRepository.getOrCreateActiveSession(rootId)
|
||||||
_session.value = session
|
_session.value = session
|
||||||
combine(
|
scanRepository.observePages(session.id).collect { _pages.value = it }
|
||||||
scanRepository.observePages(session.id),
|
|
||||||
scanRepository.observePageCount(session.id),
|
|
||||||
) { pageList, _ -> pageList }
|
|
||||||
.collect { _pages.value = it }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,28 +173,47 @@ class ScanViewModel @Inject constructor(
|
|||||||
viewModelScope.launch(Dispatchers.IO) {
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
_busy.value = true
|
_busy.value = true
|
||||||
try {
|
try {
|
||||||
val (targetW, targetH) = CornerGeometry.outputSize(currentDraft.quad.points)
|
if (CornerGeometry.isDegenerate(currentDraft.quad.points)) {
|
||||||
|
_message.value = context.getString(R.string.scan_error_page)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
val processed = imageProcessor.process(
|
val processed = imageProcessor.process(
|
||||||
currentDraft.bitmap,
|
currentDraft.bitmap,
|
||||||
currentDraft.quad,
|
currentDraft.quad,
|
||||||
_renderMode.value,
|
_renderMode.value,
|
||||||
)
|
)
|
||||||
val order = scanRepository.pageCount(currentSession.id) + 1
|
try {
|
||||||
val sessionDir = ensureSessionDir(currentSession.id)
|
val sessionDir = ensureSessionDir(currentSession.id)
|
||||||
val finalFile = File(sessionDir, "page_$order.jpg")
|
// Nom unique (timestamp + aléatoire), jamais `page_$order` :
|
||||||
FileOutputStream(finalFile).use { out ->
|
// après suppression, COUNT réutilisait un nom existant et
|
||||||
processed.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out)
|
// écrasait le JPEG d'une autre page.
|
||||||
|
val finalFile = uniquePageFile(sessionDir)
|
||||||
|
FileOutputStream(finalFile).use { out ->
|
||||||
|
processed.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
scanRepository.addPage(
|
||||||
|
session = currentSession,
|
||||||
|
tempUri = finalFile.absolutePath,
|
||||||
|
cornersJson = quadToString(currentDraft.quad),
|
||||||
|
// Dimensions réelles post-scale (le processeur
|
||||||
|
// plafonne à 2400 px), pas celles du quad.
|
||||||
|
width = processed.width,
|
||||||
|
height = processed.height,
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// Insert Room échoué : pas de JPEG orphelin.
|
||||||
|
finalFile.delete()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
// `process()` alias l'entrée si OpenCV est indisponible :
|
||||||
|
// ne recycler que la nouvelle instance, jamais le bitmap
|
||||||
|
// du brouillon encore dessiné par CropStage.
|
||||||
|
if (processed !== currentDraft.bitmap) processed.recycle()
|
||||||
}
|
}
|
||||||
processed.recycle()
|
|
||||||
currentDraft.sourceFile.delete()
|
currentDraft.sourceFile.delete()
|
||||||
|
|
||||||
scanRepository.addPage(
|
|
||||||
session = currentSession,
|
|
||||||
tempUri = finalFile.absolutePath,
|
|
||||||
cornersJson = quadToString(currentDraft.quad),
|
|
||||||
width = targetW,
|
|
||||||
height = targetH,
|
|
||||||
)
|
|
||||||
_draft.value = null
|
_draft.value = null
|
||||||
_stage.value = ScanStage.CAMERA
|
_stage.value = ScanStage.CAMERA
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -230,8 +245,12 @@ class ScanViewModel @Inject constructor(
|
|||||||
fun deletePage(page: ScanPageEntity) {
|
fun deletePage(page: ScanPageEntity) {
|
||||||
val currentSession = _session.value ?: return
|
val currentSession = _session.value ?: return
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
File(page.tempUri).delete()
|
// DB d'abord, fichier ensuite : un crash entre les deux laisse au
|
||||||
scanRepository.deletePage(page.id, currentSession.id)
|
// pire un JPEG orphelin (nettoyé à l'abandon), jamais une ligne
|
||||||
|
// vers un fichier absent.
|
||||||
|
runCatching { scanRepository.deletePage(page.id, currentSession.id) }
|
||||||
|
.onSuccess { File(page.tempUri).delete() }
|
||||||
|
.onFailure { Timber.w(it, "scan delete page failed") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,7 +261,12 @@ class ScanViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Exporte toutes les pages dans le dossier racine, 1 fichier = 1 outbox. */
|
/**
|
||||||
|
* Exporte les pages en attente dans le dossier racine, 1 fichier =
|
||||||
|
* 1 outbox. Idempotent : seul le `PENDING` est exporté (un retry ne
|
||||||
|
* duplique jamais l'`EXPORTED`) ; seules les pages réussies sont marquées
|
||||||
|
* `EXPORTED` et la session ne passe `DONE` que si tout a réussi.
|
||||||
|
*/
|
||||||
fun export() {
|
fun export() {
|
||||||
val currentSession = _session.value ?: return
|
val currentSession = _session.value ?: return
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
@@ -256,48 +280,70 @@ class ScanViewModel @Inject constructor(
|
|||||||
val rootUri = SafUris.toDocumentUri(rootFolder.uri)
|
val rootUri = SafUris.toDocumentUri(rootFolder.uri)
|
||||||
?: error("default root has no uri")
|
?: error("default root has no uri")
|
||||||
|
|
||||||
val pages = scanRepository.getPages(currentSession.id)
|
val pages = ScanExport.pendingForExport(scanRepository.getPages(currentSession.id))
|
||||||
|
if (pages.isEmpty()) {
|
||||||
|
// Retry après succès : rien à faire, on termine.
|
||||||
|
scanRepository.finishSession(currentSession.id)
|
||||||
|
_exported.value = true
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
|
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
|
||||||
|
var failures = 0
|
||||||
pages.forEachIndexed { index, page ->
|
pages.forEachIndexed { index, page ->
|
||||||
val file = File(page.tempUri)
|
val file = File(page.tempUri)
|
||||||
if (!file.exists()) return@forEachIndexed
|
if (!file.isFile) {
|
||||||
val displayName = "scan_${stamp}_${(index + 1).toString().padStart(2, '0')}.jpg"
|
// Temp manquant : échec compté (reprise possible, pas
|
||||||
val createdUri = SafWriter.createDocument(
|
// de DONE silencieux avec un PENDING abandonné).
|
||||||
resolver = context.contentResolver,
|
Timber.w("scan export: missing temp for page %d", page.id)
|
||||||
treeUri = rootUri.toString(),
|
failures++
|
||||||
mimeType = "image/jpeg",
|
return@forEachIndexed
|
||||||
displayName = displayName,
|
}
|
||||||
) ?: error("cannot create document in default root")
|
|
||||||
SafWriter.copyInto(createdUri, file, context.contentResolver)
|
|
||||||
runCatching {
|
runCatching {
|
||||||
context.contentResolver.takePersistableUriPermission(
|
val displayName = "scan_${stamp}_${(index + 1).toString().padStart(2, '0')}.jpg"
|
||||||
createdUri,
|
val createdUri = SafWriter.createDocument(
|
||||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
|
resolver = context.contentResolver,
|
||||||
)
|
treeUri = rootUri.toString(),
|
||||||
}.onFailure { Timber.w(it, "persistable uri permission absent") }
|
|
||||||
|
|
||||||
val folderId = SafWriter.resolveTargetFolder(folderRepository, createdUri)
|
|
||||||
?: rootFolderId
|
|
||||||
val name = SafWriter.displayName(context.contentResolver, createdUri)
|
|
||||||
?: displayName
|
|
||||||
fileRepository.saveLocalFile(
|
|
||||||
input = SaveFileInput(
|
|
||||||
uri = createdUri.toString(),
|
|
||||||
name = name,
|
|
||||||
extension = "jpg",
|
|
||||||
size = file.length(),
|
|
||||||
mimeType = "image/jpeg",
|
mimeType = "image/jpeg",
|
||||||
lastModified = file.lastModified(),
|
displayName = displayName,
|
||||||
exists = true,
|
) ?: error("cannot create document in default root")
|
||||||
// Déjà traité au scan : ne pas remonter dans la review.
|
SafWriter.copyInto(createdUri, file, context.contentResolver)
|
||||||
processed = true,
|
runCatching {
|
||||||
),
|
context.contentResolver.takePersistableUriPermission(
|
||||||
folderResourceId = folderId,
|
createdUri,
|
||||||
)
|
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
|
||||||
scanRepository.markPageExported(page.copy(status = ScanPageStatus.EXPORTED))
|
)
|
||||||
|
}.onFailure { Timber.w(it, "persistable uri permission absent") }
|
||||||
|
|
||||||
|
val folderId = SafWriter.resolveTargetFolder(folderRepository, createdUri)
|
||||||
|
?: rootFolderId
|
||||||
|
val name = SafWriter.displayName(context.contentResolver, createdUri)
|
||||||
|
?: displayName
|
||||||
|
fileRepository.saveLocalFile(
|
||||||
|
input = SaveFileInput(
|
||||||
|
uri = createdUri.toString(),
|
||||||
|
name = name,
|
||||||
|
extension = "jpg",
|
||||||
|
size = file.length(),
|
||||||
|
mimeType = "image/jpeg",
|
||||||
|
lastModified = file.lastModified(),
|
||||||
|
exists = true,
|
||||||
|
// Déjà traité au scan : ne pas remonter dans la review.
|
||||||
|
processed = true,
|
||||||
|
),
|
||||||
|
folderResourceId = folderId,
|
||||||
|
)
|
||||||
|
scanRepository.markPageExported(page)
|
||||||
|
}.onFailure { e ->
|
||||||
|
Timber.e(e, "scan export failed for page %d", page.id)
|
||||||
|
failures++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ScanExport.shouldFinishSession(failures)) {
|
||||||
|
scanRepository.finishSession(currentSession.id)
|
||||||
|
_exported.value = true
|
||||||
|
} else {
|
||||||
|
_message.value = context.getString(R.string.scan_error_export)
|
||||||
}
|
}
|
||||||
scanRepository.finishSession(currentSession.id)
|
|
||||||
_exported.value = true
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Timber.e(e, "scan export failed")
|
Timber.e(e, "scan export failed")
|
||||||
_message.value = when (e) {
|
_message.value = when (e) {
|
||||||
@@ -328,8 +374,13 @@ class ScanViewModel @Inject constructor(
|
|||||||
val rootUri = SafUris.toDocumentUri(rootFolder.uri)
|
val rootUri = SafUris.toDocumentUri(rootFolder.uri)
|
||||||
?: error("default root has no uri")
|
?: error("default root has no uri")
|
||||||
|
|
||||||
val pages = scanRepository.getPages(currentSession.id)
|
val pages = ScanExport.pendingForExport(scanRepository.getPages(currentSession.id))
|
||||||
if (pages.isEmpty()) return@launch
|
if (pages.isEmpty()) {
|
||||||
|
// Retry après succès : rien à faire, on termine.
|
||||||
|
scanRepository.finishSession(currentSession.id)
|
||||||
|
_exported.value = true
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
|
||||||
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
|
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
|
||||||
val displayName = "scan_$stamp.pdf"
|
val displayName = "scan_$stamp.pdf"
|
||||||
@@ -381,14 +432,21 @@ class ScanViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
cacheFile.delete()
|
cacheFile.delete()
|
||||||
|
|
||||||
if (result.failedIds.isNotEmpty()) {
|
// Seules les pages effectivement embarquées sont marquées :
|
||||||
Timber.w("scan pdf: %d page(s) not embedded", result.failedIds.size)
|
// un échec partiel garde ses PENDING pour reprise, sans DONE.
|
||||||
|
val failedSet = result.failedIds.toHashSet()
|
||||||
|
if (failedSet.isNotEmpty()) {
|
||||||
|
Timber.w("scan pdf: %d page(s) not embedded", failedSet.size)
|
||||||
}
|
}
|
||||||
pages.forEach { page ->
|
ScanExport.succeeded(pages, failedSet).forEach { page ->
|
||||||
scanRepository.markPageExported(page.copy(status = ScanPageStatus.EXPORTED))
|
scanRepository.markPageExported(page)
|
||||||
|
}
|
||||||
|
if (ScanExport.shouldFinishSession(failedSet.size)) {
|
||||||
|
scanRepository.finishSession(currentSession.id)
|
||||||
|
_exported.value = true
|
||||||
|
} else {
|
||||||
|
_message.value = context.getString(R.string.scan_error_export)
|
||||||
}
|
}
|
||||||
scanRepository.finishSession(currentSession.id)
|
|
||||||
_exported.value = true
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Timber.e(e, "scan pdf export failed")
|
Timber.e(e, "scan pdf export failed")
|
||||||
_message.value = when (e) {
|
_message.value = when (e) {
|
||||||
@@ -408,12 +466,19 @@ class ScanViewModel @Inject constructor(
|
|||||||
/** Annule la session : suppression des fichiers temp + fermeture. */
|
/** Annule la session : suppression des fichiers temp + fermeture. */
|
||||||
fun abandon() {
|
fun abandon() {
|
||||||
val currentSession = _session.value ?: return
|
val currentSession = _session.value ?: return
|
||||||
|
_session.value = null
|
||||||
cleanupScope.launch {
|
cleanupScope.launch {
|
||||||
scanRepository.getPages(currentSession.id).forEach { File(it.tempUri).delete() }
|
val pages = scanRepository.getPages(currentSession.id)
|
||||||
sessionDir(currentSession.id)?.delete()
|
pages.forEach { File(it.tempUri).delete() }
|
||||||
|
val dir = sessionDir(currentSession.id)
|
||||||
|
if (dir.exists()) dir.deleteRecursively()
|
||||||
_pages.value = emptyList()
|
_pages.value = emptyList()
|
||||||
scanRepository.abandonSession(currentSession.id)
|
if (pages.isEmpty()) {
|
||||||
_session.value = null
|
// Session vide : purge de la ligne, pas de ABANDONED orphelin.
|
||||||
|
runCatching { scanRepository.deleteSession(currentSession.id) }
|
||||||
|
} else {
|
||||||
|
scanRepository.abandonSession(currentSession.id)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -424,11 +489,21 @@ class ScanViewModel @Inject constructor(
|
|||||||
// ------------------------------------------------------------ helpers
|
// ------------------------------------------------------------ helpers
|
||||||
|
|
||||||
private fun ensureSessionDir(sessionId: Long): File =
|
private fun ensureSessionDir(sessionId: Long): File =
|
||||||
sessionDir(sessionId)?.apply { if (!exists()) mkdirs() } ?: sessionDir(sessionId)!!
|
sessionDir(sessionId).apply { if (!exists()) mkdirs() }
|
||||||
|
|
||||||
private fun sessionDir(sessionId: Long): File? = runCatching {
|
/** Getter pur (jamais de `mkdirs`) : ne recrée pas ce que `abandon` supprime. */
|
||||||
File(context.filesDir, "$SCAN_DIR/$sessionId").also { it.mkdirs() }
|
private fun sessionDir(sessionId: Long): File =
|
||||||
}.getOrNull()
|
File(context.filesDir, "$SCAN_DIR/$sessionId")
|
||||||
|
|
||||||
|
/** Nom de page unique (timestamp + aléatoire) — jamais de collision. */
|
||||||
|
private fun uniquePageFile(dir: File): File {
|
||||||
|
var file: File
|
||||||
|
do {
|
||||||
|
val suffix = UUID.randomUUID().toString().replace("-", "").take(8)
|
||||||
|
file = File(dir, "page_${System.currentTimeMillis()}_$suffix.jpg")
|
||||||
|
} while (file.exists())
|
||||||
|
return file
|
||||||
|
}
|
||||||
|
|
||||||
private fun defaultQuad(width: Int, height: Int): List<PointF> {
|
private fun defaultQuad(width: Int, height: Int): List<PointF> {
|
||||||
val inset = min(width, height) * 0.08f
|
val inset = min(width, height) * 0.08f
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import androidx.compose.runtime.LaunchedEffect
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -96,9 +97,9 @@ fun SearchScreen(
|
|||||||
val deleteError by viewModel.deleteError.collectAsStateWithLifecycle()
|
val deleteError by viewModel.deleteError.collectAsStateWithLifecycle()
|
||||||
val deleteSuccess by viewModel.deleteSuccess.collectAsStateWithLifecycle()
|
val deleteSuccess by viewModel.deleteSuccess.collectAsStateWithLifecycle()
|
||||||
val selection = rememberSelectionState()
|
val selection = rememberSelectionState()
|
||||||
var showMoveDialog by remember { mutableStateOf(false) }
|
var showMoveDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteWarning by remember { mutableStateOf(false) }
|
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
||||||
var showDeleteConfirm by remember { mutableStateOf(false) }
|
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
@@ -166,12 +167,15 @@ fun SearchScreen(
|
|||||||
},
|
},
|
||||||
bottomBar = {
|
bottomBar = {
|
||||||
if (selection.active) {
|
if (selection.active) {
|
||||||
|
// M34 : les actions portent sur les résultats visibles —
|
||||||
|
// la sélection ne survit ni à la frappe ni au changement de filtre.
|
||||||
|
val visibleIds = uiState.results.map { it.resourceId }.toSet()
|
||||||
|
val selectedVisibleIds = selection.ids.filter { it in visibleIds }
|
||||||
SelectionNavBar(
|
SelectionNavBar(
|
||||||
onMove = { showMoveDialog = true },
|
onMove = { showMoveDialog = true },
|
||||||
onBuildPdf = {
|
onBuildPdf = {
|
||||||
val ids = selection.ids.toList()
|
|
||||||
selection.clear()
|
selection.clear()
|
||||||
onBuildPdf(ids)
|
onBuildPdf(selectedVisibleIds)
|
||||||
},
|
},
|
||||||
onDeleteModeSelected = { mode ->
|
onDeleteModeSelected = { mode ->
|
||||||
val selectedFiles = uiState.results.filter { it.resourceId in selection.ids }
|
val selectedFiles = uiState.results.filter { it.resourceId in selection.ids }
|
||||||
@@ -184,7 +188,7 @@ fun SearchScreen(
|
|||||||
showDeleteConfirm = true
|
showDeleteConfirm = true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = selection.ids.isNotEmpty(),
|
enabled = selectedVisibleIds.isNotEmpty(),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
FloatingNavBar(selected = selectedTab, onSelect = onTabSelected)
|
FloatingNavBar(selected = selectedTab, onSelect = onTabSelected)
|
||||||
@@ -212,7 +216,9 @@ fun SearchScreen(
|
|||||||
viewModel.closeMovePicker()
|
viewModel.closeMovePicker()
|
||||||
},
|
},
|
||||||
onConfirm = { folderId ->
|
onConfirm = { folderId ->
|
||||||
val ids = selection.ids.toList()
|
// M34 : seuls les ids encore visibles sont déplacés.
|
||||||
|
val visibleIds = uiState.results.map { it.resourceId }.toSet()
|
||||||
|
val ids = selection.ids.filter { it in visibleIds }
|
||||||
selection.clear()
|
selection.clear()
|
||||||
showMoveDialog = false
|
showMoveDialog = false
|
||||||
viewModel.moveSelectedFiles(ids, folderId)
|
viewModel.moveSelectedFiles(ids, folderId)
|
||||||
@@ -240,7 +246,9 @@ fun SearchScreen(
|
|||||||
DeleteConfirmDialog(
|
DeleteConfirmDialog(
|
||||||
count = selection.ids.size,
|
count = selection.ids.size,
|
||||||
onConfirm = {
|
onConfirm = {
|
||||||
val ids = selection.ids.toList()
|
// M34 : seuls les ids encore visibles sont supprimés.
|
||||||
|
val visibleIds = uiState.results.map { it.resourceId }.toSet()
|
||||||
|
val ids = selection.ids.filter { it in visibleIds }
|
||||||
val mode = pendingDeleteMode!!
|
val mode = pendingDeleteMode!!
|
||||||
selection.clear()
|
selection.clear()
|
||||||
showDeleteConfirm = false
|
showDeleteConfirm = false
|
||||||
@@ -291,6 +299,9 @@ private fun SearchContent(
|
|||||||
CategoryChip(
|
CategoryChip(
|
||||||
label = stringResource(R.string.category_all),
|
label = stringResource(R.string.category_all),
|
||||||
selected = uiState.selectedCategory == null,
|
selected = uiState.selectedCategory == null,
|
||||||
|
// M34 : les filtres sont figés en mode sélection (les
|
||||||
|
// résultats sous la sélection ne doivent pas changer).
|
||||||
|
enabled = !selection.active,
|
||||||
onClick = { onCategorySelect(null) },
|
onClick = { onCategorySelect(null) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -298,6 +309,7 @@ private fun SearchContent(
|
|||||||
CategoryChip(
|
CategoryChip(
|
||||||
label = categoryLabel(category),
|
label = categoryLabel(category),
|
||||||
selected = uiState.selectedCategory == category.dbValue,
|
selected = uiState.selectedCategory == category.dbValue,
|
||||||
|
enabled = !selection.active,
|
||||||
onClick = { onCategorySelect(category.dbValue) },
|
onClick = { onCategorySelect(category.dbValue) },
|
||||||
category = category,
|
category = category,
|
||||||
)
|
)
|
||||||
@@ -319,10 +331,12 @@ private fun CategoryChip(
|
|||||||
selected: Boolean,
|
selected: Boolean,
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
category: FileCategory? = null,
|
category: FileCategory? = null,
|
||||||
|
enabled: Boolean = true,
|
||||||
) {
|
) {
|
||||||
FilterChip(
|
FilterChip(
|
||||||
selected = selected,
|
selected = selected,
|
||||||
onClick = onClick,
|
onClick = onClick,
|
||||||
|
enabled = enabled,
|
||||||
label = { Text(label) },
|
label = { Text(label) },
|
||||||
leadingIcon = category?.let { cat ->
|
leadingIcon = category?.let { cat ->
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import kotlinx.coroutines.flow.asStateFlow
|
|||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.flow.debounce
|
import kotlinx.coroutines.flow.debounce
|
||||||
import kotlinx.coroutines.flow.flatMapLatest
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -51,20 +50,34 @@ class SearchViewModel @Inject constructor(
|
|||||||
private val _deleteSuccess = MutableStateFlow(false)
|
private val _deleteSuccess = MutableStateFlow(false)
|
||||||
val deleteSuccess: StateFlow<Boolean> = _deleteSuccess.asStateFlow()
|
val deleteSuccess: StateFlow<Boolean> = _deleteSuccess.asStateFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résultats Room : seule cette branche est debouncée (300 ms). La requête
|
||||||
|
* affichée ([uiState.query]) suit la frappe brute sans à-coups (M31).
|
||||||
|
*/
|
||||||
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
|
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
|
||||||
val uiState: StateFlow<SearchUiState> = combine(
|
private val results: StateFlow<List<FileEntity>> = combine(
|
||||||
_searchQuery.debounce(SEARCH_DEBOUNCE_MS),
|
_searchQuery.debounce(SEARCH_DEBOUNCE_MS),
|
||||||
_selectedCategory,
|
_selectedCategory,
|
||||||
) { query, category -> CategoryQuery(query, category) }
|
) { query, category -> CategoryQuery(query, category) }
|
||||||
.flatMapLatest { (query, category) ->
|
.flatMapLatest { (query, category) ->
|
||||||
val trimmed = query.trim()
|
val trimmed = query.trim()
|
||||||
val flow = if (trimmed.isEmpty()) {
|
if (trimmed.isEmpty()) {
|
||||||
fileRepository.recentFiles(category)
|
fileRepository.recentFiles(category)
|
||||||
} else {
|
} else {
|
||||||
fileRepository.searchFiles(trimmed, category)
|
fileRepository.searchFiles(trimmed, category)
|
||||||
}
|
}
|
||||||
flow.map { files -> SearchUiState(query, category, files) }
|
|
||||||
}
|
}
|
||||||
|
.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS),
|
||||||
|
initialValue = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
val uiState: StateFlow<SearchUiState> = combine(
|
||||||
|
_searchQuery,
|
||||||
|
_selectedCategory,
|
||||||
|
results,
|
||||||
|
) { query, category, files -> SearchUiState(query, category, files) }
|
||||||
.stateIn(
|
.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS),
|
started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS),
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package com.kazier.mobile.ui.settings
|
package com.kazier.mobile.ui.settings
|
||||||
|
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.isSystemInDarkTheme
|
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
@@ -20,13 +19,13 @@ import androidx.compose.material.icons.filled.Person
|
|||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Switch
|
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
@@ -80,12 +79,6 @@ fun SettingsScreen(
|
|||||||
var username by rememberSaveable { mutableStateOf("") }
|
var username by rememberSaveable { mutableStateOf("") }
|
||||||
var password by rememberSaveable { mutableStateOf("") }
|
var password by rememberSaveable { mutableStateOf("") }
|
||||||
|
|
||||||
val darkNow = when (theme) {
|
|
||||||
ThemePreference.DARK -> true
|
|
||||||
ThemePreference.LIGHT -> false
|
|
||||||
ThemePreference.SYSTEM -> isSystemInDarkTheme()
|
|
||||||
}
|
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
@@ -110,19 +103,22 @@ fun SettingsScreen(
|
|||||||
.verticalScroll(rememberScrollState()),
|
.verticalScroll(rememberScrollState()),
|
||||||
) {
|
) {
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
|
// M36 : 3 états (Système/Clair/Sombre) — le Switch DARK/LIGHT
|
||||||
|
// rendait SYSTEM inatteignable alors que le store le supporte.
|
||||||
SettingsRow(
|
SettingsRow(
|
||||||
icon = { Icon(Icons.Filled.DarkMode, contentDescription = null) },
|
icon = { Icon(Icons.Filled.DarkMode, contentDescription = null) },
|
||||||
title = stringResource(R.string.settings_dark_mode),
|
title = stringResource(R.string.settings_theme),
|
||||||
subtitle = stringResource(
|
subtitle = stringResource(
|
||||||
if (darkNow) R.string.settings_dark_mode_on
|
when (theme) {
|
||||||
else R.string.settings_dark_mode_off,
|
ThemePreference.DARK -> R.string.settings_theme_dark
|
||||||
|
ThemePreference.LIGHT -> R.string.settings_theme_light
|
||||||
|
ThemePreference.SYSTEM -> R.string.settings_theme_system
|
||||||
|
},
|
||||||
),
|
),
|
||||||
trailing = {
|
trailing = {
|
||||||
Switch(
|
ThemeSelector(
|
||||||
checked = darkNow,
|
selected = theme,
|
||||||
onCheckedChange = { on ->
|
onSelect = viewModel::setTheme,
|
||||||
viewModel.setTheme(if (on) ThemePreference.DARK else ThemePreference.LIGHT)
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -267,6 +263,43 @@ fun SettingsScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ThemeSelector(
|
||||||
|
selected: ThemePreference,
|
||||||
|
onSelect: (ThemePreference) -> Unit,
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
ThemeChip(
|
||||||
|
label = stringResource(R.string.settings_theme_system),
|
||||||
|
selected = selected == ThemePreference.SYSTEM,
|
||||||
|
onClick = { onSelect(ThemePreference.SYSTEM) },
|
||||||
|
)
|
||||||
|
ThemeChip(
|
||||||
|
label = stringResource(R.string.settings_theme_light),
|
||||||
|
selected = selected == ThemePreference.LIGHT,
|
||||||
|
onClick = { onSelect(ThemePreference.LIGHT) },
|
||||||
|
)
|
||||||
|
ThemeChip(
|
||||||
|
label = stringResource(R.string.settings_theme_dark),
|
||||||
|
selected = selected == ThemePreference.DARK,
|
||||||
|
onClick = { onSelect(ThemePreference.DARK) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ThemeChip(
|
||||||
|
label: String,
|
||||||
|
selected: Boolean,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
) {
|
||||||
|
FilterChip(
|
||||||
|
selected = selected,
|
||||||
|
onClick = onClick,
|
||||||
|
label = { Text(label) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun SettingsRow(
|
private fun SettingsRow(
|
||||||
icon: @Composable () -> Unit,
|
icon: @Composable () -> Unit,
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import com.kazier.mobile.domain.ThemePreference
|
|||||||
import com.kazier.mobile.domain.ThemePreferenceStore
|
import com.kazier.mobile.domain.ThemePreferenceStore
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
@@ -27,11 +29,18 @@ class SettingsViewModel @Inject constructor(
|
|||||||
private val _testUiState = MutableStateFlow(ServerTestUiState())
|
private val _testUiState = MutableStateFlow(ServerTestUiState())
|
||||||
val testUiState: StateFlow<ServerTestUiState> = _testUiState.asStateFlow()
|
val testUiState: StateFlow<ServerTestUiState> = _testUiState.asStateFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M37 : dès que l'utilisateur tape, le champ est « sale » — le `load()`
|
||||||
|
* asynchrone de l'init ne doit plus écraser sa saisie à son retour.
|
||||||
|
*/
|
||||||
|
private var dirty = false
|
||||||
|
private var saveJob: Job? = null
|
||||||
|
|
||||||
init {
|
init {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
themePreferenceStore.load()
|
themePreferenceStore.load()
|
||||||
serverConfigStore.load()
|
serverConfigStore.load()
|
||||||
_serverUrl.value = serverConfigStore.current
|
if (!dirty) _serverUrl.value = serverConfigStore.current
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,10 +48,18 @@ class SettingsViewModel @Inject constructor(
|
|||||||
viewModelScope.launch { themePreferenceStore.set(theme) }
|
viewModelScope.launch { themePreferenceStore.set(theme) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Persiste la base serveur au fil de la frappe (affichage = saisie brute). */
|
/**
|
||||||
|
* Affichage = saisie brute immédiate ; persistance debouncée (m36 : une
|
||||||
|
* écriture prefs par frappe = churn IO, une par pause suffit).
|
||||||
|
*/
|
||||||
fun onServerUrlChange(url: String) {
|
fun onServerUrlChange(url: String) {
|
||||||
|
dirty = true
|
||||||
_serverUrl.value = url
|
_serverUrl.value = url
|
||||||
viewModelScope.launch { serverConfigStore.set(url) }
|
saveJob?.cancel()
|
||||||
|
saveJob = viewModelScope.launch {
|
||||||
|
delay(SAVE_DEBOUNCE_MS)
|
||||||
|
serverConfigStore.set(url)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ping `/health` sur l'URL saisie (même non sauvegardée). */
|
/** Ping `/health` sur l'URL saisie (même non sauvegardée). */
|
||||||
@@ -70,4 +87,6 @@ data class ServerTestUiState(
|
|||||||
val isTesting: Boolean = false,
|
val isTesting: Boolean = false,
|
||||||
/** null = pas encore testé ; true/false = résultat du dernier test. */
|
/** null = pas encore testé ; true/false = résultat du dernier test. */
|
||||||
val success: Boolean? = null,
|
val success: Boolean? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private const val SAVE_DEBOUNCE_MS = 500L
|
||||||
+3
-1
@@ -24,5 +24,7 @@ class WatchedFoldersViewModel @Inject constructor(
|
|||||||
/** Nombre de racines surveillées — l'UI plafonne l'affichage à 99 (« 99+ »). */
|
/** Nombre de racines surveillées — l'UI plafonne l'affichage à 99 (« 99+ »). */
|
||||||
val count: StateFlow<Int> = folderRepository.observeSafRoots()
|
val count: StateFlow<Int> = folderRepository.observeSafRoots()
|
||||||
.map { it.size }
|
.map { it.size }
|
||||||
.stateIn(viewModelScope, SharingStarted.Eagerly, 0)
|
// m35 : WhileSubscribed — Eagerly collectait Room en continu même sur
|
||||||
|
// les autres onglets (aggravé par la double instance du badge).
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)
|
||||||
}
|
}
|
||||||
@@ -28,6 +28,7 @@
|
|||||||
<string name="review_mark_all_message">The remaining documents will be marked as reviewed and synced to the cloud without being checked.</string>
|
<string name="review_mark_all_message">The remaining documents will be marked as reviewed and synced to the cloud without being checked.</string>
|
||||||
<string name="review_load_error">Could not load the documents to review.</string>
|
<string name="review_load_error">Could not load the documents to review.</string>
|
||||||
<string name="review_delete_error">Could not delete this document — permission denied.</string>
|
<string name="review_delete_error">Could not delete this document — permission denied.</string>
|
||||||
|
<string name="review_keep_error">Could not keep this document — try again.</string>
|
||||||
<string name="browse_up">Up</string>
|
<string name="browse_up">Up</string>
|
||||||
<string name="move_here_count">Move here (%1$d)</string>
|
<string name="move_here_count">Move here (%1$d)</string>
|
||||||
<string name="move_pick_title">Move %1$d file(s)…</string>
|
<string name="move_pick_title">Move %1$d file(s)…</string>
|
||||||
@@ -107,6 +108,10 @@
|
|||||||
<string name="settings_dark_mode">Dark mode</string>
|
<string name="settings_dark_mode">Dark mode</string>
|
||||||
<string name="settings_dark_mode_on">Dark theme active</string>
|
<string name="settings_dark_mode_on">Dark theme active</string>
|
||||||
<string name="settings_dark_mode_off">Light theme active</string>
|
<string name="settings_dark_mode_off">Light theme active</string>
|
||||||
|
<string name="settings_theme">Theme</string>
|
||||||
|
<string name="settings_theme_system">System</string>
|
||||||
|
<string name="settings_theme_light">Light</string>
|
||||||
|
<string name="settings_theme_dark">Dark</string>
|
||||||
<string name="settings_server">Server</string>
|
<string name="settings_server">Server</string>
|
||||||
<string name="settings_server_url">Server address</string>
|
<string name="settings_server_url">Server address</string>
|
||||||
<string name="settings_test_connection">Test connection</string>
|
<string name="settings_test_connection">Test connection</string>
|
||||||
|
|||||||
@@ -28,6 +28,7 @@
|
|||||||
<string name="review_mark_all_message">Les documents restants seront considérés comme traités et synchronisés vers le cloud sans être revus.</string>
|
<string name="review_mark_all_message">Les documents restants seront considérés comme traités et synchronisés vers le cloud sans être revus.</string>
|
||||||
<string name="review_load_error">Impossible de charger les documents à traiter.</string>
|
<string name="review_load_error">Impossible de charger les documents à traiter.</string>
|
||||||
<string name="review_delete_error">Impossible de supprimer ce document — permission refusée.</string>
|
<string name="review_delete_error">Impossible de supprimer ce document — permission refusée.</string>
|
||||||
|
<string name="review_keep_error">Impossible de garder ce document — réessaie.</string>
|
||||||
<string name="browse_up">Remonter</string>
|
<string name="browse_up">Remonter</string>
|
||||||
<string name="move_here_count">Déplacer ici (%1$d)</string>
|
<string name="move_here_count">Déplacer ici (%1$d)</string>
|
||||||
<string name="move_pick_title">Déplacer %1$d fichier(s)…</string>
|
<string name="move_pick_title">Déplacer %1$d fichier(s)…</string>
|
||||||
@@ -107,6 +108,10 @@
|
|||||||
<string name="settings_dark_mode">Mode sombre</string>
|
<string name="settings_dark_mode">Mode sombre</string>
|
||||||
<string name="settings_dark_mode_on">Thème sombre actif</string>
|
<string name="settings_dark_mode_on">Thème sombre actif</string>
|
||||||
<string name="settings_dark_mode_off">Thème clair actif</string>
|
<string name="settings_dark_mode_off">Thème clair actif</string>
|
||||||
|
<string name="settings_theme">Thème</string>
|
||||||
|
<string name="settings_theme_system">Système</string>
|
||||||
|
<string name="settings_theme_light">Clair</string>
|
||||||
|
<string name="settings_theme_dark">Sombre</string>
|
||||||
<string name="settings_server">Serveur</string>
|
<string name="settings_server">Serveur</string>
|
||||||
<string name="settings_server_url">Adresse du serveur</string>
|
<string name="settings_server_url">Adresse du serveur</string>
|
||||||
<string name="settings_test_connection">Tester la connexion</string>
|
<string name="settings_test_connection">Tester la connexion</string>
|
||||||
|
|||||||
+124
@@ -0,0 +1,124 @@
|
|||||||
|
package com.kazier.mobile.data.local.dao
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P8 : le lien parent→enfant de la cascade est dénormalisé en colonne
|
||||||
|
* `parent_resource_id` (robuste au format Moshi), avec repli `LIKE` sur le
|
||||||
|
* payload pour les lignes pré-v14.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class ParentLinkCascadeTest {
|
||||||
|
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var opsDao: PendingOperationDao
|
||||||
|
private lateinit var outboxRepository: OutboxRepository
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
opsDao = db.pendingOperationDao()
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
val generateId = GenerateId()
|
||||||
|
outboxRepository = OutboxRepository(
|
||||||
|
opsDao,
|
||||||
|
generateId,
|
||||||
|
DeviceIdentity(db.userPreferenceDao(), generateId),
|
||||||
|
moshi,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun enqueue_remplit_la_colonne_parent() = runTest {
|
||||||
|
outboxRepository.enqueueCreateResource(
|
||||||
|
resourceId = CHILD,
|
||||||
|
resourceType = "folder",
|
||||||
|
name = "Enfant",
|
||||||
|
parentResourceId = PARENT,
|
||||||
|
)
|
||||||
|
|
||||||
|
val rows = opsDao.selectPending(10).filter { it.resourceId == CHILD }
|
||||||
|
assertEquals(1, rows.size)
|
||||||
|
assertEquals("la colonne dénormalisée porte le parent", PARENT, rows[0].parentResourceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun cascade_via_colonne_sans_lien_json() = runTest {
|
||||||
|
// Payload volontairement vide : seul `parent_resource_id` lie l'enfant.
|
||||||
|
opsDao.insert(
|
||||||
|
op(resourceId = CHILD, parentResourceId = PARENT, payload = "{}"),
|
||||||
|
)
|
||||||
|
|
||||||
|
opsDao.failDescendants(PARENT, NOW)
|
||||||
|
|
||||||
|
// La ligne est passée `failed` : elle n'est plus `pending`.
|
||||||
|
assertEquals(0, opsDao.countByStatus(PendingOpStatus.PENDING))
|
||||||
|
assertEquals(
|
||||||
|
"l'enfant est invalidé par la colonne, sans parsing JSON",
|
||||||
|
1,
|
||||||
|
opsDao.countByStatus(PendingOpStatus.FAILED),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun repli_like_pour_lignes_pre_v14_sans_colonne() = runTest {
|
||||||
|
opsDao.insert(
|
||||||
|
op(
|
||||||
|
resourceId = CHILD,
|
||||||
|
parentResourceId = null,
|
||||||
|
payload = """{"name":"Enfant","parentResourceId":"$PARENT"}""",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
opsDao.failDescendants(PARENT, NOW)
|
||||||
|
|
||||||
|
assertEquals(1, opsDao.countByStatus(PendingOpStatus.FAILED))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun op(resourceId: String, parentResourceId: String?, payload: String) =
|
||||||
|
PendingOperationEntity(
|
||||||
|
operationId = resourceId,
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = "folder",
|
||||||
|
operation = PendingOperationType.CREATE_RESOURCE,
|
||||||
|
payload = payload,
|
||||||
|
parentResourceId = parentResourceId,
|
||||||
|
status = PendingOpStatus.PENDING,
|
||||||
|
createdAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val NOW = 1_700_000_000_000L
|
||||||
|
const val PARENT = "11111111111111111111111111111111"
|
||||||
|
const val CHILD = "22222222222222222222222222222222"
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
-2
@@ -9,11 +9,13 @@ import com.kazier.mobile.data.local.AppDatabase
|
|||||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.ApiService
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
import com.kazier.mobile.data.repository.FileRepository
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
import com.kazier.mobile.data.repository.OutboxRepository
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
import com.kazier.mobile.data.repository.SaveFileInput
|
import com.kazier.mobile.data.repository.SaveFileInput
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
import com.kazier.mobile.domain.GenerateId
|
import com.kazier.mobile.domain.GenerateId
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import org.junit.After
|
import org.junit.After
|
||||||
@@ -64,8 +66,24 @@ class ProcessedGateTest {
|
|||||||
val apiClient = ApiClient(apiService, moshi)
|
val apiClient = ApiClient(apiService, moshi)
|
||||||
val generateId = GenerateId()
|
val generateId = GenerateId()
|
||||||
|
|
||||||
outboxRepository = OutboxRepository(opsDao, generateId, moshi)
|
outboxRepository = OutboxRepository(opsDao, generateId, DeviceIdentity(db.userPreferenceDao(), generateId), moshi)
|
||||||
fileRepository = FileRepository(fileDao, apiClient, generateId, db, outboxRepository)
|
fileRepository = FileRepository(fileDao, db.folderDao(), apiClient, generateId, db, outboxRepository)
|
||||||
|
|
||||||
|
// Validation applicative du parent (M18) : le dossier hôte existe.
|
||||||
|
runTest {
|
||||||
|
db.folderDao().upsert(
|
||||||
|
FolderEntity(
|
||||||
|
resourceId = FOLDER,
|
||||||
|
uri = null,
|
||||||
|
name = FOLDER,
|
||||||
|
exists = 1,
|
||||||
|
parentResourceId = null,
|
||||||
|
syncStatus = "local",
|
||||||
|
addedAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
|
|||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
package com.kazier.mobile.data.local.migration
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||||
|
import androidx.sqlite.db.SupportSQLiteOpenHelper
|
||||||
|
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P8 : la migration 13→14 ajoute `parent_resource_id` + son index sans
|
||||||
|
* toucher aux lignes existantes (NULL → repli LIKE). Une coquille SQL ici
|
||||||
|
* briquerait l'app au démarrage après update : on rejoue la migration sur
|
||||||
|
* une table v13 minimale et on vérifie schéma + données.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class Migration13To14Test {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun migration_ajoute_la_colonne_et_l_index_en_preservant_les_lignes() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val helper = FrameworkSQLiteOpenHelperFactory().create(
|
||||||
|
SupportSQLiteOpenHelper.Configuration.builder(context)
|
||||||
|
.name(null)
|
||||||
|
.callback(V13Callback())
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
val db = helper.writableDatabase
|
||||||
|
db.execSQL(
|
||||||
|
"INSERT INTO `pending_operations` " +
|
||||||
|
"(`device_id`, `operation_id`, `resource_id`, `operation`, `payload`, `status`, `created_at`, `updated_at`) " +
|
||||||
|
"VALUES ('d1', 'op1', 'r1', 'create_resource', '{\"a\":1}', 'pending', 1, 1)",
|
||||||
|
)
|
||||||
|
|
||||||
|
val migration = Migrations.ALL.first { it.startVersion == 13 && it.endVersion == 14 }
|
||||||
|
migration.migrate(db)
|
||||||
|
|
||||||
|
// Colonne présente et NULL sur les lignes préexistantes.
|
||||||
|
val columns = mutableListOf<String>()
|
||||||
|
db.query("PRAGMA table_info(`pending_operations`)").use { cursor ->
|
||||||
|
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||||
|
while (cursor.moveToNext()) columns += cursor.getString(nameIdx)
|
||||||
|
}
|
||||||
|
assertTrue(columns.contains("parent_resource_id"))
|
||||||
|
db.query("SELECT `parent_resource_id` FROM `pending_operations`").use { cursor ->
|
||||||
|
assertTrue(cursor.moveToFirst())
|
||||||
|
assertTrue(cursor.isNull(0))
|
||||||
|
}
|
||||||
|
// Index présent.
|
||||||
|
var indexFound = false
|
||||||
|
db.query("PRAGMA index_list(`pending_operations`)").use { cursor ->
|
||||||
|
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||||
|
while (cursor.moveToNext()) {
|
||||||
|
if (cursor.getString(nameIdx) == "index_pending_operations_parent_resource_id") {
|
||||||
|
indexFound = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue("index parent_resource_id manquant", indexFound)
|
||||||
|
// Données intactes.
|
||||||
|
db.query("SELECT `operation_id`, `status` FROM `pending_operations`").use { cursor ->
|
||||||
|
assertTrue(cursor.moveToFirst())
|
||||||
|
assertEquals("op1", cursor.getString(0))
|
||||||
|
assertEquals("pending", cursor.getString(1))
|
||||||
|
}
|
||||||
|
helper.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Schéma v13 minimal de `pending_operations` (sans `parent_resource_id`). */
|
||||||
|
private class V13Callback : SupportSQLiteOpenHelper.Callback(13) {
|
||||||
|
override fun onCreate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE TABLE `pending_operations` (" +
|
||||||
|
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
|
||||||
|
"`device_id` TEXT, " +
|
||||||
|
"`operation_id` TEXT NOT NULL, " +
|
||||||
|
"`ref_type` TEXT, " +
|
||||||
|
"`ref_id` INTEGER, " +
|
||||||
|
"`resource_id` TEXT, " +
|
||||||
|
"`resource_type` TEXT, " +
|
||||||
|
"`operation` TEXT NOT NULL, " +
|
||||||
|
"`payload` TEXT NOT NULL, " +
|
||||||
|
"`status` TEXT NOT NULL, " +
|
||||||
|
"`attempts` INTEGER NOT NULL DEFAULT 0, " +
|
||||||
|
"`created_at` INTEGER NOT NULL, " +
|
||||||
|
"`updated_at` INTEGER NOT NULL)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onUpgrade(
|
||||||
|
db: SupportSQLiteDatabase,
|
||||||
|
oldVersion: Int,
|
||||||
|
newVersion: Int,
|
||||||
|
) = Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.auth.SessionManager
|
||||||
|
import com.kazier.mobile.auth.TokenProvider
|
||||||
|
import com.kazier.mobile.auth.TokenStore
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import com.kazier.mobile.data.remote.dto.UserDto
|
||||||
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
|
import com.kazier.mobile.domain.LocalModeStore
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
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
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lot E (M25) : le 401 sur endpoint protégé purge la session via le callback
|
||||||
|
* possédé par `SessionManager` (singleton) — pas par un ViewModel — donc la
|
||||||
|
* purge survit à `onCleared`. Le 401 du login reste exonéré.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class Auth401Test {
|
||||||
|
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
|
||||||
|
private lateinit var tokenStore: FakeTokenStore
|
||||||
|
private lateinit var tokenProvider: TokenProvider
|
||||||
|
private lateinit var apiClient: ApiClient
|
||||||
|
private lateinit var sessionManager: SessionManager
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
tokenStore = FakeTokenStore()
|
||||||
|
tokenProvider = TokenProvider()
|
||||||
|
apiClient = ApiClient(UnauthorizedFake(), moshi)
|
||||||
|
sessionManager = SessionManager(
|
||||||
|
tokenStore,
|
||||||
|
ActiveUserStore(db.userPreferenceDao()),
|
||||||
|
tokenProvider,
|
||||||
|
LocalModeStore(db.userPreferenceDao()),
|
||||||
|
db.pendingOperationDao(),
|
||||||
|
apiClient,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun seed() {
|
||||||
|
tokenStore.save("tok-abc", UserDto(id = "u1", username = "alice"), expiresAt = 9_999_999_999_999L)
|
||||||
|
tokenProvider.current = "tok-abc"
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun awaitPurge() = withTimeout(5_000L) {
|
||||||
|
while (tokenStore.getToken() != null) delay(10L)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `401_protege_purge_la_session`() = runBlocking {
|
||||||
|
seed()
|
||||||
|
val error = runCatching { apiClient.listFolders() }.exceptionOrNull()
|
||||||
|
assertNotNull(error)
|
||||||
|
assertEquals("UNAUTHORIZED", (error as ApiException).code)
|
||||||
|
|
||||||
|
// Token en mémoire tombé synchronement…
|
||||||
|
assertNull(tokenProvider.current)
|
||||||
|
// …persistance purgée en IO juste après.
|
||||||
|
awaitPurge()
|
||||||
|
assertNull(tokenStore.getUser())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `401_purge_encore_apres_destruction_du_viewmodel`() = runBlocking {
|
||||||
|
// `AuthViewModel` ne possède plus `onUnauthorized` : il n'y a rien à
|
||||||
|
// annuler dans `onCleared` — le callback singleton reste branché.
|
||||||
|
assertNotNull(apiClient.onUnauthorized)
|
||||||
|
|
||||||
|
seed()
|
||||||
|
runCatching { apiClient.listFolders() }
|
||||||
|
awaitPurge()
|
||||||
|
assertNull(tokenProvider.current)
|
||||||
|
|
||||||
|
// Et un second 401 purge toujours (pas de one-shot).
|
||||||
|
seed()
|
||||||
|
runCatching { apiClient.listFolders() }
|
||||||
|
awaitPurge()
|
||||||
|
assertNull(tokenProvider.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `401_login_ne_purge_pas`() = runBlocking { seed()
|
||||||
|
val error = runCatching { apiClient.login("alice", "mauvais-mdp", "device-1") }.exceptionOrNull()
|
||||||
|
assertNotNull(error)
|
||||||
|
assertEquals("UNAUTHORIZED", (error as ApiException).code)
|
||||||
|
|
||||||
|
assertEquals("tok-abc", tokenProvider.current)
|
||||||
|
assertEquals("tok-abc", tokenStore.getToken())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- C5 : pas de replay cross-account ------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `signOut_purge_pending_et_failed_conserve_synced`() = runBlocking {
|
||||||
|
seed()
|
||||||
|
val ops = db.pendingOperationDao()
|
||||||
|
ops.insert(op("a", PendingOperationType.CREATE_RESOURCE, PendingOpStatus.PENDING))
|
||||||
|
ops.insert(op("b", PendingOperationType.MOVE_RESOURCE, PendingOpStatus.FAILED))
|
||||||
|
ops.insert(op("c", PendingOperationType.CREATE_RESOURCE, PendingOpStatus.SYNCED))
|
||||||
|
|
||||||
|
sessionManager.clear()
|
||||||
|
|
||||||
|
assertNull(tokenProvider.current)
|
||||||
|
assertEquals("pending purgé", 0, ops.countByStatus(PendingOpStatus.PENDING))
|
||||||
|
assertEquals("failed purgé", 0, ops.countByStatus(PendingOpStatus.FAILED))
|
||||||
|
assertEquals("les tombstones synced survivent", 1, ops.countByStatus(PendingOpStatus.SYNCED))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `login_autre_compte_purge_la_file`() = runBlocking {
|
||||||
|
sessionManager.save("tok-a", UserDto(id = "user-a", username = "alice"), null)
|
||||||
|
val ops = db.pendingOperationDao()
|
||||||
|
ops.insert(op("a", PendingOperationType.CREATE_RESOURCE, PendingOpStatus.PENDING))
|
||||||
|
|
||||||
|
sessionManager.save("tok-b", UserDto(id = "user-b", username = "bob"), null)
|
||||||
|
|
||||||
|
assertEquals("la file de A ne part pas sous le token de B", 0, ops.countPending())
|
||||||
|
assertEquals("user-b", ActiveUserStore(db.userPreferenceDao()).get())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `relogin_meme_compte_conserve_la_file`() = runBlocking {
|
||||||
|
sessionManager.save("tok-a1", UserDto(id = "user-a", username = "alice"), null)
|
||||||
|
val ops = db.pendingOperationDao()
|
||||||
|
ops.insert(op("a", PendingOperationType.CREATE_RESOURCE, PendingOpStatus.PENDING))
|
||||||
|
|
||||||
|
sessionManager.save("tok-a2", UserDto(id = "user-a", username = "alice"), null)
|
||||||
|
|
||||||
|
assertEquals("un simple renouvellement de token ne perd rien", 1, ops.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `premier_login_conserve_le_travail_local`() = runBlocking {
|
||||||
|
val ops = db.pendingOperationDao()
|
||||||
|
ops.insert(op("a", PendingOperationType.CREATE_RESOURCE, PendingOpStatus.PENDING))
|
||||||
|
|
||||||
|
sessionManager.save("tok-a", UserDto(id = "user-a", username = "alice"), null)
|
||||||
|
|
||||||
|
assertEquals("le travail du mode local est poussé après login", 1, ops.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun op(resourceId: String, operation: String, status: String) =
|
||||||
|
com.kazier.mobile.data.local.entity.PendingOperationEntity(
|
||||||
|
operationId = resourceId,
|
||||||
|
resourceId = "r".repeat(32),
|
||||||
|
resourceType = "file",
|
||||||
|
operation = operation,
|
||||||
|
payload = "{}",
|
||||||
|
status = status,
|
||||||
|
createdAt = 1L,
|
||||||
|
updatedAt = 1L,
|
||||||
|
)
|
||||||
|
|
||||||
|
private class FakeTokenStore : TokenStore {
|
||||||
|
private var token: String? = null
|
||||||
|
private var user: UserDto? = null
|
||||||
|
private var expiresAt: Long? = null
|
||||||
|
|
||||||
|
override fun getToken(): String? = token
|
||||||
|
override fun getUser(): UserDto? = user
|
||||||
|
override fun getExpiresAt(): Long? = expiresAt
|
||||||
|
|
||||||
|
override fun save(token: String, user: UserDto, expiresAt: Long?) {
|
||||||
|
this.token = token
|
||||||
|
this.user = user
|
||||||
|
this.expiresAt = expiresAt
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun clear() {
|
||||||
|
token = null
|
||||||
|
user = null
|
||||||
|
expiresAt = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `listFolders` et `login` répondent 401 ; le reste est inutilisé. */
|
||||||
|
private class UnauthorizedFake : ApiService {
|
||||||
|
private fun unauthorized(): okhttp3.ResponseBody =
|
||||||
|
"""{"error":{"code":"UNAUTHORIZED","message":"expired"}}"""
|
||||||
|
.toResponseBody("application/json".toMediaType())
|
||||||
|
|
||||||
|
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||||
|
Response.error(401, unauthorized())
|
||||||
|
|
||||||
|
override suspend fun login(
|
||||||
|
body: LoginRequestDto,
|
||||||
|
): Response<ApiEnvelope<LoginResponseDto>> = Response.error(401, unauthorized())
|
||||||
|
|
||||||
|
override suspend fun listFiles(
|
||||||
|
folderId: String?,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun registerDevice(
|
||||||
|
body: DeviceRegistrationDto,
|
||||||
|
): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||||
|
Response.success(ApiEnvelope(data = body))
|
||||||
|
|
||||||
|
override suspend fun syncOps(
|
||||||
|
body: SyncOpsRequest,
|
||||||
|
): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||||
|
|
||||||
|
override suspend fun resolveUser(
|
||||||
|
username: String,
|
||||||
|
): Response<ApiEnvelope<ResolvedUserDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncPermissions(
|
||||||
|
after: Long?,
|
||||||
|
): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun uploadFile(
|
||||||
|
file: MultipartBody.Part,
|
||||||
|
resourceId: RequestBody?,
|
||||||
|
folderId: RequestBody?,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun submitOcr(
|
||||||
|
body: OcrSubmitDto,
|
||||||
|
): Response<ApiEnvelope<OcrJobDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getOcrJob(
|
||||||
|
jobId: String,
|
||||||
|
): Response<ApiEnvelope<OcrJobDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFileOcr(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(
|
||||||
|
token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiMeta
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import retrofit2.Response
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lot E (M21) : `refreshFromServer` draine toutes les pages en suivant `meta`
|
||||||
|
* au lieu de jeter la pagination après la 1re page de 50.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class PaginationTest {
|
||||||
|
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
|
||||||
|
private fun moshi(): Moshi = Moshi.Builder()
|
||||||
|
.add(KotlinJsonAdapterFactory())
|
||||||
|
.build()
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fileDto(i: Int) = FileDto(
|
||||||
|
id = "%032d".format(i),
|
||||||
|
name = "doc-$i.pdf",
|
||||||
|
size = 100L + i,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun repository(fake: PagedFilesFake): FileRepository {
|
||||||
|
val m = moshi()
|
||||||
|
val generateId = GenerateId()
|
||||||
|
val outbox = OutboxRepository(
|
||||||
|
db.pendingOperationDao(),
|
||||||
|
generateId,
|
||||||
|
DeviceIdentity(db.userPreferenceDao(), generateId),
|
||||||
|
m,
|
||||||
|
)
|
||||||
|
return FileRepository(db.fileDao(), db.folderDao(), ApiClient(fake, m), generateId, db, outbox)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `refreshFromServer_charge_3_pages_de_50_en_suivant_meta`() = runTest {
|
||||||
|
val all = (1..150).map(::fileDto)
|
||||||
|
val fake = PagedFilesFake(all, withMeta = true)
|
||||||
|
repository(fake).refreshFromServer("folder-x")
|
||||||
|
|
||||||
|
val stored = db.fileDao().getByFolderOnce("folder-x")
|
||||||
|
assertEquals(150, stored.size)
|
||||||
|
assertEquals(listOf(1, 2, 3), fake.requestedPages)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `refreshFromServer_sans_meta_s_arrete_a_la_page_partielle`() = runTest {
|
||||||
|
val all = (1..110).map(::fileDto)
|
||||||
|
val fake = PagedFilesFake(all, withMeta = false)
|
||||||
|
repository(fake).refreshFromServer("folder-x")
|
||||||
|
|
||||||
|
val stored = db.fileDao().getByFolderOnce("folder-x")
|
||||||
|
assertEquals(110, stored.size)
|
||||||
|
assertEquals(listOf(1, 2, 3), fake.requestedPages)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fake `GET /files` paginé côté serveur (page 1-based, pageSize 50). */
|
||||||
|
private class PagedFilesFake(
|
||||||
|
private val all: List<FileDto>,
|
||||||
|
private val withMeta: Boolean,
|
||||||
|
) : ApiService {
|
||||||
|
val requestedPages = mutableListOf<Int>()
|
||||||
|
|
||||||
|
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun listFiles(
|
||||||
|
folderId: String?,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> {
|
||||||
|
val p = page ?: 1
|
||||||
|
val ps = pageSize ?: 50
|
||||||
|
requestedPages += p
|
||||||
|
val slice = all.drop((p - 1) * ps).take(ps)
|
||||||
|
val meta = if (withMeta) ApiMeta(page = p, pageSize = ps, total = all.size) else null
|
||||||
|
return Response.success(ApiEnvelope(data = slice, meta = meta))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun registerDevice(
|
||||||
|
body: DeviceRegistrationDto,
|
||||||
|
): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||||
|
Response.success(ApiEnvelope(data = body))
|
||||||
|
|
||||||
|
override suspend fun login(
|
||||||
|
body: LoginRequestDto,
|
||||||
|
): Response<ApiEnvelope<LoginResponseDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncOps(
|
||||||
|
body: SyncOpsRequest,
|
||||||
|
): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||||
|
|
||||||
|
override suspend fun resolveUser(
|
||||||
|
username: String,
|
||||||
|
): Response<ApiEnvelope<ResolvedUserDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncPermissions(
|
||||||
|
after: Long?,
|
||||||
|
): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun uploadFile(
|
||||||
|
file: MultipartBody.Part,
|
||||||
|
resourceId: RequestBody?,
|
||||||
|
folderId: RequestBody?,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun submitOcr(
|
||||||
|
body: OcrSubmitDto,
|
||||||
|
): Response<ApiEnvelope<OcrJobDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getOcrJob(
|
||||||
|
jobId: String,
|
||||||
|
): Response<ApiEnvelope<OcrJobDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFileOcr(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(
|
||||||
|
token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package com.kazier.mobile.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||||
|
import com.kazier.mobile.domain.PrefKeys
|
||||||
|
import com.kazier.mobile.domain.ServerConfigStore
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import okhttp3.Call
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Protocol
|
||||||
|
import okhttp3.Request
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
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 java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lot E (M26/M28) : cold start avec URL custom — aucune requête ne part vers
|
||||||
|
* l'hôte par défaut (l'interceptor restaure l'URL avant la 1re requête) — et
|
||||||
|
* `set()` rejette les URL invalides sans persister.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class ServerConfigTest {
|
||||||
|
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
|
||||||
|
private fun store(): ServerConfigStore =
|
||||||
|
ServerConfigStore(db.userPreferenceDao(), OkHttpClient())
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `cold_start_custom_aucune_requete_vers_le_defaut`() = runTest {
|
||||||
|
db.userPreferenceDao().upsert(
|
||||||
|
UserPreferenceEntity(PrefKeys.SERVER_URL, "https://kazier.example.com:8443/api/v1", 1L),
|
||||||
|
)
|
||||||
|
val store = store()
|
||||||
|
assertFalse(store.isLoaded)
|
||||||
|
|
||||||
|
val chain = CapturingChain(Request.Builder().url("http://kazier.invalid/api/v1/files").build())
|
||||||
|
ServerUrlInterceptor(store).intercept(chain)
|
||||||
|
|
||||||
|
val proceeded = chain.proceeded ?: error("aucune requête relayée")
|
||||||
|
assertEquals("kazier.example.com", proceeded.url.host)
|
||||||
|
assertEquals(8443, proceeded.url.port)
|
||||||
|
assertEquals("https", proceeded.url.scheme)
|
||||||
|
assertTrue(proceeded.url.encodedPath.startsWith("/api/v1/files"))
|
||||||
|
assertTrue(store.isLoaded)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `set_invalide_rejete_sans_persister`() = runTest {
|
||||||
|
val store = store()
|
||||||
|
store.load()
|
||||||
|
|
||||||
|
assertFalse(store.set("http://"))
|
||||||
|
assertFalse(store.set("foo bar"))
|
||||||
|
assertFalse(store.set("ftp://host/api/v1"))
|
||||||
|
assertFalse(store.set(""))
|
||||||
|
assertFalse(store.set("https://"))
|
||||||
|
|
||||||
|
assertEquals(ServerConfigStore.DEFAULT_BASE_URL, store.current)
|
||||||
|
assertNull(db.userPreferenceDao().getValue(PrefKeys.SERVER_URL))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `set_valide_normalise_et_persiste`() = runTest {
|
||||||
|
val store = store()
|
||||||
|
store.load()
|
||||||
|
|
||||||
|
assertTrue(store.set("https://example.com/api/v1/"))
|
||||||
|
assertEquals("https://example.com/api/v1", store.current)
|
||||||
|
assertEquals("https://example.com/api/v1", db.userPreferenceDao().getValue(PrefKeys.SERVER_URL))
|
||||||
|
|
||||||
|
// Schéma absent → http:// préfixé.
|
||||||
|
assertTrue(store.set("example.com/api/v1"))
|
||||||
|
assertEquals("http://example.com/api/v1", store.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fake `Interceptor.Chain` qui capture la requête relayée (aucun réseau). */
|
||||||
|
private class CapturingChain(private val original: Request) : Interceptor.Chain {
|
||||||
|
var proceeded: Request? = null
|
||||||
|
|
||||||
|
override fun request(): Request = original
|
||||||
|
|
||||||
|
override fun proceed(request: Request): okhttp3.Response {
|
||||||
|
proceeded = request
|
||||||
|
return okhttp3.Response.Builder()
|
||||||
|
.request(request)
|
||||||
|
.protocol(Protocol.HTTP_1_1)
|
||||||
|
.code(200)
|
||||||
|
.message("OK")
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun connection(): okhttp3.Connection? = null
|
||||||
|
override fun call(): Call = throw UnsupportedOperationException()
|
||||||
|
override fun connectTimeoutMillis(): Int = 0
|
||||||
|
override fun withConnectTimeout(timeout: Int, unit: TimeUnit): Interceptor.Chain = this
|
||||||
|
override fun readTimeoutMillis(): Int = 0
|
||||||
|
override fun withReadTimeout(timeout: Int, unit: TimeUnit): Interceptor.Chain = this
|
||||||
|
override fun writeTimeoutMillis(): Int = 0
|
||||||
|
override fun withWriteTimeout(timeout: Int, unit: TimeUnit): Interceptor.Chain = this
|
||||||
|
}
|
||||||
|
}
|
||||||
+160
-11
@@ -9,13 +9,17 @@ import com.kazier.mobile.data.local.AppDatabase
|
|||||||
import com.kazier.mobile.data.local.dao.FolderDao
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.ApiService
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileDto
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
@@ -27,8 +31,14 @@ import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
|||||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
import com.kazier.mobile.domain.GenerateId
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import com.kazier.mobile.features.saf.FileMover
|
||||||
|
import com.kazier.mobile.features.saf.FolderDeleter
|
||||||
|
import com.kazier.mobile.features.saf.FolderMerger
|
||||||
|
import com.kazier.mobile.features.saf.SafFolderCreator
|
||||||
|
import com.kazier.mobile.features.thumbnails.ThumbnailStore
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
@@ -57,7 +67,9 @@ class FolderMergeDataTest {
|
|||||||
private lateinit var folderDao: FolderDao
|
private lateinit var folderDao: FolderDao
|
||||||
private lateinit var opsDao: PendingOperationDao
|
private lateinit var opsDao: PendingOperationDao
|
||||||
private lateinit var folderRepository: FolderRepository
|
private lateinit var folderRepository: FolderRepository
|
||||||
|
private lateinit var fileRepository: FileRepository
|
||||||
private lateinit var outboxRepository: OutboxRepository
|
private lateinit var outboxRepository: OutboxRepository
|
||||||
|
private lateinit var merger: FolderMerger
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
fun setUp() {
|
fun setUp() {
|
||||||
@@ -71,15 +83,42 @@ class FolderMergeDataTest {
|
|||||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
val generateId = GenerateId()
|
val generateId = GenerateId()
|
||||||
val deviceIdentity = DeviceIdentity(db.userPreferenceDao(), generateId)
|
val deviceIdentity = DeviceIdentity(db.userPreferenceDao(), generateId)
|
||||||
outboxRepository = OutboxRepository(opsDao, generateId, moshi)
|
outboxRepository = OutboxRepository(opsDao, generateId, deviceIdentity, moshi)
|
||||||
folderRepository = FolderRepository(
|
folderRepository = FolderRepository(
|
||||||
folderDao = folderDao,
|
folderDao = folderDao,
|
||||||
apiClient = ApiClient(FolderMergeApiService(), moshi),
|
apiClient = ApiClient(FolderMergeApiService(), moshi),
|
||||||
generateId = generateId,
|
generateId = generateId,
|
||||||
deviceIdentity = deviceIdentity,
|
activeUserStore = ActiveUserStore(db.userPreferenceDao()),
|
||||||
appDatabase = db,
|
appDatabase = db,
|
||||||
outboxRepository = outboxRepository,
|
outboxRepository = outboxRepository,
|
||||||
)
|
)
|
||||||
|
// Tout cloud-only (uri NULL) : la fusion n'atteint jamais le provider
|
||||||
|
// SAF, seul Room + l'outbox sont exercés.
|
||||||
|
fileRepository = FileRepository(
|
||||||
|
db.fileDao(),
|
||||||
|
folderDao,
|
||||||
|
ApiClient(FolderMergeApiService(), moshi),
|
||||||
|
generateId,
|
||||||
|
db,
|
||||||
|
outboxRepository,
|
||||||
|
)
|
||||||
|
val fileMover = FileMover(context, fileRepository, folderRepository)
|
||||||
|
val folderDeleter = FolderDeleter(
|
||||||
|
context,
|
||||||
|
folderRepository,
|
||||||
|
fileRepository,
|
||||||
|
outboxRepository,
|
||||||
|
db,
|
||||||
|
ThumbnailStore(context),
|
||||||
|
)
|
||||||
|
merger = FolderMerger(
|
||||||
|
context,
|
||||||
|
folderRepository,
|
||||||
|
fileRepository,
|
||||||
|
fileMover,
|
||||||
|
folderDeleter,
|
||||||
|
SafFolderCreator(context),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
@@ -92,21 +131,27 @@ class FolderMergeDataTest {
|
|||||||
folderDao.upsert(folder(ROOT, parent = null))
|
folderDao.upsert(folder(ROOT, parent = null))
|
||||||
folderDao.upsert(folder(CHILD_A, parent = ROOT))
|
folderDao.upsert(folder(CHILD_A, parent = ROOT))
|
||||||
folderDao.upsert(folder(CHILD_B, parent = ROOT))
|
folderDao.upsert(folder(CHILD_B, parent = ROOT))
|
||||||
|
folderDao.upsert(folder(MERGED, parent = ROOT))
|
||||||
|
// Gate `create` (M2) : les dossiers sont déjà connus du serveur, le
|
||||||
|
// reparent journalise donc un `move_resource` par dossier.
|
||||||
|
opsDao.insert(createOp(CHILD_A, "aa"))
|
||||||
|
opsDao.insert(createOp(CHILD_B, "bb"))
|
||||||
|
|
||||||
folderRepository.reparentSubFolders(listOf(CHILD_A, CHILD_B), MERGED)
|
folderRepository.reparentSubFolders(listOf(CHILD_A, CHILD_B), MERGED)
|
||||||
|
|
||||||
assertEquals("parent_A repositionné", MERGED, folderDao.getByResourceId(CHILD_A)!!.parentResourceId)
|
assertEquals("parent_A repositionné", MERGED, folderDao.getByResourceId(CHILD_A)!!.parentResourceId)
|
||||||
assertEquals("parent_B repositionné", MERGED, folderDao.getByResourceId(CHILD_B)!!.parentResourceId)
|
assertEquals("parent_B repositionné", MERGED, folderDao.getByResourceId(CHILD_B)!!.parentResourceId)
|
||||||
|
|
||||||
val ops = opsDao.selectPending(10)
|
val moves = opsDao.selectPending(10)
|
||||||
assertEquals("une op move par dossier (ordre outbox)", 2, ops.size)
|
.filter { it.operation == PendingOperationType.MOVE_RESOURCE }
|
||||||
assertEquals(PendingOperationType.MOVE_RESOURCE, ops[0].operation)
|
assertEquals("une op move par dossier (ordre outbox)", 2, moves.size)
|
||||||
assertEquals("folder", ops[0].resourceType)
|
assertEquals(PendingOperationType.MOVE_RESOURCE, moves[0].operation)
|
||||||
assertEquals(CHILD_A, ops[0].resourceId)
|
assertEquals("folder", moves[0].resourceType)
|
||||||
assertEquals(ROOT_WITH_MERGED, ops[0].payload)
|
assertEquals(CHILD_A, moves[0].resourceId)
|
||||||
assertEquals(PendingOperationType.MOVE_RESOURCE, ops[1].operation)
|
assertEquals(ROOT_WITH_MERGED, moves[0].payload)
|
||||||
assertEquals(CHILD_B, ops[1].resourceId)
|
assertEquals(PendingOperationType.MOVE_RESOURCE, moves[1].operation)
|
||||||
assertEquals(PendingOpStatus.PENDING, ops[1].status)
|
assertEquals(CHILD_B, moves[1].resourceId)
|
||||||
|
assertEquals(PendingOpStatus.PENDING, moves[1].status)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -114,6 +159,9 @@ class FolderMergeDataTest {
|
|||||||
folderDao.upsert(folder(ROOT, parent = null))
|
folderDao.upsert(folder(ROOT, parent = null))
|
||||||
folderDao.upsert(folder(CHILD_A, parent = ROOT))
|
folderDao.upsert(folder(CHILD_A, parent = ROOT))
|
||||||
folderDao.upsert(folder(CHILD_B, parent = ROOT))
|
folderDao.upsert(folder(CHILD_B, parent = ROOT))
|
||||||
|
// Dossier cible au niveau racine : il existe (validation M18) sans
|
||||||
|
// fausser le comptage des enfants de ROOT.
|
||||||
|
folderDao.upsert(folder(MERGED, parent = null))
|
||||||
// L'ancien parent n'a plus d'enfants visibles.
|
// L'ancien parent n'a plus d'enfants visibles.
|
||||||
assertEquals(2, folderRepository.getChildren(ROOT).size)
|
assertEquals(2, folderRepository.getChildren(ROOT).size)
|
||||||
|
|
||||||
@@ -129,6 +177,42 @@ class FolderMergeDataTest {
|
|||||||
assertEquals(0, opsDao.selectPending(10).size)
|
assertEquals(0, opsDao.selectPending(10).size)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun relance_apres_crash_mi_fusion_reutilise_le_dossier_fusionne() = runTest {
|
||||||
|
// État après crash à mi-fusion : le dossier fusionné existe déjà (avec
|
||||||
|
// son `create_resource`), une partie du contenu est déjà déplacée.
|
||||||
|
folderDao.upsert(folder(ROOT, parent = null))
|
||||||
|
folderDao.upsert(folder(SRC_A, parent = ROOT))
|
||||||
|
folderDao.upsert(folder(SRC_B, parent = ROOT))
|
||||||
|
folderDao.upsert(mergedFolder())
|
||||||
|
opsDao.insert(createOp(MERGED))
|
||||||
|
folderDao.upsert(folder(CHILD_A, parent = MERGED))
|
||||||
|
db.fileDao().upsert(cloudFile(FILE_X, SRC_B))
|
||||||
|
|
||||||
|
val report = merger.mergeSelectedFolders(
|
||||||
|
listOf(
|
||||||
|
folderDao.getByResourceId(SRC_A)!!,
|
||||||
|
folderDao.getByResourceId(SRC_B)!!,
|
||||||
|
),
|
||||||
|
MERGED_NAME,
|
||||||
|
)
|
||||||
|
|
||||||
|
val merged = folderDao.getAll()
|
||||||
|
.filter { it.name == MERGED_NAME && it.parentResourceId == ROOT }
|
||||||
|
assertEquals("aucun dossier fusionné dupliqué à la relance", 1, merged.size)
|
||||||
|
assertEquals(MERGED, merged[0].resourceId)
|
||||||
|
assertEquals(
|
||||||
|
"relance sans second create_resource",
|
||||||
|
1,
|
||||||
|
opsDao.selectPending(100).count {
|
||||||
|
it.operation == PendingOperationType.CREATE_RESOURCE && it.resourceId == MERGED
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assertEquals("contenu restant déplacé", MERGED, db.fileDao().getByResourceId(FILE_X)!!.folderResourceId)
|
||||||
|
assertEquals("enfant déjà déplacé conservé", MERGED, folderDao.getByResourceId(CHILD_A)!!.parentResourceId)
|
||||||
|
assertEquals(0, report.failed)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun hasCreateOperationAnyType_reconnait_les_dossiers_pousses() = runTest {
|
fun hasCreateOperationAnyType_reconnait_les_dossiers_pousses() = runTest {
|
||||||
opsDao.insert(
|
opsDao.insert(
|
||||||
@@ -168,12 +252,55 @@ class FolderMergeDataTest {
|
|||||||
updatedAt = NOW,
|
updatedAt = NOW,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private fun mergedFolder() = FolderEntity(
|
||||||
|
resourceId = MERGED,
|
||||||
|
uri = null,
|
||||||
|
name = MERGED_NAME,
|
||||||
|
exists = 1,
|
||||||
|
parentResourceId = ROOT,
|
||||||
|
ownerId = OWNER,
|
||||||
|
syncStatus = "cloud",
|
||||||
|
addedAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun cloudFile(resourceId: String, folderId: String) = FileEntity(
|
||||||
|
resourceId = resourceId,
|
||||||
|
uri = null,
|
||||||
|
name = "$resourceId.txt",
|
||||||
|
folderResourceId = folderId,
|
||||||
|
extension = "txt",
|
||||||
|
size = 512L,
|
||||||
|
mimeType = "text/plain",
|
||||||
|
category = "TEXT",
|
||||||
|
exists = 1,
|
||||||
|
syncStatus = "cloud",
|
||||||
|
processed = true,
|
||||||
|
addedAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun createOp(resourceId: String, opSuffix: String = "f") = PendingOperationEntity(
|
||||||
|
operationId = opSuffix.repeat(32).take(32),
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = "folder",
|
||||||
|
operation = PendingOperationType.CREATE_RESOURCE,
|
||||||
|
payload = "{}",
|
||||||
|
status = PendingOpStatus.PENDING,
|
||||||
|
createdAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val NOW = 1_700_000_000_000L
|
const val NOW = 1_700_000_000_000L
|
||||||
const val ROOT = "11111111111111111111111111111111"
|
const val ROOT = "11111111111111111111111111111111"
|
||||||
const val CHILD_A = "22222222222222222222222222222222"
|
const val CHILD_A = "22222222222222222222222222222222"
|
||||||
const val CHILD_B = "33333333333333333333333333333333"
|
const val CHILD_B = "33333333333333333333333333333333"
|
||||||
const val MERGED = "44444444444444444444444444444444"
|
const val MERGED = "44444444444444444444444444444444"
|
||||||
|
const val SRC_A = "55555555555555555555555555555555"
|
||||||
|
const val SRC_B = "66666666666666666666666666666666"
|
||||||
|
const val FILE_X = "cccccccccccccccccccccccccccccccc"
|
||||||
|
const val MERGED_NAME = "Fusion"
|
||||||
const val OWNER = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
const val OWNER = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||||
const val FOLDER_ID = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
const val FOLDER_ID = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||||
val ROOT_WITH_MERGED = """{"toFolderResourceId":"$MERGED"}"""
|
val ROOT_WITH_MERGED = """{"toFolderResourceId":"$MERGED"}"""
|
||||||
@@ -229,4 +356,26 @@ private class FolderMergeApiService : ApiService {
|
|||||||
override suspend fun getFileOcr(
|
override suspend fun getFileOcr(
|
||||||
fileId: String,
|
fileId: String,
|
||||||
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope(data = FileOcrDto(text = "")))
|
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope(data = FileOcrDto(text = "")))
|
||||||
|
|
||||||
|
override suspend fun getFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(
|
||||||
|
token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
}
|
}
|
||||||
+155
-4
@@ -1,8 +1,13 @@
|
|||||||
package com.kazier.mobile.data.repository
|
package com.kazier.mobile.data.repository
|
||||||
|
|
||||||
|
import android.content.ContentProvider
|
||||||
|
import android.content.ContentValues
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
import androidx.room.Room
|
import androidx.room.Room
|
||||||
import androidx.test.core.app.ApplicationProvider
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.squareup.moshi.Moshi
|
import com.squareup.moshi.Moshi
|
||||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
import com.kazier.mobile.data.local.AppDatabase
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
@@ -10,13 +15,17 @@ import com.kazier.mobile.data.local.dao.FileDao
|
|||||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import com.kazier.mobile.data.local.entity.FileStatus
|
import com.kazier.mobile.data.local.entity.FileStatus
|
||||||
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.ApiService
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileDto
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
@@ -28,7 +37,9 @@ import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
|||||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
import com.kazier.mobile.domain.GenerateId
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import com.kazier.mobile.features.saf.FileMover
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
@@ -41,6 +52,7 @@ import org.junit.Test
|
|||||||
import org.junit.runner.RunWith
|
import org.junit.runner.RunWith
|
||||||
import org.robolectric.RobolectricTestRunner
|
import org.robolectric.RobolectricTestRunner
|
||||||
import org.robolectric.annotation.Config
|
import org.robolectric.annotation.Config
|
||||||
|
import org.robolectric.shadows.ShadowContentResolver
|
||||||
import retrofit2.Response
|
import retrofit2.Response
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,6 +72,7 @@ class MoveProtectionTest {
|
|||||||
private lateinit var fileRepository: FileRepository
|
private lateinit var fileRepository: FileRepository
|
||||||
private lateinit var outboxRepository: OutboxRepository
|
private lateinit var outboxRepository: OutboxRepository
|
||||||
private lateinit var apiService: MoveProtectionApiService
|
private lateinit var apiService: MoveProtectionApiService
|
||||||
|
private lateinit var moshi: Moshi
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
fun setUp() {
|
fun setUp() {
|
||||||
@@ -70,13 +83,19 @@ class MoveProtectionTest {
|
|||||||
fileDao = db.fileDao()
|
fileDao = db.fileDao()
|
||||||
opsDao = db.pendingOperationDao()
|
opsDao = db.pendingOperationDao()
|
||||||
|
|
||||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build().also { this.moshi = it }
|
||||||
apiService = MoveProtectionApiService()
|
apiService = MoveProtectionApiService()
|
||||||
val apiClient = ApiClient(apiService, moshi)
|
val apiClient = ApiClient(apiService, moshi)
|
||||||
val generateId = GenerateId()
|
val generateId = GenerateId()
|
||||||
|
|
||||||
outboxRepository = OutboxRepository(opsDao, generateId, moshi)
|
outboxRepository = OutboxRepository(opsDao, generateId, DeviceIdentity(db.userPreferenceDao(), generateId), moshi)
|
||||||
fileRepository = FileRepository(fileDao, apiClient, generateId, db, outboxRepository)
|
fileRepository = FileRepository(fileDao, db.folderDao(), apiClient, generateId, db, outboxRepository)
|
||||||
|
|
||||||
|
// Validation applicative du parent (M18) : les dossiers hôtes existent.
|
||||||
|
runTest {
|
||||||
|
db.folderDao().upsert(folderRow(SOURCE_FOLDER, parent = null))
|
||||||
|
db.folderDao().upsert(folderRow(TARGET_FOLDER, parent = null))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
@@ -186,8 +205,81 @@ class MoveProtectionTest {
|
|||||||
assertEquals("la ligne émerge à nouveau", 1, row.exists)
|
assertEquals("la ligne émerge à nouveau", 1, row.exists)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- prédicats outbox ----------------------------------------------------
|
// --- applyMove : gate `create` (M2) ---------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun applyMove_sans_create_ne_journalise_pas_de_move_resource() = runTest {
|
||||||
|
// Fichier jamais poussé (ni pending ni synced) : le déplacement reste
|
||||||
|
// purement local, aucun `move_resource` (le serveur ne connaît pas la
|
||||||
|
// ressource — ce serait NOT_FOUND + ligne figée).
|
||||||
|
fileDao.upsert(file(SOURCE_FOLDER, exists = 1))
|
||||||
|
|
||||||
|
fileRepository.applyMove(FILE_ID, TARGET_FOLDER, null)
|
||||||
|
|
||||||
|
assertEquals(TARGET_FOLDER, fileDao.getByResourceId(FILE_ID)!!.folderResourceId)
|
||||||
|
assertTrue(
|
||||||
|
"aucun move_resource sans create préalable",
|
||||||
|
opsDao.selectPending(10).none { it.operation == PendingOperationType.MOVE_RESOURCE },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun applyMove_avec_create_journalise_move_resource() = runTest {
|
||||||
|
fileDao.upsert(file(SOURCE_FOLDER, exists = 1))
|
||||||
|
opsDao.insert(
|
||||||
|
op(
|
||||||
|
status = PendingOpStatus.PENDING,
|
||||||
|
operation = PendingOperationType.CREATE_RESOURCE,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
fileRepository.applyMove(FILE_ID, TARGET_FOLDER, NEW_URI)
|
||||||
|
|
||||||
|
val row = fileDao.getByResourceId(FILE_ID)!!
|
||||||
|
assertEquals(TARGET_FOLDER, row.folderResourceId)
|
||||||
|
assertEquals("l'uri suit le déplacement physique", NEW_URI, row.uri)
|
||||||
|
val moves = opsDao.selectPending(10)
|
||||||
|
.filter { it.operation == PendingOperationType.MOVE_RESOURCE && it.resourceId == FILE_ID }
|
||||||
|
assertEquals(1, moves.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- FileMover : refus SAF → Room inchangée (M3) ---------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun moveDocument_refuse_ne_change_pas_room() = runTest {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
// Provider qui refuse toute opération SAF (permission révoquée) :
|
||||||
|
// DocumentsContract.moveDocument passe par ContentResolver.call().
|
||||||
|
ShadowContentResolver.registerProviderInternal("com.test", RefusingProvider())
|
||||||
|
val fakeContext = context
|
||||||
|
val folderRepository = FolderRepository(
|
||||||
|
folderDao = db.folderDao(),
|
||||||
|
apiClient = ApiClient(apiService, moshi),
|
||||||
|
generateId = GenerateId(),
|
||||||
|
activeUserStore = ActiveUserStore(db.userPreferenceDao()),
|
||||||
|
appDatabase = db,
|
||||||
|
outboxRepository = outboxRepository,
|
||||||
|
)
|
||||||
|
val mover = FileMover(fakeContext, fileRepository, folderRepository)
|
||||||
|
|
||||||
|
// NB : `@Upsert` Room résout sur la PK, pas sur `resource_id` — pour
|
||||||
|
// changer l'uri d'une ligne existante, recopier son `id`.
|
||||||
|
val targetRow = db.folderDao().getByResourceId(TARGET_FOLDER)!!
|
||||||
|
db.folderDao().upsert(targetRow.copy(uri = TARGET_URI))
|
||||||
|
fileDao.upsert(file(SOURCE_FOLDER, exists = 1).copy(uri = FILE_URI))
|
||||||
|
|
||||||
|
mover.moveFiles(listOf(FILE_ID), TARGET_FOLDER)
|
||||||
|
|
||||||
|
val row = fileDao.getByResourceId(FILE_ID)!!
|
||||||
|
assertEquals("parent local conservé sur refus SAF", SOURCE_FOLDER, row.folderResourceId)
|
||||||
|
assertEquals("uri locale conservée sur refus SAF", FILE_URI, row.uri)
|
||||||
|
assertTrue(
|
||||||
|
"aucune op sur déplacement refusé",
|
||||||
|
opsDao.selectPending(10).isEmpty(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- prédicats outbox ----------------------------------------------------
|
||||||
@Test
|
@Test
|
||||||
fun hasPendingMoveOperation_discrimine_pending_seul() = runTest {
|
fun hasPendingMoveOperation_discrimine_pending_seul() = runTest {
|
||||||
opsDao.insert(op(status = PendingOpStatus.PENDING))
|
opsDao.insert(op(status = PendingOpStatus.PENDING))
|
||||||
@@ -218,6 +310,17 @@ class MoveProtectionTest {
|
|||||||
|
|
||||||
// --- fixtures ------------------------------------------------------------
|
// --- fixtures ------------------------------------------------------------
|
||||||
|
|
||||||
|
private fun folderRow(resourceId: String, parent: String?) = FolderEntity(
|
||||||
|
resourceId = resourceId,
|
||||||
|
uri = null,
|
||||||
|
name = resourceId,
|
||||||
|
exists = 1,
|
||||||
|
parentResourceId = parent,
|
||||||
|
syncStatus = FileStatus.LOCAL,
|
||||||
|
addedAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
private fun file(folderId: String, exists: Int) = FileEntity(
|
private fun file(folderId: String, exists: Int) = FileEntity(
|
||||||
resourceId = FILE_ID,
|
resourceId = FILE_ID,
|
||||||
uri = PRE_MOVE_URI,
|
uri = PRE_MOVE_URI,
|
||||||
@@ -261,9 +364,35 @@ class MoveProtectionTest {
|
|||||||
const val SIZE = 1024L
|
const val SIZE = 1024L
|
||||||
const val MIME = "text/plain"
|
const val MIME = "text/plain"
|
||||||
const val PRE_MOVE_URI = "content://tree/11111111111111111111111111111111/doc"
|
const val PRE_MOVE_URI = "content://tree/11111111111111111111111111111111/doc"
|
||||||
|
const val FILE_URI = "content://com.test/tree/root/document/f1"
|
||||||
|
const val TARGET_URI = "content://com.test/tree/root/document/target"
|
||||||
|
const val NEW_URI = "content://com.test/tree/root/document/target/f1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Provider qui refuse toute opération SAF (permission révoquée). */
|
||||||
|
private class RefusingProvider : ContentProvider() {
|
||||||
|
override fun onCreate(): Boolean = true
|
||||||
|
override fun call(authority: String, method: String, arg: String?, extras: Bundle?): Bundle? =
|
||||||
|
throw SecurityException("persisted permission revoked")
|
||||||
|
override fun query(
|
||||||
|
uri: Uri,
|
||||||
|
projection: Array<out String>?,
|
||||||
|
selection: String?,
|
||||||
|
selectionArgs: Array<out String>?,
|
||||||
|
sortOrder: String?,
|
||||||
|
): android.database.Cursor? = null
|
||||||
|
override fun getType(uri: Uri): String? = null
|
||||||
|
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||||
|
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||||
|
override fun update(
|
||||||
|
uri: Uri,
|
||||||
|
values: ContentValues?,
|
||||||
|
selection: String?,
|
||||||
|
selectionArgs: Array<out String>?,
|
||||||
|
): Int = 0
|
||||||
|
}
|
||||||
|
|
||||||
/** Fake `ApiService` — seul `listFiles` est réellement consommé. */
|
/** Fake `ApiService` — seul `listFiles` est réellement consommé. */
|
||||||
private class MoveProtectionApiService : ApiService {
|
private class MoveProtectionApiService : ApiService {
|
||||||
var files: List<FileDto> = emptyList()
|
var files: List<FileDto> = emptyList()
|
||||||
@@ -316,4 +445,26 @@ private class MoveProtectionApiService : ApiService {
|
|||||||
override suspend fun getFileOcr(
|
override suspend fun getFileOcr(
|
||||||
fileId: String,
|
fileId: String,
|
||||||
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope(data = FileOcrDto(text = "")))
|
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope(data = FileOcrDto(text = "")))
|
||||||
|
|
||||||
|
override suspend fun getFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(
|
||||||
|
token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
}
|
}
|
||||||
+25
@@ -13,7 +13,10 @@ import com.kazier.mobile.data.local.entity.FileStatus
|
|||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.ApiService
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileDto
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
@@ -336,6 +339,28 @@ private class OcrApiServiceFake : ApiService {
|
|||||||
return Response.success(ApiEnvelope(data = fileOcr))
|
return Response.success(ApiEnvelope(data = fileOcr))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun getFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(
|
||||||
|
token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
private fun readBody(body: RequestBody): String {
|
private fun readBody(body: RequestBody): String {
|
||||||
val buffer = okio.Buffer()
|
val buffer = okio.Buffer()
|
||||||
body.writeTo(buffer)
|
body.writeTo(buffer)
|
||||||
|
|||||||
+237
@@ -0,0 +1,237 @@
|
|||||||
|
package com.kazier.mobile.data.repository
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
|
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import retrofit2.Response
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garde-fou refresh serveur vs reparent local (miroir dossiers du
|
||||||
|
* `MoveProtectionTest` fichiers) : tant qu'un `move_resource` dossier est en
|
||||||
|
* attente de push, `refreshFromServer` ne doit pas ré-attribuer l'ancien
|
||||||
|
* parent renvoyé par le serveur. Une fois l'op soldée (ou jamais journalisée),
|
||||||
|
* le serveur redevient source de vérité.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class RefreshVsMoveTest {
|
||||||
|
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var folderDao: FolderDao
|
||||||
|
private lateinit var opsDao: PendingOperationDao
|
||||||
|
private lateinit var folderRepository: FolderRepository
|
||||||
|
private lateinit var outboxRepository: OutboxRepository
|
||||||
|
private lateinit var apiService: RefreshVsMoveApiService
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
folderDao = db.folderDao()
|
||||||
|
opsDao = db.pendingOperationDao()
|
||||||
|
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
apiService = RefreshVsMoveApiService()
|
||||||
|
val generateId = GenerateId()
|
||||||
|
outboxRepository = OutboxRepository(
|
||||||
|
opsDao,
|
||||||
|
generateId,
|
||||||
|
DeviceIdentity(db.userPreferenceDao(), generateId),
|
||||||
|
moshi,
|
||||||
|
)
|
||||||
|
folderRepository = FolderRepository(
|
||||||
|
folderDao = folderDao,
|
||||||
|
apiClient = ApiClient(apiService, moshi),
|
||||||
|
generateId = generateId,
|
||||||
|
activeUserStore = ActiveUserStore(db.userPreferenceDao()),
|
||||||
|
appDatabase = db,
|
||||||
|
outboxRepository = outboxRepository,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun reparent_pending_le_pull_ancien_parent_conserve_le_local() = runTest {
|
||||||
|
// Placement local : le dossier est déjà sous TARGET (reparent/merge).
|
||||||
|
folderDao.upsert(folder(CHILD, parent = TARGET))
|
||||||
|
// L'op move_resource n'a pas encore été poussée.
|
||||||
|
opsDao.insert(moveOp(status = PendingOpStatus.PENDING))
|
||||||
|
// Le serveur renvoie encore l'ancien parent (op pas appliquée).
|
||||||
|
apiService.folders = listOf(FolderDto(id = CHILD, name = NAME, parentId = SOURCE))
|
||||||
|
|
||||||
|
folderRepository.refreshFromServer()
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"placement local cible préservé",
|
||||||
|
TARGET,
|
||||||
|
folderDao.getByResourceId(CHILD)!!.parentResourceId,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun refresh_sans_move_pending_suit_le_serveur() = runTest {
|
||||||
|
folderDao.upsert(folder(CHILD, parent = TARGET))
|
||||||
|
apiService.folders = listOf(FolderDto(id = CHILD, name = NAME_RENAMED, parentId = SOURCE))
|
||||||
|
|
||||||
|
folderRepository.refreshFromServer()
|
||||||
|
|
||||||
|
val row = folderDao.getByResourceId(CHILD)!!
|
||||||
|
assertEquals("le serveur redevient source de vérité", SOURCE, row.parentResourceId)
|
||||||
|
assertEquals("métadonnées serveur prises en compte", NAME_RENAMED, row.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- fixtures ------------------------------------------------------------
|
||||||
|
|
||||||
|
private fun folder(resourceId: String, parent: String?) = FolderEntity(
|
||||||
|
resourceId = resourceId,
|
||||||
|
uri = null,
|
||||||
|
name = resourceId,
|
||||||
|
exists = 1,
|
||||||
|
parentResourceId = parent,
|
||||||
|
syncStatus = "local",
|
||||||
|
addedAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun moveOp(status: String) = PendingOperationEntity(
|
||||||
|
operationId = "e".repeat(32),
|
||||||
|
resourceId = CHILD,
|
||||||
|
resourceType = "folder",
|
||||||
|
operation = PendingOperationType.MOVE_RESOURCE,
|
||||||
|
payload = """{"toFolderResourceId":"$TARGET"}""",
|
||||||
|
status = status,
|
||||||
|
createdAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val NOW = 1_700_000_000_000L
|
||||||
|
const val SOURCE = "11111111111111111111111111111111"
|
||||||
|
const val TARGET = "22222222222222222222222222222222"
|
||||||
|
const val CHILD = "33333333333333333333333333333333"
|
||||||
|
const val NAME = "Enfant"
|
||||||
|
const val NAME_RENAMED = "Enfant renomme"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fake `ApiService` — seul `listFolders` est réellement consommé. */
|
||||||
|
private class RefreshVsMoveApiService : ApiService {
|
||||||
|
var folders: List<FolderDto> = emptyList()
|
||||||
|
|
||||||
|
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = folders))
|
||||||
|
|
||||||
|
override suspend fun listFiles(
|
||||||
|
folderId: String?,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun registerDevice(
|
||||||
|
body: DeviceRegistrationDto,
|
||||||
|
): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||||
|
Response.success(ApiEnvelope(data = body))
|
||||||
|
|
||||||
|
override suspend fun login(
|
||||||
|
body: LoginRequestDto,
|
||||||
|
): Response<ApiEnvelope<LoginResponseDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncOps(
|
||||||
|
body: SyncOpsRequest,
|
||||||
|
): Response<ApiEnvelope<SyncOpsResult>> = Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||||
|
|
||||||
|
override suspend fun resolveUser(
|
||||||
|
username: String,
|
||||||
|
): Response<ApiEnvelope<ResolvedUserDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun syncPermissions(
|
||||||
|
after: Long?,
|
||||||
|
): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||||
|
Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun uploadFile(
|
||||||
|
file: MultipartBody.Part,
|
||||||
|
resourceId: RequestBody?,
|
||||||
|
folderId: RequestBody?,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun submitOcr(
|
||||||
|
body: OcrSubmitDto,
|
||||||
|
): Response<ApiEnvelope<OcrJobDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getOcrJob(
|
||||||
|
jobId: String,
|
||||||
|
): Response<ApiEnvelope<OcrJobDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getFileOcr(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope(data = FileOcrDto(text = "")))
|
||||||
|
|
||||||
|
override suspend fun getFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(
|
||||||
|
token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
|
}
|
||||||
+92
-4
@@ -15,7 +15,10 @@ import com.kazier.mobile.data.local.entity.FolderEntity
|
|||||||
import com.kazier.mobile.data.remote.ApiClient
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
import com.kazier.mobile.data.remote.ApiService
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileDto
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
@@ -27,8 +30,7 @@ import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
|||||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
import com.kazier.mobile.domain.DeviceIdentity
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
import com.kazier.mobile.domain.GenerateId
|
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
@@ -63,6 +65,7 @@ class ShareRepositoryTest {
|
|||||||
private lateinit var fileDao: FileDao
|
private lateinit var fileDao: FileDao
|
||||||
private lateinit var shareRepository: ShareRepository
|
private lateinit var shareRepository: ShareRepository
|
||||||
private lateinit var apiService: FakeApiService
|
private lateinit var apiService: FakeApiService
|
||||||
|
private lateinit var activeUserStore: ActiveUserStore
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
fun setUp() {
|
fun setUp() {
|
||||||
@@ -76,9 +79,9 @@ class ShareRepositoryTest {
|
|||||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
apiService = FakeApiService()
|
apiService = FakeApiService()
|
||||||
val apiClient = ApiClient(apiService, moshi)
|
val apiClient = ApiClient(apiService, moshi)
|
||||||
val deviceIdentity = DeviceIdentity(db.userPreferenceDao(), GenerateId())
|
activeUserStore = ActiveUserStore(db.userPreferenceDao())
|
||||||
|
|
||||||
shareRepository = ShareRepository(apiClient, db, deviceIdentity)
|
shareRepository = ShareRepository(apiClient, db, activeUserStore)
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
@@ -154,6 +157,7 @@ class ShareRepositoryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun absence_du_snapshot_marque_la_ressource_partagee_disparue() = runTest {
|
fun absence_du_snapshot_marque_la_ressource_partagee_disparue() = runTest {
|
||||||
|
activeUserStore.set(CURRENT_USER)
|
||||||
folderDao.upsert(
|
folderDao.upsert(
|
||||||
folder(FOLDER_ID, uri = null, ownerId = OTHER_USER),
|
folder(FOLDER_ID, uri = null, ownerId = OTHER_USER),
|
||||||
)
|
)
|
||||||
@@ -166,6 +170,53 @@ class ShareRepositoryTest {
|
|||||||
assertNull(folder.uri)
|
assertNull(folder.uri)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fichier_d_autrui_absent_du_snapshot_marque_disparu() = runTest {
|
||||||
|
activeUserStore.set(CURRENT_USER)
|
||||||
|
fileDao.upsert(
|
||||||
|
sharedFile(FILE_ID, ownerId = OTHER_USER),
|
||||||
|
)
|
||||||
|
apiService.permissions = emptyList()
|
||||||
|
|
||||||
|
shareRepository.syncSnapshot()
|
||||||
|
|
||||||
|
assertEquals(0, fileDao.getByResourceId(FILE_ID)!!.exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ligne_cloud_only_possedee_jamais_marquee_disparue() = runTest {
|
||||||
|
// M23 : le snapshot exclut les ressources possédées → une ligne
|
||||||
|
// cloud-only propre (ownerId = user actif) ne doit jamais être
|
||||||
|
// markMissing sur snapshot vide.
|
||||||
|
activeUserStore.set(CURRENT_USER)
|
||||||
|
folderDao.upsert(
|
||||||
|
folder(FOLDER_ID, uri = null, ownerId = CURRENT_USER),
|
||||||
|
)
|
||||||
|
fileDao.upsert(
|
||||||
|
sharedFile(FILE_ID, ownerId = CURRENT_USER),
|
||||||
|
)
|
||||||
|
apiService.permissions = emptyList()
|
||||||
|
|
||||||
|
shareRepository.syncSnapshot()
|
||||||
|
|
||||||
|
assertEquals(1, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||||
|
assertEquals(1, fileDao.getByResourceId(FILE_ID)!!.exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sans_compte_actif_aucune_ligne_masquee() = runTest {
|
||||||
|
// Pas de user actif (mode local) : impossible d'attribuer les lignes
|
||||||
|
// cloud-only → convergence désactivée, rien n'est marqué disparu.
|
||||||
|
folderDao.upsert(
|
||||||
|
folder(FOLDER_ID, uri = null, ownerId = OTHER_USER),
|
||||||
|
)
|
||||||
|
apiService.permissions = emptyList()
|
||||||
|
|
||||||
|
shareRepository.syncSnapshot()
|
||||||
|
|
||||||
|
assertEquals(1, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun ligne_cloud_only_propre_non_touchee_par_convergence() = runTest {
|
fun ligne_cloud_only_propre_non_touchee_par_convergence() = runTest {
|
||||||
// Une ligne cloud-only dont `ownerId` est NULL (pas encore typée) ne
|
// Une ligne cloud-only dont `ownerId` est NULL (pas encore typée) ne
|
||||||
@@ -210,8 +261,23 @@ class ShareRepositoryTest {
|
|||||||
updatedAt = NOW,
|
updatedAt = NOW,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private fun sharedFile(id: String, ownerId: String?) = FileEntity(
|
||||||
|
resourceId = id.padEnd(32, '0'),
|
||||||
|
uri = null,
|
||||||
|
name = id,
|
||||||
|
folderResourceId = FOLDER_ID,
|
||||||
|
size = 1,
|
||||||
|
exists = 1,
|
||||||
|
ownerId = ownerId,
|
||||||
|
syncStatus = FileStatus.CLOUD,
|
||||||
|
processed = true,
|
||||||
|
addedAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
)
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val NOW = 1_700_000_000_000L
|
const val NOW = 1_700_000_000_000L
|
||||||
|
const val CURRENT_USER = "00000000000000000000000000000001"
|
||||||
const val OTHER_USER = "11111111111111111111111111111111"
|
const val OTHER_USER = "11111111111111111111111111111111"
|
||||||
const val OWNER_ID = "22222222222222222222222222222222"
|
const val OWNER_ID = "22222222222222222222222222222222"
|
||||||
const val FOLDER_ID = "f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0"
|
const val FOLDER_ID = "f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0"
|
||||||
@@ -273,4 +339,26 @@ private class FakeApiService : ApiService {
|
|||||||
override suspend fun getFileOcr(
|
override suspend fun getFileOcr(
|
||||||
fileId: String,
|
fileId: String,
|
||||||
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope(data = FileOcrDto(text = "")))
|
): Response<ApiEnvelope<FileOcrDto>> = Response.success(ApiEnvelope(data = FileOcrDto(text = "")))
|
||||||
|
|
||||||
|
override suspend fun getFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun deleteFile(
|
||||||
|
fileId: String,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = Response.success(ApiEnvelope())
|
||||||
|
|
||||||
|
override suspend fun getShareLink(
|
||||||
|
token: String,
|
||||||
|
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.kazier.mobile.domain
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.awaitAll
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
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
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat DeviceIdentity (M10) : `getOrCreate()` est atomique et ne renvoie
|
||||||
|
* jamais d'ID fantôme (non persisté).
|
||||||
|
* - appels concurrents → un seul ID persisté, tous les appelants le reçoivent ;
|
||||||
|
* - la valeur relue en DB est l'ID renvoyé ;
|
||||||
|
* - l'ID est un 32-hex valide.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class DeviceIdentityTest {
|
||||||
|
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var deviceIdentity: DeviceIdentity
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
deviceIdentity = DeviceIdentity(db.userPreferenceDao(), GenerateId())
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun appels_concurrents_un_seul_id_persiste_jamais_de_fantome() = runTest {
|
||||||
|
val ids = (1..50).map {
|
||||||
|
async { deviceIdentity.getOrCreate() }
|
||||||
|
}.awaitAll()
|
||||||
|
|
||||||
|
val distinct = ids.toSet()
|
||||||
|
assertEquals("un seul ID pour 50 appels concurrents", 1, distinct.size)
|
||||||
|
|
||||||
|
val persisted = db.userPreferenceDao().getValue(PrefKeys.DEVICE_USER_ID)
|
||||||
|
assertEquals("l'ID renvoyé est celui persisté (pas de fantôme)", ids.first(), persisted)
|
||||||
|
assertTrue("32-hex valide", Regex("^[0-9a-f]{32}$").matches(ids.first()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun second_appel_relit_sans_regenerer() = runTest {
|
||||||
|
val first = deviceIdentity.getOrCreate()
|
||||||
|
val second = deviceIdentity.getOrCreate()
|
||||||
|
assertEquals(first, second)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.kazier.mobile.domain
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat GenerateId (C1) : tout ID généré est un 32-hex minuscule
|
||||||
|
* (`^[0-9a-f]{32}$`, CHECK-enforced côté serveur, cf. docs/api-v1.md §2).
|
||||||
|
*
|
||||||
|
* Non-régression de la sign-extension `Byte` → `%02x` : tout octet >= 0x80
|
||||||
|
* produisait `ffffffxx` (8 chars) au lieu de 2. Sur 10k IDs, des octets
|
||||||
|
* négatifs sont statistiquement garantis.
|
||||||
|
*/
|
||||||
|
class GenerateIdTest {
|
||||||
|
|
||||||
|
private val generateId = GenerateId()
|
||||||
|
private val hex32 = Regex("^[0-9a-f]{32}$")
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun dix_mille_ids_sont_tous_32_hex() {
|
||||||
|
repeat(10_000) { i ->
|
||||||
|
val id = generateId.newResourceId()
|
||||||
|
assertEquals("ID #$i : longueur 32", 32, id.length)
|
||||||
|
assertTrue("ID #$i : 32-hex minuscule ($id)", hex32.matches(id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ids_successifs_distincts() {
|
||||||
|
val ids = List(1_000) { generateId.newResourceId() }.toSet()
|
||||||
|
assertEquals(1_000, ids.size)
|
||||||
|
}
|
||||||
|
}
|
||||||
+452
@@ -0,0 +1,452 @@
|
|||||||
|
package com.kazier.mobile.features.sync
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import androidx.work.Data
|
||||||
|
import androidx.work.ForegroundUpdater
|
||||||
|
import androidx.work.ListenableWorker
|
||||||
|
import androidx.work.ProgressUpdater
|
||||||
|
import androidx.work.WorkerFactory
|
||||||
|
import androidx.work.WorkerParameters
|
||||||
|
import androidx.work.impl.utils.taskexecutor.SerialExecutor
|
||||||
|
import androidx.work.impl.utils.taskexecutor.TaskExecutor
|
||||||
|
import com.squareup.moshi.JsonAdapter
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.Types
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import com.kazier.mobile.auth.TokenProvider
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.dao.FileDao
|
||||||
|
import com.kazier.mobile.data.local.dao.FolderDao
|
||||||
|
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||||
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
|
import com.kazier.mobile.data.remote.ApiException
|
||||||
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
|
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||||
|
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncFailedDto
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||||
|
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||||
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import java.util.UUID
|
||||||
|
import java.util.concurrent.Executor
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Assert.fail
|
||||||
|
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
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Protocole outbox (lot B) : le drain `POST /sync/ops` doit suivre le contrat
|
||||||
|
* `docs/api-v1.md §6.1` (séquentiel, stop à la 1re erreur, reprise à l'index).
|
||||||
|
*
|
||||||
|
* Couverts : C2 (retry sans dead-letter sur batch-level/transitoire), C6
|
||||||
|
* (stop au 1er échec + cascade enfants via `payload.parentResourceId`), C7
|
||||||
|
* (gardes anti-boucle/crash), M22 (CancellationException remonte), M24
|
||||||
|
* (`expiresAt` entier exact).
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class OutboxSyncWorkerTest {
|
||||||
|
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var opsDao: PendingOperationDao
|
||||||
|
private lateinit var fileDao: FileDao
|
||||||
|
private lateinit var folderDao: FolderDao
|
||||||
|
private lateinit var moshi: Moshi
|
||||||
|
private lateinit var payloadAdapter: JsonAdapter<Map<String, Any?>>
|
||||||
|
private lateinit var fake: FakeApiService
|
||||||
|
private lateinit var apiClient: ApiClient
|
||||||
|
private lateinit var tokenProvider: TokenProvider
|
||||||
|
private lateinit var worker: OutboxSyncWorker
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
opsDao = db.pendingOperationDao()
|
||||||
|
fileDao = db.fileDao()
|
||||||
|
folderDao = db.folderDao()
|
||||||
|
|
||||||
|
moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
payloadAdapter = moshi.adapter(
|
||||||
|
Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java),
|
||||||
|
)
|
||||||
|
fake = FakeApiService()
|
||||||
|
apiClient = ApiClient(fake, moshi)
|
||||||
|
tokenProvider = TokenProvider().apply { current = "test-token" }
|
||||||
|
worker = OutboxSyncWorker(
|
||||||
|
context, workerParams(), apiClient, opsDao, fileDao, folderDao,
|
||||||
|
tokenProvider, moshi,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- C2 : batch-level / transitoire → retry, jamais de dead-letter ------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun reponse_200_sans_data_retry_sans_deadletter() = runTest {
|
||||||
|
insertOp(opId(1))
|
||||||
|
fake.syncOpsHandler = { Response.success(ApiEnvelope<SyncOpsResult>(data = null)) }
|
||||||
|
|
||||||
|
val result = worker.doWork()
|
||||||
|
|
||||||
|
assertTrue("200 sans {data} → retry, pas failed", result is ListenableWorker.Result.Retry)
|
||||||
|
assertEquals(1, opsDao.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun erreur_429_retry_sans_deadletter() = runTest {
|
||||||
|
assertRetryOnHttpError(429)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun erreur_408_retry_sans_deadletter() = runTest {
|
||||||
|
assertRetryOnHttpError(408)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun assertRetryOnHttpError(code: Int) {
|
||||||
|
insertOp(opId(1))
|
||||||
|
insertOp(opId(2))
|
||||||
|
fake.syncOpsHandler = { httpError(code) }
|
||||||
|
|
||||||
|
val result = worker.doWork()
|
||||||
|
|
||||||
|
assertTrue("HTTP $code → retry, pas failed", result is ListenableWorker.Result.Retry)
|
||||||
|
assertEquals(2, opsDao.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- C6 : stop au 1er échec + cascade ------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun echec_op2_sur_20_seule_op2_failed_et_stop() = runTest {
|
||||||
|
val ids = (1..20).map { opId(it) }
|
||||||
|
ids.forEachIndexed { i, id ->
|
||||||
|
insertOp(operationId = id, resourceId = resId(i + 1))
|
||||||
|
}
|
||||||
|
var calls = 0
|
||||||
|
fake.syncOpsHandler = { req ->
|
||||||
|
calls++
|
||||||
|
assertEquals(20, req.operations.size)
|
||||||
|
opsResult(applied = 1, failed = SyncFailedDto(ids[1], "NAME_CONFLICT", "nom pris"))
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = worker.doWork()
|
||||||
|
|
||||||
|
assertTrue(result is ListenableWorker.Result.Success)
|
||||||
|
assertEquals("stop au 1er échec : un seul batch envoyé", 1, calls)
|
||||||
|
val byOp = opsDao.observeRecent(100).first().associateBy { it.operationId }
|
||||||
|
assertEquals(PendingOpStatus.SYNCED, byOp[ids[0]]!!.status)
|
||||||
|
assertEquals(PendingOpStatus.FAILED, byOp[ids[1]]!!.status)
|
||||||
|
ids.drop(2).forEach { id ->
|
||||||
|
assertEquals("op $id reste pending (run stoppé)", PendingOpStatus.PENDING, byOp[id]!!.status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun echec_create_parent_cascade_enfant_via_parentResourceId() = runTest {
|
||||||
|
val parent = "p".repeat(32)
|
||||||
|
val child = "c".repeat(32)
|
||||||
|
val sibling = "s".repeat(32)
|
||||||
|
insertOp(
|
||||||
|
operationId = opId(1), resourceId = parent,
|
||||||
|
payload = """{"name":"parent"}""",
|
||||||
|
)
|
||||||
|
insertOp(
|
||||||
|
operationId = opId(2), resourceId = child,
|
||||||
|
payload = """{"name":"enfant","parentResourceId":"$parent"}""",
|
||||||
|
)
|
||||||
|
insertOp(
|
||||||
|
operationId = opId(3), resourceId = sibling,
|
||||||
|
payload = """{"name":"voisin"}""",
|
||||||
|
)
|
||||||
|
var calls = 0
|
||||||
|
fake.syncOpsHandler = { _ ->
|
||||||
|
calls++
|
||||||
|
opsResult(applied = 0, failed = SyncFailedDto(opId(1), "NOT_FOUND", "parent inconnu"))
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = worker.doWork()
|
||||||
|
|
||||||
|
assertTrue(result is ListenableWorker.Result.Success)
|
||||||
|
assertEquals(1, calls)
|
||||||
|
val byOp = opsDao.observeRecent(100).first().associateBy { it.operationId }
|
||||||
|
assertEquals(PendingOpStatus.FAILED, byOp[opId(1)]!!.status)
|
||||||
|
assertEquals("l'enfant (autre resource_id) est cascadé", PendingOpStatus.FAILED, byOp[opId(2)]!!.status)
|
||||||
|
assertEquals("le voisin est intact", PendingOpStatus.PENDING, byOp[opId(3)]!!.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- C7 : gardes ----------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun failed_inconnu_pas_de_boucle() = runTest {
|
||||||
|
insertOp(opId(1))
|
||||||
|
insertOp(opId(2))
|
||||||
|
var calls = 0
|
||||||
|
fake.syncOpsHandler = { _ ->
|
||||||
|
calls++
|
||||||
|
opsResult(applied = 0, failed = SyncFailedDto("f".repeat(32), "X", "inconnu"))
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = worker.doWork()
|
||||||
|
|
||||||
|
assertTrue("failed inconnu → sortie, pas de boucle", result is ListenableWorker.Result.Success)
|
||||||
|
assertEquals(1, calls)
|
||||||
|
assertEquals(2, opsDao.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun applied_superieur_taille_pas_de_crash() = runTest {
|
||||||
|
insertOp(opId(1))
|
||||||
|
insertOp(opId(2))
|
||||||
|
insertOp(opId(3))
|
||||||
|
var calls = 0
|
||||||
|
fake.syncOpsHandler = { _ ->
|
||||||
|
calls++
|
||||||
|
opsResult(applied = 999, failed = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = worker.doWork()
|
||||||
|
|
||||||
|
assertTrue(result is ListenableWorker.Result.Success)
|
||||||
|
assertEquals(1, calls)
|
||||||
|
assertEquals("tout le batch est acquitté (clamp), sans crash", 0, opsDao.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun applied_zero_sans_failed_sortie() = runTest {
|
||||||
|
insertOp(opId(1))
|
||||||
|
insertOp(opId(2))
|
||||||
|
var calls = 0
|
||||||
|
fake.syncOpsHandler = { _ ->
|
||||||
|
calls++
|
||||||
|
opsResult(applied = 0, failed = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = worker.doWork()
|
||||||
|
|
||||||
|
assertTrue("applied=0 sans failed → sortie, pas de busy-loop", result is ListenableWorker.Result.Success)
|
||||||
|
assertEquals(1, calls)
|
||||||
|
assertEquals(2, opsDao.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- M22 : annulation -----------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun cancellation_exception_remonte() = runTest {
|
||||||
|
insertOp(opId(1))
|
||||||
|
fake.syncOpsHandler = { throw CancellationException("annulé") }
|
||||||
|
|
||||||
|
try {
|
||||||
|
worker.doWork()
|
||||||
|
fail("CancellationException attendue, pas de conversion")
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
// Attendu : remonte telle quelle (M22).
|
||||||
|
} catch (e: ApiException) {
|
||||||
|
fail("l'annulation ne doit pas devenir ApiException (${e.code})")
|
||||||
|
}
|
||||||
|
assertEquals(1, opsDao.countPending())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- M24 : expiresAt entier exact -----------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun share_expiresAt_entier_exact() = runTest {
|
||||||
|
val outbox = OutboxRepository(
|
||||||
|
opsDao, GenerateId(),
|
||||||
|
DeviceIdentity(db.userPreferenceDao(), GenerateId()), moshi,
|
||||||
|
)
|
||||||
|
val resourceId = "a".repeat(32)
|
||||||
|
val opId = outbox.enqueueShare(
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = "folder",
|
||||||
|
granteeUserId = "b".repeat(32),
|
||||||
|
access = "viewer",
|
||||||
|
expiresAt = EXPIRES_AT,
|
||||||
|
)
|
||||||
|
|
||||||
|
val stored = opsDao.selectPending(10).first { it.operationId == opId }
|
||||||
|
assertTrue(
|
||||||
|
"payload stocké entier exact, pas de notation E",
|
||||||
|
stored.payload.contains("\"expiresAt\":$EXPIRES_AT"),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Round-trip worker : décodage Moshi (Double) → normalisation (Long).
|
||||||
|
val decoded = payloadAdapter.fromJson(stored.payload)!!
|
||||||
|
val normalized = normalizePayloadNumbers(decoded)
|
||||||
|
assertEquals(EXPIRES_AT, normalized["expiresAt"])
|
||||||
|
assertTrue(
|
||||||
|
"re-sérialisation entière exacte",
|
||||||
|
payloadAdapter.toJson(normalized).contains("\"expiresAt\":$EXPIRES_AT"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- fixtures --------------------------------------------------------------
|
||||||
|
|
||||||
|
private suspend fun insertOp(
|
||||||
|
operationId: String,
|
||||||
|
resourceId: String = "r".repeat(31) + operationId.takeLast(1),
|
||||||
|
resourceType: String = "folder",
|
||||||
|
operation: String = PendingOperationType.CREATE_RESOURCE,
|
||||||
|
payload: String = "{}",
|
||||||
|
status: String = PendingOpStatus.PENDING,
|
||||||
|
) {
|
||||||
|
opsDao.insert(
|
||||||
|
PendingOperationEntity(
|
||||||
|
operationId = operationId,
|
||||||
|
resourceId = resourceId,
|
||||||
|
resourceType = resourceType,
|
||||||
|
operation = operation,
|
||||||
|
payload = payload,
|
||||||
|
status = status,
|
||||||
|
createdAt = NOW,
|
||||||
|
updatedAt = NOW,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun opId(i: Int): String = "%032x".format(i)
|
||||||
|
|
||||||
|
private fun resId(i: Int): String = "abcd" + "%028x".format(i)
|
||||||
|
|
||||||
|
private fun opsResult(applied: Int, failed: SyncFailedDto?): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
Response.success(ApiEnvelope(data = SyncOpsResult(applied, failed)))
|
||||||
|
|
||||||
|
private fun httpError(code: Int): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
Response.error(code, "{}".toResponseBody("application/json".toMediaType()))
|
||||||
|
|
||||||
|
private fun workerParams(): WorkerParameters {
|
||||||
|
val direct = Executor { command -> command.run() }
|
||||||
|
val taskExecutor = object : TaskExecutor {
|
||||||
|
override fun getMainThreadExecutor(): Executor = direct
|
||||||
|
override fun getSerialTaskExecutor(): SerialExecutor =
|
||||||
|
object : SerialExecutor {
|
||||||
|
override fun hasPendingTasks(): Boolean = false
|
||||||
|
override fun execute(command: Runnable) {
|
||||||
|
command.run()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return WorkerParameters(
|
||||||
|
UUID.randomUUID(),
|
||||||
|
Data.EMPTY,
|
||||||
|
emptyList(),
|
||||||
|
WorkerParameters.RuntimeExtras(),
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
direct,
|
||||||
|
taskExecutor,
|
||||||
|
WorkerFactory.getDefaultWorkerFactory(),
|
||||||
|
ProgressUpdater { _, _, _ -> throw UnsupportedOperationException() },
|
||||||
|
ForegroundUpdater { _, _, _ -> throw UnsupportedOperationException() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val NOW = 1_700_000_000_000L
|
||||||
|
const val EXPIRES_AT = 1_700_000_000_000L
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fake piloté : seul `syncOps` est scripté, le reste est hors scope. */
|
||||||
|
private class FakeApiService : ApiService {
|
||||||
|
lateinit var syncOpsHandler: suspend (SyncOpsRequest) -> Response<ApiEnvelope<SyncOpsResult>>
|
||||||
|
|
||||||
|
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||||
|
syncOpsHandler(body)
|
||||||
|
|
||||||
|
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||||
|
throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun listFiles(
|
||||||
|
folderId: String?,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun registerDevice(
|
||||||
|
body: DeviceRegistrationDto,
|
||||||
|
): Response<ApiEnvelope<DeviceRegistrationDto>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun login(
|
||||||
|
body: LoginRequestDto,
|
||||||
|
): Response<ApiEnvelope<LoginResponseDto>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun resolveUser(
|
||||||
|
username: String,
|
||||||
|
): Response<ApiEnvelope<ResolvedUserDto>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun syncPermissions(
|
||||||
|
after: Long?,
|
||||||
|
): Response<ApiEnvelope<List<ResourcePermissionDto>>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun uploadFile(
|
||||||
|
file: MultipartBody.Part,
|
||||||
|
resourceId: RequestBody?,
|
||||||
|
folderId: RequestBody?,
|
||||||
|
): Response<ApiEnvelope<FileDto>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||||
|
throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||||
|
throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||||
|
throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||||
|
throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun searchFiles(
|
||||||
|
query: String,
|
||||||
|
page: Int?,
|
||||||
|
pageSize: Int?,
|
||||||
|
): Response<ApiEnvelope<List<FileDto>>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun changePassword(
|
||||||
|
body: ChangePasswordDto,
|
||||||
|
): Response<ApiEnvelope<IdResultDto>> = throw UnsupportedOperationException()
|
||||||
|
|
||||||
|
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||||
|
throw UnsupportedOperationException()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package com.kazier.mobile.features.sync
|
||||||
|
|
||||||
|
import android.content.ContentProvider
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Context
|
||||||
|
import android.database.Cursor
|
||||||
|
import android.database.MatrixCursor
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.DocumentsContract
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
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 org.robolectric.shadows.ShadowContentResolver
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garde-fous du walk SAF (lot D) :
|
||||||
|
* - permission révoquée → résultat propre (racine vide), jamais de crash ;
|
||||||
|
* - curseur dégénéré (colonne DOCUMENT_ID absente, valeurs nulles) → dossier
|
||||||
|
* vu vide, pas de crash ;
|
||||||
|
* - fichiers 0-octet → importés comme les autres (review + push au « garder »).
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class SafScannerTest {
|
||||||
|
|
||||||
|
private lateinit var appContext: Context
|
||||||
|
private val treeUri: Uri = Uri.parse("content://com.kazier.test/tree/rootDoc")
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
appContext = ApplicationProvider.getApplicationContext()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun permission_perdue_retourne_une_racine_vide_sans_crash() = runTest {
|
||||||
|
val scanner = scannerWith { throw SecurityException("persisted permission revoked") }
|
||||||
|
|
||||||
|
val nodes = scanner.scanTree(treeUri)
|
||||||
|
|
||||||
|
assertEquals("la racine reste listée (vide), sans exception", 1, nodes.size)
|
||||||
|
assertTrue(nodes[0].files.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun curseur_degenere_sans_colonne_document_id_ne_crash_pas() = runTest {
|
||||||
|
val scanner = scannerWith { uri ->
|
||||||
|
if (isChildrenQuery(uri)) {
|
||||||
|
MatrixCursor(arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME)).apply {
|
||||||
|
addRow(arrayOf<Any?>(null))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
nameCursor("Root")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val nodes = scanner.scanTree(treeUri)
|
||||||
|
|
||||||
|
assertEquals(1, nodes.size)
|
||||||
|
assertTrue("dossier dégénéré vu vide", nodes[0].files.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fichier_zero_octet_importe() = runTest {
|
||||||
|
val scanner = scannerWith { uri ->
|
||||||
|
if (isChildrenQuery(uri) && uri.toString().contains("rootDoc")) {
|
||||||
|
MatrixCursor(
|
||||||
|
arrayOf(
|
||||||
|
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||||
|
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||||
|
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
||||||
|
DocumentsContract.Document.COLUMN_SIZE,
|
||||||
|
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
|
||||||
|
),
|
||||||
|
).apply {
|
||||||
|
addRow(arrayOf<Any?>("rootDoc:empty.txt", "empty.txt", "text/plain", 0L, 123L))
|
||||||
|
addRow(
|
||||||
|
arrayOf<Any?>(
|
||||||
|
"rootDoc:sub",
|
||||||
|
"sub",
|
||||||
|
DocumentsContract.Document.MIME_TYPE_DIR,
|
||||||
|
0L,
|
||||||
|
null,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else if (isChildrenQuery(uri)) {
|
||||||
|
MatrixCursor(
|
||||||
|
arrayOf(
|
||||||
|
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||||
|
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||||
|
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
||||||
|
DocumentsContract.Document.COLUMN_SIZE,
|
||||||
|
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
nameCursor("Root")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val nodes = scanner.scanTree(treeUri)
|
||||||
|
|
||||||
|
assertEquals("racine + sous-dossier", 2, nodes.size)
|
||||||
|
val root = nodes.first { it.parentUri == null }
|
||||||
|
assertEquals(1, root.files.size)
|
||||||
|
assertEquals("empty.txt", root.files[0].name)
|
||||||
|
assertEquals("les 0-octet sont importés, pas exclus", 0L, root.files[0].size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- fakes ---------------------------------------------------------------
|
||||||
|
|
||||||
|
private fun scannerWith(handler: (Uri) -> Cursor?): SafScanner {
|
||||||
|
val provider = object : ContentProvider() {
|
||||||
|
override fun onCreate(): Boolean = true
|
||||||
|
override fun query(
|
||||||
|
uri: Uri,
|
||||||
|
projection: Array<out String>?,
|
||||||
|
selection: String?,
|
||||||
|
selectionArgs: Array<out String>?,
|
||||||
|
sortOrder: String?,
|
||||||
|
): Cursor? = handler(uri)
|
||||||
|
override fun getType(uri: Uri): String? = null
|
||||||
|
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||||
|
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||||
|
override fun update(
|
||||||
|
uri: Uri,
|
||||||
|
values: ContentValues?,
|
||||||
|
selection: String?,
|
||||||
|
selectionArgs: Array<out String>?,
|
||||||
|
): Int = 0
|
||||||
|
}
|
||||||
|
ShadowContentResolver.registerProviderInternal("com.kazier.test", provider)
|
||||||
|
return SafScanner(appContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isChildrenQuery(uri: Uri): Boolean =
|
||||||
|
uri.pathSegments.contains("children")
|
||||||
|
|
||||||
|
private fun nameCursor(name: String): Cursor =
|
||||||
|
MatrixCursor(arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME)).apply {
|
||||||
|
addRow(arrayOf<Any?>(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
+131
-1
@@ -1,6 +1,12 @@
|
|||||||
package com.kazier.mobile.features.thumbnails
|
package com.kazier.mobile.features.thumbnails
|
||||||
|
|
||||||
|
import android.content.ContentProvider
|
||||||
|
import android.content.ContentValues
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.database.Cursor
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.ParcelFileDescriptor
|
||||||
import androidx.test.core.app.ApplicationProvider
|
import androidx.test.core.app.ApplicationProvider
|
||||||
import com.kazier.mobile.data.local.entity.FileEntity
|
import com.kazier.mobile.data.local.entity.FileEntity
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
@@ -13,7 +19,9 @@ import org.junit.Test
|
|||||||
import org.junit.runner.RunWith
|
import org.junit.runner.RunWith
|
||||||
import org.robolectric.RobolectricTestRunner
|
import org.robolectric.RobolectricTestRunner
|
||||||
import org.robolectric.annotation.Config
|
import org.robolectric.annotation.Config
|
||||||
|
import org.robolectric.shadows.ShadowContentResolver
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.io.FileNotFoundException
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Contrat du ThumbnailStore — les coûts ressources sont bornés par design :
|
* Contrat du ThumbnailStore — les coûts ressources sont bornés par design :
|
||||||
@@ -33,6 +41,10 @@ class ThumbnailStoreTest {
|
|||||||
fun setUp() {
|
fun setUp() {
|
||||||
context = ApplicationProvider.getApplicationContext()
|
context = ApplicationProvider.getApplicationContext()
|
||||||
store = ThumbnailStore(context)
|
store = ThumbnailStore(context)
|
||||||
|
// Toute URI `content://root/…` lève à l'ouverture (provider absent) :
|
||||||
|
// la génération échoue proprement au lieu de produire un bitmap
|
||||||
|
// fantôme des shadows Robolectric.
|
||||||
|
ShadowContentResolver.registerProviderInternal("root", ThrowingProvider())
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -127,20 +139,138 @@ class ThumbnailStoreTest {
|
|||||||
assertFalse(target.exists())
|
assertFalse(target.exists())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- versions mtime + taille ------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nom_versionne_encode_mtime_et_taille() {
|
||||||
|
val id = "7".repeat(32)
|
||||||
|
val versioned = store.thumbnailFile(id, 10_000L, 1234L)
|
||||||
|
assertEquals("${id}_10000_1234.webp", versioned.name)
|
||||||
|
assertEquals(store.thumbnailFile(id).parent, versioned.parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nom_legacy_sans_mtime_ni_taille() {
|
||||||
|
val id = "8".repeat(32)
|
||||||
|
assertEquals(store.thumbnailFile(id), store.thumbnailFile(id, null, 1L))
|
||||||
|
assertEquals(store.thumbnailFile(id), store.thumbnailFile(id, 10_000L, null))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ensure_version_en_place_retournee_sans_generation() {
|
||||||
|
val resourceId = "9".repeat(32)
|
||||||
|
val file = fileWith(
|
||||||
|
resourceId = resourceId,
|
||||||
|
category = "IMAGE",
|
||||||
|
uri = "content://root/doc",
|
||||||
|
lastModified = 10_000L,
|
||||||
|
size = 1234L,
|
||||||
|
)
|
||||||
|
val versioned = store.thumbnailFile(resourceId, 10_000L, 1234L)
|
||||||
|
versioned.parentFile?.mkdirs()
|
||||||
|
versioned.writeBytes(ByteArray(4))
|
||||||
|
versioned.setLastModified(20_000L)
|
||||||
|
|
||||||
|
runTest {
|
||||||
|
val thumb = store.ensure(file)
|
||||||
|
assertEquals(versioned.absolutePath, thumb?.absolutePath)
|
||||||
|
assertEquals(0, store.lockCount())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun version_perimee_regeneration_echoue_sans_supprimer_sans_fuite_mutex() {
|
||||||
|
val resourceId = "a".repeat(32)
|
||||||
|
val stale = store.thumbnailFile(resourceId, 5_000L, 111L)
|
||||||
|
stale.parentFile?.mkdirs()
|
||||||
|
stale.writeBytes(ByteArray(4))
|
||||||
|
stale.setLastModified(20_000L)
|
||||||
|
val file = fileWith(
|
||||||
|
resourceId = resourceId,
|
||||||
|
category = "IMAGE",
|
||||||
|
// URI non résolvable : la génération échoue.
|
||||||
|
uri = "content://root/absent",
|
||||||
|
lastModified = 10_000L,
|
||||||
|
size = 222L,
|
||||||
|
)
|
||||||
|
|
||||||
|
runTest {
|
||||||
|
assertNull(store.ensure(file))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Échec conservateur : l'ancienne version reste, aucun mutex ne fuit.
|
||||||
|
assertTrue(stale.isFile)
|
||||||
|
assertEquals(0, store.lockCount())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fichier_vide_jamais_a_jour() {
|
||||||
|
val target = store.thumbnailFile("b".repeat(32))
|
||||||
|
target.parentFile?.mkdirs()
|
||||||
|
target.writeBytes(ByteArray(0))
|
||||||
|
target.setLastModified(20_000L)
|
||||||
|
|
||||||
|
assertFalse(store.isUpToDate(target, 10_000L))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun delete_purge_toutes_les_versions_et_les_tmp() {
|
||||||
|
val resourceId = "c".repeat(32)
|
||||||
|
val legacy = store.thumbnailFile(resourceId)
|
||||||
|
val v1 = store.thumbnailFile(resourceId, 5_000L, 111L)
|
||||||
|
val tmp = java.io.File(legacy.parentFile, "${v1.name}.tmp")
|
||||||
|
listOf(legacy, v1, tmp).forEach {
|
||||||
|
it.parentFile?.mkdirs()
|
||||||
|
it.writeBytes(ByteArray(4))
|
||||||
|
}
|
||||||
|
|
||||||
|
store.delete(resourceId)
|
||||||
|
|
||||||
|
assertFalse(legacy.exists())
|
||||||
|
assertFalse(v1.exists())
|
||||||
|
assertFalse(tmp.exists())
|
||||||
|
}
|
||||||
|
|
||||||
private fun fileWith(
|
private fun fileWith(
|
||||||
resourceId: String,
|
resourceId: String,
|
||||||
category: String?,
|
category: String?,
|
||||||
uri: String?,
|
uri: String?,
|
||||||
lastModified: Long? = null,
|
lastModified: Long? = null,
|
||||||
|
size: Long = 1L,
|
||||||
) = FileEntity(
|
) = FileEntity(
|
||||||
resourceId = resourceId,
|
resourceId = resourceId,
|
||||||
name = "doc",
|
name = "doc",
|
||||||
folderResourceId = "f".repeat(32),
|
folderResourceId = "f".repeat(32),
|
||||||
size = 1L,
|
size = size,
|
||||||
uri = uri,
|
uri = uri,
|
||||||
category = category,
|
category = category,
|
||||||
lastModified = lastModified,
|
lastModified = lastModified,
|
||||||
addedAt = 0L,
|
addedAt = 0L,
|
||||||
updatedAt = 0L,
|
updatedAt = 0L,
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Provider qui lève à l'ouverture (fichier SAF absent / permission révoquée). */
|
||||||
|
private class ThrowingProvider : ContentProvider() {
|
||||||
|
override fun onCreate(): Boolean = true
|
||||||
|
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? =
|
||||||
|
throw FileNotFoundException("no such document: $uri")
|
||||||
|
override fun query(
|
||||||
|
uri: Uri,
|
||||||
|
projection: Array<out String>?,
|
||||||
|
selection: String?,
|
||||||
|
selectionArgs: Array<out String>?,
|
||||||
|
sortOrder: String?,
|
||||||
|
): Cursor? = throw FileNotFoundException("no such document: $uri")
|
||||||
|
override fun call(authority: String, method: String, arg: String?, extras: Bundle?): Bundle? =
|
||||||
|
throw FileNotFoundException("no such document")
|
||||||
|
override fun getType(uri: Uri): String? = null
|
||||||
|
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||||
|
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||||
|
override fun update(
|
||||||
|
uri: Uri,
|
||||||
|
values: ContentValues?,
|
||||||
|
selection: String?,
|
||||||
|
selectionArgs: Array<out String>?,
|
||||||
|
): Int = 0
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.kazier.mobile.ui.document
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M35 — clamp du pager après suppression : le viewer ne reste jamais sur une
|
||||||
|
* page hors bornes (écran vide), il retombe sur une page valide.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class PagerClampTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun suppression_du_dernier_doc_retombe_sur_le_precedent() {
|
||||||
|
// 3 docs, page 2/2 supprimée → liste de 2, page mémorisée hors bornes.
|
||||||
|
assertEquals(1, resolveViewerPage(currentPage = 2, restoredPage = 2, itemCount = 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun suppression_du_premier_doc_clampe_la_page_courante() {
|
||||||
|
// Page 0 supprimée, pager resté en tête d'une liste raccourcie.
|
||||||
|
assertEquals(0, resolveViewerPage(currentPage = 0, restoredPage = -1, itemCount = 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun page_courante_haute_clampee_sans_memoire() {
|
||||||
|
assertEquals(2, resolveViewerPage(currentPage = 9, restoredPage = -1, itemCount = 3))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun page_courante_negative_clampee_a_zero() {
|
||||||
|
assertEquals(0, resolveViewerPage(currentPage = -4, restoredPage = -1, itemCount = 3))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun page_memorisee_valide_prime_sur_la_courante() {
|
||||||
|
// Rotation : pager tout neuf à 0, mémoire saveable restaurée à 2.
|
||||||
|
assertEquals(2, resolveViewerPage(currentPage = 0, restoredPage = 2, itemCount = 5))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun liste_vide_retourne_zero() {
|
||||||
|
assertEquals(0, resolveViewerPage(currentPage = 0, restoredPage = 0, itemCount = 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.kazier.mobile.ui.document
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M30 — survie à la rotation : l'état persisté (`jumpPending`, `savedPage`,
|
||||||
|
* tous deux primitifs donc `rememberSaveable` sans Saver custom) suffit à
|
||||||
|
* retrouver la page lue au lieu de retomber sur le document initial, et le
|
||||||
|
* vide transitoire du rechargement ne quitte jamais l'écran.
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class RotationStateTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rotation_revient_a_la_page_memorisee_pas_a_l_initiale() {
|
||||||
|
// Avant rotation : page 3 lue (jumpPending=false, savedPage=3).
|
||||||
|
// Après rotation : pager tout neuf (currentPage=0) + mémoire restaurée.
|
||||||
|
val target = resolveViewerPage(currentPage = 0, restoredPage = 3, itemCount = 5)
|
||||||
|
assertEquals(3, target)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rotation_avant_le_saut_initial_rejoue_le_saut() {
|
||||||
|
// jumpPending restauré à true → le saut vers le document demandé rejoue
|
||||||
|
// dès que la liste est chargée (index retrouvé dans la liste).
|
||||||
|
val jumpPending = true
|
||||||
|
val docs = listOf("a".repeat(32), "b".repeat(32), "c".repeat(32))
|
||||||
|
val index = docs.indexOfFirst { it == "b".repeat(32) }
|
||||||
|
assertTrue(jumpPending)
|
||||||
|
assertEquals(1, index)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rechargement_vide_apres_rotation_ne_quitte_pas() {
|
||||||
|
// hadDocuments retombe à false dans la composition toute neuve :
|
||||||
|
// le vide transitoire du reload ne déclenche pas onBack.
|
||||||
|
assertFalse(shouldExitViewer(jumpPending = false, hadDocuments = false, isEmpty = true))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun vide_pendant_le_saut_initial_ne_quitte_pas() {
|
||||||
|
assertFalse(shouldExitViewer(jumpPending = true, hadDocuments = false, isEmpty = true))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun liste_videe_apres_affichage_quitte() {
|
||||||
|
// Dernier document supprimé sous les yeux de l'utilisateur → retour.
|
||||||
|
assertTrue(shouldExitViewer(jumpPending = false, hadDocuments = true, isEmpty = true))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun liste_non_vide_ne_quitte_jamais() {
|
||||||
|
assertFalse(shouldExitViewer(jumpPending = false, hadDocuments = true, isEmpty = false))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.kazier.mobile.ui.navigation
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* m29 — la route pdfbuilder ne produit jamais `"pdfbuilder/"` (qui ne matche
|
||||||
|
* pas `"pdfbuilder/{ids}"`) ; la sélection vide passe par la sentinelle
|
||||||
|
* `"empty"`, re-parsée en liste vide (aller-retour).
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class NavGraphTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun selection_vide_ne_produit_pas_une_route_vide() {
|
||||||
|
val route = Routes.pdfBuilder(emptyList())
|
||||||
|
assertFalse("route vide interdite : $route", route == "pdfbuilder/")
|
||||||
|
assertTrue(route.startsWith("pdfbuilder/"))
|
||||||
|
assertEquals(emptyList<String>(), Routes.parseBuilderIds(route.substringAfter("pdfbuilder/")))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun selection_vide_aller_retour_sentinelle() {
|
||||||
|
assertEquals("pdfbuilder/${Routes.BUILDER_EMPTY}", Routes.pdfBuilder(emptyList()))
|
||||||
|
assertEquals(emptyList<String>(), Routes.parseBuilderIds(Routes.BUILDER_EMPTY))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ids_aller_retour() {
|
||||||
|
val ids = listOf("a".repeat(32), "b".repeat(32))
|
||||||
|
val route = Routes.pdfBuilder(ids)
|
||||||
|
assertEquals("pdfbuilder/${ids.joinToString(",")}", route)
|
||||||
|
assertEquals(ids, Routes.parseBuilderIds(route.substringAfter("pdfbuilder/")))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun blancs_filtres_avant_construction() {
|
||||||
|
val id = "a".repeat(32)
|
||||||
|
assertEquals("pdfbuilder/$id", Routes.pdfBuilder(listOf("", " ", id)))
|
||||||
|
assertEquals(emptyList<String>(), Routes.parseBuilderIds(" , "))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun parse_nul_et_vide() {
|
||||||
|
assertEquals(emptyList<String>(), Routes.parseBuilderIds(null))
|
||||||
|
assertEquals(emptyList<String>(), Routes.parseBuilderIds(""))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun routes_folder_et_document() {
|
||||||
|
assertEquals("folder/abc", Routes.folder("abc"))
|
||||||
|
assertEquals("document/abc", Routes.document("abc"))
|
||||||
|
}
|
||||||
|
}
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
package com.kazier.mobile.ui.pdfbuilder
|
||||||
|
|
||||||
|
import com.kazier.mobile.data.local.entity.FileStatus
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat d'import d'un PDF assemblé : déjà « traité » (l'utilisateur vient
|
||||||
|
* de le construire — jamais dans la file de review, comme l'export scan) et
|
||||||
|
* placement via la constante `FileStatus.LOCAL`.
|
||||||
|
*/
|
||||||
|
class PdfBuilderImportTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun import_marche_processed_et_local() {
|
||||||
|
val input = pdfSaveFileInput(
|
||||||
|
uri = "content://tree/generated.pdf",
|
||||||
|
name = "rapport.pdf",
|
||||||
|
bytes = 2048L,
|
||||||
|
now = 42L,
|
||||||
|
)
|
||||||
|
|
||||||
|
assertTrue("un PDF assemblé ne remonte jamais en review", input.processed)
|
||||||
|
assertEquals(FileStatus.LOCAL, input.syncStatus)
|
||||||
|
assertEquals("pdf", input.extension)
|
||||||
|
assertEquals("application/pdf", input.mimeType)
|
||||||
|
assertEquals("content://tree/generated.pdf", input.uri)
|
||||||
|
assertEquals("rapport.pdf", input.name)
|
||||||
|
assertEquals(2048L, input.size)
|
||||||
|
assertEquals(42L, input.lastModified)
|
||||||
|
assertTrue(input.exists)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package com.kazier.mobile.ui.review
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.kazier.mobile.R
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
|
import com.kazier.mobile.data.repository.SaveFileInput
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import com.kazier.mobile.features.saf.SafFileDeleter
|
||||||
|
import com.kazier.mobile.features.thumbnails.ThumbnailStore
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||||
|
import kotlinx.coroutines.test.TestScope
|
||||||
|
import kotlinx.coroutines.test.advanceUntilIdle
|
||||||
|
import kotlinx.coroutines.test.resetMain
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import kotlinx.coroutines.test.setMain
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat optimiste de la review : un échec ne perd jamais de carte —
|
||||||
|
* - `keep` en échec → carte réinsérée en tête + erreur ;
|
||||||
|
* - `delete` en échec (provider refuse) → carte réinsérée en tête + erreur ;
|
||||||
|
* - `markAllProcessed` en échec → deck restauré + erreur ;
|
||||||
|
* - `load` en échec → deck existant conservé (jamais vidé à tort) + erreur.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class ReviewOptimisticTest {
|
||||||
|
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var fileRepository: FileRepository
|
||||||
|
private lateinit var deleter: SafFileDeleter
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
context = ApplicationProvider.getApplicationContext()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
val apiService = Retrofit.Builder()
|
||||||
|
.baseUrl("http://localhost:1/")
|
||||||
|
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
||||||
|
.build()
|
||||||
|
.create(ApiService::class.java)
|
||||||
|
val apiClient = ApiClient(apiService, moshi)
|
||||||
|
val generateId = GenerateId()
|
||||||
|
val outboxRepository =
|
||||||
|
OutboxRepository(db.pendingOperationDao(), generateId, DeviceIdentity(db.userPreferenceDao(), generateId), moshi)
|
||||||
|
fileRepository = FileRepository(db.fileDao(), db.folderDao(), apiClient, generateId, db, outboxRepository)
|
||||||
|
deleter = SafFileDeleter(context, fileRepository, outboxRepository, db, ThumbnailStore(context))
|
||||||
|
// Validation applicative du parent (M18) : le dossier hôte existe.
|
||||||
|
runBlocking {
|
||||||
|
db.folderDao().upsert(
|
||||||
|
com.kazier.mobile.data.local.entity.FolderEntity(
|
||||||
|
resourceId = FOLDER,
|
||||||
|
uri = "content://tree/root",
|
||||||
|
name = "root",
|
||||||
|
exists = 1,
|
||||||
|
parentResourceId = null,
|
||||||
|
syncStatus = com.kazier.mobile.data.local.entity.FileStatus.LOCAL,
|
||||||
|
addedAt = 0L,
|
||||||
|
updatedAt = 0L,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
runCatching { db.close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun garder_succes_retire_la_carte_sans_erreur() = runTest {
|
||||||
|
withMain {
|
||||||
|
saveUnprocessed(RESOURCE_A)
|
||||||
|
val vm = SwipeReviewViewModel(fileRepository, deleter, context)
|
||||||
|
awaitUiState(vm) { it.cards.size == 1 }
|
||||||
|
assertEquals(1, vm.uiState.value.cards.size)
|
||||||
|
|
||||||
|
vm.keep(vm.uiState.value.cards.first())
|
||||||
|
awaitUiState(vm) { it.cards.isEmpty() }
|
||||||
|
|
||||||
|
assertTrue(vm.uiState.value.cards.isEmpty())
|
||||||
|
assertNull(vm.uiState.value.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun garder_echec_carte_reinseree_en_tete() = runTest {
|
||||||
|
withMain {
|
||||||
|
saveUnprocessed(RESOURCE_A)
|
||||||
|
val vm = SwipeReviewViewModel(fileRepository, deleter, context)
|
||||||
|
awaitUiState(vm) { it.cards.size == 1 }
|
||||||
|
val file = vm.uiState.value.cards.first()
|
||||||
|
|
||||||
|
// Table pierres : `markProcessed` lève (SQLiteException) → échec.
|
||||||
|
// (NB : `db.close()` suspend indéfiniment les appels Room au lieu
|
||||||
|
// de lever — inutilisable comme injection de faute.)
|
||||||
|
dropFilesTable()
|
||||||
|
vm.keep(file)
|
||||||
|
awaitUiState(vm) { it.error != null }
|
||||||
|
|
||||||
|
assertEquals(listOf(RESOURCE_A), vm.uiState.value.cards.map { it.resourceId })
|
||||||
|
assertEquals(context.getString(R.string.review_keep_error), vm.uiState.value.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun supprimer_echec_provider_carte_reinseree_en_tete() = runTest {
|
||||||
|
withMain {
|
||||||
|
saveUnprocessed(RESOURCE_A)
|
||||||
|
val vm = SwipeReviewViewModel(fileRepository, deleter, context)
|
||||||
|
awaitUiState(vm) { it.cards.size == 1 }
|
||||||
|
val file = vm.uiState.value.cards.first()
|
||||||
|
|
||||||
|
// URI inconnu : le provider refuse → `delete` retourne false.
|
||||||
|
vm.delete(file)
|
||||||
|
awaitUiState(vm) { it.error != null }
|
||||||
|
|
||||||
|
assertEquals(listOf(RESOURCE_A), vm.uiState.value.cards.map { it.resourceId })
|
||||||
|
assertEquals(context.getString(R.string.review_delete_error), vm.uiState.value.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun tout_marquer_echec_deck_restaure() = runTest {
|
||||||
|
withMain {
|
||||||
|
saveUnprocessed(RESOURCE_A)
|
||||||
|
val vm = SwipeReviewViewModel(fileRepository, deleter, context)
|
||||||
|
awaitUiState(vm) { it.cards.size == 1 }
|
||||||
|
assertEquals(1, vm.uiState.value.cards.size)
|
||||||
|
|
||||||
|
dropFilesTable()
|
||||||
|
vm.markAllProcessed()
|
||||||
|
awaitUiState(vm) { it.error != null }
|
||||||
|
|
||||||
|
assertEquals(listOf(RESOURCE_A), vm.uiState.value.cards.map { it.resourceId })
|
||||||
|
assertEquals(context.getString(R.string.review_keep_error), vm.uiState.value.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rechargement_echec_deck_existant_conserve() = runTest {
|
||||||
|
withMain {
|
||||||
|
saveUnprocessed(RESOURCE_A)
|
||||||
|
val vm = SwipeReviewViewModel(fileRepository, deleter, context)
|
||||||
|
awaitUiState(vm) { it.cards.size == 1 }
|
||||||
|
assertEquals(1, vm.uiState.value.cards.size)
|
||||||
|
|
||||||
|
dropFilesTable()
|
||||||
|
vm.load()
|
||||||
|
awaitUiState(vm) { it.error != null }
|
||||||
|
|
||||||
|
assertEquals(listOf(RESOURCE_A), vm.uiState.value.cards.map { it.resourceId })
|
||||||
|
assertEquals(context.getString(R.string.review_load_error), vm.uiState.value.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun reinsertion_sans_doublon() {
|
||||||
|
val file = fileEntity(RESOURCE_A)
|
||||||
|
val cards = listOf(fileEntity(RESOURCE_B), file)
|
||||||
|
|
||||||
|
val result = reinsertHead(cards, file)
|
||||||
|
|
||||||
|
assertEquals(listOf(RESOURCE_A, RESOURCE_B), result.map { it.resourceId })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Injection de faute : toute lecture/écriture `files` lève aussitôt. */
|
||||||
|
private suspend fun dropFilesTable() {
|
||||||
|
db.openHelper.writableDatabase.execSQL("DROP TABLE `files`")
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun saveUnprocessed(resourceId: String) { fileRepository.saveLocalFile(
|
||||||
|
input = SaveFileInput(
|
||||||
|
uri = "content://tree/$resourceId",
|
||||||
|
name = "$resourceId.jpg",
|
||||||
|
extension = "jpg",
|
||||||
|
size = 1024,
|
||||||
|
mimeType = "image/jpeg",
|
||||||
|
resourceId = resourceId,
|
||||||
|
processed = false,
|
||||||
|
),
|
||||||
|
folderResourceId = FOLDER,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fileEntity(resourceId: String) = com.kazier.mobile.data.local.entity.FileEntity(
|
||||||
|
resourceId = resourceId,
|
||||||
|
name = "$resourceId.jpg",
|
||||||
|
folderResourceId = FOLDER,
|
||||||
|
size = 1024L,
|
||||||
|
addedAt = 0L,
|
||||||
|
updatedAt = 0L,
|
||||||
|
)
|
||||||
|
|
||||||
|
private suspend fun TestScope.withMain(block: suspend () -> Unit) { val dispatcher = StandardTestDispatcher(testScheduler)
|
||||||
|
Dispatchers.setMain(dispatcher)
|
||||||
|
try {
|
||||||
|
block()
|
||||||
|
} finally {
|
||||||
|
Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attente déterministe d'un état VM : `advanceUntilIdle()` seul ne suffit
|
||||||
|
* pas — les lectures Room s'exécutent sur l'executor Room (thread réel) et
|
||||||
|
* `advanceUntilIdle` peut revenir avant leur reprise (temps virtuel brûlé
|
||||||
|
* sans attente réelle). On attend donc en temps RÉEL (`Dispatchers.IO` +
|
||||||
|
* `withTimeout` réel) la première valeur concordante du StateFlow.
|
||||||
|
*/
|
||||||
|
private suspend fun awaitUiState(
|
||||||
|
vm: SwipeReviewViewModel,
|
||||||
|
timeoutMs: Long = 10_000,
|
||||||
|
predicate: (SwipeReviewViewModel.ReviewUiState) -> Boolean,
|
||||||
|
) {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
withTimeout(timeoutMs) {
|
||||||
|
vm.uiState.first(predicate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val FOLDER = "f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0"
|
||||||
|
const val RESOURCE_A = "aabbccddeeff11223344556677889900"
|
||||||
|
const val RESOURCE_B = "bbaa11223344556677889900ccddeeff"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.kazier.mobile.ui.scan
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.PointF
|
||||||
|
import com.kazier.mobile.features.scan.ScanImageProcessor
|
||||||
|
import com.kazier.mobile.features.scan.ScanQuad
|
||||||
|
import com.kazier.mobile.features.scan.ScanRenderMode
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertSame
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat OpenCV-absent : `process()` retourne l'instance d'entrée elle-même
|
||||||
|
* (alias) — l'appelant (`ScanViewModel.confirmPage`) ne recycle que les
|
||||||
|
* nouvelles instances, jamais cet alias encore dessiné par `CropStage`
|
||||||
|
* (sinon crash `recycled bitmap` au retour caméra).
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class CropNoCvTest {
|
||||||
|
|
||||||
|
private val processor = ScanImageProcessor()
|
||||||
|
|
||||||
|
private fun bitmap() =
|
||||||
|
Bitmap.createBitmap(64, 48, Bitmap.Config.ARGB_8888)
|
||||||
|
|
||||||
|
private fun quad() = ScanQuad(
|
||||||
|
listOf(
|
||||||
|
PointF(4f, 4f),
|
||||||
|
PointF(60f, 4f),
|
||||||
|
PointF(60f, 44f),
|
||||||
|
PointF(4f, 44f),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun process_sans_opencv_retourne_l_alias_d_entree() {
|
||||||
|
val input = bitmap()
|
||||||
|
|
||||||
|
val result = processor.process(input, quad(), ScanRenderMode.COLOR)
|
||||||
|
|
||||||
|
assertSame("sans OpenCV, process() doit aliaser l'entrée", input, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun detection_sans_opencv_retourne_null() {
|
||||||
|
assertNull(processor.detectCorners(bitmap()))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.kazier.mobile.ui.scan
|
||||||
|
|
||||||
|
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||||
|
import com.kazier.mobile.data.local.entity.ScanPageStatus
|
||||||
|
import com.kazier.mobile.features.scan.ScanExport
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat d'export d'une session de scan (décisions pures consommées par
|
||||||
|
* `ScanViewModel.export/exportPdf`) :
|
||||||
|
* - échec partiel → seules les pages réussies sont marquées `EXPORTED`,
|
||||||
|
* la session ne passe jamais `DONE` ;
|
||||||
|
* - retry idempotent → seul le `PENDING` est réexporté, l'`EXPORTED`
|
||||||
|
* n'est jamais rejoué (aucun doublon SAF/Room/outbox).
|
||||||
|
*/
|
||||||
|
class ScanExportTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun echec_partiel_seuls_les_succes_marques_pas_de_done() {
|
||||||
|
val pages = listOf(
|
||||||
|
page("a".repeat(32), ScanPageStatus.PENDING),
|
||||||
|
page("b".repeat(32), ScanPageStatus.PENDING),
|
||||||
|
)
|
||||||
|
val failedIds = setOf("b".repeat(32))
|
||||||
|
|
||||||
|
val marked = ScanExport.succeeded(pages, failedIds)
|
||||||
|
|
||||||
|
assertEquals(listOf("a".repeat(32)), marked.map { it.resourceId })
|
||||||
|
assertFalse("un échec partiel ne termine jamais la session", ScanExport.shouldFinishSession(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun retry_idempotent_seul_le_pending_reexporte() {
|
||||||
|
val pages = listOf(
|
||||||
|
page("a".repeat(32), ScanPageStatus.PENDING),
|
||||||
|
page("b".repeat(32), ScanPageStatus.EXPORTED),
|
||||||
|
)
|
||||||
|
|
||||||
|
val retry = ScanExport.pendingForExport(pages)
|
||||||
|
|
||||||
|
assertEquals(listOf("a".repeat(32)), retry.map { it.resourceId })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun succes_total_marque_tout_et_termine() {
|
||||||
|
val pages = listOf(
|
||||||
|
page("a".repeat(32), ScanPageStatus.PENDING),
|
||||||
|
page("b".repeat(32), ScanPageStatus.PENDING),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(pages, ScanExport.succeeded(pages, emptySet()))
|
||||||
|
assertTrue(ScanExport.shouldFinishSession(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun session_deja_exportee_retry_sans_rien() {
|
||||||
|
val pages = listOf(page("a".repeat(32), ScanPageStatus.EXPORTED))
|
||||||
|
|
||||||
|
assertTrue(ScanExport.pendingForExport(pages).isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun page(resourceId: String, status: String) = ScanPageEntity(
|
||||||
|
resourceId = resourceId,
|
||||||
|
sessionId = 1L,
|
||||||
|
tempUri = "/tmp/$resourceId.jpg",
|
||||||
|
cornersJson = "{}",
|
||||||
|
width = 100,
|
||||||
|
height = 100,
|
||||||
|
sortOrder = 0,
|
||||||
|
status = status,
|
||||||
|
createdAt = 0L,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package com.kazier.mobile.ui.scan
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.local.dao.ScanDao
|
||||||
|
import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
||||||
|
import com.kazier.mobile.data.repository.ScanRepository
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
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
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat d'ordre des pages de scan : `sort_order` est `MAX + 1`, jamais
|
||||||
|
* `COUNT` — après suppression, un ajout ne réutilise aucun ordre existant
|
||||||
|
* (sinon `ORDER BY sort_order` instable + `swapOrder` ambigu).
|
||||||
|
*/
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class ScanOrderTest {
|
||||||
|
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var scanDao: ScanDao
|
||||||
|
private lateinit var repository: ScanRepository
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
scanDao = db.scanDao()
|
||||||
|
repository = ScanRepository(db, scanDao, GenerateId())
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ajout_suppression_ajout_ordres_uniques() = runTest {
|
||||||
|
val session = repository.getOrCreateActiveSession(null)
|
||||||
|
|
||||||
|
val a = repository.addPage(session, "/tmp/a.jpg", "{}", 10, 10)
|
||||||
|
val b = repository.addPage(session, "/tmp/b.jpg", "{}", 10, 10)
|
||||||
|
repository.deletePage(a.id, session.id)
|
||||||
|
val c = repository.addPage(session, "/tmp/c.jpg", "{}", 10, 10)
|
||||||
|
|
||||||
|
val pages = repository.getPages(session.id)
|
||||||
|
assertEquals(2, pages.size)
|
||||||
|
val orders = pages.map { it.sortOrder }
|
||||||
|
assertEquals("les ordres doivent rester uniques", orders.size, orders.toSet().size)
|
||||||
|
// MAX(0,1) + 1 = 2 : aucun recyclage de l'ordre de A.
|
||||||
|
assertEquals(2, c.sortOrder)
|
||||||
|
assertTrue(pages.none { it.id == a.id })
|
||||||
|
assertTrue(pages.any { it.id == b.id })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ajouts_successifs_ordres_croissants_max_plus_un() = runTest {
|
||||||
|
val session = repository.getOrCreateActiveSession(null)
|
||||||
|
|
||||||
|
val orders = (0 until 3).map { i ->
|
||||||
|
repository.addPage(session, "/tmp/$i.jpg", "{}", 10, 10).sortOrder
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(listOf(0, 1, 2), orders)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sessions_independantes_compteurs_separes() = runTest {
|
||||||
|
val first = repository.getOrCreateActiveSession(null)
|
||||||
|
repository.addPage(first, "/tmp/a.jpg", "{}", 10, 10)
|
||||||
|
repository.abandonSession(first.id)
|
||||||
|
|
||||||
|
val second = repository.getOrCreateActiveSession(null)
|
||||||
|
val page = repository.addPage(second, "/tmp/b.jpg", "{}", 10, 10)
|
||||||
|
|
||||||
|
assertEquals(0, page.sortOrder)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package com.kazier.mobile.ui.search
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.kazier.mobile.data.local.AppDatabase
|
||||||
|
import com.kazier.mobile.data.remote.ApiClient
|
||||||
|
import com.kazier.mobile.data.remote.ApiService
|
||||||
|
import com.kazier.mobile.data.repository.FileRepository
|
||||||
|
import com.kazier.mobile.data.repository.FolderRepository
|
||||||
|
import com.kazier.mobile.data.repository.OutboxRepository
|
||||||
|
import com.kazier.mobile.data.repository.SaveFileInput
|
||||||
|
import com.kazier.mobile.domain.ActiveUserStore
|
||||||
|
import com.kazier.mobile.domain.DeviceIdentity
|
||||||
|
import com.kazier.mobile.domain.GenerateId
|
||||||
|
import com.kazier.mobile.features.saf.FileDeleter
|
||||||
|
import com.kazier.mobile.features.saf.FileMover
|
||||||
|
import com.kazier.mobile.features.thumbnails.ThumbnailStore
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||||
|
import kotlinx.coroutines.test.advanceTimeBy
|
||||||
|
import kotlinx.coroutines.test.runCurrent
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import kotlinx.coroutines.test.setMain
|
||||||
|
import kotlinx.coroutines.test.resetMain
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
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.Retrofit
|
||||||
|
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||||
|
|
||||||
|
/**
|
||||||
|
* M31 — le champ suit la frappe brute : `uiState.query` reflète la saisie
|
||||||
|
* sans attendre le debounce (300 ms), qui ne s'applique qu'à la requête Room.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class SearchFieldTest {
|
||||||
|
|
||||||
|
private lateinit var db: AppDatabase
|
||||||
|
private lateinit var fileRepository: FileRepository
|
||||||
|
private lateinit var context: Context
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
context = ApplicationProvider.getApplicationContext()
|
||||||
|
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
val apiService = Retrofit.Builder()
|
||||||
|
.baseUrl("http://localhost:1/")
|
||||||
|
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
||||||
|
.build()
|
||||||
|
.create(ApiService::class.java)
|
||||||
|
val apiClient = ApiClient(apiService, moshi)
|
||||||
|
val generateId = GenerateId()
|
||||||
|
val outboxRepository = OutboxRepository(
|
||||||
|
db.pendingOperationDao(),
|
||||||
|
generateId,
|
||||||
|
DeviceIdentity(db.userPreferenceDao(), generateId),
|
||||||
|
moshi,
|
||||||
|
)
|
||||||
|
fileRepository = FileRepository(db.fileDao(), db.folderDao(), apiClient, generateId, db, outboxRepository)
|
||||||
|
// Validation applicative du parent (M18) : le dossier hôte existe.
|
||||||
|
runBlocking {
|
||||||
|
db.folderDao().upsert(
|
||||||
|
com.kazier.mobile.data.local.entity.FolderEntity(
|
||||||
|
resourceId = FOLDER,
|
||||||
|
uri = "content://tree/root",
|
||||||
|
name = "root",
|
||||||
|
exists = 1,
|
||||||
|
parentResourceId = null,
|
||||||
|
syncStatus = com.kazier.mobile.data.local.entity.FileStatus.LOCAL,
|
||||||
|
addedAt = 0L,
|
||||||
|
updatedAt = 0L,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun champ_suit_la_frappe_brute_sans_attendre_le_debounce() = runTest {
|
||||||
|
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
|
||||||
|
try {
|
||||||
|
val viewModel = newViewModel()
|
||||||
|
backgroundScope.launch { viewModel.uiState.collect {} }
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
// Trois frappes sans avancer l'horloge virtuelle (debounce = 300 ms).
|
||||||
|
viewModel.onQueryChange("r")
|
||||||
|
viewModel.onQueryChange("ra")
|
||||||
|
viewModel.onQueryChange("rap")
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"le champ doit suivre la frappe brute, pas la valeur debouncée",
|
||||||
|
"rap",
|
||||||
|
viewModel.uiState.value.query,
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun resultats_room_seulement_apres_debounce() = runTest {
|
||||||
|
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
|
||||||
|
try {
|
||||||
|
fileRepository.saveLocalFile(
|
||||||
|
input = SaveFileInput(
|
||||||
|
uri = "content://tree/rapport",
|
||||||
|
name = "rapport annuel.pdf",
|
||||||
|
extension = "pdf",
|
||||||
|
size = 1024,
|
||||||
|
mimeType = "application/pdf",
|
||||||
|
resourceId = RESOURCE_ID,
|
||||||
|
processed = true,
|
||||||
|
),
|
||||||
|
folderResourceId = FOLDER,
|
||||||
|
)
|
||||||
|
val viewModel = newViewModel()
|
||||||
|
backgroundScope.launch { viewModel.uiState.collect {} }
|
||||||
|
// Laisse l'état initial (requête vide → récents) se stabiliser :
|
||||||
|
// les lectures Room tournent sur l'executor Room (thread réel),
|
||||||
|
// on attend en temps RÉEL la première émission contenant le seed.
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
withTimeout(10_000) {
|
||||||
|
viewModel.uiState.first { state ->
|
||||||
|
state.results.any { it.resourceId == RESOURCE_ID }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
viewModel.onQueryChange("zzz-sans-match")
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
// Champ brut immédiat…
|
||||||
|
assertEquals("zzz-sans-match", viewModel.uiState.value.query)
|
||||||
|
// …mais la recherche Room n'a pas encore tourné : les récents
|
||||||
|
// (dont le fichier seedé) sont toujours affichés.
|
||||||
|
assertTrue(
|
||||||
|
"résultats prématurés : la requête Room doit attendre le debounce",
|
||||||
|
viewModel.uiState.value.results.any { it.resourceId == RESOURCE_ID },
|
||||||
|
)
|
||||||
|
|
||||||
|
// Debounce écoulé → la recherche tourne et ne matche plus rien.
|
||||||
|
// Attente en temps RÉEL (même raison que la stabilisation).
|
||||||
|
advanceTimeBy(400)
|
||||||
|
val settled = withContext(Dispatchers.IO) {
|
||||||
|
withTimeout(10_000) {
|
||||||
|
viewModel.uiState.first {
|
||||||
|
it.query == "zzz-sans-match" && it.results.none { f -> f.resourceId == RESOURCE_ID }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(settled.results.isEmpty())
|
||||||
|
} finally {
|
||||||
|
Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun newViewModel(): SearchViewModel {
|
||||||
|
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||||
|
val apiService = Retrofit.Builder()
|
||||||
|
.baseUrl("http://localhost:1/")
|
||||||
|
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
||||||
|
.build()
|
||||||
|
.create(ApiService::class.java)
|
||||||
|
val apiClient = ApiClient(apiService, moshi)
|
||||||
|
val generateId = GenerateId()
|
||||||
|
val outboxRepository = OutboxRepository(
|
||||||
|
db.pendingOperationDao(),
|
||||||
|
generateId,
|
||||||
|
DeviceIdentity(db.userPreferenceDao(), generateId),
|
||||||
|
moshi,
|
||||||
|
)
|
||||||
|
val fileRepo = fileRepository
|
||||||
|
val folderRepository = FolderRepository(
|
||||||
|
db.folderDao(),
|
||||||
|
apiClient,
|
||||||
|
generateId,
|
||||||
|
ActiveUserStore(db.userPreferenceDao()),
|
||||||
|
db,
|
||||||
|
outboxRepository,
|
||||||
|
)
|
||||||
|
return SearchViewModel(
|
||||||
|
fileRepo,
|
||||||
|
folderRepository,
|
||||||
|
FileMover(context, fileRepo, folderRepository),
|
||||||
|
FileDeleter(context, fileRepo, outboxRepository, db, ThumbnailStore(context)),
|
||||||
|
context,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val FOLDER = "f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0"
|
||||||
|
const val RESOURCE_ID = "aabbccddeeff11223344556677889900"
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user