V2-2/V2-3 : download hors-ligne SAF + purge sûre (Room v18, DownloadWorker, release)

This commit is contained in:
venture
2026-09-25 19:27:08 +02:00
parent dd053a50c8
commit 0f90aad938
25 changed files with 1887 additions and 12 deletions
@@ -0,0 +1,754 @@
{
"formatVersion": 1,
"database": {
"version": 18,
"identityHash": "443cfaf8d993f1ce6f39b9b8ad67dd23",
"entities": [
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `exists` INTEGER, `parent_resource_id` TEXT, `owner_id` TEXT, `sync_status` TEXT NOT NULL, `created_in_app` INTEGER NOT NULL DEFAULT 0, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdInApp",
"columnName": "created_in_app",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_folders_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_folders_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "user_preferences",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`key`))",
"fields": [
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"key"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "files",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `folder_resource_id` TEXT NOT NULL, `extension` TEXT, `size` INTEGER NOT NULL, `mime_type` TEXT, `exists` INTEGER, `last_modified` INTEGER, `owner_id` TEXT, `category` TEXT, `sync_status` TEXT NOT NULL, `content` TEXT, `processed` INTEGER NOT NULL, `ocr_text` TEXT, `ocr_attempts` INTEGER NOT NULL, `ocr_queued_at` INTEGER, `bytes_uploaded` INTEGER NOT NULL, `bytes_upload_attempts` INTEGER NOT NULL, `has_content_server` INTEGER NOT NULL, `wanted_offline` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderResourceId",
"columnName": "folder_resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "extension",
"columnName": "extension",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "size",
"columnName": "size",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mimeType",
"columnName": "mime_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "exists",
"columnName": "exists",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "category",
"columnName": "category",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "syncStatus",
"columnName": "sync_status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "content",
"columnName": "content",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "processed",
"columnName": "processed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrText",
"columnName": "ocr_text",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ocrAttempts",
"columnName": "ocr_attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ocrQueuedAt",
"columnName": "ocr_queued_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "bytesUploaded",
"columnName": "bytes_uploaded",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "bytesUploadAttempts",
"columnName": "bytes_upload_attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasContentServer",
"columnName": "has_content_server",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "wantedOffline",
"columnName": "wanted_offline",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "added_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_files_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_files_uri",
"unique": true,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_uri` ON `${TABLE_NAME}` (`uri`)"
},
{
"name": "index_files_folder_resource_id",
"unique": false,
"columnNames": [
"folder_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_folder_resource_id` ON `${TABLE_NAME}` (`folder_resource_id`)"
},
{
"name": "index_files_category",
"unique": false,
"columnNames": [
"category"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_category` ON `${TABLE_NAME}` (`category`)"
},
{
"name": "index_files_exists_processed_sync_status",
"unique": false,
"columnNames": [
"exists",
"processed",
"sync_status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` ON `${TABLE_NAME}` (`exists`, `processed`, `sync_status`)"
}
],
"foreignKeys": []
},
{
"tableName": "pending_operations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_id` TEXT, `operation_id` TEXT NOT NULL, `ref_type` TEXT, `ref_id` INTEGER, `resource_id` TEXT, `resource_type` TEXT, `operation` TEXT NOT NULL, `payload` TEXT NOT NULL, `parent_resource_id` TEXT, `status` TEXT NOT NULL, `attempts` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "deviceId",
"columnName": "device_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operationId",
"columnName": "operation_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "refType",
"columnName": "ref_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "refId",
"columnName": "ref_id",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "operation",
"columnName": "operation",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "payload",
"columnName": "payload",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentResourceId",
"columnName": "parent_resource_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "attempts",
"columnName": "attempts",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_pending_operations_device_id_operation_id",
"unique": true,
"columnNames": [
"device_id",
"operation_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_pending_operations_device_id_operation_id` ON `${TABLE_NAME}` (`device_id`, `operation_id`)"
},
{
"name": "index_pending_operations_status",
"unique": false,
"columnNames": [
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_status` ON `${TABLE_NAME}` (`status`)"
},
{
"name": "index_pending_operations_resource_id",
"unique": false,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_pending_operations_resource_id_operation_status",
"unique": false,
"columnNames": [
"resource_id",
"operation",
"status"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` ON `${TABLE_NAME}` (`resource_id`, `operation`, `status`)"
},
{
"name": "index_pending_operations_parent_resource_id",
"unique": false,
"columnNames": [
"parent_resource_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_sessions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `root_folder_id` TEXT, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "rootFolderId",
"columnName": "root_folder_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_sessions_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_sessions_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
}
],
"foreignKeys": []
},
{
"tableName": "scan_pages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `session_id` INTEGER NOT NULL, `temp_uri` TEXT NOT NULL, `corners_json` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, FOREIGN KEY(`session_id`) REFERENCES `scan_sessions`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sessionId",
"columnName": "session_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "tempUri",
"columnName": "temp_uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cornersJson",
"columnName": "corners_json",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "width",
"columnName": "width",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "height",
"columnName": "height",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_scan_pages_resource_id",
"unique": true,
"columnNames": [
"resource_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_pages_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
},
{
"name": "index_scan_pages_session_id",
"unique": false,
"columnNames": [
"session_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_session_id` ON `${TABLE_NAME}` (`session_id`)"
},
{
"name": "index_scan_pages_sort_order",
"unique": false,
"columnNames": [
"sort_order"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_sort_order` ON `${TABLE_NAME}` (`sort_order`)"
}
],
"foreignKeys": [
{
"table": "scan_sessions",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"session_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "resource_permissions",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resource_id` TEXT NOT NULL, `resource_type` TEXT NOT NULL, `effective_access` TEXT NOT NULL, `owner_id` TEXT, `shared_by_id` TEXT, `expires_at` INTEGER, `cached_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`resource_id`))",
"fields": [
{
"fieldPath": "resourceId",
"columnName": "resource_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "resourceType",
"columnName": "resource_type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "effectiveAccess",
"columnName": "effective_access",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "ownerId",
"columnName": "owner_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "sharedById",
"columnName": "shared_by_id",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "expiresAt",
"columnName": "expires_at",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "cachedAt",
"columnName": "cached_at",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updatedAt",
"columnName": "updated_at",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"resource_id"
]
},
"indices": [
{
"name": "index_resource_permissions_expires_at",
"unique": false,
"columnNames": [
"expires_at"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` ON `${TABLE_NAME}` (`expires_at`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '443cfaf8d993f1ce6f39b9b8ad67dd23')"
]
}
}
@@ -33,6 +33,7 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity
* v15: backfill exists NULL→1 sur folders/files (M13).
* v16: table resource_permissions (cache snapshot, M27).
* v17: bytes_uploaded + bytes_upload_attempts sur files (upload V2).
* v18: has_content_server + wanted_offline sur files (download V2).
*/
@Database(
entities = [
@@ -40,7 +41,7 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
ResourcePermissionEntity::class,
],
version = 17,
version = 18,
// m19 : schéma exporté (`app/schemas/`) — toute dérive non migrée casse
// la compilation au lieu de briqueter les utilisateurs au démarrage.
exportSchema = true,
@@ -241,4 +241,70 @@ interface FileDao {
/** Échec terminal d'upload (4xx : trop gros, inconnu, rejeté). */
@Query("UPDATE files SET bytes_upload_attempts = bytes_upload_attempts + 1, updated_at = :now WHERE resource_id = :resourceId")
suspend fun markBytesUploadFailure(resourceId: String, now: Long)
/**
* Candidats download V2 : cloud-only (`uri` NULL) encore visibles, avec
* octets constatés serveur, dont le rapatriement a été demandé
* (`wanted_offline`, survit au reboot). Le worker efface `wanted_offline`
* au succès (ligne rattachée) ou sur 404 (+ `has_content_server = 0`).
*/
@Query("""
SELECT * FROM files
WHERE "exists" = 1
AND uri IS NULL
AND has_content_server = 1
AND wanted_offline = 1
ORDER BY updated_at ASC
""")
suspend fun getOfflineWantedCandidates(): List<FileEntity>
/** Demande (`wanted_offline = 1`) ou annule le rapatriement d'un fichier. */
@Query("UPDATE files SET wanted_offline = :wanted, updated_at = :now WHERE resource_id = :resourceId")
suspend fun setWantedOffline(resourceId: String, wanted: Boolean, now: Long)
/** Miroir serveur de `FileDto.hasContent` (convergé par refresh). */
@Query("UPDATE files SET has_content_server = :hasContent, updated_at = :now WHERE resource_id = :resourceId")
suspend fun setHasContentServer(resourceId: String, hasContent: Boolean, now: Long)
/**
* Rattachement post-download : la copie SAF devient la localisation de la
* ligne (même `resource_id`, pas de doublon). Le walk converge par `uri`
* (index unique) vers ce même dossier — pas de réimport. Demande soldée.
*/
@Query("""
UPDATE files
SET uri = :uri,
folder_resource_id = :folderId,
sync_status = 'local-cloud',
processed = 1,
"exists" = 1,
wanted_offline = 0,
size = :size,
updated_at = :now
WHERE resource_id = :resourceId
""")
suspend fun attachDownloaded(
resourceId: String,
uri: String,
folderId: String,
size: Long,
now: Long,
)
/**
* Détachement V2-3 (« libérer de l'espace ») : supprime la localisation
* SAF, la ligne redevient cloud-only (`uri` NULL) mais reste visible
* (`exists = 1`). Aucune op outbox — le serveur est inchangé (il garde
* les octets, d'où le gate `isReleasable` côté repository). Demande
* hors-ligne éventuelle soldée.
*/
@Query("""
UPDATE files
SET uri = NULL,
sync_status = 'cloud',
wanted_offline = 0,
updated_at = :now
WHERE resource_id = :resourceId
""")
suspend fun detachLocalCopy(resourceId: String, now: Long)
}
@@ -73,6 +73,20 @@ data class FileEntity(
/** Tentatives d'upload définitives (4xx) — cap 3, comme `ocr_attempts`. */
@ColumnInfo(name = "bytes_upload_attempts")
val bytesUploadAttempts: Int = 0,
/**
* V2-2 : miroir de `FileDto.hasContent` (octets vus présents serveur).
* Renseigné par `refreshFromServer` ; `FALSE` = jamais constatés, pas
* « certifié absent » (lazy healing côté serveur).
*/
@ColumnInfo(name = "has_content_server")
val hasContentServer: Boolean = false,
/**
* V2-2 : download demandé mais pas encore accompli (file du
* `DownloadWorker`, reprise après reboot). Le worker l'efface au succès
* (ligne rattachée) ou sur 404 (avec `has_content_server = 0`).
*/
@ColumnInfo(name = "wanted_offline")
val wantedOffline: Boolean = false,
@ColumnInfo(name = "added_at")
val addedAt: Long,
@ColumnInfo(name = "updated_at")
@@ -84,4 +98,13 @@ object FileStatus {
const val LOCAL = "local"
const val CLOUD = "cloud"
const val LOCAL_CLOUD = "local-cloud"
}
}
/**
* Purge sûre V2-3 : vrai si les octets locaux peuvent être supprimés sans
* risque de perte — une autre copie durable existe côté serveur
* (`has_content_server`, miroir) ou a été poussée par ce device
* (`bytes_uploaded`, vérité locale). Pure (testée sans Robolectric).
*/
fun FileEntity.isReleasable(): Boolean =
uri != null && exists != 0 && (hasContentServer || bytesUploaded == 1)
@@ -304,7 +304,19 @@ object Migrations {
}
}
/**
* V2-2 : download persistant — `has_content_server` (miroir serveur) +
* `wanted_offline` (download demandé, reprise après reboot). Défauts
* FALSE : rien n'est présumé rapatriable ni demandé.
*/
private val MIGRATION_17_18 = object : Migration(17, 18) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `files` ADD COLUMN `has_content_server` INTEGER NOT NULL DEFAULT 0")
db.execSQL("ALTER TABLE `files` ADD COLUMN `wanted_offline` INTEGER NOT NULL DEFAULT 0")
}
}
val ALL: Array<Migration> = arrayOf(
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17,
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18,
)
}
@@ -373,11 +373,32 @@ class FileRepository @Inject constructor(
// de l'uri / de régression du placement).
syncStatus = SyncPlacement.confirmed(existing?.uri != null),
processed = existing?.processed ?: false,
// V2-2 : miroir serveur (converge vers la vérité lue) ; intention
// locale préservée (le serveur ne la connaît pas).
hasContentServer = dto.hasContent,
wantedOffline = existing?.wantedOffline ?: false,
addedAt = existing?.addedAt ?: now,
updatedAt = now,
)
}
/**
* Demande le rapatriement hors-ligne d'un fichier cloud-only (V2-2) :
* pose `wanted_offline`, drainé par `DownloadWorker` (reprise reboot).
* Faux si la ligne est absente, déjà locale ou déjà demandée.
*/
suspend fun requestOffline(resourceId: String): Boolean {
val file = fileDao.getByResourceId(resourceId) ?: return false
if (file.uri != null || file.exists == 0 || file.wantedOffline) return false
fileDao.setWantedOffline(resourceId, true, System.currentTimeMillis())
return true
}
/** Détache la copie locale (Room seul — le SAF est supprimé par l'appelant). */
suspend fun detachLocalCopy(resourceId: String) {
fileDao.detachLocalCopy(resourceId, System.currentTimeMillis())
}
companion object {
private const val PAGE_SIZE = 50
private const val RECENT_LIMIT = 5
@@ -1,13 +1,22 @@
package com.kazier.mobile.data.repository
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.dao.FolderDao
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.preferences.DefaultRootStore
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.remote.safFilePart
import com.kazier.mobile.features.saf.SafUris
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@@ -28,6 +37,8 @@ import javax.inject.Singleton
class RemoteContentRepository @Inject constructor(
private val apiClient: ApiClient,
private val fileDao: FileDao,
private val folderDao: FolderDao,
private val defaultRootStore: DefaultRootStore,
@ApplicationContext private val context: Context,
) {
/** Octets du fichier, bornés ([ApiClient.MAX_CONTENT_BYTES]). */
@@ -65,6 +76,109 @@ class RemoteContentRepository @Inject constructor(
BytesUploadOutcome.Failed
}
}
suspend fun download(
file: FileEntity,
write: (suspend (folderUri: String, name: String, mime: String, bytes: ByteArray) -> String?)? = null,
): DownloadOutcome {
val now = System.currentTimeMillis()
// Cible : dossier propre s'il a une URI SAF, sinon racine par défaut.
// Aucun des deux → demande soldée (l'utilisateur retentera plus tard).
val target = resolveDownloadTarget(file)
if (target == null) {
fileDao.setWantedOffline(file.resourceId, false, now)
return DownloadOutcome.NoLocalFolder
}
val bytes = try {
apiClient.downloadContentBytes(file.resourceId)
} catch (e: ApiException) {
return when {
e.code == "NOT_FOUND" -> {
// Pas d'octets serveur : solder + converger le miroir.
fileDao.setWantedOffline(file.resourceId, false, now)
fileDao.setHasContentServer(file.resourceId, false, now)
DownloadOutcome.NoContent
}
e.code == "NETWORK_ERROR" || e.httpCode >= 500 -> DownloadOutcome.Retryable
e.httpCode == 401 -> DownloadOutcome.Unauthorized
else -> {
fileDao.setWantedOffline(file.resourceId, false, now)
DownloadOutcome.Failed
}
}
} catch (e: Exception) {
Timber.w(e, "download: unexpected fetch failure for %s", file.resourceId)
return DownloadOutcome.Retryable
}
val mime = file.mimeType?.takeIf { it.isNotBlank() } ?: "application/octet-stream"
val createdUri = try {
write?.invoke(target.uri, file.name, mime, bytes)
?: writeDownloadedBytes(target.uri, file.name, mime, bytes)
} catch (e: Exception) {
Timber.w(e, "download: write failed for %s", file.resourceId)
null
}
if (createdUri == null) return DownloadOutcome.Retryable
fileDao.attachDownloaded(file.resourceId, createdUri, target.folderId, bytes.size.toLong(), now)
return DownloadOutcome.Done
}
/** Dossier d'accueil SAF : dossier propre, sinon racine par défaut. */
private suspend fun resolveDownloadTarget(file: FileEntity): DownloadTarget? {
folderDao.getByResourceId(file.folderResourceId)?.uri?.let {
return DownloadTarget(it, file.folderResourceId)
}
val rootId = defaultRootStore.get() ?: return null
val rootUri = folderDao.getByResourceId(rootId)?.uri ?: return null
return DownloadTarget(rootUri, rootId)
}
/** Écriture SAF réelle : createDocument + copie + permission persistante. */
private suspend fun writeDownloadedBytes(
folderUri: String,
name: String,
mime: String,
bytes: ByteArray,
): String? = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val parent = SafUris.toDocumentUri(folderUri) ?: error("bad folder uri")
val created = DocumentsContract.createDocument(resolver, parent, mime, name)
?: error("cannot create document")
resolver.openOutputStream(created)?.use { it.write(bytes) }
?: error("cannot open output stream")
runCatching {
resolver.takePersistableUriPermission(
created,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
)
}
created.toString()
}.getOrNull()
}
private data class DownloadTarget(val uri: String, val folderId: String)
}
/** Résultat d'une passe de download V2 (un fichier max). */
sealed interface DownloadOutcome {
/** Rattaché : `uri` posée, `local-cloud`, demande soldée. */
data object Done : DownloadOutcome
/** Pas d'octets serveur : demande soldée, miroir convergé à 0. */
data object NoContent : DownloadOutcome
/** Aucun dossier SAF local (ni propre ni racine) : demande soldée. */
data object NoLocalFolder : DownloadOutcome
/** Erreur permanente (autre 4xx) : demande soldée. */
data object Failed : DownloadOutcome
/** Erreur transitoire : demande conservée, à retenter via backoff. */
data object Retryable : DownloadOutcome
/** Token expiré/révoqué : le re-login passera par l'UI. */
data object Unauthorized : DownloadOutcome
}
/** Résultat d'une passe d'upload V2 (un fichier max). */
@@ -81,3 +195,14 @@ sealed interface BytesUploadOutcome {
/** Token expiré/révoqué : le re-login passera par l'UI. */
data object Unauthorized : BytesUploadOutcome
}
/**
* Rapatrie durablement un fichier cloud-only vers SAF (V2-2) : octets
* téléchargés puis écrits comme nouveau document dans son dossier s'il a
* une URI SAF, sinon dans la racine par défaut. La ligne est rattachée
* (même `resource_id`, `local-cloud`, `processed`) — le walk converge par
* `uri` (index unique), pas de doublon ni de review.
*
* `write` est un seam de test : écrit les octets et retourne l'URI créée,
* ou null si l'écriture échoue. Null (défaut) = vraie écriture SAF.
*/
@@ -283,6 +283,10 @@ class ShareRepository @Inject constructor(
ownerId = perm.ownerId ?: existing?.ownerId,
syncStatus = SyncPlacement.confirmed(false),
processed = true,
// V2-2 : le snapshot ne dit rien des octets ni de l'intention
// locale — préserver, jamais écraser.
hasContentServer = existing?.hasContentServer ?: false,
wantedOffline = existing?.wantedOffline ?: false,
addedAt = existing?.addedAt ?: now,
updatedAt = now,
)
@@ -8,6 +8,7 @@ import androidx.room.withTransaction
import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus
import com.kazier.mobile.data.local.entity.isReleasable
import com.kazier.mobile.data.repository.FileRepository
import com.kazier.mobile.data.repository.OutboxRepository
import com.kazier.mobile.features.thumbnails.ThumbnailStore
@@ -179,7 +180,55 @@ class FileDeleter @Inject constructor(
return swept
}
/**
* Purge sûre V2-3 (« libérer de l'espace ») : supprime les octets SAF des
* fichiers dont une copie durable existe côté serveur (gate
* [FileRepository.isReleasable]), puis détache la ligne (cloud-only,
* toujours visible — contrairement à LOCALLY qui la fait disparaître).
* Aucune op outbox : le serveur est inchangé. `deleteDoc` est un seam de
* test (défaut = vrai `deleteDocument`).
*/
suspend fun releaseLocalCopies(
files: List<FileEntity>,
deleteDoc: (suspend (uri: String) -> Boolean)? = null,
): ReleaseReport {
var released = 0
var skipped = 0
var failed = 0
withContext(Dispatchers.IO) {
for (file in files) {
val uri = file.uri
if (!file.isReleasable() || uri == null) {
skipped++
} else {
val deleted = runCatching {
deleteDoc?.invoke(uri)
?: DocumentsContract.deleteDocument(resolver, Uri.parse(uri))
}.onFailure { e ->
Timber.w(e, "release: deleteDocument failed for %s", uri)
}.getOrDefault(false)
if (!deleted) {
failed++
} else {
fileRepository.detachLocalCopy(file.resourceId)
thumbnailStore.delete(file.resourceId)
released++
Timber.d("released local copy %s", uri)
}
}
}
}
return ReleaseReport(released, skipped, failed)
}
companion object {
private const val SWEEP_LIMIT = 50
}
}
/** Bilan d'une purge « libérer de l'espace » (fichiers). */
data class ReleaseReport(
val released: Int,
val skipped: Int,
val failed: Int,
)
@@ -0,0 +1,101 @@
package com.kazier.mobile.features.sync
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.kazier.mobile.auth.TokenProvider
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.repository.DownloadOutcome
import com.kazier.mobile.data.repository.RemoteContentRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.util.concurrent.TimeUnit
import timber.log.Timber
/**
* Download persistant V2, fichier par fichier : à chaque exécution, un seul
* fichier cloud-only demandé (`wanted_offline`, octets constatés serveur)
* est téléchargé puis écrit en SAF (dossier propre, sinon racine par
* défaut) et rattaché (même `resource_id`, `local-cloud`). Un seul run à la
* fois via `enqueueUniqueWork(KEEP)`, self-chain tant qu'il reste des
* candidats (même discipline que `BytesUploadWorker`).
*
* Erreurs :
* - **réseau / 5xx / écriture** → `Result.retry()` (backoff 30 s), demande
* conservée (reprise après reboot via `wanted_offline`) ;
* - **404** → demande soldée + miroir `has_content_server = 0` ;
* - **sans dossier SAF / autre 4xx** → demande soldée ;
* - **token expiré (401)** → `Result.success()` (re-login passera par l'UI).
*/
@HiltWorker
class DownloadWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val remoteContentRepository: RemoteContentRepository,
private val fileDao: FileDao,
private val tokenProvider: TokenProvider,
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
if (tokenProvider.current == null) return Result.success()
val file = fileDao.getOfflineWantedCandidates().firstOrNull()
?: return Result.success()
Timber.d("download: candidate %s (%s)", file.name, file.resourceId)
val outcome = try {
remoteContentRepository.download(file)
} catch (e: ApiException) {
when {
e.code == "NETWORK_ERROR" || e.httpCode >= 500 -> DownloadOutcome.Retryable
e.httpCode == 401 -> DownloadOutcome.Unauthorized
else -> DownloadOutcome.Failed
}
} catch (e: Exception) {
Timber.w(e, "download: unexpected failure for %s", file.resourceId)
DownloadOutcome.Retryable
}
when (outcome) {
is DownloadOutcome.Done ->
Timber.d("download: done %s", file.resourceId)
is DownloadOutcome.NoContent,
is DownloadOutcome.NoLocalFolder,
is DownloadOutcome.Failed ->
Timber.w("download: settled %s (%s)", file.resourceId, outcome)
is DownloadOutcome.Retryable -> return Result.retry()
is DownloadOutcome.Unauthorized -> return Result.success()
}
// Self-chain : une autre demande attend ?
val more = fileDao.getOfflineWantedCandidates().any { it.resourceId != file.resourceId }
if (more) {
enqueue(applicationContext)
}
return Result.success()
}
companion object {
const val NAME = "offline_download"
fun enqueue(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<DownloadWorker>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(NAME, ExistingWorkPolicy.KEEP, request)
}
}
}
@@ -25,6 +25,7 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material3.AlertDialog
@@ -195,6 +196,12 @@ fun DocumentViewerScreen(
viewModel.clearKeepMessage()
}
}
LaunchedEffect(viewerState.releaseMessage) {
viewerState.releaseMessage?.let {
snackbarHostState.showSnackbar(it)
viewModel.clearReleaseMessage()
}
}
// Confirmation avant suppression d'un document déjà traité.
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
@@ -317,6 +324,8 @@ fun DocumentViewerScreen(
pendingDeleteMode = mode
showDeleteConfirm = true
},
releasable = viewModel.isReleasable(current),
onRelease = { viewModel.release(current) },
onOcr = if (ocrCanRun || hasOcr) {
{
if (!hasOcr) ocrViewModel.run(current)
@@ -630,6 +639,8 @@ private fun DocumentActionBar(
onKeep: () -> Unit,
onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit,
onOcr: (() -> Unit)? = null,
releasable: Boolean = false,
onRelease: (() -> Unit)? = null,
modifier: Modifier = Modifier,
) {
val pendingReview = !file.processed && file.uri != null
@@ -685,6 +696,12 @@ private fun DocumentActionBar(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
if (onRelease != null && releasable) {
DocumentReleaseButton(
enabled = !busy,
onClick = onRelease,
)
}
if (onOcr != null) {
DocumentOcrButton(
label = if (file.ocrText != null) R.string.ocr_open else R.string.ocr_action,
@@ -703,6 +720,31 @@ private fun DocumentActionBar(
}
}
/** Bouton « Libérer » V2-3 — purge sûre (le serveur garde les octets). */
@Composable
private fun DocumentReleaseButton(
enabled: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
FilledTonalButton(
onClick = onClick,
enabled = enabled,
modifier = modifier,
) {
Icon(
imageVector = Icons.Filled.CloudOff,
contentDescription = null,
modifier = Modifier.size(20.dp),
)
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
Text(
text = stringResource(R.string.release_action),
maxLines = 1,
)
}
}
/** Bouton « OCR » M3 — gabarit adaptatif (plus de Surface 88×48 fixe). */
@Composable
private fun DocumentOcrButton(
@@ -6,6 +6,7 @@ import androidx.lifecycle.viewModelScope
import com.kazier.mobile.R
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus
import com.kazier.mobile.data.local.entity.isReleasable
import com.kazier.mobile.data.local.orderedByReferenceDateDesc
import com.kazier.mobile.data.repository.FileRepository
import com.kazier.mobile.features.saf.FileDeleter
@@ -40,6 +41,8 @@ class DocumentViewerViewModel @Inject constructor(
val deleteError: String? = null,
/** Succès transitoire « gardé » — affiché en Snackbar puis effacé. */
val keepMessage: String? = null,
/** Message transitoire de purge « libérer de l'espace ». */
val releaseMessage: String? = null,
)
private val _documents = MutableStateFlow<List<FileEntity>>(emptyList())
@@ -84,6 +87,30 @@ class DocumentViewerViewModel @Inject constructor(
}
}
/** Purge sûre V2-3 : libère la copie locale (le serveur garde les octets). */
fun release(file: FileEntity) {
_uiState.update { it.copy(busy = true) }
viewModelScope.launch {
val report = fileDeleter.releaseLocalCopies(listOf(file))
val message = when {
report.released > 0 ->
context.getString(R.string.release_done, report.released)
report.failed > 0 ->
context.getString(R.string.release_error)
else ->
context.getString(R.string.release_none)
}
_uiState.update { it.copy(releaseMessage = message) }
_uiState.update { it.copy(busy = false) }
}
}
fun isReleasable(file: FileEntity): Boolean = file.isReleasable()
fun clearReleaseMessage() {
_uiState.update { it.copy(releaseMessage = null) }
}
fun clearDeleteError() {
_uiState.update { it.copy(deleteError = null) }
}
@@ -1,9 +1,13 @@
package com.kazier.mobile.ui.document
import android.content.Context
import androidx.lifecycle.ViewModel
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.repository.FileRepository
import com.kazier.mobile.data.repository.RemoteContentRepository
import com.kazier.mobile.features.sync.DownloadWorker
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
/**
@@ -11,15 +15,28 @@ import javax.inject.Inject
*
* Stateless : [load] lit les octets via `GET /files/:id/content` sans les
* persister. Le composant appelant garde l'état (idle/loading/loaded/error).
*
* Rapatriement V2-2 ([requestOffline]) : pose `wanted_offline` et enchaîne
* `DownloadWorker` — la ligne rattachée (`uri` posée) fait basculer le viewer
* vers le contenu local automatiquement.
*/
@HiltViewModel
class RemoteContentViewModel @Inject constructor(
private val repository: RemoteContentRepository,
private val fileRepository: FileRepository,
@ApplicationContext private val appContext: Context,
) : ViewModel() {
suspend fun load(fileId: String): Result<ByteArray> =
runCatching { repository.fetch(fileId) }
/** Demande le rapatriement hors-ligne (faux si déjà local/demandé). */
suspend fun requestOffline(resourceId: String): Boolean {
val requested = fileRepository.requestOffline(resourceId)
if (requested) DownloadWorker.enqueue(appContext)
return requested
}
companion object {
/** Code quand le serveur n'a aucun octet (metadata-only jamais uploadé). */
fun isNoContent(e: Throwable): Boolean =
@@ -7,15 +7,19 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -68,6 +72,7 @@ fun RemoteDocumentViewer(
var loading by remember(file.resourceId) { mutableStateOf(false) }
var bytes by remember(file.resourceId) { mutableStateOf<ByteArray?>(null) }
var error by remember(file.resourceId) { mutableStateOf<Throwable?>(null) }
var offlineRequested by remember(file.resourceId) { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun reload() {
@@ -116,16 +121,24 @@ fun RemoteDocumentViewer(
started = true
reload()
},
onRequestOffline = {
scope.launch {
if (viewModel.requestOffline(file.resourceId)) offlineRequested = true
}
},
offlineRequested = offlineRequested,
modifier = modifier,
)
}
}
/** État initial : métadonnées + bouton de lecture à la demande (pas d'auto-load). */
/** État initial : métadonnées + lecture streaming ou rapatriement à la demande. */
@Composable
private fun RemoteContentGate(
file: FileEntity,
onLoad: () -> Unit,
onRequestOffline: () -> Unit,
offlineRequested: Boolean,
modifier: Modifier = Modifier,
) {
Column(
@@ -141,7 +154,10 @@ private fun RemoteContentGate(
)
Spacer(Modifier.height(8.dp))
Text(
text = stringResource(R.string.document_cloud_only_hint),
text = stringResource(
if (file.hasContentServer) R.string.document_cloud_only_hint
else R.string.document_stream_no_content_hint,
),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
@@ -150,6 +166,22 @@ private fun RemoteContentGate(
Button(onClick = onLoad) {
Text(stringResource(R.string.document_stream_load))
}
Spacer(Modifier.height(8.dp))
if (offlineRequested || file.wantedOffline) {
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(8.dp))
Text(
text = stringResource(R.string.document_offline_pending),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
OutlinedButton(onClick = onRequestOffline) {
Text(stringResource(R.string.document_offline_request))
}
}
}
}
@@ -145,6 +145,13 @@ fun FolderDetailScreen(
}
}
LaunchedEffect(uiState.releaseMessage) {
uiState.releaseMessage?.let {
snackbarHostState.showSnackbar(it)
viewModel.clearReleaseMessage()
}
}
LaunchedEffect(showMoveDialog) {
if (showMoveDialog) viewModel.loadMoveFolders()
}
@@ -235,8 +242,7 @@ fun FolderDetailScreen(
selection.clear()
onBuildPdf(ids)
},
onDeleteModeSelected = { mode ->
val files = uiState.files.filter { it.resourceId in selection.ids }
onDeleteModeSelected = { mode -> val files = uiState.files.filter { it.resourceId in selection.ids }
val review = reviewDelete(files, mode)
pendingDeleteMode = mode
pendingDeleteReview = review
@@ -247,6 +253,11 @@ fun FolderDetailScreen(
}
},
enabled = selection.ids.isNotEmpty(),
onRelease = {
viewModel.releaseSelectedFiles(selection.ids.toList())
selection.clear()
},
releaseEnabled = viewModel.countReleasable(selection.ids.toList()) > 0,
)
}
},
@@ -8,6 +8,7 @@ import com.kazier.mobile.R
import com.kazier.mobile.auth.TokenProvider
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FolderEntity
import com.kazier.mobile.data.local.entity.isReleasable
import com.kazier.mobile.data.repository.FileRepository
import com.kazier.mobile.data.repository.FolderRepository
import com.kazier.mobile.data.repository.SaveFolderInput
@@ -41,6 +42,8 @@ data class FolderDetailUiState(
val deleteError: String? = null,
/** Succès transitoire de suppression — affiché en Snackbar puis effacé. */
val deleteSuccess: Boolean = false,
/** Message transitoire de purge « libérer de l'espace » (Snackbar). */
val releaseMessage: String? = null,
/** Le dossier courant peut être partagé (connecté + possédé, cf. FolderList). */
val canShare: Boolean = false,
)
@@ -209,6 +212,32 @@ class FolderDetailViewModel @Inject constructor(
}
}
/** Purge sûre V2-3 : libère les copies locales dont le serveur a les octets. */
fun releaseSelectedFiles(resourceIds: List<String>) {
viewModelScope.launch {
val files = resourceIds.mapNotNull { fileRepository.getFile(it) }
if (files.isEmpty()) return@launch
val report = fileDeleter.releaseLocalCopies(files)
val message = when {
report.released > 0 ->
context.getString(R.string.release_done, report.released)
report.failed > 0 ->
context.getString(R.string.release_error)
else ->
context.getString(R.string.release_none)
}
_uiState.update { it.copy(releaseMessage = message) }
}
}
/** Nombre de fichiers sélectionnés purgeables (bouton libérer). */
fun countReleasable(resourceIds: List<String>): Int =
_uiState.value.files.count { it.resourceId in resourceIds && it.isReleasable() }
fun clearReleaseMessage() {
_uiState.update { it.copy(releaseMessage = null) }
}
fun clearDeleteError() {
_uiState.update { it.copy(deleteError = null) }
}
@@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.Dashboard
import androidx.compose.material.icons.filled.DriveFileMove
import androidx.compose.material.icons.filled.Folder
@@ -155,6 +156,9 @@ fun SelectionNavBar(
onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit,
enabled: Boolean,
modifier: Modifier = Modifier,
/** Purge sûre V2-3 (null = pas de bouton libérer sur cet écran). */
onRelease: (() -> Unit)? = null,
releaseEnabled: Boolean = false,
) {
FloatingPillContainer(modifier = modifier) {
SelectionAction(
@@ -171,6 +175,15 @@ fun SelectionNavBar(
onClick = onBuildPdf,
modifier = Modifier.weight(1f),
)
if (onRelease != null) {
SelectionAction(
label = stringResource(R.string.release_action),
icon = Icons.Filled.CloudOff,
enabled = enabled && releaseEnabled,
onClick = onRelease,
modifier = Modifier.weight(1f),
)
}
DeleteDropdownButton(
enabled = enabled,
onModeSelected = onDeleteModeSelected,
@@ -91,6 +91,13 @@
<string name="document_stream_no_content">No server content for this file.</string>
<string name="document_stream_too_large">File too large for streaming (max 12 MB).</string>
<string name="document_stream_unsupported">Streaming preview not supported for this file type.</string>
<string name="document_stream_no_content_hint">The server may have no content for this file — reading may fail.</string>
<string name="document_offline_request">Make available offline</string>
<string name="document_offline_pending">Downloading…</string>
<string name="release_action">Free up</string>
<string name="release_done">%1$d file(s) freed — server copy kept.</string>
<string name="release_none">Nothing to free — server copies missing.</string>
<string name="release_error">Could not free space.</string>
<string name="document_page_unreadable">Unreadable page</string>
<string name="focus_tap_to_exit">Tap to exit</string>
<string name="login_show_password">Show password</string>
@@ -91,6 +91,14 @@
<string name="document_stream_no_content">Aucun contenu sur le serveur pour ce fichier.</string>
<string name="document_stream_too_large">Fichier trop volumineux pour le streaming (max 12 Mo).</string>
<string name="document_stream_unsupported">Aperçu en streaming non supporté pour ce type de fichier.</string>
<string name="document_stream_no_content_hint">Le serveur n\'a peut-être aucun contenu pour ce fichier — la lecture peut échouer.</string>
<string name="document_offline_request">Rendre disponible hors-ligne</string>
<string name="document_offline_pending">Téléchargement en cours…</string>
<!-- Purge sûre V2-3 (libérer de l'espace) -->
<string name="release_action">Libérer</string>
<string name="release_done">%1$d fichier(s) libéré(s) — copie serveur conservée.</string>
<string name="release_none">Rien à libérer — copies serveur manquantes.</string>
<string name="release_error">Échec de la libération.</string>
<string name="document_page_unreadable">Page illisible</string>
<string name="focus_tap_to_exit">Toucher pour quitter</string>
<string name="login_show_password">Afficher le mot de passe</string>
@@ -0,0 +1,82 @@
package com.kazier.mobile.data.local.migration
import android.content.Context
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteOpenHelper
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import androidx.test.core.app.ApplicationProvider
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* V2-2 : la migration 17→18 ajoute `has_content_server` (miroir serveur) +
* `wanted_offline` (download demandé, reprise reboot) sur `files`.
* Défauts FALSE : rien n'est présumé rapatriable ni demandé.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class Migration17To18Test {
@Test
fun migration_ajoute_les_colonnes_avec_defaut_zero() {
val context = ApplicationProvider.getApplicationContext<Context>()
val helper = FrameworkSQLiteOpenHelperFactory().create(
SupportSQLiteOpenHelper.Configuration.builder(context)
.name(null)
.callback(V17Callback())
.build(),
)
val db = helper.writableDatabase
db.execSQL(
"INSERT INTO `files` (`resource_id`, `name`, `folder_resource_id`, `size`, `added_at`, `updated_at`) " +
"VALUES ('d-old', 'vieux.txt', 'f-one', 10, 1, 1)",
)
val migration = Migrations.ALL.first { it.startVersion == 17 && it.endVersion == 18 }
migration.migrate(db)
val columns = mutableListOf<String>()
db.query("PRAGMA table_info(`files`)").use { cursor ->
val nameIdx = cursor.getColumnIndexOrThrow("name")
while (cursor.moveToNext()) columns += cursor.getString(nameIdx)
}
assertTrue("colonne has_content_server manquante", columns.contains("has_content_server"))
assertTrue("colonne wanted_offline manquante", columns.contains("wanted_offline"))
db.query("SELECT `has_content_server`, `wanted_offline` FROM `files` WHERE `resource_id` = 'd-old'").use { cursor ->
assertTrue(cursor.moveToFirst())
assertEquals(0, cursor.getInt(0))
assertEquals(0, cursor.getInt(1))
}
helper.close()
}
/** Schéma v17 minimal de `files` (sans les colonnes V2-2). */
private class V17Callback : SupportSQLiteOpenHelper.Callback(17) {
override fun onCreate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE `files` (" +
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"`resource_id` TEXT NOT NULL, " +
"`uri` TEXT, " +
"`name` TEXT NOT NULL, " +
"`folder_resource_id` TEXT NOT NULL, " +
"`size` INTEGER NOT NULL, " +
"`bytes_uploaded` INTEGER NOT NULL DEFAULT 0, " +
"`bytes_upload_attempts` INTEGER NOT NULL DEFAULT 0, " +
"`added_at` INTEGER NOT NULL, " +
"`updated_at` INTEGER NOT NULL)",
)
}
override fun onUpgrade(
db: SupportSQLiteDatabase,
oldVersion: Int,
newVersion: Int,
) = Unit
}
}
@@ -10,6 +10,7 @@ import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus
import com.kazier.mobile.data.preferences.DefaultRootStore
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiException
import com.kazier.mobile.data.remote.ApiService
@@ -72,7 +73,10 @@ class BytesUploadTest {
.build()
fileDao = db.fileDao()
apiService = UploadFake()
repository = RemoteContentRepository(ApiClient(apiService, moshi()), fileDao, context)
repository = RemoteContentRepository(
ApiClient(apiService, moshi()), fileDao, db.folderDao(),
DefaultRootStore(context), context,
)
}
@After
@@ -0,0 +1,283 @@
package com.kazier.mobile.data.repository
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.dao.FileDao
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus
import com.kazier.mobile.data.local.entity.FolderEntity
import com.kazier.mobile.data.preferences.DefaultRootStore
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiService
import com.kazier.mobile.data.remote.dto.ApiEnvelope
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
import com.kazier.mobile.data.remote.dto.FileDto
import com.kazier.mobile.data.remote.dto.FileOcrDto
import com.kazier.mobile.data.remote.dto.FolderDto
import com.kazier.mobile.data.remote.dto.IdResultDto
import com.kazier.mobile.data.remote.dto.LoginRequestDto
import com.kazier.mobile.data.remote.dto.LoginResponseDto
import com.kazier.mobile.data.remote.dto.OcrJobDto
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
import com.kazier.mobile.data.remote.dto.ShareGrantDto
import com.kazier.mobile.data.remote.dto.ShareLinkDto
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
import com.kazier.mobile.data.remote.dto.SyncOpsResult
import kotlinx.coroutines.test.runTest
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import retrofit2.Response
/**
* Download persistant V2 : `RemoteContentRepository.download` rapatrie les
* octets vers SAF (dossier propre, sinon racine par défaut) et rattache la
* ligne (même `resource_id`, `local-cloud`). 404 → demande soldée + miroir
* convergé à 0 ; transitoire → demande conservée (reprise reboot).
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class OfflineDownloadTest {
private lateinit var context: Context
private lateinit var db: AppDatabase
private lateinit var fileDao: FileDao
private lateinit var fake: DownloadFake
private lateinit var repository: RemoteContentRepository
private lateinit var rootStore: DefaultRootStore
private val folderId = "f".repeat(32)
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
.allowMainThreadQueries()
.build()
fileDao = db.fileDao()
fake = DownloadFake()
rootStore = DefaultRootStore(context)
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
repository = RemoteContentRepository(
ApiClient(fake, moshi), fileDao, db.folderDao(), rootStore, context,
)
}
@After
fun tearDown() {
rootStore.clear()
db.close()
}
@Test
fun `download_succes_rattache_la_ligne_et_solde`() = runTest {
db.folderDao().upsert(folder(folderId, "content://tree/root"))
val file = insertCloudFile(folderId)
val outcome = repository.download(file) { _, _, _, _ -> "content://tree/root/doc1" }
assertTrue(outcome is DownloadOutcome.Done)
val stored = fileDao.getByResourceId(file.resourceId)!!
assertEquals("content://tree/root/doc1", stored.uri)
assertEquals(folderId, stored.folderResourceId)
assertEquals(FileStatus.LOCAL_CLOUD, stored.syncStatus)
assertTrue(stored.processed)
assertEquals(false, stored.wantedOffline)
assertEquals(1, stored.exists)
}
@Test
fun `download_replis_racine_par_defaut`() = runTest {
db.folderDao().upsert(folder("d".repeat(32), null))
val rootId = "e".repeat(32)
db.folderDao().upsert(folder(rootId, "content://tree/downloads"))
rootStore.set(rootId)
val file = insertCloudFile("d".repeat(32))
var usedFolderUri: String? = null
val outcome = repository.download(file) { folderUri, _, _, _ ->
usedFolderUri = folderUri
"content://tree/downloads/doc2"
}
assertTrue(outcome is DownloadOutcome.Done)
assertEquals("content://tree/downloads", usedFolderUri)
val stored = fileDao.getByResourceId(file.resourceId)!!
assertEquals(rootId, stored.folderResourceId)
}
@Test
fun `download_404_solde_et_converge_miroir`() = runTest {
db.folderDao().upsert(folder(folderId, "content://tree/root"))
fake.mode = DownloadFake.Mode.NOT_FOUND
val file = insertCloudFile(folderId, wanted = true)
val outcome = repository.download(file) { _, _, _, _ -> "content://x" }
assertTrue(outcome is DownloadOutcome.NoContent)
val stored = fileDao.getByResourceId(file.resourceId)!!
assertEquals(false, stored.wantedOffline)
assertEquals(false, stored.hasContentServer)
assertNull(stored.uri)
}
@Test
fun `download_reseau_conserve_la_demande`() = runTest {
db.folderDao().upsert(folder(folderId, "content://tree/root"))
fake.mode = DownloadFake.Mode.NETWORK
val file = insertCloudFile(folderId, wanted = true)
val outcome = repository.download(file) { _, _, _, _ -> "content://x" }
assertTrue(outcome is DownloadOutcome.Retryable)
assertEquals(true, fileDao.getByResourceId(file.resourceId)!!.wantedOffline)
}
@Test
fun `download_sans_dossier_local_solde`() = runTest {
db.folderDao().upsert(folder(folderId, null))
val file = insertCloudFile(folderId, wanted = true)
val outcome = repository.download(file) { _, _, _, _ -> "content://x" }
assertTrue(outcome is DownloadOutcome.NoLocalFolder)
assertEquals(false, fileDao.getByResourceId(file.resourceId)!!.wantedOffline)
}
@Test
fun `candidats_seulement_cloud_only_demandes_avec_contenu`() = runTest {
db.folderDao().upsert(folder(folderId, "content://tree/root"))
val wanted = insertCloudFile(folderId, wanted = true)
insertCloudFile(folderId, wanted = false)
insertCloudFile(folderId, wanted = true, hasContent = false)
val candidates = fileDao.getOfflineWantedCandidates()
assertEquals(listOf(wanted.resourceId), candidates.map { it.resourceId })
}
private suspend fun insertCloudFile(
folder: String,
wanted: Boolean = false,
hasContent: Boolean = true,
): FileEntity {
val file = FileEntity(
resourceId = generateResourceId(),
uri = null,
name = "shared.txt",
folderResourceId = folder,
size = 0L,
mimeType = "text/plain",
exists = 1,
syncStatus = FileStatus.CLOUD,
processed = true,
hasContentServer = hasContent,
wantedOffline = wanted,
addedAt = 1_700_000_000_000L,
updatedAt = 1_700_000_000_000L,
)
fileDao.upsert(file)
return file
}
private fun folder(resourceId: String, uri: String?) = FolderEntity(
resourceId = resourceId,
uri = uri,
name = "dossier",
addedAt = 1_700_000_000_000L,
updatedAt = 1_700_000_000_000L,
)
private var idSeq = 500L
private fun generateResourceId(): String {
val hex = (++idSeq).toString(16).padStart(32, '0')
return hex
}
private class DownloadFake : ApiService {
enum class Mode { SUCCESS, NOT_FOUND, NETWORK }
var mode = Mode.SUCCESS
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
Response.success(ApiEnvelope(data = body))
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> =
Response.success(ApiEnvelope())
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
Response.success(ApiEnvelope())
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
Response.success(ApiEnvelope())
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
Response.success(ApiEnvelope())
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
Response.success(ApiEnvelope())
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
Response.success(ApiEnvelope())
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
Response.success(ApiEnvelope())
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
Response.success(ApiEnvelope())
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
Response.success(ApiEnvelope())
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
Response.success(ApiEnvelope())
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = when (mode) {
Mode.SUCCESS -> Response.success("bytes-distant".toResponseBody("text/plain".toMediaType()))
Mode.NOT_FOUND -> Response.error(
404,
"{\"error\":{\"code\":\"NOT_FOUND\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType()),
)
Mode.NETWORK -> throw com.kazier.mobile.data.remote.ApiException("NETWORK_ERROR", "down", 0)
}
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
}
}
@@ -0,0 +1,162 @@
package com.kazier.mobile.features.saf
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.kazier.mobile.data.local.AppDatabase
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.local.entity.FileStatus
import com.kazier.mobile.data.local.entity.isReleasable
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiService
import com.kazier.mobile.data.repository.FileRepository
import com.kazier.mobile.data.repository.OutboxRepository
import com.kazier.mobile.domain.DeviceIdentity
import com.kazier.mobile.domain.GenerateId
import com.kazier.mobile.features.thumbnails.ThumbnailStore
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Purge sûre V2-3 : le gate `isReleasable` exige une copie serveur
* (`has_content_server` ou `bytes_uploaded`), le détachement rend la ligne
* cloud-only visible (jamais supprimée), sans aucune op outbox.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ReleaseLocalCopyTest {
private lateinit var context: Context
private lateinit var db: AppDatabase
private lateinit var fileRepository: FileRepository
private lateinit var fileDeleter: FileDeleter
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
.allowMainThreadQueries()
.build()
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val generateId = GenerateId()
val outbox = OutboxRepository(
db.pendingOperationDao(), generateId,
DeviceIdentity(db.userPreferenceDao(), generateId), moshi,
)
fileRepository = FileRepository(
db.fileDao(), db.folderDao(),
ApiClient(NoOpApiService, moshi), generateId, db, outbox,
)
fileDeleter = FileDeleter(
context, fileRepository, outbox, db, ThumbnailStore(context),
)
}
@After
fun tearDown() {
db.close()
}
@Test
fun gate_exige_copie_locale_et_copie_serveur() {
val base = file("a".repeat(32), uri = "content://x/1", hasContent = true)
assertTrue(base.isReleasable())
// Poussé par ce device : miroir inconnu mais vérité locale.
assertTrue(base.copy(hasContentServer = false, bytesUploaded = 1).isReleasable())
// Déjà cloud-only.
assertFalse(base.copy(uri = null).isReleasable())
// Masqué (exists = 0).
assertFalse(base.copy(exists = 0).isReleasable())
// Aucune copie serveur connue.
assertFalse(base.copy(hasContentServer = false, bytesUploaded = 0).isReleasable())
}
@Test
fun release_detache_sans_supprimer_la_ligne_ni_journaliser() = runTest {
val releasable = file("b".repeat(32), uri = "content://x/2", hasContent = true)
val unsafe = file("c".repeat(32), uri = "content://x/3", hasContent = false)
db.fileDao().upsert(releasable)
db.fileDao().upsert(unsafe)
var deletedUris = 0
val report = fileDeleter.releaseLocalCopies(listOf(releasable, unsafe)) {
deletedUris++
true
}
assertEquals(ReleaseReport(released = 1, skipped = 1, failed = 0), report)
assertEquals(1, deletedUris)
val stored = db.fileDao().getByResourceId(releasable.resourceId)!!
assertNull("uri détachée", stored.uri)
assertEquals(FileStatus.CLOUD, stored.syncStatus)
assertEquals("ligne toujours visible", 1, stored.exists)
// L'intouchable n'a même pas été tenté en SAF.
assertEquals("content://x/3", db.fileDao().getByResourceId(unsafe.resourceId)!!.uri)
// Aucune op outbox (purge purement locale).
assertEquals(0, db.pendingOperationDao().countPending())
}
@Test
fun release_echec_saf_laisse_la_ligne_intacte() = runTest {
val releasable = file("d".repeat(32), uri = "content://x/4", hasContent = true)
db.fileDao().upsert(releasable)
val report = fileDeleter.releaseLocalCopies(listOf(releasable)) { false }
assertEquals(ReleaseReport(released = 0, skipped = 0, failed = 1), report)
assertEquals("content://x/4", db.fileDao().getByResourceId(releasable.resourceId)!!.uri)
}
private fun file(
resourceId: String,
uri: String?,
hasContent: Boolean,
) = FileEntity(
resourceId = resourceId,
uri = uri,
name = "doc.txt",
folderResourceId = "f".repeat(32),
size = 100L,
mimeType = "text/plain",
exists = 1,
syncStatus = FileStatus.LOCAL_CLOUD,
processed = true,
hasContentServer = hasContent,
addedAt = 1_700_000_000_000L,
updatedAt = 1_700_000_000_000L,
)
/** Jamais appelé (purge sans réseau) — stub de compilation. */
private object NoOpApiService : ApiService {
override suspend fun listFolders(): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FolderDto>>> = TODO()
override suspend fun listFiles(folderId: 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 registerDevice(body: com.kazier.mobile.data.remote.dto.DeviceRegistrationDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.DeviceRegistrationDto>> = TODO()
override suspend fun login(body: com.kazier.mobile.data.remote.dto.LoginRequestDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.LoginResponseDto>> = TODO()
override suspend fun syncOps(body: com.kazier.mobile.data.remote.dto.SyncOpsRequest): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.SyncOpsResult>> = TODO()
override suspend fun resolveUser(username: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.ResolvedUserDto>> = TODO()
override suspend fun syncPermissions(after: Long?): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ResourcePermissionDto>>> = TODO()
override suspend fun uploadFile(file: okhttp3.MultipartBody.Part, resourceId: okhttp3.RequestBody?, folderId: okhttp3.RequestBody?): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun submitOcr(body: com.kazier.mobile.data.remote.dto.OcrSubmitDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.OcrJobDto>> = TODO()
override suspend fun getOcrJob(jobId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.OcrJobDto>> = TODO()
override suspend fun getFileOcr(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO()
override suspend fun getFile(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun deleteFile(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = 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()
override suspend fun downloadContent(fileId: String): retrofit2.Response<okhttp3.ResponseBody> = TODO()
override suspend fun listShares(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareGrantDto>>> = TODO()
override suspend fun listLinks(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareLinkDto>>> = TODO()
}
}