V3 S6 : confiance (révocation, quota, appareils, conflits) + import + onboarding
Backend : token_version (000022, claim tv, 401 si révoqué, bump au password — fin limite V1), quota (000023 idempotente, colonne héritée de 000001, 413 QUOTA_EXCEEDED, GET /users/me/usage), devices (GET + DELETE révocation, EnforceDeviceExists en prod), renames concurrents transparents (baseUpdatedAt + conflicts[] non-fataux, tolérance 2 s). Tests service + handlers + migrations + auth. Mobile : pipeline conflits (DTO + SyncConflictStore + worker + dialogue), baseUpdatedAt prêt, liens 7j par défaut, écran Appareils (+ quota), import classeur unifié (scan/note/dossier), onboarding cercle Famille. Contrat docs/api-v1.md, V3.md (S6 livré).
This commit is contained in:
@@ -14,6 +14,7 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve
|
||||
- Corrections V3 (S3) : `PATCH /files/:id/facts` + op `correct_facts` (full-replace du jeu `user`, editor+, validation Go → 400 jamais 500), Room v20 (`resource_facts` + `FactsDao`, migration 19→20), fiche « Ce qu'on a compris » sur le viewer (chips, confiance grisée + suggéré, édition par type, reset auto), `FactsRepository` (sync remplace-en-bloc, correction optimiste + outbox atomique), `GET /files/:id/facts` consommé côté client.
|
||||
- Recherche V3 (S4) : colonne `search_tsv` (migration `000020`, `french`, index GIN) + `SearchDocumentsVisible` (nom LIKE + TS + faits, rang nom > TS > fait sûr > fait douteux, facettes émetteur/type/montant/période), `GET /files/search` étendu (400 si facette malformée), Room v21 (FTS4 `files_fts` + triggers partagés fresh-install/migration, entité déclarée pour KSP), `searchDocuments` offline (même rang, accents préservés) + UI filtres (émetteur, types chips, montants, période ISO, compteur, effacer).
|
||||
- Relations V3 (S5) : table `resource_links` + `scan_session_id` (migration `000021`), réconciliation déterministe (same_scan via outbox, doublons via SHA-256 posé à l'upload + backfill boot, same_issuer/référence via faits effectifs, verdicts préservés, élagage auto), `GET /files/:id/relations` + verdict (owner-only), `GET /duplicates` (groupes + gain récupérable), Room v22 (links + collections), « Voir aussi » dans la fiche (verdicts en ligne), écran Doublons (garder le plus récent), collections locales (sauver/rejouer/supprimer depuis la recherche), `scanSessionId` dans les creates de scan.
|
||||
- Confiance V3 (S6) : `token_version` (migration `000022`, claim `tv`, 401 si révoqué, bump au changement de mot de passe — fin de la limite V1), quota (colonne héritée de `000001`, `000023` idempotente, 413 `QUOTA_EXCEEDED` sur créations, `GET /users/me/usage`), appareils (`GET /devices`, `DELETE /devices/:id`, `EnforceDeviceExists` en prod, écran Appareils + quota), renames concurrents transparents (`baseUpdatedAt` + `conflicts[]` non-fataux, gracieuseté 2 s, pipeline mobile persistance + dialogue), liens à expiration 7j par défaut, import « classeur » unifié (scan/note/dossier), onboarding cercle Famille.
|
||||
- Corbeille V3 (S1 mobile, Room v19) : colonne `trashed_at` (files + folders, migration 18→19), tombstone `exists = 0` (requêtes `exists = 1` inchangées), `FileDeleter`/`FolderDeleter`/`SafFileDeleter` → ops `trash_resource` (plus de `delete_resource` émis), garde walk anti-résurrection + reconcile, `TrashRepository` (restore/purge/convergence `GET /trash`/expiration locale 31j), écran Corbeille (Réglages → restore/purge avec confirmation), expiration tombstones dans `RetentionWorker`, dialogue de suppression rewordé (corbeille 30j, plus « irréversible »).
|
||||
|
||||
## [1.1.0] - 2026-09-25
|
||||
|
||||
@@ -113,7 +113,7 @@ Sans ces 4 items, les piliers grincent. Ils sont petits et intégrés aux slices
|
||||
3. **S3 — Fiche + correction** (livré : `PATCH /files/:id/facts` + op `correct_facts` editor+ + Room v20 facts + fiche viewer + `FactsRepository` + B4 a11y fiche) — done quand : corriger en un tap converge serveur ↔ 2e device.
|
||||
4. **S4 — Recherche** (livré : `000020` FTS + facettes serveur + Room FTS v21 + UI filtres + B4 a11y) — done quand : « facture edf mars » trouve `scan_042.pdf` offline ET online.
|
||||
5. **S5 — Relations + B2** (livré : `000021` links + doublons SHA-256 + same_scan outbox + `GET /relations` + verdict + `GET /duplicates` + Room v22 + « Voir aussi » + Doublons + collections locales) — done quand : fiche CNI → verso + doublon listés, invalidables ; doublons chiffrés en Mo récupérables.
|
||||
6. **S6 — Partage sobre + A1/A2/A4 + B1 (+B5 si temps)** (expiration défaut 7j + `000022` token_version + `000023` quota + `413 QUOTA_EXCEEDED` + `GET /devices` + écran Appareils + `update_metadata{baseUpdatedAt}` + flag `conflict` + import « classeur » unifié B1 + onboarding cercle B5) — done quand : lien RIB expiré → `NOT_FOUND`, password changé → autres devices re-logués, device perdu révoqué, quota plein → 413 propre, rename concurrent → badge « renommé ailleurs ».
|
||||
6. **S6 — Partage sobre + A1/A2/A4 + B1 (+B5 si temps)** (livré : expiration liens 7j défaut + `000022` token_version + `000023` quota idempotente + `413 QUOTA_EXCEEDED` + `GET /devices` + `DELETE /devices/:id` + `EnforceDeviceExists` prod + écran Appareils + quota/usage + `update_metadata{baseUpdatedAt}` + `conflicts[]` + pipeline mobile + import « classeur » unifié + onboarding cercle Famille) — done quand : lien RIB expiré → `NOT_FOUND`, password changé → autres devices re-logués, device perdu révoqué, quota plein → 413 propre, rename concurrent → badge « renommé ailleurs ».
|
||||
7. **S7 — Preview 1ère page** (`pdf_preview` V2.md §3.3, une seule taille) + **C3 export chiffré** (`GET /export` zip + manifest) + B3 impression si temps + polish + release 1.2.0. Arbitrage stretch : **export > embeddings** (vrai 3-2-1 perçu, zéro GPU).
|
||||
|
||||
## 6. Tests (mêmes harnais, pas de nouveau framework)
|
||||
|
||||
@@ -61,6 +61,9 @@ func main() {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
handlers.Auth = authManager
|
||||
// V3 S6 A1 : les tokens d'un device révoqué (ligne `devices` supprimée)
|
||||
// sont rejetés en 401 — révocation réelle, pas décorative.
|
||||
handlers.EnforceDeviceExists = true
|
||||
|
||||
repo := repository.NewRepository(conn)
|
||||
|
||||
|
||||
@@ -35,6 +35,10 @@ var expectedRoutes = []string{
|
||||
|
||||
"GET /api/v1/users/resolve",
|
||||
"PATCH /api/v1/users/me/password",
|
||||
"GET /api/v1/users/me/usage",
|
||||
|
||||
"GET /api/v1/devices",
|
||||
"DELETE /api/v1/devices/:id",
|
||||
|
||||
"POST /api/v1/groups",
|
||||
"GET /api/v1/groups",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE users DROP COLUMN IF EXISTS token_version;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- V3 S6 : révocation des tokens au changement de mot de passe.
|
||||
-- `token_version` est bumpé par PATCH /users/me/password ; le middleware
|
||||
-- rejette les tokens dont le claim `tv` diffère (401). Défaut 0 : les tokens
|
||||
-- pré-V3 (sans claim `tv`, lus comme 0) restent valides jusqu'au premier
|
||||
-- changement de mot de passe — montée en version sans coupure.
|
||||
ALTER TABLE users ADD COLUMN token_version INT NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- No-op : la colonne prédate cette migration (000001), on ne la supprime pas.
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- V3 S6 (A2) : quota de stockage par compte (10 Go par défaut, V2.md §3.1).
|
||||
-- Garde-fou à l'upload (413 QUOTA_EXCEEDED) + affichage `GET /users/me/usage`.
|
||||
-- L'usage est calculé (somme `size_bytes` des fichiers vifs), jamais stocké.
|
||||
-- Note : la colonne existe depuis 000001 (modèle V2) — IF NOT EXISTS pour
|
||||
-- les bases créées avant/après, sans double ajout.
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS storage_quota_bytes BIGINT NOT NULL DEFAULT 10737418240;
|
||||
@@ -491,6 +491,30 @@ func TestMigrationsUpDown(t *testing.T) {
|
||||
t.Error("colonne resources.scan_session_id manquante après 000021")
|
||||
}
|
||||
|
||||
// --- 000022 : révocation tokens ------------------------------------------
|
||||
var tvCol int
|
||||
err = conn.QueryRow(`
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'token_version'`).Scan(&tvCol)
|
||||
if err != nil {
|
||||
t.Fatalf("token_version column: %v", err)
|
||||
}
|
||||
if tvCol == 0 {
|
||||
t.Error("colonne users.token_version manquante après 000022")
|
||||
}
|
||||
|
||||
// --- 000023 : quota (colonne héritée de 000001, IF NOT EXISTS) ------------
|
||||
var quotaCol int
|
||||
err = conn.QueryRow(`
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'storage_quota_bytes'`).Scan("aCol)
|
||||
if err != nil {
|
||||
t.Fatalf("storage_quota_bytes column: %v", err)
|
||||
}
|
||||
if quotaCol == 0 {
|
||||
t.Error("colonne users.storage_quota_bytes manquante après 000023")
|
||||
}
|
||||
|
||||
if err := MigrateDownDatabase(url); err != nil {
|
||||
t.Fatalf("migrate down: %v", err)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -156,7 +157,7 @@ func AuthLogin(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresAt, err := Auth.IssueWithExpiry(user.ID, req.DeviceID)
|
||||
token, expiresAt, err := Auth.IssueWithExpiry(user.ID, req.DeviceID, user.TokenVersion)
|
||||
if err != nil {
|
||||
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not issue token")
|
||||
return
|
||||
@@ -179,8 +180,9 @@ type changePasswordRequest struct {
|
||||
}
|
||||
|
||||
// ChangePassword met à jour le hash du compte connecté. Le mot de passe
|
||||
// courant est requis. Limite connue V1 : les tokens déjà émis restent valides
|
||||
// jusqu'à expiration (7 j, pas de révocation) — cf. docs/api-v1.md §7.
|
||||
// courant est requis. V3 S6 : le changement bumpe `token_version` — tous les
|
||||
// autres tokens (autres devices, sessions volées) sont révoqués aussitôt
|
||||
// (le token courant aussi : le client doit se reconnecter).
|
||||
func ChangePassword(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
@@ -217,6 +219,11 @@ func ChangePassword(c *gin.Context) {
|
||||
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not update password")
|
||||
return
|
||||
}
|
||||
// Révocation (V3 S6) : bump best-effort — un échec ici ne doit pas faire
|
||||
// croire que le password n'a pas changé (il l'est, ligne ci-dessus).
|
||||
if err := Store.Repository.Users.BumpTokenVersion(userID); err != nil {
|
||||
log.Printf("auth: bump token_version(%s): %v", userID, err)
|
||||
}
|
||||
|
||||
api.OK(c, gin.H{"id": userID})
|
||||
}
|
||||
|
||||
@@ -105,3 +105,51 @@ func DevicesRegister(c *gin.Context) {
|
||||
api.OK(c, gin.H{"deviceId": req.DeviceID})
|
||||
|
||||
}
|
||||
|
||||
// DeviceDTO expose un device du compte (A1 — voir / révoquer).
|
||||
type DeviceDTO struct {
|
||||
DeviceID string `json:"deviceId"`
|
||||
LastSeenAt *int64 `json:"lastSeenAt"`
|
||||
}
|
||||
|
||||
// DevicesList renvoie les devices du compte connecté (`GET /devices`,
|
||||
// dernier login = ce compte, les plus récemment vus d'abord).
|
||||
func DevicesList(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
rows, err := Store.Repository.Devices.ListByUser(userID)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]DeviceDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
out = append(out, DeviceDTO{DeviceID: row.DeviceID, LastSeenAt: row.LastSeenAt})
|
||||
}
|
||||
api.OK(c, out)
|
||||
}
|
||||
|
||||
// DeviceRevoke révoque un device du compte (`DELETE /devices/:id`, A1 —
|
||||
// téléphone perdu). Avec EnforceDeviceExists, ses tokens deviennent 401 et
|
||||
// son login est refusé (ré-enregistrement explicite requis). Ligne absente
|
||||
// ou d'un autre compte → 404 (pas d'énumération).
|
||||
func DeviceRevoke(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
id := c.Param("id")
|
||||
if !deviceIDPattern.MatchString(id) {
|
||||
api.Error(c, http.StatusNotFound, "NOT_FOUND", "device not found")
|
||||
return
|
||||
}
|
||||
if err := Store.Repository.Devices.Revoke(userID, id); err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
api.OK(c, gin.H{"id": id})
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func RequireAuth(c *gin.Context) {
|
||||
// Le store peut être nil dans les tests middleware purs ; sinon on vérifie
|
||||
// que le compte existe toujours (supprimé → accès refusé).
|
||||
if Store != nil && Store.Repository != nil {
|
||||
_, err := Store.Repository.Users.GetByID(identity.UserID)
|
||||
user, err := Store.Repository.Users.GetByID(identity.UserID)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "account no longer exists")
|
||||
c.Abort()
|
||||
@@ -71,6 +71,14 @@ func RequireAuth(c *gin.Context) {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// V3 S6 : révocation — un changement de mot de passe (bump de
|
||||
// token_version) invalide tous les tokens antérieurs, même non expirés.
|
||||
if identity.TokenVersion != user.TokenVersion {
|
||||
log.Printf("auth: token révoqué rejeté (user=%s tv=%d, attendu %d)", identity.UserID, identity.TokenVersion, user.TokenVersion)
|
||||
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "token revoked")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if EnforceDeviceExists && Store != nil && Store.Repository != nil {
|
||||
|
||||
@@ -51,6 +51,10 @@ func RegisterRoutes(r *gin.Engine) {
|
||||
|
||||
protected.GET("/users/resolve", ResolveUser)
|
||||
protected.PATCH("/users/me/password", ChangePassword)
|
||||
protected.GET("/users/me/usage", UsersUsage)
|
||||
|
||||
protected.GET("/devices", DevicesList)
|
||||
protected.DELETE("/devices/:id", DeviceRevoke)
|
||||
|
||||
protected.POST("/groups", GroupsCreate)
|
||||
protected.GET("/groups", GroupsList)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package handlers_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/kazier/backend/handlers"
|
||||
"github.com/kazier/backend/repository"
|
||||
)
|
||||
|
||||
// TestPasswordChangeRevokesTokens : le bump de token_version invalide tous
|
||||
// les tokens antérieurs (V3 S6) — l'ancien token devient 401, un nouveau
|
||||
// login fonctionne.
|
||||
func TestPasswordChangeRevokesTokens(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
device := repository.NewID()
|
||||
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "rv"), "revoke-test-password", device)
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files", token, nil, "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("token initial rejeté: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
body := `{"current_password":"revoke-test-password","new_password":"revoke-test-password-2"}`
|
||||
rec, _ = doRequest(t, r, http.MethodPatch, "/api/v1/users/me/password", token, []byte(body), "application/json")
|
||||
expectOK(t, rec, "password-change")
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files", token, nil, "")
|
||||
expectError(t, rec, http.StatusUnauthorized, "UNAUTHORIZED", "revoked-token")
|
||||
|
||||
// Nouveau login (nouvelle version) : fonctionne.
|
||||
body = fmt.Sprintf(`{"username":%q,"password":"revoke-test-password-2","device_id":%q}`,
|
||||
testUserUsername(device, "rv"), device)
|
||||
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/auth/login", "", []byte(body), "application/json")
|
||||
expectOK(t, rec, "relogin")
|
||||
var login struct {
|
||||
Data struct {
|
||||
Token string `json:"token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &login); err != nil || login.Data.Token == "" {
|
||||
t.Fatalf("relogin sans token: %s", rec.Body.String())
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files", login.Data.Token, nil, "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("nouveau token rejeté: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDevicesListAndRevoke : liste les devices du compte, révoque (A1) —
|
||||
// avec EnforceDeviceExists, le token du device révoqué devient 401 et son
|
||||
// login est refusé (ré-enregistrement requis).
|
||||
func TestDevicesListAndRevoke(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
handlers.EnforceDeviceExists = true
|
||||
defer func() { handlers.EnforceDeviceExists = false }()
|
||||
device := repository.NewID()
|
||||
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "dv"), "devices-test-password", device)
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/devices", token, nil, "")
|
||||
env := expectOK(t, rec, "devices-list")
|
||||
var devices []struct {
|
||||
DeviceID string `json:"deviceId"`
|
||||
LastSeenAt *int64 `json:"lastSeenAt"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &devices); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, d := range devices {
|
||||
if d.DeviceID == device {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("device absent de la liste: %+v", devices)
|
||||
}
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/devices/"+device, token, nil, "")
|
||||
expectOK(t, rec, "devices-revoke")
|
||||
|
||||
// Token existant → 401 (device inconnu).
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files", token, nil, "")
|
||||
expectError(t, rec, http.StatusUnauthorized, "UNAUTHORIZED", "revoked-device-token")
|
||||
|
||||
// Login refusé (device inconnu, indistinguable — 401).
|
||||
body := fmt.Sprintf(`{"username":%q,"password":"devices-test-password","device_id":%q}`,
|
||||
testUserUsername(device, "dv"), device)
|
||||
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/auth/login", "", []byte(body), "application/json")
|
||||
expectError(t, rec, http.StatusUnauthorized, "UNAUTHORIZED", "revoked-device-login")
|
||||
|
||||
// Révoquer l'inexistant / malformé → 404 (avec un token encore valide).
|
||||
deviceB := repository.NewID()
|
||||
tokenB, _ := registerAndLogin(t, r, repo, testUserUsername(deviceB, "dv2"), "devices-test-password", deviceB)
|
||||
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/devices/"+repository.NewID(), tokenB, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "revoke-unknown")
|
||||
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/devices/nope", tokenB, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "revoke-malformed")
|
||||
}
|
||||
|
||||
// TestUsageAndQuota : GET /users/me/usage reflète l'état, et un upload
|
||||
// au-delà du quota est rejeté en 413 QUOTA_EXCEEDED (V3 S6 A2).
|
||||
func TestUsageAndQuota(t *testing.T) {
|
||||
r, store, repo := setup(t)
|
||||
_ = store
|
||||
device := repository.NewID()
|
||||
token, userID := registerAndLogin(t, r, repo, testUserUsername(device, "qu"), "quota-test-password", device)
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/users/me/usage", token, nil, "")
|
||||
env := expectOK(t, rec, "usage-empty")
|
||||
var usage struct {
|
||||
UsedBytes int64 `json:"usedBytes"`
|
||||
QuotaBytes int64 `json:"quotaBytes"`
|
||||
FileCount int `json:"fileCount"`
|
||||
TrashCount int `json:"trashCount"`
|
||||
TrashedBytes int64 `json:"trashedBytes"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &usage); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if usage.UsedBytes != 0 || usage.QuotaBytes != 10737418240 || usage.FileCount != 0 {
|
||||
t.Fatalf("usage initial inattendu: %+v", usage)
|
||||
}
|
||||
|
||||
// Quota miniature (10 octets) → l'upload passe sous le seuil puis casse.
|
||||
if _, err := repo.Users.DB.Exec(`UPDATE users SET storage_quota_bytes = 10 WHERE id = $1`, userID); err != nil {
|
||||
t.Fatalf("shrink quota: %v", err)
|
||||
}
|
||||
rec = uploadMultipart(t, r, token, "", "a.txt", []byte("12345"))
|
||||
expectOK(t, rec, "usage-under-quota")
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/users/me/usage", token, nil, "")
|
||||
env = expectOK(t, rec, "usage-after")
|
||||
usage = struct {
|
||||
UsedBytes int64 `json:"usedBytes"`
|
||||
QuotaBytes int64 `json:"quotaBytes"`
|
||||
FileCount int `json:"fileCount"`
|
||||
TrashCount int `json:"trashCount"`
|
||||
TrashedBytes int64 `json:"trashedBytes"`
|
||||
}{}
|
||||
if err := json.Unmarshal(env.Data, &usage); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if usage.UsedBytes != 5 || usage.FileCount != 1 {
|
||||
t.Fatalf("usage après upload: %+v", usage)
|
||||
}
|
||||
|
||||
rec = uploadMultipart(t, r, token, "", "b.txt", []byte("123456"))
|
||||
expectError(t, rec, http.StatusRequestEntityTooLarge, "QUOTA_EXCEEDED", "usage-over-quota")
|
||||
}
|
||||
@@ -30,6 +30,8 @@ func writeError(c *gin.Context, err error) {
|
||||
api.Error(c, 409, "NAME_CONFLICT", "a resource with this name already exists here")
|
||||
case errors.Is(err, service.ErrFileTooLarge):
|
||||
api.Error(c, 413, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
|
||||
case errors.Is(err, service.ErrQuotaExceeded):
|
||||
api.Error(c, 413, "QUOTA_EXCEEDED", "storage quota exceeded")
|
||||
default:
|
||||
// Jamais de err.Error() brut au client (fuite SQL/FS/paths, cf.
|
||||
// FEEDBACK #8) : message générique, détail au log serveur.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/kazier/backend/pkg/api"
|
||||
)
|
||||
|
||||
// UsersUsage expose l'empreinte du compte (V3 S6 A2) : `GET /users/me/usage`
|
||||
// `{ usedBytes, quotaBytes, fileCount, trashCount, trashedBytes }` —
|
||||
// calculé, jamais stocké. La corbeille est détaillée (octets récupérables).
|
||||
func UsersUsage(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
usage, err := Store.Usage(userID)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
api.OK(c, usage)
|
||||
}
|
||||
+28
-12
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"aidanwoods.dev/go-paseto"
|
||||
@@ -17,11 +18,14 @@ var ErrInvalidToken = errors.New("invalid token")
|
||||
|
||||
var hex32Pattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
||||
|
||||
// Identity est le résultat de Verify : l'utilisateur (sujet du token, autorisant)
|
||||
// et le device (claim secondaire, porté mais NON autorisant seul).
|
||||
// Identity est le résultat de Verify : l'utilisateur (sujet du token, autorisant),
|
||||
// le device (claim secondaire, porté mais NON autorisant seul) et la version
|
||||
// de révocation (claim `tv`, V3 S6 — le middleware la compare à
|
||||
// users.token_version).
|
||||
type Identity struct {
|
||||
UserID string
|
||||
DeviceID string
|
||||
UserID string
|
||||
DeviceID string
|
||||
TokenVersion int
|
||||
}
|
||||
|
||||
// Manager issues and verifies paseto v4-local bearer tokens.
|
||||
@@ -40,16 +44,19 @@ func NewManager(secret string) (*Manager, error) {
|
||||
return &Manager{key: key}, nil
|
||||
}
|
||||
|
||||
// Issue émet un token lié à un utilisateur ET à un device.
|
||||
// Issue émet un token lié à un utilisateur ET à un device (version 0 —
|
||||
// compat pré-V3, cf. IssueWithExpiry).
|
||||
func (m *Manager) Issue(userID, deviceID string) (string, error) {
|
||||
token, _, err := m.IssueWithExpiry(userID, deviceID)
|
||||
token, _, err := m.IssueWithExpiry(userID, deviceID, 0)
|
||||
return token, err
|
||||
}
|
||||
|
||||
// IssueWithExpiry émet un token et retourne son expiration réelle (le `exp`
|
||||
// embarqué). Les appelants doivent exposer expiresAt, jamais le recalculer
|
||||
// via Now()+TTL (dérive d'horloge, cf. FEEDBACK A7).
|
||||
func (m *Manager) IssueWithExpiry(userID, deviceID string) (string, time.Time, error) {
|
||||
// via Now()+TTL (dérive d'horloge, cf. FEEDBACK A7). `tokenVersion` est le
|
||||
// compteur de révocation du compte (V3 S6) — bumpé à chaque changement de
|
||||
// mot de passe, vérifié par le middleware.
|
||||
func (m *Manager) IssueWithExpiry(userID, deviceID string, tokenVersion int) (string, time.Time, error) {
|
||||
now := time.Now()
|
||||
expiresAt := now.Add(TokenTTL)
|
||||
token := paseto.NewToken()
|
||||
@@ -59,12 +66,14 @@ func (m *Manager) IssueWithExpiry(userID, deviceID string) (string, time.Time, e
|
||||
token.SetSubject(userID)
|
||||
// v1.6.0 : SetString n'expose pas d'erreur (panic si non sérialisable).
|
||||
token.SetString("device_id", deviceID)
|
||||
token.SetString("tv", strconv.Itoa(tokenVersion))
|
||||
return token.V4Encrypt(m.key, nil), expiresAt, nil
|
||||
}
|
||||
|
||||
// Verify décode et contrôle le token, retourne l'identité (user + device).
|
||||
// Les deux identifiants doivent être 32-hex (cf. docs/api-v1.md) — rejet
|
||||
// sinon pour préserver les invariants UNIQUE(device_id,operation_id)/CHECK.
|
||||
// Verify décode et contrôle le token, retourne l'identité (user + device +
|
||||
// version). Les deux identifiants doivent être 32-hex (cf. docs/api-v1.md) —
|
||||
// rejet sinon pour préserver les invariants UNIQUE(device_id,operation_id)/CHECK.
|
||||
// `tv` absent (tokens pré-V3) → 0 ; non numérique → rejet.
|
||||
func (m *Manager) Verify(signed string) (Identity, error) {
|
||||
parsed, err := paseto.NewParserForValidNow().ParseV4Local(m.key, signed, nil)
|
||||
if err != nil {
|
||||
@@ -78,5 +87,12 @@ func (m *Manager) Verify(signed string) (Identity, error) {
|
||||
if err != nil || !hex32Pattern.MatchString(deviceID) {
|
||||
return Identity{}, ErrInvalidToken
|
||||
}
|
||||
return Identity{UserID: userID, DeviceID: deviceID}, nil
|
||||
tv := 0
|
||||
if raw, err := parsed.GetString("tv"); err == nil && raw != "" {
|
||||
tv, err = strconv.Atoi(raw)
|
||||
if err != nil || tv < 0 {
|
||||
return Identity{}, ErrInvalidToken
|
||||
}
|
||||
}
|
||||
return Identity{UserID: userID, DeviceID: deviceID, TokenVersion: tv}, nil
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ func TestIssueSetsExpiration(t *testing.T) {
|
||||
|
||||
func TestIssueWithExpiryMatchesTokenExp(t *testing.T) {
|
||||
m, _ := NewManager("test-secret")
|
||||
signed, expiresAt, err := m.IssueWithExpiry(testUserID, testDeviceID)
|
||||
signed, expiresAt, err := m.IssueWithExpiry(testUserID, testDeviceID, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueWithExpiry: %v", err)
|
||||
}
|
||||
@@ -177,4 +177,28 @@ func TestIssueWithExpiryMatchesTokenExp(t *testing.T) {
|
||||
if exp.Unix() != expiresAt.Unix() {
|
||||
t.Errorf("expiresAt = %v, exp token = %v", expiresAt, exp)
|
||||
}
|
||||
id, err := m.Verify(signed)
|
||||
if err != nil {
|
||||
t.Fatalf("Verify: %v", err)
|
||||
}
|
||||
if id.TokenVersion != 3 {
|
||||
t.Errorf("tv = %d, attendu 3", id.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyLegacyTokenWithoutTv(t *testing.T) {
|
||||
m, _ := NewManager("test-secret")
|
||||
// Tokens pré-V3 (Issue, tv=0) : Verify lit 0 — valides tant que le
|
||||
// compte n'a jamais bumpé (montée en version sans coupure).
|
||||
signed, err := m.Issue(testUserID, testDeviceID)
|
||||
if err != nil {
|
||||
t.Fatalf("Issue: %v", err)
|
||||
}
|
||||
id, err := m.Verify(signed)
|
||||
if err != nil {
|
||||
t.Fatalf("Verify legacy: %v", err)
|
||||
}
|
||||
if id.TokenVersion != 0 {
|
||||
t.Errorf("tv legacy = %d, attendu 0", id.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,3 +52,61 @@ func (d *Devices) MarkUser(deviceID, userID string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeviceRow is one registered device of an account (A1 — voir / révoquer).
|
||||
type DeviceRow struct {
|
||||
DeviceID string
|
||||
LastSeenAt *int64 // ms epoch, NULL si jamais vu depuis l'enregistrement
|
||||
}
|
||||
|
||||
// ListByUser returns the devices whose last login was this account
|
||||
// (devices.user_id informatif, jamais autorisant).
|
||||
func (d *Devices) ListByUser(userID string) ([]DeviceRow, error) {
|
||||
rows, err := d.DB.Query(
|
||||
`SELECT device_id, (EXTRACT(EPOCH FROM last_seen_at) * 1000)::bigint
|
||||
FROM devices WHERE user_id = $1 ORDER BY last_seen_at DESC NULLS LAST`,
|
||||
userID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []DeviceRow{}
|
||||
for rows.Next() {
|
||||
var row DeviceRow
|
||||
if err := rows.Scan(&row.DeviceID, &row.LastSeenAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Revoke deletes a device registration of this account (A1 — téléphone
|
||||
// perdu). Avec EnforceDeviceExists, les tokens du device deviennent 401 et
|
||||
// le login refuse le device (ré-enregistrement explicite requis).
|
||||
// Ligne absente ou d'un autre compte → ErrNotFound (pas d'énumération).
|
||||
// Les hints de présence (`storage_locations`) suivent.
|
||||
func (d *Devices) Revoke(userID, deviceID string) error {
|
||||
result, err := d.DB.Exec(
|
||||
`DELETE FROM devices WHERE device_id = $1 AND user_id = $2`,
|
||||
deviceID, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
if _, err := d.DB.Exec(
|
||||
`DELETE FROM storage_locations WHERE device_id = $1 AND user_id = $2`,
|
||||
deviceID, userID,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -124,6 +124,39 @@ func (r *Resources) ListMissingHashes(limit int) ([]MissingHash, error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// StorageUsage aggregates a user's footprint (V3 S6 A2 — calculé, jamais
|
||||
// stocké). Les trashés sont exclus (octets récupérables à la purge).
|
||||
type StorageUsage struct {
|
||||
UsedBytes int64
|
||||
FileCount int
|
||||
TrashCount int
|
||||
TrashedBytes int64
|
||||
}
|
||||
|
||||
// StorageUsage sums live file bytes + counts (live + trashed) for a user.
|
||||
func (r *Resources) StorageUsage(ownerID string) (StorageUsage, error) {
|
||||
var u StorageUsage
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT COALESCE(SUM(size_bytes), 0), COUNT(*)
|
||||
FROM resources
|
||||
WHERE user_id = $1 AND type = 'file' AND deleted_at IS NULL`,
|
||||
ownerID,
|
||||
).Scan(&u.UsedBytes, &u.FileCount)
|
||||
if err != nil {
|
||||
return StorageUsage{}, err
|
||||
}
|
||||
err = r.DB.QueryRow(
|
||||
`SELECT COUNT(*), COALESCE(SUM(size_bytes), 0)
|
||||
FROM resources
|
||||
WHERE user_id = $1 AND deleted_at IS NOT NULL`,
|
||||
ownerID,
|
||||
).Scan(&u.TrashCount, &u.TrashedBytes)
|
||||
if err != nil {
|
||||
return StorageUsage{}, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
type FileRow struct {
|
||||
ID string
|
||||
Name string
|
||||
@@ -700,6 +733,24 @@ func (r *Resources) TouchResource(resourceID string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// LiveNameAndUpdatedAt returns the current name and updated_at (ms epoch) of
|
||||
// a live resource, any type, unscoped — the caller (sync) has already
|
||||
// verified effective access. Absent/trashed → ErrNotFound. Sert à la
|
||||
// détection de conflits de rename (S6 A4 : baseUpdatedAt périmé).
|
||||
func (r *Resources) LiveNameAndUpdatedAt(resourceID string) (string, int64, error) {
|
||||
var name string
|
||||
var ms int64
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT name, (EXTRACT(EPOCH FROM updated_at) * 1000)::bigint
|
||||
FROM resources WHERE resource_id = $1 AND deleted_at IS NULL`,
|
||||
resourceID,
|
||||
).Scan(&name, &ms)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", 0, ErrNotFound
|
||||
}
|
||||
return name, ms, err
|
||||
}
|
||||
|
||||
// OwnedRow is a snapshot row: resource identity + freshness.
|
||||
type OwnedRow struct {
|
||||
ID string
|
||||
|
||||
@@ -13,6 +13,10 @@ type UserRow struct {
|
||||
PasswordHash string
|
||||
IsAdmin bool
|
||||
CreatedAt time.Time
|
||||
// V3 S6 : révocation des tokens (bump au changement de password) et
|
||||
// quota de stockage (garde-fou upload).
|
||||
TokenVersion int
|
||||
QuotaBytes int64
|
||||
}
|
||||
|
||||
// Users persiste les comptes utilisateurs (auth par login, cf. tranche identité).
|
||||
@@ -33,7 +37,8 @@ func (u *Users) Count() (int, error) {
|
||||
// (lowercase, unique). Absent → ErrNotFound.
|
||||
func (u *Users) GetByUsernameNormalized(normalized string) (*UserRow, error) {
|
||||
row := u.DB.QueryRow(
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at,
|
||||
token_version, storage_quota_bytes
|
||||
FROM users
|
||||
WHERE username_normalized = $1 AND deleted_at IS NULL`,
|
||||
normalized,
|
||||
@@ -48,7 +53,8 @@ func (u *Users) GetByUsernameNormalized(normalized string) (*UserRow, error) {
|
||||
// GetByID charge un compte actif par id. Absent → ErrNotFound.
|
||||
func (u *Users) GetByID(id string) (*UserRow, error) {
|
||||
row := u.DB.QueryRow(
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at,
|
||||
token_version, storage_quota_bytes
|
||||
FROM users
|
||||
WHERE id = $1 AND deleted_at IS NULL`,
|
||||
id,
|
||||
@@ -131,6 +137,27 @@ func (u *Users) MarkDeleted(id string) error {
|
||||
|
||||
func scanUser(scan func(...any) error) (*UserRow, error) {
|
||||
var user UserRow
|
||||
err := scan(&user.ID, &user.Username, &user.UsernameNormalized, &user.PasswordHash, &user.IsAdmin, &user.CreatedAt)
|
||||
err := scan(&user.ID, &user.Username, &user.UsernameNormalized, &user.PasswordHash, &user.IsAdmin, &user.CreatedAt, &user.TokenVersion, &user.QuotaBytes)
|
||||
return &user, err
|
||||
}
|
||||
|
||||
// BumpTokenVersion invalide tous les tokens émis (V3 S6) : le middleware
|
||||
// rejette les tokens dont le claim `tv` diffère. Compte absent → ErrNotFound.
|
||||
func (u *Users) BumpTokenVersion(id string) error {
|
||||
result, err := u.DB.Exec(
|
||||
`UPDATE users SET token_version = token_version + 1, updated_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL`,
|
||||
id,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -18,6 +18,10 @@ import (
|
||||
// ErrFileTooLarge signals an upload above MaxFileSize.
|
||||
var ErrFileTooLarge = errors.New("file too large")
|
||||
|
||||
// ErrQuotaExceeded signals an upload that would overflow the account quota
|
||||
// (V3 S6 A2). Handlers map it to 413 QUOTA_EXCEEDED (never 500).
|
||||
var ErrQuotaExceeded = errors.New("storage quota exceeded")
|
||||
|
||||
// ErrInvalidUpload signals a rejected upload (display name or path component).
|
||||
// Handlers map it to 400 INVALID_REQUEST (never 500).
|
||||
var ErrInvalidUpload = errors.New("invalid upload name")
|
||||
@@ -343,6 +347,14 @@ func (s *Resources) Upload(ownerID string, file *multipart.FileHeader, folderID,
|
||||
if ferr != nil {
|
||||
return FileDTO{}, ferr
|
||||
}
|
||||
} else {
|
||||
// V3 S6 A2 : garde-fou quota sur les créations (les overwrites
|
||||
// ciblées remplacent des octets existants — gain net ~nul, pas de
|
||||
// check). Vérifié au header (rejet rapide) PUIS aux octets réels
|
||||
// (vérité, le header peut mentir, cf. A2).
|
||||
if err := s.checkQuotaFor(ownerID, file.Size); err != nil {
|
||||
return FileDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
written, err := copyMultipartAtomic(file, destDir, destPath, s.MaxFileSize)
|
||||
@@ -352,6 +364,14 @@ func (s *Resources) Upload(ownerID string, file *multipart.FileHeader, folderID,
|
||||
}
|
||||
return FileDTO{}, err
|
||||
}
|
||||
if !targetExisting {
|
||||
// Vérité aux octets réels (le header `file.Size` peut mentir) :
|
||||
// dépassement → fichier supprimé + 413 (pas d'orphelin).
|
||||
if err := s.checkQuotaFor(ownerID, written); err != nil {
|
||||
_ = os.Remove(destPath)
|
||||
return FileDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
mimeType := sanitizeMimeType(file.Header.Get("Content-Type"))
|
||||
var extPtr *string
|
||||
@@ -486,3 +506,48 @@ func toFileDTO(row repository.FileRow) FileDTO {
|
||||
UpdatedAt: row.UpdatedAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
// UsageDTO serializes GET /users/me/usage (V3 S6 A2) : quota + empreinte,
|
||||
// dont la corbeille (octets récupérables à la purge).
|
||||
type UsageDTO struct {
|
||||
UsedBytes int64 `json:"usedBytes"`
|
||||
QuotaBytes int64 `json:"quotaBytes"`
|
||||
FileCount int `json:"fileCount"`
|
||||
TrashCount int `json:"trashCount"`
|
||||
TrashedBytes int64 `json:"trashedBytes"`
|
||||
}
|
||||
|
||||
// Usage returns the account footprint (computed, never stored).
|
||||
func (s *Resources) Usage(ownerID string) (UsageDTO, error) {
|
||||
user, err := s.Repository.Users.GetByID(ownerID)
|
||||
if err != nil {
|
||||
return UsageDTO{}, err
|
||||
}
|
||||
usage, err := s.Repo.StorageUsage(ownerID)
|
||||
if err != nil {
|
||||
return UsageDTO{}, err
|
||||
}
|
||||
return UsageDTO{
|
||||
UsedBytes: usage.UsedBytes, QuotaBytes: user.QuotaBytes,
|
||||
FileCount: usage.FileCount, TrashCount: usage.TrashCount,
|
||||
TrashedBytes: usage.TrashedBytes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// checkQuotaFor rejects a creation of incoming bytes that would overflow the
|
||||
// account quota (V3 S6 A2). Compte absent → l'erreur remonte (jamais de
|
||||
// défaut silencieux qui laisserait passer).
|
||||
func (s *Resources) checkQuotaFor(ownerID string, incoming int64) error {
|
||||
user, err := s.Repository.Users.GetByID(ownerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
usage, err := s.Repo.StorageUsage(ownerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if usage.UsedBytes+incoming > user.QuotaBytes {
|
||||
return ErrQuotaExceeded
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+80
-13
@@ -53,10 +53,22 @@ type FailedOperation struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// SyncResult is the outbox response: applied = index of the next op to send.
|
||||
// ConflictInfo reports a last-writer-wins rename applied over a concurrent
|
||||
// change (V3 S6 A4). Non-fatal : le batch continue, le client affiche
|
||||
// « renommé ailleurs » avec le nom serveur gagnant.
|
||||
type ConflictInfo struct {
|
||||
OperationID string `json:"operation_id"`
|
||||
ResourceID string `json:"resource_id"`
|
||||
ServerName string `json:"serverName"`
|
||||
ServerUpdatedAt int64 `json:"serverUpdatedAt"`
|
||||
}
|
||||
|
||||
// SyncResult is the outbox response: applied = index of the next op to send,
|
||||
// conflicts = renames concurrents appliqués quand même (non-fataux, S6 A4).
|
||||
type SyncResult struct {
|
||||
Applied int `json:"applied"`
|
||||
Failed *FailedOperation `json:"failed,omitempty"`
|
||||
Applied int `json:"applied"`
|
||||
Failed *FailedOperation `json:"failed,omitempty"`
|
||||
Conflicts []ConflictInfo `json:"conflicts,omitempty"`
|
||||
}
|
||||
|
||||
type createResourcePayload struct {
|
||||
@@ -71,6 +83,11 @@ type createResourcePayload struct {
|
||||
|
||||
type renamePayload struct {
|
||||
Name string `json:"name"`
|
||||
// V3 S6 A4 : `updated_at` (ms epoch) vu par le client au moment du
|
||||
// rename. Si la ressource a bougé depuis (concurrent), le rename
|
||||
// s'applique quand même (last-writer-wins) mais est signalé en
|
||||
// `conflicts` (transparence, pas de CRDT).
|
||||
BaseUpdatedAt *int64 `json:"baseUpdatedAt"`
|
||||
}
|
||||
|
||||
type movePayload struct {
|
||||
@@ -156,33 +173,39 @@ var errCycle = errors.New("cannot move a resource into its own subtree")
|
||||
// explicite avec code INTERNAL, jamais en erreur Go nue (500 nu) — le client
|
||||
// sait exactement où reprendre.
|
||||
func (s *Resources) ApplyBatch(userID, deviceID string, ops []SyncOperation) (SyncResult, error) {
|
||||
// Conflits de rename (S6 A4) : non-fataux, collectés tout au long du
|
||||
// batch et renvoyés avec le résultat (le batch continue).
|
||||
var conflicts []ConflictInfo
|
||||
fail := func(i int, op *SyncOperation, code, message string) (SyncResult, error) {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}, Conflicts: conflicts}, nil
|
||||
}
|
||||
for i := range ops {
|
||||
op := &ops[i]
|
||||
if err := validateSyncOp(op); err != nil {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: err.Error()}}, nil
|
||||
return fail(i, op, "INVALID_REQUEST", err.Error())
|
||||
}
|
||||
claimed, err := s.Repository.Operations.Claim(deviceID, op.OperationID, op.Operation, derefString(op.RefType), nullableInt64(derefInt64(op.RefID)), derefString(op.ResourceID), op.Payload)
|
||||
if err != nil {
|
||||
// Faute client (clé ou payload malformé) → INVALID_REQUEST halt,
|
||||
// message statique sûr ; panne persistance → INTERNAL explicite.
|
||||
if errors.Is(err, repository.ErrInvalidOperationID) {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: "operation_id must be 32 lowercase hex chars"}}, nil
|
||||
return fail(i, op, "INVALID_REQUEST", "operation_id must be 32 lowercase hex chars")
|
||||
}
|
||||
if errors.Is(err, repository.ErrInvalidPayload) {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: "invalid payload JSON"}}, nil
|
||||
return fail(i, op, "INVALID_REQUEST", "invalid payload JSON")
|
||||
}
|
||||
log.Printf("sync: claim device=%s op=%s: %v", deviceID, op.OperationID, err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INTERNAL", Message: "failed to persist operation state"}}, nil
|
||||
return fail(i, op, "INTERNAL", "failed to persist operation state")
|
||||
}
|
||||
if !claimed {
|
||||
// Rejeu : même (device, op) déjà tracé — comparer (A9).
|
||||
stored, err := s.Repository.Operations.Get(deviceID, op.OperationID)
|
||||
if err != nil {
|
||||
log.Printf("sync: replay read device=%s op=%s: %v", deviceID, op.OperationID, err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INTERNAL", Message: "failed to read operation state"}}, nil
|
||||
return fail(i, op, "INTERNAL", "failed to read operation state")
|
||||
}
|
||||
if err := stored.MatchesReplay(op.Operation, derefString(op.ResourceID), op.Payload); err != nil {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: "operation replayed with different payload"}}, nil
|
||||
return fail(i, op, "INVALID_REQUEST", "operation replayed with different payload")
|
||||
}
|
||||
if stored.Status == repository.OpStatusApplied {
|
||||
continue // déjà appliquée à l'identique → skip idempotent
|
||||
@@ -190,16 +213,18 @@ func (s *Resources) ApplyBatch(userID, deviceID string, ops []SyncOperation) (Sy
|
||||
// Trace 'failed' à payload identique : la première tentative est
|
||||
// morte avant MarkApplied (crash) → on ré-applique (recovery).
|
||||
}
|
||||
if err := s.applySyncOp(userID, deviceID, op); err != nil {
|
||||
if conflict, err := s.applySyncOpWithConflict(userID, deviceID, op); err != nil {
|
||||
code, message := classifySyncError(err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}}, nil
|
||||
return fail(i, op, code, message)
|
||||
} else if conflict != nil {
|
||||
conflicts = append(conflicts, *conflict)
|
||||
}
|
||||
if err := s.Repository.Operations.MarkApplied(deviceID, op.OperationID); err != nil {
|
||||
log.Printf("sync: promote device=%s op=%s: %v", deviceID, op.OperationID, err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INTERNAL", Message: "operation applied but trace update failed; safe to retry"}}, nil
|
||||
return fail(i, op, "INTERNAL", "operation applied but trace update failed; safe to retry")
|
||||
}
|
||||
}
|
||||
return SyncResult{Applied: len(ops)}, nil
|
||||
return SyncResult{Applied: len(ops), Conflicts: conflicts}, nil
|
||||
}
|
||||
|
||||
func validateSyncOp(op *SyncOperation) error {
|
||||
@@ -226,6 +251,48 @@ func validateSyncOp(op *SyncOperation) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// conflictToleranceMs absorbe le skew d'horloge client/serveur ET la
|
||||
// troncation à la seconde des `updatedAt` RFC3339 lus par le client : un
|
||||
// écart ≤ 2 s n'est pas un conflit (ex. create suivi d'un rename immédiat
|
||||
// par le même device). Au-delà, quelqu'un d'autre a écrit entre-temps.
|
||||
const conflictToleranceMs = 2000
|
||||
|
||||
// applySyncOpWithConflict applique une op et détecte les renames concurrents
|
||||
// (S6 A4) : si `baseUpdatedAt` est fourni et que la ressource a bougé depuis
|
||||
// (au-delà de la tolérance), le rename s'applique quand même (LWW) mais est
|
||||
// signalé. Sans base (vieux clients) : aucun signalement, comportement V1.
|
||||
func (s *Resources) applySyncOpWithConflict(ownerID, deviceID string, op *SyncOperation) (*ConflictInfo, error) {
|
||||
var base *int64
|
||||
resID := derefString(op.ResourceID)
|
||||
if op.Operation == OpUpdateMetadata {
|
||||
var p renamePayload
|
||||
if err := json.Unmarshal(op.Payload, &p); err == nil && p.BaseUpdatedAt != nil {
|
||||
base = p.BaseUpdatedAt
|
||||
}
|
||||
}
|
||||
var preMs int64
|
||||
havePre := false
|
||||
if base != nil {
|
||||
if _, ms, err := s.Repo.LiveNameAndUpdatedAt(resID); err == nil {
|
||||
preMs, havePre = ms, true
|
||||
}
|
||||
}
|
||||
if err := s.applySyncOp(ownerID, deviceID, op); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if base != nil && havePre && preMs > *base+conflictToleranceMs {
|
||||
name, ms, err := s.Repo.LiveNameAndUpdatedAt(resID)
|
||||
if err != nil {
|
||||
return nil, nil // renommé puis supprimé dans le même batch : rien à signaler.
|
||||
}
|
||||
return &ConflictInfo{
|
||||
OperationID: op.OperationID, ResourceID: resID,
|
||||
ServerName: name, ServerUpdatedAt: ms,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Resources) applySyncOp(ownerID, deviceID string, op *SyncOperation) error {
|
||||
resourceID := derefString(op.ResourceID)
|
||||
switch op.Operation {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/kazier/backend/repository"
|
||||
)
|
||||
|
||||
// TestRenameConflictReporting : un rename avec baseUpdatedAt périmée
|
||||
// s'applique quand même (LWW) mais est signalé en conflicts[] (S6 A4) ;
|
||||
// avec une base fraîche, aucun signalement.
|
||||
func TestRenameConflictReporting(t *testing.T) {
|
||||
s := newServiceStore(t)
|
||||
userID := mustCreateUser(t, s.Repository, "conflict-user")
|
||||
deviceA := mustRegisterDevice(t, s.Repository, "c0000000000000000000000000000001")
|
||||
fileID := repository.NewID()
|
||||
if err := s.Repository.Resources.InsertFile(userID, fileID, "origine.txt", "", 0, nil, nil); err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
|
||||
// Base fraîche : pas de conflit.
|
||||
name, ms, err := s.Repository.Resources.LiveNameAndUpdatedAt(fileID)
|
||||
if err != nil || name != "origine.txt" {
|
||||
t.Fatalf("live: %q %d %v", name, ms, err)
|
||||
}
|
||||
res, err := s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{
|
||||
"name": "v2.txt", "baseUpdatedAt": ms,
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if res.Applied != 1 || res.Failed != nil || len(res.Conflicts) != 0 {
|
||||
t.Fatalf("rename frais doit être silencieux: %+v", res)
|
||||
}
|
||||
|
||||
// Base périmée (concurrent théorique entre-temps) : appliqué + signalé.
|
||||
stale := ms - 60_000
|
||||
res, err = s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{
|
||||
"name": "v3.txt", "baseUpdatedAt": stale,
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if res.Applied != 1 || res.Failed != nil {
|
||||
t.Fatalf("rename concurrent doit s'appliquer (LWW): %+v", res)
|
||||
}
|
||||
if len(res.Conflicts) != 1 {
|
||||
t.Fatalf("conflit manquant: %+v", res)
|
||||
}
|
||||
c := res.Conflicts[0]
|
||||
if c.ResourceID != fileID || c.ServerName != "v3.txt" || c.ServerUpdatedAt <= 0 {
|
||||
t.Fatalf("conflit inattendu: %+v", c)
|
||||
}
|
||||
|
||||
// Sans base (vieux client) : appliqué, jamais signalé.
|
||||
res, err = s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{"name": "v4.txt"}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if res.Applied != 1 || res.Failed != nil || len(res.Conflicts) != 0 {
|
||||
t.Fatalf("sans base : silencieux: %+v", res)
|
||||
}
|
||||
|
||||
// Tolérance 2 s : un écart d'1 s (skew/troncation) n'est pas un conflit.
|
||||
_, nowMs, _ := s.Repository.Resources.LiveNameAndUpdatedAt(fileID)
|
||||
res, err = s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{
|
||||
"name": "v5.txt", "baseUpdatedAt": nowMs - 1000,
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if len(res.Conflicts) != 0 {
|
||||
t.Fatalf("écart 1 s ne doit pas signaler: %+v", res)
|
||||
}
|
||||
}
|
||||
+11
-8
@@ -18,8 +18,8 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
|
||||
|
||||
- **User-first (V1 finale)** : le device s'enregistre d'abord (`POST /devices`) avec son identité **générée localement** (`device_user_id` 32-hex mobile) — **réponse `{ "deviceId" }` uniquement, sans token**. Puis le client appelle `POST /auth/login` (`username` + `password` + `device_id`) pour obtenir son token **paseto** v4-local. Requêtes suivantes : `Authorization: Bearer <token>` (toutes les routes **sauf `/health`, `/devices`, `/auth/login`**).
|
||||
- **Claims du token** : le **subject = `user_id`** (AUTORISE, clé de scoping de toutes les ressources) ; `device_id` est un **claim secondaire, porté mais NON autorisant seul** (idempotence outbox + jobs OCR). Résolu par middleware `RequireAuth` qui vérifie aussi que le compte existe toujours (`deleted_at IS NULL`).
|
||||
- **TTL : 7 jours, sans refresh.** À expiration, le client re-logine (`POST /auth/login`). Le changement de mot de passe (`PATCH /users/me/password`) **n'invalide pas** les tokens déjà émis — limite V1 assumée (pas de liste de révocation) jusqu'à l'expiration.
|
||||
- Au login, `devices.user_id` mémorise le **dernier user connecté** (INFORMATIF uniquement, jamais autorisant — recommande `POST /devices` → `POST /auth/login` pour un nouveau device, sans réutiliser le device d'un autre compte).
|
||||
- **TTL : 7 jours, sans refresh.** À expiration, le client re-logine (`POST /auth/login`). **Révocation V3 (S6)** : `PATCH /users/me/password` bumpe `users.token_version` — tous les tokens antérieurs deviennent 401 (`token revoked`), y compris non expirés ; le client doit se reconnecter (le claim `tv` porte la version, les tokens pré-V3 sans `tv` valent 0 et survivent jusqu'au premier changement de mot de passe).
|
||||
- Au login, `devices.user_id` mémorise le **dernier user connecté** (INFORMATIF uniquement, jamais autorisant — recommande `POST /devices` → `POST /auth/login` pour un nouveau device, sans réutiliser le device d'un autre compte). **Révocation V3 (S6 A1)** : `DELETE /devices/:id` supprime l'enregistrement (téléphone perdu) — avec `EnforceDeviceExists` (prod), les tokens du device deviennent 401 et son login est refusé ; seule une ré-inscription explicite (`POST /devices`) restaure l'accès. `GET /devices` liste les devices du compte (dernier login = ce compte).
|
||||
- **Identifiants** : `resource_id`, `device_user_id`, `user_id`, `is_admin`… = **TEXT opaque 32-hex minuscule**, `^[0-9a-f]{32}$`. Le mobile génère toujours `lower(hex(randomblob(16)))` ; le serveur stocke **tel quel**, sans conversion UUID (cf. note V2.md). Contrainte serveur : `CHECK (col ~ '^[0-9a-f]{32}$')` sur toutes les colonnes id + FK.
|
||||
- **Usernames** : `username` = forme affichée ; l'unicité et la résolution portent sur `username_normalized` (lowercase + trim). Résolution d'un destinataire : `GET /users/resolve?username=` (exact uniquement, jamais de listing ni de préfixe — pas d'énumération de comptes).
|
||||
- **Bootstrap** : au premier démarrage, si `users` est vide, `ADMIN_USERNAME`/`ADMIN_PASSWORD` (env) créent le **premier admin** ; absents → le serveur **refuse de démarrer**. L'env n'écrase jamais un compte existant.
|
||||
@@ -34,7 +34,10 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
|
||||
| POST | `/auth/login` | `{ "username", "password", "device_id" }` | `{ "token", "expires_at" (ms), "user": { "id", "username", "is_admin" } }` | `UNAUTHORIZED` / `INVALID_DEVICE_ID` |
|
||||
| GET | `/shares/links/:token` | — (public, sans auth) | `{ "token", "resource_id", "resourceType", "name", "access", "expiresAt" }` | `NOT_FOUND` (inconnu/révoqué/expiré) |
|
||||
| GET | `/users/resolve` | query `username` (obligatoire) | `{ "id", "username" }` | `NOT_FOUND` |
|
||||
| PATCH | `/users/me/password` | `{ "current_password", "new_password" }` | `{ "id" }` | `INVALID_PASSWORD` (403) |
|
||||
| PATCH | `/users/me/password` | `{ "current_password", "new_password" }` | `{ "id" }` (+ révocation globale des tokens) | `INVALID_PASSWORD` (403) |
|
||||
| GET | `/users/me/usage` | — | `{ usedBytes, quotaBytes, fileCount, trashCount, trashedBytes }` (calculé, corbeille détaillée) | — |
|
||||
| GET | `/devices` | — | `[{ deviceId, lastSeenAt }]` (dernier login = ce compte) | — |
|
||||
| DELETE | `/devices/:id` | — (téléphone perdu, A1) | `{ "id" }` | `NOT_FOUND` (absent/autre compte — pas d'énumération) |
|
||||
| GET | `/files` | query `folderId?`, `page?`, `pageSize?`, `sort?` | `FileDto[]` (+ `meta`) | — |
|
||||
| GET | `/files/:id` | — | `FileDto` | `NOT_FOUND` |
|
||||
| GET | `/files/:id/content` | — (binaire brut, hors enveloppe `{data}` ; `Range` supporté) | octets physiques (`Content-Type` du fichier, `Content-Disposition: inline`) — streaming lecture seule, jamais persisté côté client | `NOT_FOUND` (invisible OU metadata-only jamais uploadé — indistinguables) |
|
||||
@@ -128,11 +131,11 @@ type FileOcr = { text: string; updatedAt?: string | null };
|
||||
- `operation` ∈ `create_resource | update_metadata | delete_resource | move_resource | share | revoke_share | update_share | create_link | revoke_link | report_bytes | trash_resource | restore_resource | purge_resource | correct_facts` (cf. `PendingOperationType` mobile).
|
||||
- **Identifiants** : `operation_id` est un **TEXT 32-hex** généré par le client (`^[0-9a-f]{32}$`, CHECK-enforced depuis la migration `000008`), distinct de `resource_id`. L'idempotence outbox reste **par device** : `UNIQUE(device_id, operation_id)` (la réinscription d'un device avec un login différent ne réutilise pas l'historique outbox d'un autre compte). Pour chaque op : si déjà traitée → **no-op** (comptée comme appliquée, les doublons arrivent à cause du backoff/retry). Sinon appliquée si valide.
|
||||
- **Ordre** : les opérations sont appliquées **séquentiellement**, dans l'ordre du batch. Le serveur **s'arrête à la première erreur non-idempotente** et renvoie l'index atteint — le client reprend à cet index.
|
||||
- Réponse : `2xx` avec `{ "applied": int, "failed": { "operation_id": "…32-hex", "code": string, "message": string } | null }` (`applied` = index de la prochaine op à envoyer).
|
||||
- Réponse : `2xx` avec `{ "applied": int, "failed": { "operation_id": "…32-hex", "code": string, "message": string } | null, "conflicts"?: [{ "operation_id", "resource_id", "serverName", "serverUpdatedAt" }] }` (`applied` = index de la prochaine op à envoyer ; `conflicts` = renames LWW appliqués malgré une `baseUpdatedAt` périmée — non-fataux, le batch continue).
|
||||
- Côté client, le `pushStatus` (pending/synced/failed) des shares/share_links est **dérivé** de l'état des opérations de l'outbox ; **dead-letter immédiat** sur erreur 4xx non-idempotente (`failed`, non resélectionné ; `attempts` reste un compteur diagnostic, pas un seuil) — seul le transitoire (`NETWORK_ERROR`/5xx) est rejoué avec backoff. **Côté serveur, les ops partage créent un état réel** (tables `shares`/`share_links`, migration `000009`) — l'outbox est le seul chemin d'écriture des droits.
|
||||
- Sémantique d'application (côté serveur) :
|
||||
- `create_resource` : crée la ressource ; **déjà présente → no-op** (rejeu idempotent). `payload.name` obligatoire ; `payload.parentResourceId` (32-hex, optionnel) = dossier parent — absent → racine. **Parent inexistant → `NOT_FOUND`** (cohérent avec `move_resource`). Ordre garanti par construction client : le walk SAF émet les `create` des dossiers (ordre préfixe) avant ceux des fichiers, dans la même transaction Room → `id ASC` = parent avant enfant. `payload.scanSessionId` (32-hex, optionnel, V3 S5) = session de scan opaque — le serveur en déduit les arêtes `same_scan` (même session, même compte) ; format invalide → `INVALID_REQUEST`.
|
||||
- `update_metadata` : ressource absente → **no-op** (état terminal atteint) ; **ressource partagée : nécessite `editor+`** (§6.2) — sinon `NOT_FOUND` (une ressource visible mais sans droit de mutation n'est pas renommée) ; une ressource sans relation applicable (ni owner, ni grant) reste un no-op (pas d'énumération). `move_resource` / `delete_resource` restent **owner-only** (scoping par `user_id`, les ops d'un non-owner sont des no-op).
|
||||
- `update_metadata` : ressource absente → **no-op** (état terminal atteint) ; **ressource partagée : nécessite `editor+`** (§6.2) — sinon `NOT_FOUND` (une ressource visible mais sans droit de mutation n'est pas renommée) ; une ressource sans relation applicable (ni owner, ni grant) reste un no-op (pas d'énumération). `payload = { "name", "baseUpdatedAt"? }` (V3 S6 A4 : `updated_at` ms vu par le client — périmé au-delà de 2 s de tolérance → rename appliqué quand même + signalé en `conflicts`, transparence sans CRDT). `move_resource` / `delete_resource` restent **owner-only** (scoping par `user_id`, les ops d'un non-owner sont des no-op).
|
||||
- `delete_resource` : **legacy → mappé vers `trash_resource`** (corbeille, restaurable, même idempotence : absent/déjà trashé = succès, vivant d'autrui = `NOT_FOUND` halt).
|
||||
- **Corbeille V3** (`trash_resource` / `restore_resource` / `purge_resource`, owner-only) : `trash` pose `deleted_at` sur la ressource **et son subtree** (dossier → contenu) ; `restore` lève le flag sur la ressource, son subtree **et sa chaîne d'ancêtres** (un fichier restauré dont le dossier est encore trashé resterait injoignable) ; `purge` détruit lignes + versions + octets. Sémantique : absent → no-op (`trash`/`restore`/`purge`), vivant d'autrui → `NOT_FOUND` halt, `restore` d'un live → no-op succès. Une ressource trashée reste `NOT_FOUND` en lecture normale, visible seulement via `GET /trash`. Passe serveur : destruction définitive après 30j (`TrashRetention`).
|
||||
- **Corrections V3** (`correct_facts`, editor+) : `payload = { "facts": [{ "factType", "valueText"?, "valueNum"?, "valueDate"? (ISO `YYYY-MM-DD`), "confidence"? }] }` — remplace le jeu `user` complet (full-replace, jamais de diff ; jeu vide = efface les corrections, l'auto survit). Mêmes gardes qu'`update_metadata` (viewer- → `NOT_FOUND` halt) ; fait invalide (type inconnu, date non ISO, sans valeur) → `INVALID_REQUEST` avec arrêt du batch. Le client corrige en un tap depuis la fiche document et pousse dans la même transaction Room que l'écriture optimiste.
|
||||
@@ -183,8 +186,8 @@ type ResourcePermission = {
|
||||
|
||||
## 7. Codes d'erreur courants
|
||||
|
||||
- Authentification : `UNAUTHORIZED` (**401** — token manquant/invalide/expiré, compte supprimé, OU identifiants de login erronés : **indistinguables par design**, même code+message), `INVALID_DEVICE_ID` (**400** — device non enregistré au login).
|
||||
- Ressources : `NOT_FOUND` (404), `NAME_CONFLICT` (409 — même nom dans le même parent, cf. `UNIQUE(parent_id, name)`, **ou à la racine**, index partiel `(user_id, name) WHERE parent_id IS NULL`), `FILE_TOO_LARGE` (413), `INVALID_PASSWORD` (403 sur `PATCH /users/me/password`).
|
||||
- Authentification : `UNAUTHORIZED` (**401** — token manquant/invalide/expiré/**révoqué** (mot de passe changé, device révoqué), compte supprimé, OU identifiants de login erronés : **indistinguables par design**, même code+message), `INVALID_DEVICE_ID` (**400** — device non enregistré au login).
|
||||
- Ressources : `NOT_FOUND` (404), `NAME_CONFLICT` (409 — même nom dans le même parent, cf. `UNIQUE(parent_id, name)`, **ou à la racine**, index partiel `(user_id, name) WHERE parent_id IS NULL`), `FILE_TOO_LARGE` (413), `QUOTA_EXCEEDED` (413 — créations au-delà de `storage_quota_bytes`, 10 Go par défaut ; overwrites ciblées exemptées, gain net ~nul), `INVALID_PASSWORD` (403 sur `PATCH /users/me/password`).
|
||||
- Partage : `GRANTEE_NOT_FOUND` (404 — grantee inexistant sur une op share), `GROUP_NOT_FOUND` (404 — groupe inexistant sur une op share ou un endpoint membres), `NOT_FOUND` (404 — ressource non possédée sur une op share : scoping, pas d'énumération).
|
||||
- Client-only : `NETWORK_ERROR`, `INVALID_RESPONSE` (2xx mais corps d'enveloppe invalide), `HTTP_<status>` (fallback). Statut `SERVICE_UNAVAILABLE` (503) si le backend n'est pas initialisé.
|
||||
- **V1 finale : toutes les routes sont réelles** (pas de 501 restant).
|
||||
@@ -193,4 +196,4 @@ type ResourcePermission = {
|
||||
|
||||
- `POST /auth/login` : le **device doit exister** (`POST /devices` d'abord, sinon 400 `INVALID_DEVICE_ID`). La vérification du mot de passe est **constant-time** (`argon2id`, comparaison `subtle`) et le délai est **égalisé** entre « username inconnu » et « mauvais mot de passe » (vérification contre un dummy-hash) — les deux produisent exactement la même réponse 401.
|
||||
- `GET /users/resolve` : résolution **exacte** du `username_normalized` uniquement ; ne renvoie **jamais** `email` ni `is_admin` (ni listing, ni préfixe → pas d'énumération de comptes).
|
||||
- `PATCH /users/me/password` : exige `current_password` (mauvais curl → 403). Minimum 8 caractères. **Limite V1** : tokens émis non révoqués (validité 7 j), et `is_admin`/`ADMIN_*` non modifiables par API.
|
||||
- `PATCH /users/me/password` : exige `current_password` (mauvais curl → 403). Minimum 8 caractères. **V3 S6** : bumpe `token_version` (tous les tokens antérieurs révoqués — le client se reconnecte) ; `is_admin`/`ADMIN_*` non modifiables par API.
|
||||
@@ -30,11 +30,13 @@ import com.kazier.mobile.data.remote.dto.SyncOpDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import com.kazier.mobile.data.remote.dto.CorrectFactsDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceDto
|
||||
import com.kazier.mobile.data.remote.dto.DuplicateGroupDto
|
||||
import com.kazier.mobile.data.remote.dto.FactDto
|
||||
import com.kazier.mobile.data.remote.dto.RelationDto
|
||||
import com.kazier.mobile.data.remote.dto.RelationVerdictDto
|
||||
import com.kazier.mobile.data.remote.dto.TrashDto
|
||||
import com.kazier.mobile.data.remote.dto.UsageDto
|
||||
import com.kazier.mobile.data.remote.dto.VersionDto
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import okhttp3.MultipartBody
|
||||
@@ -190,6 +192,18 @@ class ApiClient @Inject constructor(
|
||||
suspend fun listDuplicates(): List<DuplicateGroupDto> =
|
||||
unwrap({ apiService.listDuplicates() })
|
||||
|
||||
/** Devices du compte — `GET /devices`. */
|
||||
suspend fun listDevices(): List<DeviceDto> =
|
||||
unwrap({ apiService.listDevices() })
|
||||
|
||||
/** Révoque un device — `DELETE /devices/:id`. */
|
||||
suspend fun revokeDevice(deviceId: String): String =
|
||||
unwrap({ apiService.revokeDevice(deviceId) }).id
|
||||
|
||||
/** Empreinte du compte — `GET /users/me/usage`. */
|
||||
suspend fun getUsage(): UsageDto =
|
||||
unwrap({ apiService.getUsage() })
|
||||
|
||||
/** Recherche serveur paginée — `GET /files/search?q=…` (+ `meta`). */
|
||||
suspend fun searchFilesPaged(
|
||||
query: String,
|
||||
|
||||
@@ -23,11 +23,13 @@ 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.CorrectFactsDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceDto
|
||||
import com.kazier.mobile.data.remote.dto.DuplicateGroupDto
|
||||
import com.kazier.mobile.data.remote.dto.FactDto
|
||||
import com.kazier.mobile.data.remote.dto.RelationDto
|
||||
import com.kazier.mobile.data.remote.dto.RelationVerdictDto
|
||||
import com.kazier.mobile.data.remote.dto.TrashDto
|
||||
import com.kazier.mobile.data.remote.dto.UsageDto
|
||||
import com.kazier.mobile.data.remote.dto.VersionDto
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
@@ -223,6 +225,20 @@ interface ApiService {
|
||||
@GET("duplicates")
|
||||
suspend fun listDuplicates(): Response<ApiEnvelope<List<DuplicateGroupDto>>>
|
||||
|
||||
/** Devices du compte (`GET /devices`, dernier login = ce compte). */
|
||||
@GET("devices")
|
||||
suspend fun listDevices(): Response<ApiEnvelope<List<DeviceDto>>>
|
||||
|
||||
/** Révoque un device (`DELETE /devices/:id`, A1 — téléphone perdu). */
|
||||
@DELETE("devices/{id}")
|
||||
suspend fun revokeDevice(
|
||||
@Path("id") deviceId: String,
|
||||
): Response<ApiEnvelope<IdResultDto>>
|
||||
|
||||
/** Empreinte du compte (`GET /users/me/usage`, calculée serveur). */
|
||||
@GET("users/me/usage")
|
||||
suspend fun getUsage(): Response<ApiEnvelope<UsageDto>>
|
||||
|
||||
/**
|
||||
* Recherche serveur (`GET /files/search?q=…`, paginé `meta`). Non consommée
|
||||
* en V1 (recherche 100 % locale via Room) — exposée pour parité contrat.
|
||||
|
||||
@@ -191,6 +191,19 @@ data class SyncOpsRequest(
|
||||
data class SyncOpsResult(
|
||||
@Json(name = "applied") val applied: Int,
|
||||
@Json(name = "failed") val failed: SyncFailedDto? = null,
|
||||
/**
|
||||
* Renames LWW appliqués malgré une base périmée (V3 S6 A4) — non-fataux,
|
||||
* le batch continue. Absent (vieux serveur) = liste vide.
|
||||
*/
|
||||
@Json(name = "conflicts") val conflicts: List<SyncConflictDto>? = null,
|
||||
)
|
||||
|
||||
/** Rename concurrent appliqué quand même (transparence, pas de CRDT). */
|
||||
data class SyncConflictDto(
|
||||
@Json(name = "operation_id") val operationId: String,
|
||||
@Json(name = "resource_id") val resourceId: String,
|
||||
@Json(name = "serverName") val serverName: String = "",
|
||||
@Json(name = "serverUpdatedAt") val serverUpdatedAt: Long = 0L,
|
||||
)
|
||||
|
||||
/** Première erreur non-idempotente du batch (arrêt du serveur). */
|
||||
@@ -335,4 +348,25 @@ data class DuplicateGroupDto(
|
||||
@Json(name = "totalBytes") val totalBytes: Long = 0L,
|
||||
@Json(name = "reclaimableBytes") val reclaimableBytes: Long = 0L,
|
||||
@Json(name = "files") val files: List<DuplicateFileDto> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Device du compte `GET /devices` (V3 S6 A1) — dernier login = ce compte.
|
||||
* `lastSeenAt` ms epoch (null si jamais revu depuis l'enregistrement).
|
||||
*/
|
||||
data class DeviceDto(
|
||||
@Json(name = "deviceId") val deviceId: String,
|
||||
@Json(name = "lastSeenAt") val lastSeenAt: Long? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Empreinte du compte `GET /users/me/usage` (V3 S6 A2) — calculée serveur,
|
||||
* corbeille détaillée (octets récupérables à la purge).
|
||||
*/
|
||||
data class UsageDto(
|
||||
@Json(name = "usedBytes") val usedBytes: Long = 0L,
|
||||
@Json(name = "quotaBytes") val quotaBytes: Long = 0L,
|
||||
@Json(name = "fileCount") val fileCount: Int = 0,
|
||||
@Json(name = "trashCount") val trashCount: Int = 0,
|
||||
@Json(name = "trashedBytes") val trashedBytes: Long = 0L,
|
||||
)
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.kazier.mobile.data.repository
|
||||
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.dto.DeviceDto
|
||||
import com.kazier.mobile.data.remote.dto.UsageDto
|
||||
import com.kazier.mobile.domain.DeviceIdentity
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Appareils + empreinte du compte (V3 S6 A1/A2).
|
||||
*
|
||||
* - `listDevices` : devices dont le dernier login est ce compte ;
|
||||
* `isCurrent` repère ce téléphone (via `DeviceIdentity`) — le bouton
|
||||
* révoquer n'apparaît jamais dessus (pas de suicide) ;
|
||||
* - `revoke` : `DELETE /devices/:id` (téléphone perdu) — avec
|
||||
* `EnforceDeviceExists`, ses tokens deviennent 401 ;
|
||||
* - `usage` : `GET /users/me/usage` (quota + corbeille détaillée).
|
||||
*/
|
||||
@Singleton
|
||||
class DevicesRepository @Inject constructor(
|
||||
private val apiClient: ApiClient,
|
||||
private val deviceIdentity: DeviceIdentity,
|
||||
) {
|
||||
|
||||
data class DeviceUi(
|
||||
val deviceId: String,
|
||||
val lastSeenAt: Long?,
|
||||
val isCurrent: Boolean,
|
||||
)
|
||||
|
||||
suspend fun listDevices(): List<DeviceUi> {
|
||||
val current = runCatching { deviceIdentity.getOrCreate() }.getOrNull()
|
||||
return apiClient.listDevices().map { dto: DeviceDto ->
|
||||
DeviceUi(
|
||||
deviceId = dto.deviceId,
|
||||
lastSeenAt = dto.lastSeenAt,
|
||||
isCurrent = current != null && dto.deviceId == current,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun revoke(deviceId: String) {
|
||||
apiClient.revokeDevice(deviceId)
|
||||
}
|
||||
|
||||
suspend fun usage(): UsageDto = apiClient.getUsage()
|
||||
}
|
||||
+10
-4
@@ -185,19 +185,25 @@ class OutboxRepository @Inject constructor(
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `update_metadata` — payload `{ name }` (rename d'une ressource
|
||||
* partagée, `editor+`, docs/api-v1.md §6.1). m21 : rend le rename partagé
|
||||
* émissible — l'op n'avait aucun écrivain côté client.
|
||||
* Raccourci `update_metadata` — payload `{ name, baseUpdatedAt? }`
|
||||
* (rename d'une ressource partagée, `editor+`, docs/api-v1.md §6.1).
|
||||
* `baseUpdatedAt` (ms epoch, V3 S6 A4) = `updated_at` vu par le client :
|
||||
* périmé au-delà de 2 s de tolérance → rename appliqué quand même (LWW)
|
||||
* mais signalé en `conflicts` (« renommé ailleurs »).
|
||||
*/
|
||||
suspend fun enqueueUpdateMetadata(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
name: String,
|
||||
baseUpdatedAt: Long? = null,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.UPDATE_METADATA,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = mapOf("name" to name),
|
||||
payload = buildMap {
|
||||
put("name", name)
|
||||
baseUpdatedAt?.let { put("baseUpdatedAt", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,4 +12,6 @@ object PrefKeys {
|
||||
const val PERMISSIONS_CACHED_AT = "permissions_cached_at"
|
||||
/** Règle de rétention locale V2-5 : `all` | `last_months:N`. */
|
||||
const val RETENTION_RULE = "retention_rule"
|
||||
/** Conflits de rename LWW (S6 A4) : JSON `[{operationId,…}]`, max 10. */
|
||||
const val SYNC_CONFLICTS = "sync_conflicts"
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.kazier.mobile.domain
|
||||
|
||||
import com.squareup.moshi.JsonAdapter
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.Types
|
||||
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
||||
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
/**
|
||||
* Conflit de rename LWW signalé par le serveur (V3 S6 A4) : un
|
||||
* `update_metadata` appliqué malgré une `baseUpdatedAt` périmée — « renommé
|
||||
* ailleurs », nom serveur gagnant. Persisté en `user_preferences`
|
||||
* (JSON, max 10, dédupliqué par `operationId`), exposé en [StateFlow] pour
|
||||
* la « liste des sync », effaçable en un tap.
|
||||
*/
|
||||
data class SyncConflict(
|
||||
val operationId: String,
|
||||
val resourceId: String,
|
||||
val serverName: String,
|
||||
val serverUpdatedAt: Long,
|
||||
val seenAt: Long,
|
||||
)
|
||||
|
||||
@Singleton
|
||||
class SyncConflictStore @Inject constructor(
|
||||
private val userPreferenceDao: UserPreferenceDao,
|
||||
moshi: Moshi,
|
||||
) {
|
||||
|
||||
private val adapter: JsonAdapter<List<SyncConflict>> = moshi.adapter(
|
||||
Types.newParameterizedType(List::class.java, SyncConflict::class.java),
|
||||
)
|
||||
|
||||
private val _conflicts = MutableStateFlow<List<SyncConflict>>(emptyList())
|
||||
val conflicts: StateFlow<List<SyncConflict>> = _conflicts.asStateFlow()
|
||||
|
||||
suspend fun load() {
|
||||
val raw = userPreferenceDao.getValue(PrefKeys.SYNC_CONFLICTS) ?: return
|
||||
_conflicts.value = runCatching { adapter.fromJson(raw).orEmpty() }.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
suspend fun addAll(incoming: List<SyncConflict>) {
|
||||
if (incoming.isEmpty()) return
|
||||
val merged = (incoming + _conflicts.value)
|
||||
.distinctBy { it.operationId }
|
||||
.take(MAX_CONFLICTS)
|
||||
_conflicts.value = merged
|
||||
persist(merged)
|
||||
}
|
||||
|
||||
suspend fun clear() {
|
||||
_conflicts.value = emptyList()
|
||||
userPreferenceDao.delete(PrefKeys.SYNC_CONFLICTS)
|
||||
}
|
||||
|
||||
private suspend fun persist(conflicts: List<SyncConflict>) {
|
||||
userPreferenceDao.upsert(
|
||||
UserPreferenceEntity(PrefKeys.SYNC_CONFLICTS, adapter.toJson(conflicts), System.currentTimeMillis()),
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MAX_CONFLICTS = 10
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,8 @@ 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.domain.SyncConflict
|
||||
import com.kazier.mobile.domain.SyncConflictStore
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpDto
|
||||
@@ -96,6 +98,7 @@ class OutboxSyncWorker @AssistedInject constructor(
|
||||
private val fileDao: FileDao,
|
||||
private val folderDao: FolderDao,
|
||||
private val tokenProvider: TokenProvider,
|
||||
private val conflictStore: SyncConflictStore,
|
||||
moshi: Moshi,
|
||||
) : CoroutineWorker(appContext, workerParams) {
|
||||
|
||||
@@ -151,6 +154,23 @@ class OutboxSyncWorker @AssistedInject constructor(
|
||||
}
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
// Conflits de rename LWW (S6 A4) : non-fataux, persistés pour la
|
||||
// « liste des sync » (« renommé ailleurs », nom serveur gagnant).
|
||||
result.conflicts.orEmpty().takeIf { it.isNotEmpty() }?.let { batchConflicts ->
|
||||
runCatching {
|
||||
conflictStore.addAll(
|
||||
batchConflicts.map {
|
||||
SyncConflict(
|
||||
operationId = it.operationId,
|
||||
resourceId = it.resourceId,
|
||||
serverName = it.serverName,
|
||||
serverUpdatedAt = it.serverUpdatedAt,
|
||||
seenAt = now,
|
||||
)
|
||||
},
|
||||
)
|
||||
}.onFailure { e -> Timber.w(e, "outbox: conflits non persistés") }
|
||||
}
|
||||
// Garde C7 : `applied` incohérent → clamp, jamais de crash.
|
||||
val appliedCount = result.applied.coerceIn(0, pending.size)
|
||||
if (appliedCount != result.applied) {
|
||||
|
||||
@@ -12,6 +12,8 @@ import com.kazier.mobile.data.repository.FolderRepository
|
||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||
import com.kazier.mobile.data.repository.ShareRepository
|
||||
import com.kazier.mobile.data.repository.TrashRepository
|
||||
import com.kazier.mobile.domain.SyncConflict
|
||||
import com.kazier.mobile.domain.SyncConflictStore
|
||||
import com.kazier.mobile.features.ocr.OcrAutoWorker
|
||||
import com.kazier.mobile.features.saf.FileDeleter
|
||||
import com.kazier.mobile.features.saf.FolderDeleter
|
||||
@@ -53,6 +55,7 @@ class SyncViewModel @Inject constructor(
|
||||
private val pendingOperationDao: PendingOperationDao,
|
||||
private val shareRepository: ShareRepository,
|
||||
private val trashRepository: TrashRepository,
|
||||
private val conflictStore: SyncConflictStore,
|
||||
private val fileDeleter: FileDeleter,
|
||||
private val folderDeleter: FolderDeleter,
|
||||
@ApplicationContext private val appContext: Context,
|
||||
@@ -75,6 +78,8 @@ class SyncViewModel @Inject constructor(
|
||||
val failed: Int = 0,
|
||||
/** Dernières opérations (tous statuts) — « liste des sync ». */
|
||||
val operations: List<PendingOperationEntity> = emptyList(),
|
||||
/** Renames LWW concurrents (S6 A4) — « renommé ailleurs ». */
|
||||
val conflicts: List<SyncConflict> = emptyList(),
|
||||
)
|
||||
|
||||
private val _importState = MutableStateFlow(ImportState())
|
||||
@@ -88,7 +93,8 @@ class SyncViewModel @Inject constructor(
|
||||
WorkManager.getInstance(appContext).getWorkInfosForUniqueWorkFlow(OutboxSyncWorker.NAME),
|
||||
pendingOperationDao.observePendingCount(),
|
||||
pendingOperationDao.observeRecent(RECENT_LIMIT),
|
||||
) { walking, workInfos, pending, operations ->
|
||||
conflictStore.conflicts,
|
||||
) { walking, workInfos, pending, operations, conflicts ->
|
||||
// RUNNING = drain en cours ; ENQUEUED = planifié (attente réseau/backoff).
|
||||
val draining = workInfos.any { it.state == WorkInfo.State.RUNNING || it.state == WorkInfo.State.ENQUEUED }
|
||||
SyncStatus(
|
||||
@@ -96,12 +102,22 @@ class SyncViewModel @Inject constructor(
|
||||
pending = pending,
|
||||
failed = operations.count { it.status == PendingOpStatus.FAILED },
|
||||
operations = operations,
|
||||
conflicts = conflicts,
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SyncStatus())
|
||||
|
||||
/** Efface les conflits affichés (lus et assumés). */
|
||||
fun clearConflicts() {
|
||||
viewModelScope.launch {
|
||||
runCatching { conflictStore.clear() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Démarre la boucle une seule fois (idempotent). */
|
||||
fun ensureStarted() {
|
||||
if (loopJob?.isActive == true) return
|
||||
// Conflits persistés (S6 A4) : chargés pour la « liste des sync ».
|
||||
viewModelScope.launch { runCatching { conflictStore.load() } }
|
||||
// Rétention auto V2-5 : passe quotidienne périodique (KEEP).
|
||||
RetentionWorker.enqueuePeriodic(appContext)
|
||||
loopJob = viewModelScope.launch {
|
||||
|
||||
@@ -175,6 +175,7 @@ fun HeaderStatusAction(
|
||||
SyncOperationsDialog(
|
||||
status = syncStatus,
|
||||
onDismiss = { showQueue = false },
|
||||
onClearConflicts = syncViewModel::clearConflicts,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+63
-1
@@ -27,6 +27,7 @@ import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||
import com.kazier.mobile.domain.SyncConflict
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
import com.kazier.mobile.ui.theme.ErrorDark
|
||||
import com.kazier.mobile.ui.theme.ErrorLight
|
||||
@@ -38,12 +39,14 @@ import com.kazier.mobile.ui.theme.SyncingLight
|
||||
|
||||
/**
|
||||
* Dialogue « liste des sync » : dernières opérations de l'outbox (tous statuts),
|
||||
* avec un résumé (en attente / échouées) en tête de liste.
|
||||
* avec un résumé (en attente / échouées) en tête de liste — plus les renames
|
||||
* concurrents LWW (S6 A4, « renommé ailleurs », effaçables).
|
||||
*/
|
||||
@Composable
|
||||
internal fun SyncOperationsDialog(
|
||||
status: SyncViewModel.SyncStatus,
|
||||
onDismiss: () -> Unit,
|
||||
onClearConflicts: () -> Unit = {},
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -51,6 +54,12 @@ internal fun SyncOperationsDialog(
|
||||
text = {
|
||||
Column {
|
||||
SyncListSummary(status)
|
||||
if (status.conflicts.isNotEmpty()) {
|
||||
ConflictsSection(
|
||||
conflicts = status.conflicts,
|
||||
onClear = onClearConflicts,
|
||||
)
|
||||
}
|
||||
if (status.operations.isEmpty()) {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_list_empty),
|
||||
@@ -158,4 +167,57 @@ private fun operationLabel(operation: String): String = when (operation) {
|
||||
"delete_resource" -> stringResource(R.string.sync_op_delete)
|
||||
"update_metadata" -> stringResource(R.string.sync_op_update)
|
||||
else -> operation
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames concurrents LWW (S6 A4) : nom serveur gagnant + effacement en un
|
||||
* tap (lus et assumés). La liste est courte (max 10, persistée).
|
||||
*/
|
||||
@Composable
|
||||
private fun ConflictsSection(
|
||||
conflicts: List<SyncConflict>,
|
||||
onClear: () -> Unit,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(bottom = 8.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_conflicts_title, conflicts.size),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onClear) {
|
||||
Text(stringResource(R.string.sync_conflicts_clear))
|
||||
}
|
||||
}
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = KazierDimens.DialogListMaxHeight / 2),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
items(conflicts, key = { it.operationId }) { conflict ->
|
||||
Column(modifier = Modifier.padding(vertical = 4.dp)) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.sync_conflict_renamed,
|
||||
conflict.serverName,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
Text(
|
||||
text = android.text.format.DateUtils
|
||||
.getRelativeTimeSpanString(conflict.serverUpdatedAt).toString(),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,14 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.DocumentScanner
|
||||
import androidx.compose.material.icons.filled.Group
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SmallFloatingActionButton
|
||||
import androidx.compose.material3.Text
|
||||
@@ -60,10 +63,15 @@ fun DashboardScreen(
|
||||
) {
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle()
|
||||
val groupCount by viewModel.groupCount.collectAsStateWithLifecycle()
|
||||
val creatingCircle by viewModel.creatingCircle.collectAsStateWithLifecycle()
|
||||
val syncStatus by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
||||
// Mode local : rien n'est poussé vers le serveur, la carte sync est inutile.
|
||||
val isLocal = connectionStatus == ServerConnectionStatus.Local
|
||||
val showSyncCard = !isLocal && (syncStatus.syncing || syncStatus.pending > 0 || syncStatus.failed > 0)
|
||||
// Onboarding foyer B5 : en ligne, aucun cercle → proposition « Famille ».
|
||||
val showFamilyCard = !isLocal &&
|
||||
connectionStatus == ServerConnectionStatus.Online && groupCount == 0
|
||||
|
||||
// Tirer-pour-actualiser = revérifier le serveur (review + file sont déjà
|
||||
// temps réel via les flows, il n'y a rien d'autre à recharger ici).
|
||||
@@ -131,6 +139,13 @@ fun DashboardScreen(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
if (showFamilyCard) {
|
||||
FamilyCircleCard(
|
||||
creating = creatingCircle,
|
||||
onCreate = { viewModel.createFamilyCircle(it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
if (showSyncCard) {
|
||||
SyncSummaryCard(
|
||||
status = syncStatus,
|
||||
@@ -229,3 +244,75 @@ private fun SyncSummaryCard(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Onboarding foyer B5 : aucun cercle et en ligne → proposition de créer le
|
||||
* cercle « Famille » en un tap (nom éditable, pré-rempli). Disparaît après
|
||||
* création (compteur rechargé) ou hors-ligne.
|
||||
*/
|
||||
@Composable
|
||||
private fun FamilyCircleCard(
|
||||
creating: Boolean,
|
||||
onCreate: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var name by rememberSaveable { mutableStateOf("") }
|
||||
// Pré-remplissage paresseux une fois (pas d'écrasement de la saisie).
|
||||
val defaultName = stringResource(R.string.family_default_name)
|
||||
LaunchedEffect(defaultName) {
|
||||
if (name.isBlank()) name = defaultName
|
||||
}
|
||||
KazierCard(modifier = modifier) {
|
||||
Column(
|
||||
modifier = Modifier.padding(20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Group,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.family_title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.family_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text(stringResource(R.string.family_name)) },
|
||||
singleLine = true,
|
||||
enabled = !creating,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Button(
|
||||
onClick = { onCreate(name.trim()) },
|
||||
enabled = !creating && name.trim().isNotEmpty(),
|
||||
) {
|
||||
if (creating) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp))
|
||||
} else {
|
||||
Text(stringResource(R.string.family_create))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,19 +2,61 @@ package com.kazier.mobile.ui.dashboard
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.repository.FileRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class DashboardViewModel @Inject constructor(
|
||||
fileRepository: FileRepository,
|
||||
private val apiClient: ApiClient,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Nombre de documents locaux restant à traiter (mode review). */
|
||||
val unprocessedCount: StateFlow<Int> = fileRepository.observeUnprocessedCount()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialValue = 0)
|
||||
|
||||
/**
|
||||
* Onboarding foyer B5 : nombre de groupes (cercles) du compte, NULL tant
|
||||
* que non chargé ou hors-ligne (best-effort — jamais bloquant, jamais
|
||||
* d'erreur visible : la carte s'affiche seulement si 0 avéré en ligne).
|
||||
*/
|
||||
private val _groupCount = MutableStateFlow<Int?>(null)
|
||||
val groupCount: StateFlow<Int?> = _groupCount.asStateFlow()
|
||||
|
||||
private val _creatingCircle = MutableStateFlow(false)
|
||||
val creatingCircle: StateFlow<Boolean> = _creatingCircle.asStateFlow()
|
||||
|
||||
init {
|
||||
refreshGroups()
|
||||
}
|
||||
|
||||
fun refreshGroups() {
|
||||
viewModelScope.launch {
|
||||
runCatching { apiClient.listGroups() }
|
||||
.onSuccess { groups -> _groupCount.update { groups.size } }
|
||||
.onFailure { e -> Timber.d("dashboard groups skipped: %s", e.message) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Crée le cercle « Famille » en un tap (puis recharge le compteur). */
|
||||
fun createFamilyCircle(name: String) {
|
||||
if (_creatingCircle.value) return
|
||||
viewModelScope.launch {
|
||||
_creatingCircle.value = true
|
||||
runCatching { apiClient.createGroup(name) }
|
||||
.onSuccess { refreshGroups() }
|
||||
.onFailure { e -> Timber.w(e, "dashboard create circle failed") }
|
||||
_creatingCircle.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package com.kazier.mobile.ui.devices
|
||||
|
||||
import android.text.format.DateUtils
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.repository.DevicesRepository
|
||||
import com.kazier.mobile.ui.components.formatFileSize
|
||||
|
||||
/**
|
||||
* Appareils du compte (V3 S6 A1) : ce téléphone repéré (« cet appareil »,
|
||||
* jamais révocable), les autres révocables après confirmation (téléphone
|
||||
* perdu — leurs tokens deviennent 401). Tête : quota utilisé.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DevicesScreen(
|
||||
onBack: () -> Unit,
|
||||
viewModel: DevicesViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
LaunchedEffect(state.error) {
|
||||
state.error?.let {
|
||||
snackbarHostState.showSnackbar(it)
|
||||
viewModel.clearError()
|
||||
}
|
||||
}
|
||||
var pendingRevoke by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
|
||||
pendingRevoke?.let { deviceId ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { pendingRevoke = null },
|
||||
title = { Text(stringResource(R.string.devices_revoke_confirm_title)) },
|
||||
text = { Text(stringResource(R.string.devices_revoke_confirm_message)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
pendingRevoke = null
|
||||
viewModel.revoke(deviceId)
|
||||
}) { Text(stringResource(R.string.devices_revoke_confirm)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingRevoke = null }) {
|
||||
Text(stringResource(R.string.delete_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.devices_title)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(R.string.back),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
state.usage?.let { usage ->
|
||||
item(key = "usage") {
|
||||
UsageCard(
|
||||
usedBytes = usage.usedBytes,
|
||||
quotaBytes = usage.quotaBytes,
|
||||
fileCount = usage.fileCount,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.isLoading && state.devices.isEmpty()) {
|
||||
item(key = "loading") {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
}
|
||||
items(state.devices, key = { it.deviceId }) { device ->
|
||||
DeviceRow(
|
||||
device = device,
|
||||
onRevoke = { pendingRevoke = device.deviceId },
|
||||
)
|
||||
}
|
||||
if (!state.isLoading && state.devices.isEmpty()) {
|
||||
item(key = "empty") {
|
||||
Text(
|
||||
text = stringResource(R.string.devices_empty),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth().padding(32.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun UsageCard(usedBytes: Long, quotaBytes: Long, fileCount: Int) {
|
||||
val fraction = if (quotaBytes > 0) (usedBytes.toFloat() / quotaBytes).coerceIn(0f, 1f) else 0f
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.devices_usage,
|
||||
formatFileSize(usedBytes),
|
||||
formatFileSize(quotaBytes),
|
||||
fileCount,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
LinearProgressIndicator(
|
||||
progress = { fraction },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeviceRow(
|
||||
device: DevicesRepository.DeviceUi,
|
||||
onRevoke: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.PhoneAndroid,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = if (device.isCurrent) {
|
||||
stringResource(R.string.devices_current)
|
||||
} else {
|
||||
stringResource(R.string.devices_other, device.deviceId.take(8))
|
||||
},
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
device.lastSeenAt?.let { seen ->
|
||||
Text(
|
||||
text = DateUtils.getRelativeTimeSpanString(seen).toString(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!device.isCurrent) {
|
||||
IconButton(onClick = onRevoke) {
|
||||
Icon(
|
||||
Icons.Filled.Delete,
|
||||
contentDescription = stringResource(R.string.devices_revoke),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.kazier.mobile.ui.devices
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.kazier.mobile.data.remote.dto.UsageDto
|
||||
import com.kazier.mobile.data.repository.DevicesRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import javax.inject.Inject
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
|
||||
/**
|
||||
* Appareils du compte + empreinte (V3 S6 A1/A2) : liste (ce téléphone
|
||||
* repéré, jamais révocable), révocation d'un device perdu (avec confirmation),
|
||||
* quota utilisé affiché en tête.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class DevicesViewModel @Inject constructor(
|
||||
private val devicesRepository: DevicesRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
data class DevicesUiState(
|
||||
val isLoading: Boolean = false,
|
||||
val devices: List<DevicesRepository.DeviceUi> = emptyList(),
|
||||
val usage: UsageDto? = null,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
private val _uiState = MutableStateFlow(DevicesUiState())
|
||||
val uiState: StateFlow<DevicesUiState> = _uiState.asStateFlow()
|
||||
|
||||
init {
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(isLoading = true, error = null) }
|
||||
val devices = runCatching { devicesRepository.listDevices() }
|
||||
val usage = runCatching { devicesRepository.usage() }
|
||||
devices.onFailure { e -> Timber.d("devices list failed: %s", e.message) }
|
||||
usage.onFailure { e -> Timber.d("usage failed: %s", e.message) }
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
isLoading = false,
|
||||
devices = devices.getOrDefault(emptyList()),
|
||||
usage = usage.getOrNull(),
|
||||
error = (devices.exceptionOrNull() ?: usage.exceptionOrNull())
|
||||
?.let { e -> e.message ?: e.javaClass.simpleName },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearError() {
|
||||
_uiState.update { it.copy(error = null) }
|
||||
}
|
||||
|
||||
/** Révoque un device perdu (jamais celui-ci — le bouton est masqué). */
|
||||
fun revoke(deviceId: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching { devicesRepository.revoke(deviceId) }
|
||||
.onSuccess { refresh() }
|
||||
.onFailure { e ->
|
||||
Timber.w(e, "devices revoke failed")
|
||||
_uiState.update { it.copy(error = e.message ?: e.javaClass.simpleName) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,6 +229,23 @@ fun FolderListScreen(
|
||||
syncViewModel.importRoot(uri = uri.toString(), name = rootName)
|
||||
}
|
||||
|
||||
// B1 : « classeur » unifié — le menu + accueille aussi l'ajout d'un
|
||||
// dossier surveillé (même importRoot que l'onboarding, sans la création
|
||||
// du sous-dossier « Kazier » réservée à la racine par défaut).
|
||||
val pickWatchLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocumentTree(),
|
||||
) { uri: Uri? ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
runCatching {
|
||||
context.contentResolver.takePersistableUriPermission(
|
||||
uri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
|
||||
)
|
||||
}.onFailure { Timber.w(it, "persistable permission absent on watch pick") }
|
||||
val rootName = uri.safDisplayName(context) ?: uri.lastPathSegment ?: folderLabel
|
||||
syncViewModel.importRoot(uri = uri.toString(), name = rootName)
|
||||
}
|
||||
|
||||
// Attend la création de la racine (importRoot la sauvegarde puis lance le
|
||||
// walk), crée le sous-dossier « Kazier » et l'enregistre comme racine.
|
||||
LaunchedEffect(pendingDefaultPick) {
|
||||
@@ -450,6 +467,14 @@ fun FolderListScreen(
|
||||
showNoteDialog = true
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.create_option_watch)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Folder, contentDescription = null) },
|
||||
onClick = {
|
||||
showCreateMenu = false
|
||||
pickWatchLauncher.launch(null)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ import com.kazier.mobile.ui.settings.SettingsScreen
|
||||
import com.kazier.mobile.ui.share.OpenLinkScreen
|
||||
import com.kazier.mobile.ui.trash.TrashScreen
|
||||
import com.kazier.mobile.ui.duplicates.DuplicatesScreen
|
||||
import com.kazier.mobile.ui.devices.DevicesScreen
|
||||
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersScreen
|
||||
|
||||
object Routes {
|
||||
@@ -42,6 +43,7 @@ object Routes {
|
||||
const val WATCHED_FOLDERS = "watched"
|
||||
const val TRASH = "trash"
|
||||
const val DUPLICATES = "duplicates"
|
||||
const val DEVICES = "devices"
|
||||
const val FOLDER_DETAIL = "folder/{folderResourceId}"
|
||||
const val ARG_FOLDER = "folderResourceId"
|
||||
const val DOCUMENT = "document/{documentResourceId}"
|
||||
@@ -152,6 +154,7 @@ fun NavGraph(
|
||||
onOpenWatchedFolders = onOpenWatchedFolders,
|
||||
onOpenTrash = { navController.navigate(Routes.TRASH) },
|
||||
onOpenDuplicates = { navController.navigate(Routes.DUPLICATES) },
|
||||
onOpenDevices = { navController.navigate(Routes.DEVICES) },
|
||||
authViewModel = authViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
syncViewModel = syncViewModel,
|
||||
@@ -195,6 +198,11 @@ fun NavGraph(
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Routes.DEVICES) {
|
||||
DevicesScreen(
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = Routes.FOLDER_DETAIL,
|
||||
arguments = listOf(
|
||||
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CloudOff
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.DarkMode
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
@@ -73,6 +74,7 @@ fun SettingsScreen(
|
||||
onOpenWatchedFolders: () -> Unit,
|
||||
onOpenTrash: () -> Unit,
|
||||
onOpenDuplicates: () -> Unit,
|
||||
onOpenDevices: () -> Unit,
|
||||
authViewModel: AuthViewModel,
|
||||
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||
syncViewModel: SyncViewModel,
|
||||
@@ -173,6 +175,14 @@ fun SettingsScreen(
|
||||
onClick = onOpenDuplicates,
|
||||
)
|
||||
|
||||
HorizontalDivider()
|
||||
SettingsRow(
|
||||
icon = { Icon(Icons.Filled.PhoneAndroid, contentDescription = null) },
|
||||
title = stringResource(R.string.devices_title),
|
||||
subtitle = stringResource(R.string.devices_hint),
|
||||
onClick = onOpenDevices,
|
||||
)
|
||||
|
||||
HorizontalDivider()
|
||||
SettingsRow(
|
||||
icon = { Icon(Icons.Filled.Dns, contentDescription = null) },
|
||||
|
||||
@@ -519,6 +519,13 @@ private fun LinksSection(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 2,
|
||||
)
|
||||
link.expiresAt?.let { expiry ->
|
||||
Text(
|
||||
text = stringResource(R.string.share_link_expires, expiry),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
OutlinedButton(onClick = {
|
||||
clipboard.setText(AnnotatedString(link.url))
|
||||
Toast.makeText(context, context.getString(R.string.share_link_copied), Toast.LENGTH_SHORT).show()
|
||||
|
||||
@@ -295,23 +295,30 @@ class ShareViewModel @Inject constructor(
|
||||
|
||||
/**
|
||||
* Crée un lien public (`create_link`, token 32-hex généré localement).
|
||||
* Le lien est exposé en [ShareUiState.lastCreatedLink] pour copie.
|
||||
* Expiration par défaut 7j (V3 S6 — un lien permanent est un RIB qui
|
||||
* traîne ; révocable à tout moment). Le lien est exposé en
|
||||
* [ShareUiState.lastCreatedLink] pour copie.
|
||||
*/
|
||||
fun createLink(resourceId: String, resourceType: String, access: String) {
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(actionError = null, lastCreatedLink = null) }
|
||||
val token = generateId.newResourceId()
|
||||
val expiresAt = System.currentTimeMillis() + LINK_DEFAULT_TTL_MS
|
||||
runCatching {
|
||||
outboxRepository.enqueueCreateLink(
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
token = token,
|
||||
access = access,
|
||||
expiresAt = expiresAt,
|
||||
)
|
||||
}.onSuccess {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
val expiryLabel = java.text.DateFormat
|
||||
.getDateInstance(java.text.DateFormat.SHORT)
|
||||
.format(java.util.Date(expiresAt))
|
||||
_uiState.update {
|
||||
it.copy(lastCreatedLink = ShareLinkUi(token, access, null, ShareLinkParser.shareUrl(token)))
|
||||
it.copy(lastCreatedLink = ShareLinkUi(token, access, expiryLabel, ShareLinkParser.shareUrl(token)))
|
||||
}
|
||||
refreshPending(resourceId)
|
||||
}.onFailure { e ->
|
||||
@@ -521,6 +528,11 @@ class ShareViewModel @Inject constructor(
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Expiration par défaut des liens créés : 7 jours (V3 S6). */
|
||||
const val LINK_DEFAULT_TTL_MS = 7L * 24 * 60 * 60 * 1000
|
||||
}
|
||||
}
|
||||
|
||||
/** Quadruplet local (pas de Tuple4 stdlib en Kotlin). */
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
<string name="new_folder_error">Could not create the folder.</string>
|
||||
<string name="create_option_scan">Scan a document</string>
|
||||
<string name="create_option_note">Add a note</string>
|
||||
<string name="create_option_watch">Watch a folder</string>
|
||||
<string name="create_option_title">Add</string>
|
||||
<string name="note_dialog_title">New note</string>
|
||||
<string name="note_title_label">Title</string>
|
||||
@@ -344,6 +345,7 @@
|
||||
<string name="share_link_created">Link created — copy it before closing.</string>
|
||||
<string name="share_link_copy">Copy</string>
|
||||
<string name="share_link_copied">Link copied.</string>
|
||||
<string name="share_link_expires">Expires %1$s (7 days by default).</string>
|
||||
<string name="share_link_revoke_confirm">Revoke this link? It will stop working.</string>
|
||||
<string name="share_open_link_hint">Paste a received link or token</string>
|
||||
<string name="share_open_link_button">Open</string>
|
||||
@@ -453,4 +455,25 @@
|
||||
<string name="collection_delete_title">Delete “%1$s”?</string>
|
||||
<string name="collection_delete_message">The collection disappears from this device.</string>
|
||||
<string name="collection_delete_confirm">Delete</string>
|
||||
<!-- Rename conflicts V3 S6 A4 -->
|
||||
<string name="sync_conflicts_title">Renamed elsewhere (%1$d)</string>
|
||||
<string name="sync_conflicts_clear">Clear</string>
|
||||
<string name="sync_conflict_renamed">“%1$s” (server name kept)</string>
|
||||
<!-- Devices V3 S6 A1 -->
|
||||
<string name="devices_title">Devices</string>
|
||||
<string name="devices_hint">View and revoke connected devices</string>
|
||||
<string name="devices_empty">No registered devices.</string>
|
||||
<string name="devices_current">This device</string>
|
||||
<string name="devices_other">Device %1$s…</string>
|
||||
<string name="devices_revoke">Revoke this device</string>
|
||||
<string name="devices_revoke_confirm_title">Revoke this device?</string>
|
||||
<string name="devices_revoke_confirm_message">Its sessions will be signed out and it must re-register.</string>
|
||||
<string name="devices_revoke_confirm">Revoke</string>
|
||||
<string name="devices_usage">%1$s / %2$s (%3$d files)</string>
|
||||
<!-- Family onboarding V3 S6 B5 -->
|
||||
<string name="family_title">Create your Family circle</string>
|
||||
<string name="family_hint">Share your papers with loved ones in one tap.</string>
|
||||
<string name="family_name">Circle name</string>
|
||||
<string name="family_default_name">Family</string>
|
||||
<string name="family_create">Create</string>
|
||||
</resources>
|
||||
@@ -43,6 +43,7 @@
|
||||
<string name="new_folder_error">Impossible de créer le dossier.</string>
|
||||
<string name="create_option_scan">Scanner un document</string>
|
||||
<string name="create_option_note">Ajouter une note</string>
|
||||
<string name="create_option_watch">Surveiller un dossier</string>
|
||||
<string name="create_option_title">Ajouter</string>
|
||||
<string name="note_dialog_title">Nouvelle note</string>
|
||||
<string name="note_title_label">Titre</string>
|
||||
@@ -345,6 +346,7 @@
|
||||
<string name="share_link_created">Lien créé — copiez-le avant de fermer.</string>
|
||||
<string name="share_link_copy">Copier</string>
|
||||
<string name="share_link_copied">Lien copié.</string>
|
||||
<string name="share_link_expires">Expire le %1$s (7 jours par défaut).</string>
|
||||
<string name="share_link_revoke_confirm">Révoquer ce lien ? Il ne fonctionnera plus.</string>
|
||||
<string name="share_open_link_hint">Collez un lien ou un token reçu</string>
|
||||
<string name="share_open_link_button">Ouvrir</string>
|
||||
@@ -454,4 +456,25 @@
|
||||
<string name="collection_delete_title">Supprimer « %1$s » ?</string>
|
||||
<string name="collection_delete_message">La collection disparaît de cet appareil.</string>
|
||||
<string name="collection_delete_confirm">Supprimer</string>
|
||||
<!-- Conflits rename V3 S6 A4 -->
|
||||
<string name="sync_conflicts_title">Renommés ailleurs (%1$d)</string>
|
||||
<string name="sync_conflicts_clear">Effacer</string>
|
||||
<string name="sync_conflict_renamed">« %1$s » (nom serveur conservé)</string>
|
||||
<!-- Appareils V3 S6 A1 -->
|
||||
<string name="devices_title">Appareils</string>
|
||||
<string name="devices_hint">Voir et révoquer les appareils connectés</string>
|
||||
<string name="devices_empty">Aucun appareil enregistré.</string>
|
||||
<string name="devices_current">Cet appareil</string>
|
||||
<string name="devices_other">Appareil %1$s…</string>
|
||||
<string name="devices_revoke">Révoquer cet appareil</string>
|
||||
<string name="devices_revoke_confirm_title">Révoquer cet appareil ?</string>
|
||||
<string name="devices_revoke_confirm_message">Ses sessions seront déconnectées et il devra se ré-enregistrer.</string>
|
||||
<string name="devices_revoke_confirm">Révoquer</string>
|
||||
<string name="devices_usage">%1$s / %2$s (%3$d fichiers)</string>
|
||||
<!-- Onboarding foyer V3 S6 B5 -->
|
||||
<string name="family_title">Crée ton cercle Famille</string>
|
||||
<string name="family_hint">Partage tes papiers avec tes proches en un tap.</string>
|
||||
<string name="family_name">Nom du cercle</string>
|
||||
<string name="family_default_name">Famille</string>
|
||||
<string name="family_create">Créer</string>
|
||||
</resources>
|
||||
@@ -357,6 +357,15 @@ class Auth401Test {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
@@ -231,6 +231,15 @@ class PaginationTest {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
@@ -159,6 +159,15 @@ class RemoteContentTest {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
|
||||
@@ -365,6 +365,15 @@ class SessionReloginTest {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
|
||||
@@ -198,6 +198,15 @@ class ShareManagementTest {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
|
||||
@@ -292,6 +292,15 @@ class BytesUploadTest {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
|
||||
+3
@@ -195,6 +195,9 @@ class FactsRepositoryTest {
|
||||
override suspend fun listRelations(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.RelationDto>>> = TODO()
|
||||
override suspend fun verdictRelation(fileId: String, body: com.kazier.mobile.data.remote.dto.RelationVerdictDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.RelationDto>>> = TODO()
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> = TODO()
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> = TODO()
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> = TODO()
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FileDto>>> = TODO()
|
||||
override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO()
|
||||
|
||||
+9
@@ -417,6 +417,15 @@ private class FolderMergeApiService : ApiService {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
+3
@@ -155,6 +155,9 @@ class LinksRepositoryTest {
|
||||
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> = TODO()
|
||||
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> = TODO()
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> = TODO()
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> = TODO()
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> = TODO()
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FileDto>>> = TODO()
|
||||
override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO()
|
||||
|
||||
+9
@@ -506,6 +506,15 @@ private class MoveProtectionApiService : ApiService {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
@@ -418,6 +418,15 @@ private class OcrApiServiceFake : ApiService {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
+9
@@ -300,6 +300,15 @@ class OfflineDownloadTest {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
|
||||
@@ -273,6 +273,15 @@ private class RefreshVsMoveApiService : ApiService {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
+9
@@ -527,6 +527,15 @@ private class FakeApiService : ApiService {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
Response.success(ApiEnvelope(data = com.kazier.mobile.data.remote.dto.UsageDto()))
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.kazier.mobile.domain
|
||||
|
||||
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 kotlinx.coroutines.flow.first
|
||||
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
|
||||
|
||||
/**
|
||||
* Conflits LWW (S6 A4) : persistance JSON (max 10, dédupliqués), rechargement,
|
||||
* effacement.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class SyncConflictStoreTest {
|
||||
|
||||
private lateinit var db: AppDatabase
|
||||
private lateinit var store: SyncConflictStore
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
store = SyncConflictStore(db.userPreferenceDao(), moshi)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ajout_persiste_et_recharge() = runTest {
|
||||
store.addAll(
|
||||
listOf(
|
||||
SyncConflict("op1", "res1", "v3.txt", 1000L, 2000L),
|
||||
SyncConflict("op2", "res2", "w.txt", 1000L, 2000L),
|
||||
),
|
||||
)
|
||||
assertEquals(2, store.conflicts.first().size)
|
||||
|
||||
// Nouveau store sur la même DB : recharge.
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
val reloaded = SyncConflictStore(db.userPreferenceDao(), moshi)
|
||||
reloaded.load()
|
||||
val list = reloaded.conflicts.first()
|
||||
assertEquals(2, list.size)
|
||||
assertEquals("v3.txt", list[0].serverName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dedupe_par_operation_et_plafond() = runTest {
|
||||
val many = (1..12).map { SyncConflict("op$it", "r$it", "n$it", 1L, 2L) }
|
||||
store.addAll(many)
|
||||
assertEquals(10, store.conflicts.first().size)
|
||||
|
||||
// Re-ajout du même : pas de doublon, ordre conservé (récents d'abord).
|
||||
store.addAll(listOf(SyncConflict("op1", "r1", "n1", 1L, 3L)))
|
||||
val list = store.conflicts.first()
|
||||
assertEquals(10, list.size)
|
||||
assertEquals("op1", list[0].operationId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun effacement() = runTest {
|
||||
store.addAll(listOf(SyncConflict("op1", "r1", "n", 1L, 2L)))
|
||||
store.clear()
|
||||
assertTrue(store.conflicts.first().isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -164,6 +164,9 @@ class ReleaseLocalCopyTest {
|
||||
override suspend fun listRelations(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.RelationDto>>> = TODO()
|
||||
override suspend fun verdictRelation(fileId: String, body: com.kazier.mobile.data.remote.dto.RelationVerdictDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.RelationDto>>> = TODO()
|
||||
override suspend fun listDuplicates(): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> = TODO()
|
||||
override suspend fun listDevices(): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> = TODO()
|
||||
override suspend fun revokeDevice(deviceId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
|
||||
override suspend fun getUsage(): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> = TODO()
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FileDto>>> = TODO()
|
||||
override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
|
||||
override suspend fun getShareLink(token: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO()
|
||||
|
||||
+43
-3
@@ -27,6 +27,8 @@ 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.SyncConflictDto
|
||||
import com.kazier.mobile.domain.SyncConflictStore
|
||||
import com.kazier.mobile.data.remote.dto.AddGroupMemberDto
|
||||
import com.kazier.mobile.data.remote.dto.CreateGroupDto
|
||||
import com.kazier.mobile.data.remote.dto.GroupDto
|
||||
@@ -95,6 +97,7 @@ class OutboxSyncWorkerTest {
|
||||
private lateinit var fake: FakeApiService
|
||||
private lateinit var apiClient: ApiClient
|
||||
private lateinit var tokenProvider: TokenProvider
|
||||
private lateinit var conflictStore: SyncConflictStore
|
||||
private lateinit var worker: OutboxSyncWorker
|
||||
|
||||
@Before
|
||||
@@ -114,9 +117,10 @@ class OutboxSyncWorkerTest {
|
||||
fake = FakeApiService()
|
||||
apiClient = ApiClient(fake, moshi)
|
||||
tokenProvider = TokenProvider().apply { current = "test-token" }
|
||||
conflictStore = SyncConflictStore(db.userPreferenceDao(), moshi)
|
||||
worker = OutboxSyncWorker(
|
||||
context, workerParams(), apiClient, opsDao, fileDao, folderDao,
|
||||
tokenProvider, moshi,
|
||||
tokenProvider, conflictStore, moshi,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -252,8 +256,7 @@ class OutboxSyncWorkerTest {
|
||||
assertEquals(0, opsDao.countPending())
|
||||
}
|
||||
|
||||
// --- C7 : gardes ----------------------------------------------------------
|
||||
@Test
|
||||
// --- C7 : gardes ---------------------------------------------------------- @Test
|
||||
fun failed_inconnu_pas_de_boucle() = runTest {
|
||||
insertOp(opId(1))
|
||||
insertOp(opId(2))
|
||||
@@ -376,6 +379,34 @@ class OutboxSyncWorkerTest {
|
||||
)
|
||||
}
|
||||
|
||||
// --- S6 A4 : conflits LWW persistés, batch non bloqué ---------------------
|
||||
|
||||
@Test
|
||||
fun conflits_rename_persites_sans_bloquer() = runTest {
|
||||
insertOp(opId(1))
|
||||
val conflict = SyncConflictDto(opId(1), resId(1), "v3.txt", 1_700_000_000_1000L)
|
||||
fake.syncOpsHandler = {
|
||||
Response.success(
|
||||
ApiEnvelope(
|
||||
data = com.kazier.mobile.data.remote.dto.SyncOpsResult(
|
||||
applied = 1,
|
||||
failed = null,
|
||||
conflicts = listOf(conflict),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val result = worker.doWork()
|
||||
|
||||
assertTrue(result is ListenableWorker.Result.Success)
|
||||
assertEquals(PendingOpStatus.SYNCED, opsDao.observeRecent(100).first().first().status)
|
||||
val stored = conflictStore.conflicts.first()
|
||||
assertEquals(1, stored.size)
|
||||
assertEquals(opId(1), stored[0].operationId)
|
||||
assertEquals("v3.txt", stored[0].serverName)
|
||||
}
|
||||
|
||||
// --- fixtures --------------------------------------------------------------
|
||||
|
||||
private suspend fun insertOp(
|
||||
@@ -522,6 +553,15 @@ class OutboxSyncWorkerTest {
|
||||
override suspend fun listDuplicates(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DuplicateGroupDto>>> =
|
||||
throw UnsupportedOperationException()
|
||||
|
||||
override suspend fun listDevices(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.DeviceDto>>> =
|
||||
throw UnsupportedOperationException()
|
||||
|
||||
override suspend fun revokeDevice(deviceId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> =
|
||||
throw UnsupportedOperationException()
|
||||
|
||||
override suspend fun getUsage(): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.UsageDto>> =
|
||||
throw UnsupportedOperationException()
|
||||
|
||||
override suspend fun searchFiles(
|
||||
query: String,
|
||||
page: Int?,
|
||||
|
||||
@@ -215,8 +215,88 @@ class SearchFieldTest {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* S6 facettes : la saisie émetteur filtre les résultats FTS après
|
||||
* debounce (triggers posés à la main — hors migration en in-memory).
|
||||
*/
|
||||
@Test
|
||||
fun facette_emetteur_filtre_les_resultats() = runTest {
|
||||
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
|
||||
try {
|
||||
val raw = db.openHelper.writableDatabase
|
||||
for (trigger in com.kazier.mobile.data.local.fts.FtsTriggers.TRIGGERS) {
|
||||
raw.execSQL(trigger)
|
||||
}
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(
|
||||
uri = "content://tree/a",
|
||||
name = "a.pdf",
|
||||
extension = "pdf",
|
||||
size = 10,
|
||||
mimeType = "application/pdf",
|
||||
resourceId = RESOURCE_A,
|
||||
processed = true,
|
||||
),
|
||||
folderResourceId = FOLDER,
|
||||
)
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(
|
||||
uri = "content://tree/b",
|
||||
name = "b.pdf",
|
||||
extension = "pdf",
|
||||
size = 10,
|
||||
mimeType = "application/pdf",
|
||||
resourceId = RESOURCE_B,
|
||||
processed = true,
|
||||
),
|
||||
folderResourceId = FOLDER,
|
||||
)
|
||||
db.fileDao().updateOcrText(RESOURCE_A, "facture EDF", 1L)
|
||||
db.fileDao().updateOcrText(RESOURCE_B, "facture ENGIE", 1L)
|
||||
db.factsDao().insertAll(
|
||||
listOf(
|
||||
com.kazier.mobile.data.local.entity.ResourceFact(
|
||||
resourceId = RESOURCE_A, factType = "issuer",
|
||||
valueText = "EDF", confidence = 0.9,
|
||||
origin = "auto", updatedAt = 1L,
|
||||
),
|
||||
com.kazier.mobile.data.local.entity.ResourceFact(
|
||||
resourceId = RESOURCE_B, factType = "issuer",
|
||||
valueText = "ENGIE", confidence = 0.9,
|
||||
origin = "auto", updatedAt = 1L,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val viewModel = newViewModel()
|
||||
backgroundScope.launch { viewModel.uiState.collect {} }
|
||||
viewModel.onQueryChange("facture")
|
||||
advanceTimeBy(400)
|
||||
withContext(Dispatchers.IO) {
|
||||
withTimeout(10_000) {
|
||||
viewModel.uiState.first { it.results.size == 2 }
|
||||
}
|
||||
}
|
||||
|
||||
viewModel.onIssuerChange("edf")
|
||||
advanceTimeBy(400)
|
||||
val filtered = withContext(Dispatchers.IO) {
|
||||
withTimeout(10_000) {
|
||||
viewModel.uiState.first {
|
||||
it.results.size == 1 && it.results[0].resourceId == RESOURCE_A
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(1, filtered.activeFacetCount)
|
||||
} finally {
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val FOLDER = "f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0"
|
||||
const val RESOURCE_ID = "aabbccddeeff11223344556677889900"
|
||||
const val RESOURCE_A = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
const val RESOURCE_B = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user