fix feedback bugs
CI / lint-backend (push) Successful in 1m27s
CI / lint-mobile (push) Successful in 10m24s
CI / test-backend (push) Successful in 1m33s
CI / test-mobile (push) Failing after 12m6s
CI / build-backend (push) Successful in 59s
CI / docker (push) Successful in 8s
CI / lint-backend (push) Successful in 1m27s
CI / lint-mobile (push) Successful in 10m24s
CI / test-backend (push) Successful in 1m33s
CI / test-mobile (push) Failing after 12m6s
CI / build-backend (push) Successful in 59s
CI / docker (push) Successful in 8s
This commit is contained in:
@@ -84,6 +84,11 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// m19 : export du schéma Room (`app/schemas/`) pour détecter les dérives en CI.
|
||||
ksp {
|
||||
arg("room.schemaLocation", "$projectDir/schemas")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
|
||||
@@ -0,0 +1,730 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 16,
|
||||
"identityHash": "ec10fdb23d5da3a76a73222e9c404561",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "folders",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `exists` INTEGER, `parent_resource_id` TEXT, `owner_id` TEXT, `sync_status` TEXT NOT NULL, `created_in_app` INTEGER NOT NULL DEFAULT 0, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "exists",
|
||||
"columnName": "exists",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "parentResourceId",
|
||||
"columnName": "parent_resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "owner_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "syncStatus",
|
||||
"columnName": "sync_status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdInApp",
|
||||
"columnName": "created_in_app",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "0"
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "added_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_folders_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_uri",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_parent_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"parent_resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "user_preferences",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`key`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "key",
|
||||
"columnName": "key",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "value",
|
||||
"columnName": "value",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"key"
|
||||
]
|
||||
},
|
||||
"indices": [],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "files",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `folder_resource_id` TEXT NOT NULL, `extension` TEXT, `size` INTEGER NOT NULL, `mime_type` TEXT, `exists` INTEGER, `last_modified` INTEGER, `owner_id` TEXT, `category` TEXT, `sync_status` TEXT NOT NULL, `content` TEXT, `processed` INTEGER NOT NULL, `ocr_text` TEXT, `ocr_attempts` INTEGER NOT NULL, `ocr_queued_at` INTEGER, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "folderResourceId",
|
||||
"columnName": "folder_resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "extension",
|
||||
"columnName": "extension",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "size",
|
||||
"columnName": "size",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "mimeType",
|
||||
"columnName": "mime_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "exists",
|
||||
"columnName": "exists",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastModified",
|
||||
"columnName": "last_modified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "owner_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "category",
|
||||
"columnName": "category",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "syncStatus",
|
||||
"columnName": "sync_status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "content",
|
||||
"columnName": "content",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "processed",
|
||||
"columnName": "processed",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ocrText",
|
||||
"columnName": "ocr_text",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "ocrAttempts",
|
||||
"columnName": "ocr_attempts",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ocrQueuedAt",
|
||||
"columnName": "ocr_queued_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "added_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_files_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_uri",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_folder_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"folder_resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_folder_resource_id` ON `${TABLE_NAME}` (`folder_resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_category",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"category"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_category` ON `${TABLE_NAME}` (`category`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_exists_processed_sync_status",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"exists",
|
||||
"processed",
|
||||
"sync_status"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` ON `${TABLE_NAME}` (`exists`, `processed`, `sync_status`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "pending_operations",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_id` TEXT, `operation_id` TEXT NOT NULL, `ref_type` TEXT, `ref_id` INTEGER, `resource_id` TEXT, `resource_type` TEXT, `operation` TEXT NOT NULL, `payload` TEXT NOT NULL, `parent_resource_id` TEXT, `status` TEXT NOT NULL, `attempts` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "deviceId",
|
||||
"columnName": "device_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "operationId",
|
||||
"columnName": "operation_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "refType",
|
||||
"columnName": "ref_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "refId",
|
||||
"columnName": "ref_id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceType",
|
||||
"columnName": "resource_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "operation",
|
||||
"columnName": "operation",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "payload",
|
||||
"columnName": "payload",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "parentResourceId",
|
||||
"columnName": "parent_resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "attempts",
|
||||
"columnName": "attempts",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "created_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_pending_operations_device_id_operation_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"device_id",
|
||||
"operation_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_pending_operations_device_id_operation_id` ON `${TABLE_NAME}` (`device_id`, `operation_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_status",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"status"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_status` ON `${TABLE_NAME}` (`status`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_resource_id_operation_status",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"resource_id",
|
||||
"operation",
|
||||
"status"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` ON `${TABLE_NAME}` (`resource_id`, `operation`, `status`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_parent_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"parent_resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "scan_sessions",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `root_folder_id` TEXT, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "rootFolderId",
|
||||
"columnName": "root_folder_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "created_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_scan_sessions_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_sessions_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "scan_pages",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `session_id` INTEGER NOT NULL, `temp_uri` TEXT NOT NULL, `corners_json` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, FOREIGN KEY(`session_id`) REFERENCES `scan_sessions`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sessionId",
|
||||
"columnName": "session_id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "tempUri",
|
||||
"columnName": "temp_uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "cornersJson",
|
||||
"columnName": "corners_json",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "width",
|
||||
"columnName": "width",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "height",
|
||||
"columnName": "height",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sortOrder",
|
||||
"columnName": "sort_order",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "created_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_scan_pages_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_pages_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_scan_pages_session_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"session_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_session_id` ON `${TABLE_NAME}` (`session_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_scan_pages_sort_order",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"sort_order"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_sort_order` ON `${TABLE_NAME}` (`sort_order`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "scan_sessions",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"session_id"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "resource_permissions",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resource_id` TEXT NOT NULL, `resource_type` TEXT NOT NULL, `effective_access` TEXT NOT NULL, `owner_id` TEXT, `shared_by_id` TEXT, `expires_at` INTEGER, `cached_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`resource_id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceType",
|
||||
"columnName": "resource_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "effectiveAccess",
|
||||
"columnName": "effective_access",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "owner_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "sharedById",
|
||||
"columnName": "shared_by_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "expiresAt",
|
||||
"columnName": "expires_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "cachedAt",
|
||||
"columnName": "cached_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_resource_permissions_expires_at",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"expires_at"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` ON `${TABLE_NAME}` (`expires_at`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
}
|
||||
],
|
||||
"views": [],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ec10fdb23d5da3a76a73222e9c404561')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,13 @@ import androidx.room.RoomDatabase
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
|
||||
import com.kazier.mobile.data.local.dao.ScanDao
|
||||
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||
import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
||||
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||
@@ -27,14 +29,20 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||
* operation_id) (contrat outbox docs/api-v1.md §6.1).
|
||||
* v13: index composites files(exists, processed, sync_status) et
|
||||
* pending_operations(resource_id, operation, status) (requêtes review/OCR/gates).
|
||||
* v14: parent_resource_id sur pending_operations (cascade P8).
|
||||
* v15: backfill exists NULL→1 sur folders/files (M13).
|
||||
* v16: table resource_permissions (cache snapshot, M27).
|
||||
*/
|
||||
@Database(
|
||||
entities = [
|
||||
FolderEntity::class, UserPreferenceEntity::class, FileEntity::class,
|
||||
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
|
||||
ResourcePermissionEntity::class,
|
||||
],
|
||||
version = 14,
|
||||
exportSchema = false,
|
||||
version = 16,
|
||||
// m19 : schéma exporté (`app/schemas/`) — toute dérive non migrée casse
|
||||
// la compilation au lieu de briqueter les utilisateurs au démarrage.
|
||||
exportSchema = true,
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
|
||||
@@ -43,4 +51,5 @@ abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun fileDao(): FileDao
|
||||
abstract fun pendingOperationDao(): PendingOperationDao
|
||||
abstract fun scanDao(): ScanDao
|
||||
abstract fun resourcePermissionDao(): ResourcePermissionDao
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.kazier.mobile.data.local
|
||||
|
||||
/**
|
||||
* Échappe les jokers `LIKE` (`%`, `_`) et l'échappement lui-même (`\`) dans
|
||||
* un fragment destiné à une requête `... LIKE ... ESCAPE '\'` (m5, m7).
|
||||
* Sans ça, un `%`/`_` saisi (recherche) ou présent (uris SAF encodées
|
||||
* `%3A…`) agit comme joker : match-all en recherche, sur-sélection au walk.
|
||||
*/
|
||||
internal fun String.escapeLike(): String =
|
||||
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
@@ -15,6 +15,12 @@ interface FileDao {
|
||||
@Query("SELECT * FROM files ORDER BY name ASC")
|
||||
suspend fun getAll(): List<FileEntity>
|
||||
|
||||
/**
|
||||
* Lignes sous une racine SAF (m5) — voir `FolderDao.getUnderRoot`.
|
||||
*/
|
||||
@Query("SELECT * FROM files WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
|
||||
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FileEntity>
|
||||
|
||||
/**
|
||||
* Repasse C4 : lignes déjà journalisées (`exists = 0`) dont les octets
|
||||
* sont peut-être encore sur le disque (journal-first, crash ou refus SAF
|
||||
@@ -39,10 +45,17 @@ interface FileDao {
|
||||
@Query("SELECT * FROM files WHERE uri = :uri LIMIT 1")
|
||||
suspend fun getByUri(uri: String): FileEntity?
|
||||
|
||||
/**
|
||||
* Recherche par nom (m7) : `:query` arrive déjà échappé (`escapeLike`,
|
||||
* `%`/`_` littéraux, pas des jokers) avec `ESCAPE '\'`. `COLLATE NOCASE`
|
||||
* sur l'opérande gauche pour une casse ASCII insensible explicite
|
||||
* (le repli Unicode « ete » → « ÉTÉ » demanderait une colonne normalisée,
|
||||
* hors scope — voir FEEDBACK).
|
||||
*/
|
||||
@Query("""
|
||||
SELECT * FROM files
|
||||
WHERE "exists" = 1
|
||||
AND (:query IS NULL OR name LIKE '%' || :query || '%')
|
||||
AND (:query IS NULL OR name COLLATE NOCASE LIKE '%' || :query || '%' ESCAPE '\')
|
||||
AND (:category IS NULL OR category = :category)
|
||||
ORDER BY name ASC
|
||||
""")
|
||||
|
||||
@@ -18,6 +18,14 @@ interface FolderDao {
|
||||
@Query("SELECT * FROM folders ORDER BY name ASC")
|
||||
suspend fun getAll(): List<FolderEntity>
|
||||
|
||||
/**
|
||||
* Lignes sous une racine SAF (m5) : le walk et sa réconciliation ne
|
||||
* scannent plus toute la table par racine. `:escapedRoot` est la racine
|
||||
* avec `%`, `_`, `\` échappés côté appelant (`ESCAPE '\'`).
|
||||
*/
|
||||
@Query("SELECT * FROM folders WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
|
||||
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FolderEntity>
|
||||
|
||||
/**
|
||||
* Repasse C4 (dossiers) : voir `FileDao.getMissingWithUri`. Un dossier
|
||||
* n'est re-supprimé physiquement que si toute sa descendance Room est
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.kazier.mobile.data.local.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Query
|
||||
import androidx.room.Upsert
|
||||
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||
|
||||
@Dao
|
||||
interface ResourcePermissionDao {
|
||||
|
||||
@Upsert
|
||||
suspend fun upsertAll(perms: List<ResourcePermissionEntity>)
|
||||
|
||||
@Query("SELECT * FROM resource_permissions WHERE resource_id = :resourceId LIMIT 1")
|
||||
suspend fun getByResourceId(resourceId: String): ResourcePermissionEntity?
|
||||
|
||||
/** Grants périmés à masquer localement (`expires_at` passé). */
|
||||
@Query("SELECT * FROM resource_permissions WHERE expires_at IS NOT NULL AND expires_at <= :now")
|
||||
suspend fun getExpired(now: Long): List<ResourcePermissionEntity>
|
||||
|
||||
/**
|
||||
* Convergence du pull complet : oublie les grants absents du snapshot
|
||||
* (révocation/expiration côté serveur).
|
||||
*/
|
||||
@Query("DELETE FROM resource_permissions WHERE resource_id NOT IN (:snapshotIds)")
|
||||
suspend fun deleteNotIn(snapshotIds: List<String>)
|
||||
|
||||
@Query("DELETE FROM resource_permissions")
|
||||
suspend fun clear()
|
||||
}
|
||||
@@ -42,8 +42,9 @@ data class FileEntity(
|
||||
val size: Long,
|
||||
@ColumnInfo(name = "mime_type")
|
||||
val mimeType: String? = null,
|
||||
// M13 : voir `FolderEntity.exists` — défaut 1, backfill en migration 14→15.
|
||||
@ColumnInfo(name = "exists")
|
||||
val exists: Int? = null,
|
||||
val exists: Int? = 1,
|
||||
@ColumnInfo(name = "last_modified")
|
||||
val lastModified: Long? = null,
|
||||
@ColumnInfo(name = "owner_id")
|
||||
|
||||
@@ -32,8 +32,11 @@ data class FolderEntity(
|
||||
val uri: String? = null,
|
||||
@ColumnInfo(name = "name")
|
||||
val name: String,
|
||||
// M13 : défaut 1 — une ligne sans `exists` explicite restait invisible
|
||||
// des requêtes `WHERE exists = 1`. La colonne reste nullable côté schéma
|
||||
// (pas de rewrite), le backfill NULL→1 est fait en migration 14→15.
|
||||
@ColumnInfo(name = "exists")
|
||||
val exists: Int? = null,
|
||||
val exists: Int? = 1,
|
||||
@ColumnInfo(name = "parent_resource_id")
|
||||
val parentResourceId: String? = null,
|
||||
@ColumnInfo(name = "owner_id")
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.kazier.mobile.data.local.entity
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Cache local du snapshot `GET /sync/permissions` (M27, docs/api-v1.md §6.2).
|
||||
*
|
||||
* Une ligne = la permission effective connue pour une ressource NON possédée
|
||||
* (les ressources `owner` ne sont pas stockées : l'ownership se résout depuis
|
||||
* les lignes `files`/`folders`). Fondement de [canAccess][com.kazier.mobile.data.repository.ShareRepository.canAccess]
|
||||
* sans réseau : rang effectif, expiration du grant et fraîcheur du snapshot
|
||||
* (TTL 24h → downgrade lecture seule).
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "resource_permissions",
|
||||
indices = [
|
||||
Index(value = ["expires_at"]),
|
||||
],
|
||||
)
|
||||
data class ResourcePermissionEntity(
|
||||
@PrimaryKey
|
||||
@ColumnInfo(name = "resource_id")
|
||||
val resourceId: String,
|
||||
@ColumnInfo(name = "resource_type")
|
||||
val resourceType: String,
|
||||
@ColumnInfo(name = "effective_access")
|
||||
val effectiveAccess: String,
|
||||
@ColumnInfo(name = "owner_id")
|
||||
val ownerId: String? = null,
|
||||
@ColumnInfo(name = "shared_by_id")
|
||||
val sharedById: String? = null,
|
||||
/** Fin du grant, ms epoch ; null = jamais. */
|
||||
@ColumnInfo(name = "expires_at")
|
||||
val expiresAt: Long? = null,
|
||||
/** Horodatage du snapshot serveur, ms epoch (TTL 24h). */
|
||||
@ColumnInfo(name = "cached_at")
|
||||
val cachedAt: Long,
|
||||
@ColumnInfo(name = "updated_at")
|
||||
val updatedAt: Long,
|
||||
)
|
||||
|
||||
/** Rangs d'accès effectif — `viewer < commenter < editor < owner`. */
|
||||
object AccessRank {
|
||||
const val VIEWER = "viewer"
|
||||
const val COMMENTER = "commenter"
|
||||
const val EDITOR = "editor"
|
||||
const val OWNER = "owner"
|
||||
|
||||
fun rank(access: String?): Int = when (access) {
|
||||
OWNER -> 4
|
||||
EDITOR -> 3
|
||||
COMMENTER -> 2
|
||||
VIEWER -> 1
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
+46
-1
@@ -33,6 +33,9 @@ import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
* v13 : index composites `files(exists, processed, sync_status)` (review +
|
||||
* candidats OCR auto) et `pending_operations(resource_id, operation, status)`
|
||||
* (gates outbox create/move) — requêtes à chaud sans full-table scan.
|
||||
* v14 : colonne `parent_resource_id` sur `pending_operations` (cascade P8).
|
||||
* v15 : backfill `exists` NULL→1 sur `folders`/`files` (M13) + défaut Kotlin 1.
|
||||
* v16 : table `resource_permissions` (cache snapshot, M27) + index `expires_at`.
|
||||
*/
|
||||
object Migrations {
|
||||
|
||||
@@ -246,7 +249,49 @@ object Migrations {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* M13 : backfill `exists` NULL→1 sur `folders` et `files`. Les lignes
|
||||
* insérées sans `exists` explicite (défaut Kotlin `null` avant ce fix)
|
||||
* étaient invisibles des requêtes `WHERE exists = 1` — elles
|
||||
* réapparaissent comme présentes, état le plus sûr (le walk les
|
||||
* re-marque `exists = 0` si elles ont vraiment disparu).
|
||||
*/
|
||||
private val MIGRATION_14_15 = object : Migration(14, 15) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("UPDATE `folders` SET `exists` = 1 WHERE `exists` IS NULL")
|
||||
db.execSQL("UPDATE `files` SET `exists` = 1 WHERE `exists` IS NULL")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* M27 : cache du snapshot permissions — table `resource_permissions`
|
||||
* (rang effectif + expiration + fraîcheur, fondement de `canAccess`).
|
||||
*/
|
||||
private val MIGRATION_15_16 = object : Migration(15, 16) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS `resource_permissions` (
|
||||
`resource_id` TEXT NOT NULL,
|
||||
`resource_type` TEXT NOT NULL,
|
||||
`effective_access` TEXT NOT NULL,
|
||||
`owner_id` TEXT,
|
||||
`shared_by_id` TEXT,
|
||||
`expires_at` INTEGER,
|
||||
`cached_at` INTEGER NOT NULL,
|
||||
`updated_at` INTEGER NOT NULL,
|
||||
PRIMARY KEY(`resource_id`)
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL(
|
||||
"CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` " +
|
||||
"ON `resource_permissions` (`expires_at`)",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val ALL: Array<Migration> = arrayOf(
|
||||
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14,
|
||||
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,
|
||||
)
|
||||
}
|
||||
@@ -140,15 +140,19 @@ data class SyncFailedDto(
|
||||
@Json(name = "message") val message: String,
|
||||
)
|
||||
|
||||
/** Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2). */
|
||||
/**
|
||||
* Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2, miroir de
|
||||
* `ResourcePermission` Go : `sharedById *string`, `expiresAt *int64` ms epoch).
|
||||
* M27 : typés (fini les `Any?` jamais lus) — lus par le cache et `canAccess`.
|
||||
*/
|
||||
data class ResourcePermissionDto(
|
||||
@Json(name = "resource_id") val resourceId: String,
|
||||
@Json(name = "resourceType") val resourceType: String,
|
||||
@Json(name = "effectiveAccess") val effectiveAccess: String,
|
||||
@Json(name = "inherit") val inherit: Boolean,
|
||||
@Json(name = "ownerId") val ownerId: String? = null,
|
||||
@Json(name = "sharedById") val sharedById: Any? = null,
|
||||
@Json(name = "expiresAt") val expiresAt: Any? = null,
|
||||
@Json(name = "sharedById") val sharedById: String? = null,
|
||||
@Json(name = "expiresAt") val expiresAt: Long? = null,
|
||||
@Json(name = "cachedAt") val cachedAt: Long,
|
||||
@Json(name = "updatedAt") val updatedAt: Long,
|
||||
@Json(name = "name") val name: String = "",
|
||||
|
||||
+10
-2
@@ -2,6 +2,7 @@ package com.kazier.mobile.data.repository
|
||||
|
||||
import androidx.room.withTransaction
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.escapeLike
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
@@ -46,10 +47,13 @@ class FileRepository @Inject constructor(
|
||||
/** Fichiers visibles de toute l'arborescence — écran d'accueil (grille par date). */
|
||||
fun observeAllVisible(): Flow<List<FileEntity>> = fileDao.observeAllVisible()
|
||||
|
||||
/** Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel). */
|
||||
/**
|
||||
* Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel).
|
||||
* m7 : la saisie est échappée (`%`/`_` littéraux, pas des jokers).
|
||||
*/
|
||||
fun searchFiles(query: String?, category: String?): Flow<List<FileEntity>> =
|
||||
fileDao.searchWithFilters(
|
||||
query = query?.trim()?.takeIf { it.isNotEmpty() },
|
||||
query = query?.trim()?.takeIf { it.isNotEmpty() }?.escapeLike(),
|
||||
category = category,
|
||||
)
|
||||
|
||||
@@ -171,6 +175,10 @@ class FileRepository @Inject constructor(
|
||||
|
||||
suspend fun getAll(): List<FileEntity> = fileDao.getAll()
|
||||
|
||||
/** Lignes sous une racine SAF (m5) — voir `FolderRepository.getUnderRoot`. */
|
||||
suspend fun getUnderRoot(rootUri: String): List<FileEntity> =
|
||||
fileDao.getUnderRoot(rootUri, rootUri.escapeLike())
|
||||
|
||||
/**
|
||||
* Upsert local d'un fichier SAF — miroir de `saveFile()` JS : déduplication
|
||||
* par `resource_id` ou `uri`, conservation de l'identité/sync_status/owner.
|
||||
|
||||
+13
-2
@@ -2,6 +2,7 @@ package com.kazier.mobile.data.repository
|
||||
|
||||
import androidx.room.withTransaction
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.escapeLike
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||
import com.kazier.mobile.data.local.entity.FolderStatus
|
||||
@@ -44,6 +45,13 @@ class FolderRepository @Inject constructor(
|
||||
|
||||
suspend fun getAll(): List<FolderEntity> = folderDao.getAll()
|
||||
|
||||
/**
|
||||
* Lignes sous une racine SAF (m5) : la racine est échappée pour le `LIKE`
|
||||
* (les uris SAF contiennent des `%` d'encodage et parfois des `_`).
|
||||
*/
|
||||
suspend fun getUnderRoot(rootUri: String): List<FolderEntity> =
|
||||
folderDao.getUnderRoot(rootUri, rootUri.escapeLike())
|
||||
|
||||
/** Snapshot des sous-dossiers visibles d'un dossier (opérations batch hors UI). */
|
||||
suspend fun getChildren(parentResourceId: String): List<FolderEntity> =
|
||||
folderDao.getByParentOnce(parentResourceId)
|
||||
@@ -83,7 +91,8 @@ class FolderRepository @Inject constructor(
|
||||
resourceId = dto.id,
|
||||
uri = existing?.uri,
|
||||
name = dto.name,
|
||||
exists = existing?.exists,
|
||||
// M13 : une ligne serveur nouvelle n'a pas d'`exists` local — 1 par défaut.
|
||||
exists = existing?.exists ?: 1,
|
||||
parentResourceId = dto.parentId,
|
||||
ownerId = existing?.ownerId,
|
||||
// Le snapshot serveur confirme la présence cloud : si une copie
|
||||
@@ -144,7 +153,9 @@ class FolderRepository @Inject constructor(
|
||||
resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(),
|
||||
uri = input.uri,
|
||||
name = input.name,
|
||||
exists = input.exists?.let { if (it) 1 else 0 },
|
||||
// M13 : `null` (défaut de `SaveFolderInput`) = présent, jamais NULL
|
||||
// en base — sinon la ligne disparaît des requêtes `exists = 1`.
|
||||
exists = if (input.exists != false) 1 else 0,
|
||||
parentResourceId = effectiveParent,
|
||||
// `owner_id` Room = user_id du compte actif, jamais l'identité device.
|
||||
ownerId = ownerId ?: existing?.ownerId ?: activeUserStore.get(),
|
||||
|
||||
@@ -62,12 +62,27 @@ class OcrRepository @Inject constructor(
|
||||
/**
|
||||
* Poll toutes les 3 s (docs §5) jusqu'à l'état terminal. [onProgress] est
|
||||
* appelé à chaque réponse du serveur (état courant exposé à l'UI).
|
||||
*
|
||||
* m20 : borné (deadline + nombre max de polls) — un job resté `processing`
|
||||
* (stale claim serveur) levait sinon une coroutine tenue indéfiniment.
|
||||
* Le timeout remonte en `ApiException("OCR_TIMEOUT")`, géré comme échec
|
||||
* par les appelants (`processAuto` → `Failed`, viewer → message d'erreur).
|
||||
*/
|
||||
suspend fun poll(jobId: String, onProgress: (OcrJobDto) -> Unit = {}): OcrJobDto {
|
||||
suspend fun poll(
|
||||
jobId: String,
|
||||
timeoutMs: Long = POLL_TIMEOUT_MS,
|
||||
onProgress: (OcrJobDto) -> Unit = {},
|
||||
): OcrJobDto {
|
||||
val deadline = System.currentTimeMillis() + timeoutMs
|
||||
var polls = 0
|
||||
while (true) {
|
||||
val job = apiClient.getOcrJob(jobId)
|
||||
onProgress(job)
|
||||
if (job.status in OcrJobStatus.TERMINAL) return job
|
||||
polls++
|
||||
if (polls >= POLL_MAX_ATTEMPTS || System.currentTimeMillis() >= deadline) {
|
||||
throw ApiException("OCR_TIMEOUT", "OCR sans réponse (job $jobId)", 0)
|
||||
}
|
||||
delay(POLL_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
@@ -144,6 +159,9 @@ class OcrRepository @Inject constructor(
|
||||
|
||||
companion object {
|
||||
const val POLL_INTERVAL_MS = 3_000L
|
||||
/** Timeout du poll (m20) : 10 min ≈ 200 polls × 3 s. */
|
||||
const val POLL_TIMEOUT_MS = 10 * 60 * 1_000L
|
||||
const val POLL_MAX_ATTEMPTS = 200
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,6 +146,79 @@ class OutboxRepository @Inject constructor(
|
||||
payload = mapOf("granteeUserId" to granteeUserId),
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `update_metadata` — payload `{ name }` (rename d'une ressource
|
||||
* partagée, `editor+`, docs/api-v1.md §6.1). m21 : rend le rename partagé
|
||||
* émissible — l'op n'avait aucun écrivain côté client.
|
||||
*/
|
||||
suspend fun enqueueUpdateMetadata(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
name: String,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.UPDATE_METADATA,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = mapOf("name" to name),
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `update_share` — même payload que `share` (m21 : update d'un
|
||||
* partage existant inopérant sans écrivain).
|
||||
*/
|
||||
suspend fun enqueueUpdateShare(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
granteeUserId: String,
|
||||
access: String,
|
||||
inherit: Boolean = true,
|
||||
expiresAt: Long? = null,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.UPDATE_SHARE,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = buildMap {
|
||||
put("granteeUserId", granteeUserId)
|
||||
put("access", access)
|
||||
put("inherit", inherit)
|
||||
expiresAt?.let { put("expiresAt", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `create_link` — payload `{ token, access, expiresAt? }`
|
||||
* (m21 : liens publics inopérants sans écrivain). Le `token` 32-hex est
|
||||
* généré côté client (`GenerateId`) : c'est l'identifiant du lien.
|
||||
*/
|
||||
suspend fun enqueueCreateLink(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
token: String,
|
||||
access: String,
|
||||
expiresAt: Long? = null,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.CREATE_LINK,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = buildMap {
|
||||
put("token", token)
|
||||
put("access", access)
|
||||
expiresAt?.let { put("expiresAt", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/** Raccourci `revoke_link` — payload `{ token }` (m21). */
|
||||
suspend fun enqueueRevokeLink(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
token: String,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.REVOKE_LINK,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = mapOf("token" to token),
|
||||
)
|
||||
|
||||
/** Nombre d'ops en attente de push (stats UI optionnelles). */
|
||||
suspend fun countPending(): Int = pendingOperationDao.countPending()
|
||||
|
||||
|
||||
+159
-30
@@ -4,11 +4,15 @@ import androidx.room.withTransaction
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.entity.AccessRank
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
import com.kazier.mobile.domain.PrefKeys
|
||||
import com.kazier.mobile.domain.SyncPlacement
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
@@ -21,8 +25,17 @@ import javax.inject.Singleton
|
||||
* de l'utilisateur. Les ressources non possédées (viewer/commenter/editor)
|
||||
* sont importées en tant que lignes cloud-only (`uri = NULL`, `sync_status = "cloud"`).
|
||||
*
|
||||
* Un pull complet (`after=0`) est effectué au login et à la restauration de
|
||||
* session pour garantir la convergence (révocations = disparition du snapshot).
|
||||
* M27 — delta, expiration et `canAccess` :
|
||||
* - le `cachedAt` du dernier pull est persisté (`user_preferences`) : pull
|
||||
* complet (`after = null`) au premier appel, au login/restauration
|
||||
* (`forceFull = true`) et quand le cache dépasse le TTL 24h ; delta
|
||||
* (`after = cachedAt`) sinon — la convergence (lignes absentes = révoquées)
|
||||
* ne tourne que sur pull complet ;
|
||||
* - chaque grant non-owner est persisté en `resource_permissions` (rang,
|
||||
* expiration, fraîcheur) : un grant expiré (`expiresAt` passé) masque la
|
||||
* ligne locale au lieu de rester visible jusqu'au prochain login ;
|
||||
* - [canAccess] répond offline (ownership local, puis rang persisté, avec
|
||||
* downgrade lecture seule après TTL sans reseed).
|
||||
*/
|
||||
@Singleton
|
||||
class ShareRepository @Inject constructor(
|
||||
@@ -32,31 +45,60 @@ class ShareRepository @Inject constructor(
|
||||
) {
|
||||
|
||||
/**
|
||||
* Récupère le snapshot complet des permissions et hydrate Room.
|
||||
* Récupère le snapshot des permissions et hydrate Room + le cache.
|
||||
*
|
||||
* Pour chaque permission non-owner :
|
||||
* Pour chaque permission non-owner non expirée :
|
||||
* - Folders : upsert cloud-only (uri=null, name, parentId, ownerId)
|
||||
* - Files : upsert cloud-only (uri=null, name, folderResourceId, ownerId, processed=true)
|
||||
*
|
||||
* Convergence : les lignes cloud-only absentes du snapshot complet sont
|
||||
* marquées `exists = 0`.
|
||||
* Convergence (pull complet uniquement) : les lignes cloud-only absentes
|
||||
* du snapshot complet sont marquées `exists = 0`, et les grants du cache
|
||||
* absents sont oubliés.
|
||||
*/
|
||||
suspend fun syncSnapshot() {
|
||||
suspend fun syncSnapshot(forceFull: Boolean = false) {
|
||||
// `ownerId` serveur = user_id : comparer au compte actif, jamais au device.
|
||||
val currentUserId = activeUserStore.get()
|
||||
val permissions = apiClient.syncPermissions()
|
||||
|
||||
val prefs = appDatabase.userPreferenceDao()
|
||||
val permDao = appDatabase.resourcePermissionDao()
|
||||
val now = System.currentTimeMillis()
|
||||
val cachedAt = prefs.getValue(PrefKeys.PERMISSIONS_CACHED_AT)?.toLongOrNull()
|
||||
val full = forceFull || cachedAt == null || now - cachedAt > PERMISSION_TTL_MS
|
||||
val permissions = apiClient.syncPermissions(if (full) null else cachedAt)
|
||||
|
||||
val folderDao = appDatabase.folderDao()
|
||||
val fileDao = appDatabase.fileDao()
|
||||
|
||||
val snapshotFolderIds = mutableSetOf<String>()
|
||||
val snapshotFileIds = mutableSetOf<String>()
|
||||
val snapshotPermIds = mutableSetOf<String>()
|
||||
|
||||
appDatabase.withTransaction {
|
||||
for (perm in permissions) {
|
||||
if (perm.effectiveAccess == "owner") continue
|
||||
snapshotPermIds += perm.resourceId
|
||||
permDao.upsertAll(
|
||||
listOf(
|
||||
ResourcePermissionEntity(
|
||||
resourceId = perm.resourceId,
|
||||
resourceType = perm.resourceType,
|
||||
effectiveAccess = perm.effectiveAccess,
|
||||
ownerId = perm.ownerId,
|
||||
sharedById = perm.sharedById,
|
||||
expiresAt = perm.expiresAt,
|
||||
// Fraîcheur = heure locale du pull (M27) : le TTL
|
||||
// mesure « 24h sans reseed », pas l'horloge serveur
|
||||
// (skew). `perm.cachedAt` sert au delta `after`.
|
||||
cachedAt = now,
|
||||
updatedAt = perm.updatedAt,
|
||||
),
|
||||
),
|
||||
)
|
||||
if (isExpired(perm.expiresAt, now)) {
|
||||
// Grant expiré : masquer la ligne locale au lieu d'hydrater.
|
||||
markSharedMissing(perm.resourceId, perm.resourceType, currentUserId, now, folderDao, fileDao)
|
||||
continue
|
||||
}
|
||||
when {
|
||||
perm.effectiveAccess == "owner" -> Unit
|
||||
perm.resourceType == "folder" -> {
|
||||
snapshotFolderIds += perm.resourceId
|
||||
upsertSharedFolder(perm, now, folderDao)
|
||||
@@ -68,36 +110,118 @@ class ShareRepository @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
// Convergence : marquer les lignes cloud-only d'autrui absentes du
|
||||
// snapshot comme disparues (révocation / expiration côté serveur).
|
||||
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le
|
||||
// snapshot exclut les ressources possédées → une ligne cloud-only
|
||||
// au vrai ownerId=user ne doit jamais être markMissing.
|
||||
for (folder in folderDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists) &&
|
||||
folder.resourceId !in snapshotFolderIds
|
||||
) {
|
||||
folderDao.markMissing(folder.resourceId, now)
|
||||
if (full) {
|
||||
// Convergence : marquer les lignes cloud-only d'autrui absentes du
|
||||
// snapshot comme disparues (révocation / expiration côté serveur).
|
||||
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le
|
||||
// snapshot exclut les ressources possédées → une ligne cloud-only
|
||||
// au vrai ownerId=user ne doit jamais être markMissing.
|
||||
for (folder in folderDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists) &&
|
||||
folder.resourceId !in snapshotFolderIds
|
||||
) {
|
||||
folderDao.markMissing(folder.resourceId, now)
|
||||
}
|
||||
}
|
||||
for (file in fileDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists) &&
|
||||
file.resourceId !in snapshotFileIds
|
||||
) {
|
||||
fileDao.markMissing(file.resourceId, now)
|
||||
}
|
||||
}
|
||||
// Oublie les grants du cache absents du snapshot complet.
|
||||
if (snapshotPermIds.isEmpty()) {
|
||||
permDao.clear()
|
||||
} else {
|
||||
permDao.deleteNotIn(snapshotPermIds.toList())
|
||||
}
|
||||
}
|
||||
for (file in fileDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists) &&
|
||||
file.resourceId !in snapshotFileIds
|
||||
) {
|
||||
fileDao.markMissing(file.resourceId, now)
|
||||
}
|
||||
|
||||
// Grants périmés connus du cache (delta ou TTL) : masquer localement.
|
||||
for (expired in permDao.getExpired(now)) {
|
||||
markSharedMissing(expired.resourceId, expired.resourceType, currentUserId, now, folderDao, fileDao)
|
||||
}
|
||||
|
||||
prefs.upsert(
|
||||
UserPreferenceEntity(
|
||||
PrefKeys.PERMISSIONS_CACHED_AT,
|
||||
now.toString(),
|
||||
now,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
Timber.d(
|
||||
"syncSnapshot: hydrated %d folders, %d files",
|
||||
"syncSnapshot: hydrated %d folders, %d files (full=%s)",
|
||||
snapshotFolderIds.size,
|
||||
snapshotFileIds.size,
|
||||
full,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Droit offline sur une ressource (docs/api-v1.md §6.2) : ownership local
|
||||
* d'abord (`owner` implique tout), sinon rang persisté du snapshot.
|
||||
* Grant expiré → refusé ; snapshot périmé (TTL 24h sans reseed) →
|
||||
* downgrade lecture seule (`viewer` exigé au plus).
|
||||
*/
|
||||
suspend fun canAccess(resourceId: String, required: String = AccessRank.VIEWER): Boolean {
|
||||
val requiredRank = AccessRank.rank(required)
|
||||
if (requiredRank <= 0) return false
|
||||
val currentUserId = activeUserStore.get()
|
||||
val now = System.currentTimeMillis()
|
||||
if (currentUserId != null) {
|
||||
val folderOwner = appDatabase.folderDao().getByResourceId(resourceId)?.ownerId
|
||||
val fileOwner = if (folderOwner == null) {
|
||||
appDatabase.fileDao().getByResourceId(resourceId)?.ownerId
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (folderOwner == currentUserId || fileOwner == currentUserId) return true
|
||||
}
|
||||
val perm = appDatabase.resourcePermissionDao().getByResourceId(resourceId) ?: return false
|
||||
if (isExpired(perm.expiresAt, now)) return false
|
||||
val effective = if (now - perm.cachedAt > PERMISSION_TTL_MS) {
|
||||
// Stale : downgrade lecture seule.
|
||||
minOf(AccessRank.rank(perm.effectiveAccess), AccessRank.rank(AccessRank.VIEWER))
|
||||
} else {
|
||||
AccessRank.rank(perm.effectiveAccess)
|
||||
}
|
||||
return effective >= requiredRank
|
||||
}
|
||||
|
||||
private fun isExpired(expiresAt: Long?, now: Long): Boolean =
|
||||
expiresAt != null && expiresAt <= now
|
||||
|
||||
/**
|
||||
* Masque une ligne partagée cloud-only d'autrui (`exists = 0`) — jamais
|
||||
* une copie physique locale ni une ressource possédée.
|
||||
*/
|
||||
private suspend fun markSharedMissing(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
currentUserId: String?,
|
||||
now: Long,
|
||||
folderDao: FolderDao,
|
||||
fileDao: FileDao,
|
||||
) {
|
||||
if (currentUserId == null) return
|
||||
if (resourceType == "folder") {
|
||||
val folder = folderDao.getByResourceId(resourceId) ?: return
|
||||
if (isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists)) {
|
||||
folderDao.markMissing(resourceId, now)
|
||||
}
|
||||
} else {
|
||||
val file = fileDao.getByResourceId(resourceId) ?: return
|
||||
if (isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists)) {
|
||||
fileDao.markMissing(resourceId, now)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ligne hébergée cloud (uri NULL), non possédée localement, encore visible.
|
||||
* Absente du snapshot → ressource partagée révoquée/expirée → marquer disparue.
|
||||
@@ -164,4 +288,9 @@ class ShareRepository @Inject constructor(
|
||||
)
|
||||
fileDao.upsert(entity)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** TTL du snapshot permissions (docs/api-v1.md §6.2) : 24h. */
|
||||
const val PERMISSION_TTL_MS = 24 * 60 * 60 * 1000L
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
|
||||
import com.kazier.mobile.data.local.dao.ScanDao
|
||||
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
||||
import com.kazier.mobile.data.local.migration.Migrations
|
||||
@@ -25,6 +26,13 @@ object DatabaseModule {
|
||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
||||
Room.databaseBuilder(context, AppDatabase::class.java, "dot.db")
|
||||
.addMigrations(*Migrations.ALL)
|
||||
// m15 : un APK plus ancien que la DB (downgrade) ne doit plus
|
||||
// crasher en `IllegalStateException` brut — reconstruction
|
||||
// destructive documentée : le miroir SAF se reconstruit au walk
|
||||
// suivant, les données serveur restent la source de vérité.
|
||||
// Perte acceptée : l'outbox non poussée (mutations locales) —
|
||||
// cas rare (rollback d'APK), préféré au crash au démarrage.
|
||||
.fallbackToDestructiveMigrationOnDowngrade()
|
||||
.build()
|
||||
|
||||
@Provides
|
||||
@@ -41,4 +49,7 @@ object DatabaseModule {
|
||||
|
||||
@Provides
|
||||
fun provideScanDao(db: AppDatabase): ScanDao = db.scanDao()
|
||||
|
||||
@Provides
|
||||
fun provideResourcePermissionDao(db: AppDatabase): ResourcePermissionDao = db.resourcePermissionDao()
|
||||
}
|
||||
@@ -8,4 +8,6 @@ object PrefKeys {
|
||||
const val SYNC_MODE = "sync_mode"
|
||||
const val THEME = "theme"
|
||||
const val SERVER_URL = "server_url"
|
||||
/** Dernier pull `GET /sync/permissions` réussi, ms epoch (M27 : delta + TTL 24h). */
|
||||
const val PERMISSIONS_CACHED_AT = "permissions_cached_at"
|
||||
}
|
||||
@@ -81,19 +81,26 @@ class FileDeleter @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Suppression cloud uniquement (outbox `delete_resource`).
|
||||
* Le fichier local n\'est pas touché. N\'a de sens que si la ressource a
|
||||
* déjà été poussée (gate « processed » : un fichier jamais envoyé est no-op).
|
||||
* Suppression cloud uniquement (outbox `delete_resource` + tombstone locale).
|
||||
* Le fichier physique local n'est pas touché, mais la ligne Room passe
|
||||
* `exists = 0` dans la MÊME transaction (M5) : sans ça la ressource restait
|
||||
* affichée, le walk la revoyait et `refreshFromServer` ne supprime jamais
|
||||
* de lignes → fantôme local vs serveur supprimé. N'a de sens que si la
|
||||
* ressource a déjà été poussée (gate « processed »).
|
||||
*/
|
||||
private suspend fun deleteInCloud(file: FileEntity): Boolean {
|
||||
var ok = false
|
||||
runCatching {
|
||||
// Jamais poussé (create encore pending) : annulation (M19), pas
|
||||
// de delete — le serveur n'a rien à oublier. Poussé (synced) :
|
||||
// `delete_resource`, le serveur connaît la ressource.
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||
val now = System.currentTimeMillis()
|
||||
appDatabase.withTransaction {
|
||||
// Jamais poussé (create encore pending) : annulation (M19), pas
|
||||
// de delete — le serveur n'a rien à oublier. Poussé (synced) :
|
||||
// `delete_resource`, le serveur connaît la ressource.
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||
}
|
||||
fileRepository.markMissing(file.resourceId, now)
|
||||
}
|
||||
ok = true
|
||||
Timber.d("enqueued cloud delete for %s", file.resourceId)
|
||||
|
||||
@@ -87,13 +87,19 @@ class FolderDeleter @Inject constructor(
|
||||
return false
|
||||
}
|
||||
|
||||
/** Suppression cloud uniquement (outbox `delete_resource`), physique intact. */
|
||||
/**
|
||||
* Suppression cloud uniquement (outbox `delete_resource` + tombstone locale,
|
||||
* M5) : le dossier et toute sa descendance Room passent `exists = 0` dans
|
||||
* la MÊME transaction — le physique reste intact mais l'arbre disparaît de
|
||||
* l'UI et le walk ne le ressuscite plus (garde `hasPendingDeleteOperation`).
|
||||
*/
|
||||
private suspend fun deleteInCloud(folder: FolderEntity): Boolean {
|
||||
var ok = false
|
||||
runCatching {
|
||||
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||
if (outboxRepository.hasSyncedCreateOperationAnyType(folder.resourceId)) {
|
||||
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder")
|
||||
val tree = collectDescendants(folder.resourceId)
|
||||
val now = System.currentTimeMillis()
|
||||
appDatabase.withTransaction {
|
||||
treeMarkMissing(folder, tree, now)
|
||||
}
|
||||
ok = true
|
||||
Timber.d("enqueued cloud delete for folder %s", folder.resourceId)
|
||||
|
||||
@@ -29,6 +29,12 @@ import javax.inject.Singleton
|
||||
*
|
||||
* L'ordre outbox est garanti par l'insertion séquentielle : `create_resource`
|
||||
* du dossier fusionné avant les `move_resource`, avant les `delete_resource`.
|
||||
*
|
||||
* M9 — reprise après crash : chaque étape est transactionnelle et idempotente
|
||||
* (dossier réutilisé, contenus déjà déplacés naturellement ignorés), et une
|
||||
* source n'est supprimée que si elle est réellement vide après déplacement
|
||||
* (gate de vidage) — jamais de suppression d'un dossier dont le contenu n'a
|
||||
* pas pu être déplacé, jamais de doublon serveur à la relance.
|
||||
*/
|
||||
@Singleton
|
||||
class FolderMerger @Inject constructor(
|
||||
@@ -68,7 +74,10 @@ class FolderMerger @Inject constructor(
|
||||
val files = fileRepository.getFilesInFolder(src.resourceId)
|
||||
if (files.isNotEmpty()) {
|
||||
fileMover.moveFiles(files.map { it.resourceId }, merged.resourceId)
|
||||
movedFiles += files.size
|
||||
// Ne compte que les fichiers réellement partis (relecture :
|
||||
// `moveFiles` ignore silencieusement les refus SAF, et une
|
||||
// relance après crash ne doit pas recompter les déjà-déplacés).
|
||||
movedFiles += files.size - fileRepository.getFilesInFolder(src.resourceId).size
|
||||
}
|
||||
val subFolders = folderRepository.getChildren(src.resourceId)
|
||||
if (subFolders.isNotEmpty()) {
|
||||
@@ -80,6 +89,14 @@ class FolderMerger @Inject constructor(
|
||||
folderRepository.reparentSubFolders(movable.map { it.resourceId }, merged.resourceId)
|
||||
}
|
||||
}
|
||||
// Gate de vidage (M9) : ne supprimer que les sources
|
||||
// réellement vidées — un refus SAF silencieux ne doit jamais
|
||||
// mener à la suppression d'un contenu non déplacé.
|
||||
val filesLeft = fileRepository.getFilesInFolder(src.resourceId).size
|
||||
val foldersLeft = folderRepository.getChildren(src.resourceId).size
|
||||
if (filesLeft > 0 || foldersLeft > 0) {
|
||||
error("source non vidée : $filesLeft fichier(s), $foldersLeft dossier(s) restants")
|
||||
}
|
||||
}.isSuccess
|
||||
if (ok) {
|
||||
readyToDelete += src
|
||||
|
||||
@@ -72,43 +72,54 @@ class DeviceSync @Inject constructor(
|
||||
// Phase 1 — listing SAF (I/O disque, HORS transaction).
|
||||
val folders = scanner.scanTree(Uri.parse(rootUri))
|
||||
|
||||
// Phase 2 — écritures Room (transaction courte, SQL pur).
|
||||
return appDatabase.withTransaction {
|
||||
val seen = HashSet<String>()
|
||||
val resourceIdByUri = HashMap<String, String>()
|
||||
var fileCount = 0
|
||||
// Phase 2 — écritures Room par lots (m5) : chaque lot est sa propre
|
||||
// transaction courte au lieu d'une transaction géante (N upserts +
|
||||
// full-table scans sous verrou écriture → lecteurs Room bloqués,
|
||||
// jank/ANR). L'ordre parent-avant-enfant est préservé (itération
|
||||
// séquentielle, seules les frontières de commit changent).
|
||||
val seen = HashSet<String>()
|
||||
val resourceIdByUri = HashMap<String, String>()
|
||||
var fileCount = 0
|
||||
|
||||
for (folder in folders) {
|
||||
seen += folder.uri
|
||||
val parentResourceId = if (folder.parentUri == null) {
|
||||
null
|
||||
} else {
|
||||
resourceIdByUri[folder.parentUri]
|
||||
}
|
||||
if (folder.parentUri != null && parentResourceId == null) {
|
||||
// Violation parent-avant-enfant (snapshot incohérent) : on
|
||||
// n'attache JAMAIS à la racine par défaut — le dossier est
|
||||
// ignoré et journalisé, le prochain walk convergera.
|
||||
Timber.w(
|
||||
"walk: parent SAF inconnu, dossier ignoré (uri=%s parent=%s)",
|
||||
folder.uri,
|
||||
folder.parentUri,
|
||||
for (chunk in folders.chunked(SYNC_BATCH)) {
|
||||
appDatabase.withTransaction {
|
||||
for (folder in chunk) {
|
||||
seen += folder.uri
|
||||
val parentResourceId = if (folder.parentUri == null) {
|
||||
null
|
||||
} else {
|
||||
resourceIdByUri[folder.parentUri]
|
||||
}
|
||||
if (folder.parentUri != null && parentResourceId == null) {
|
||||
// Violation parent-avant-enfant (snapshot incohérent) : on
|
||||
// n'attache JAMAIS à la racine par défaut — le dossier est
|
||||
// ignoré et journalisé, le prochain walk convergera.
|
||||
Timber.w(
|
||||
"walk: parent SAF inconnu, dossier ignoré (uri=%s parent=%s)",
|
||||
folder.uri,
|
||||
folder.parentUri,
|
||||
)
|
||||
continue
|
||||
}
|
||||
val saved = folderRepository.saveFolder(
|
||||
SaveFolderInput(uri = folder.uri, name = folder.name, exists = true),
|
||||
parentResourceId = parentResourceId,
|
||||
ownerId = ownerId,
|
||||
)
|
||||
continue
|
||||
resourceIdByUri[folder.uri] = saved.resourceId
|
||||
}
|
||||
val saved = folderRepository.saveFolder(
|
||||
SaveFolderInput(uri = folder.uri, name = folder.name, exists = true),
|
||||
parentResourceId = parentResourceId,
|
||||
ownerId = ownerId,
|
||||
)
|
||||
resourceIdByUri[folder.uri] = saved.resourceId
|
||||
}
|
||||
}
|
||||
|
||||
for (folder in folders) {
|
||||
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne
|
||||
// sont pas rattachés à la racine, ils attendent le walk suivant.
|
||||
val folderResourceId = resourceIdByUri[folder.uri] ?: continue
|
||||
for (file in folder.files) {
|
||||
val fileWrites = folders.flatMap { folder ->
|
||||
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne
|
||||
// sont pas rattachés à la racine, ils attendent le walk suivant.
|
||||
val folderResourceId = resourceIdByUri[folder.uri] ?: return@flatMap emptyList()
|
||||
folder.files.map { file -> folderResourceId to file }
|
||||
}
|
||||
for (chunk in fileWrites.chunked(SYNC_BATCH)) {
|
||||
appDatabase.withTransaction {
|
||||
for ((folderResourceId, file) in chunk) {
|
||||
seen += file.uri
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(
|
||||
@@ -125,45 +136,49 @@ class DeviceSync @Inject constructor(
|
||||
fileCount++
|
||||
}
|
||||
}
|
||||
|
||||
var missing = 0
|
||||
val now = System.currentTimeMillis()
|
||||
for (folder in folderRepository.getAll()) {
|
||||
val folderUri = folder.uri
|
||||
if (folder.exists != 0 && folderUri != null && isChildOf(folderUri, rootUri) && folderUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(folder.resourceId)
|
||||
) {
|
||||
folderRepository.markMissing(folder.resourceId, now)
|
||||
// Disparu avant push : annule le create pending (M19) —
|
||||
// le serveur ne doit ni le créer ni l'oublier.
|
||||
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
for (file in fileRepository.getAll()) {
|
||||
val fileUri = file.uri
|
||||
// Un `move_resource` encore `pending` fait de l'outbox la
|
||||
// source de vérité du placement : on ne masque jamais une ligne
|
||||
// en transition vers une autre arborescence physique (le
|
||||
// snapshot peut être périmé par rapport au move en cours).
|
||||
// Un move déjà `synced` ne protège plus : si le fichier a
|
||||
// ensuite disparu du disque, c'est une vraie suppression
|
||||
// (sinon fantôme `exists = 1` éternel, M4).
|
||||
if (file.exists != 0 && fileUri != null && isChildOf(fileUri, rootUri) && fileUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(file.resourceId)
|
||||
) {
|
||||
fileRepository.markMissing(file.resourceId, now)
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
|
||||
SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing)
|
||||
}
|
||||
|
||||
var missing = 0
|
||||
val now = System.currentTimeMillis()
|
||||
// Réconciliation scopée à la racine (m5) : fini les `getAll()`
|
||||
// O(racines×DB) — le SQL filtre par préfixe d'uri (échappé).
|
||||
for (folder in folderRepository.getUnderRoot(rootUri)) {
|
||||
val folderUri = folder.uri
|
||||
if (folder.exists != 0 && folderUri != null && folderUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(folder.resourceId)
|
||||
) {
|
||||
folderRepository.markMissing(folder.resourceId, now)
|
||||
// Disparu avant push : annule le create pending (M19) —
|
||||
// le serveur ne doit ni le créer ni l'oublier.
|
||||
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
for (file in fileRepository.getUnderRoot(rootUri)) {
|
||||
val fileUri = file.uri
|
||||
// Un `move_resource` encore `pending` fait de l'outbox la
|
||||
// source de vérité du placement : on ne masque jamais une ligne
|
||||
// en transition vers une autre arborescence physique (le
|
||||
// snapshot peut être périmé par rapport au move en cours).
|
||||
// Un move déjà `synced` ne protège plus : si le fichier a
|
||||
// ensuite disparu du disque, c'est une vraie suppression
|
||||
// (sinon fantôme `exists = 1` éternel, M4).
|
||||
if (file.exists != 0 && fileUri != null && fileUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(file.resourceId)
|
||||
) {
|
||||
fileRepository.markMissing(file.resourceId, now)
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
|
||||
return SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing)
|
||||
}
|
||||
|
||||
private fun isChildOf(uri: String, rootUri: String): Boolean =
|
||||
uri == rootUri || uri.startsWith("$rootUri/")
|
||||
companion object {
|
||||
/** Taille des lots d'upserts Room du walk (m5 : transactions courtes). */
|
||||
private const val SYNC_BATCH = 200
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.extensionOrNull(): String? {
|
||||
|
||||
@@ -106,31 +106,52 @@ class SyncViewModel @Inject constructor(
|
||||
delay(FIRST_DELAY_MS)
|
||||
while (isActive) {
|
||||
_walkInProgress.value = true
|
||||
runCatching { deviceSync.syncAll() }
|
||||
.onSuccess { results ->
|
||||
if (results.isNotEmpty()) Timber.d("syncAll: %s", results)
|
||||
// Les nouvelles ressources découvertes sont dans l'outbox
|
||||
// → drainer vers POST /sync/ops (single-flight via KEEP).
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
// OCR auto : uploader les octets des fichiers récemment promus (local-cloud).
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
// Repasse C4 : les suppressions journalisées dont les
|
||||
// octets ont survécu (crash entre journal et SAF).
|
||||
runCatching {
|
||||
fileDeleter.sweepPendingPhysicalDeletes() +
|
||||
folderDeleter.sweepPendingPhysicalDeletes()
|
||||
}.onSuccess { swept ->
|
||||
if (swept > 0) Timber.d("sweep: %d suppressions physiques rattrapées", swept)
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "sweep failed, retrying later")
|
||||
try {
|
||||
var changed = false
|
||||
runCatching { deviceSync.syncAll() }
|
||||
.onSuccess { results ->
|
||||
if (results.isNotEmpty()) Timber.d("syncAll: %s", results)
|
||||
changed = results.any { it.folders > 0 || it.files > 0 || it.missing > 0 }
|
||||
// Repasse C4 : les suppressions journalisées dont les
|
||||
// octets ont survécu (crash entre journal et SAF).
|
||||
runCatching {
|
||||
fileDeleter.sweepPendingPhysicalDeletes() +
|
||||
folderDeleter.sweepPendingPhysicalDeletes()
|
||||
}.onSuccess { swept ->
|
||||
if (swept > 0) {
|
||||
Timber.d("sweep: %d suppressions physiques rattrapées", swept)
|
||||
changed = true
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "sweep failed, retrying later")
|
||||
}
|
||||
}
|
||||
.onFailure { e ->
|
||||
if (e is CancellationException) throw e
|
||||
Timber.w(e, "syncAll failed, retrying later")
|
||||
}
|
||||
// Hydrate les ressources partagées depuis le snapshot serveur.
|
||||
// Échec réseau toléré : le prochain tick réessaiera.
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
.onFailure { e ->
|
||||
if (e is CancellationException) throw e
|
||||
Timber.d("syncSnapshot failed, retrying later: %s", e.message)
|
||||
}
|
||||
// m2 : ne réveiller WorkManager que si le tick a produit
|
||||
// quelque chose (walk/sweep) ou si l'outbox attend un drain
|
||||
// (op partagée depuis l'UI, drain précédent interrompu…).
|
||||
// Les nouvelles ressources découvertes sont dans l'outbox
|
||||
// → drainer vers POST /sync/ops (single-flight via KEEP) ;
|
||||
// OCR auto : octets des fichiers récemment promus.
|
||||
if (changed || pendingOperationDao.countPending() > 0) {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
}
|
||||
.onFailure { e -> Timber.w(e, "syncAll failed, retrying later") }
|
||||
// Hydrate les ressources partagées depuis le snapshot serveur.
|
||||
// Échec réseau toléré : le prochain tick réessaiera.
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
.onFailure { e -> Timber.d("syncSnapshot failed, retrying later: %s", e.message) }
|
||||
_walkInProgress.value = false
|
||||
} finally {
|
||||
// m1 : le badge « syncing » retombe même si le scope est
|
||||
// annulé ou si le snapshot réseau a échoué.
|
||||
_walkInProgress.value = false
|
||||
}
|
||||
delay(INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,8 +50,8 @@ class AuthViewModel @Inject constructor(
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
if (session != null) {
|
||||
// Snapshot complet des permissions partagées (convergence).
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
// Snapshot complet des permissions partagées (convergence, M27).
|
||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
||||
.onFailure { e -> Timber.d("syncSnapshot on restore failed: %s", e.message) }
|
||||
}
|
||||
}
|
||||
@@ -72,8 +72,8 @@ class AuthViewModel @Inject constructor(
|
||||
// Connexion réussie → pousser les mutations locales en attente.
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
// Snapshot complet des permissions partagées (convergence).
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
// Snapshot complet des permissions partagées (convergence, M27).
|
||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
||||
.onFailure { e -> Timber.d("syncSnapshot on login failed: %s", e.message) }
|
||||
}
|
||||
.onFailure { e ->
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.kazier.mobile.data.local.dao
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* m7 : la recherche `LIKE` échappe `%`/`_` (littéraux, pas des jokers) —
|
||||
* « 100% » ne matchait pas tout avant le fix. La casse ASCII reste
|
||||
* insensible (`COLLATE NOCASE`).
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class SearchEscapeTest {
|
||||
|
||||
private lateinit var db: AppDatabase
|
||||
private lateinit var fileDao: FileDao
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
fileDao = db.fileDao()
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pourcentage_litteral_ne_match_pas_tout() = runTest {
|
||||
fileDao.upsert(file("a".repeat(32), "100%.txt"))
|
||||
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
||||
fileDao.upsert(file("c".repeat(32), "normal.txt"))
|
||||
|
||||
// Le repository échappe avant d'appeler le DAO — on rejoue ici le
|
||||
// contrat (`escapeLike`) pour verrouiller le comportement SQL.
|
||||
val escaped = "100%".escapeLikeForTest()
|
||||
val rows = fileDao.searchWithFilters(escaped, null).first()
|
||||
|
||||
assertEquals(listOf("100%.txt"), rows.map { it.name })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun underscore_litteral_ne_match_pas_tout() = runTest {
|
||||
fileDao.upsert(file("a".repeat(32), "100%.txt"))
|
||||
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
||||
fileDao.upsert(file("c".repeat(32), "axb.txt"))
|
||||
|
||||
val rows = fileDao.searchWithFilters("a\\_b", null).first()
|
||||
|
||||
assertEquals(listOf("a_b.txt"), rows.map { it.name })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recherche_insensible_a_la_casse_ascii() = runTest {
|
||||
fileDao.upsert(file("a".repeat(32), "Rapport.TXT"))
|
||||
|
||||
val rows = fileDao.searchWithFilters("rapport", null).first()
|
||||
|
||||
assertEquals(listOf("Rapport.TXT"), rows.map { it.name })
|
||||
}
|
||||
|
||||
private fun file(resourceId: String, name: String) = FileEntity(
|
||||
resourceId = resourceId,
|
||||
name = name,
|
||||
folderResourceId = "f".repeat(32),
|
||||
size = 10L,
|
||||
exists = 1,
|
||||
addedAt = NOW,
|
||||
updatedAt = NOW,
|
||||
)
|
||||
|
||||
/** Miroir de `escapeLike` (interne au main) : `%`/`_`/`\` échappés. */
|
||||
private fun String.escapeLikeForTest(): String =
|
||||
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
private companion object {
|
||||
const val NOW = 1_700_000_000_000L
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.kazier.mobile.data.local.migration
|
||||
|
||||
import android.content.Context
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import androidx.sqlite.db.SupportSQLiteOpenHelper
|
||||
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* M13 : la migration 14→15 backfill `exists` NULL→1 sur `folders` et `files`.
|
||||
* Les lignes insérées sans `exists` explicite (défaut Kotlin `null` avant ce
|
||||
* fix) étaient invisibles des requêtes `WHERE exists = 1` — elles
|
||||
* réapparaissent comme présentes, état le plus sûr (le walk les re-marque
|
||||
* `exists = 0` si elles ont vraiment disparu). Les lignes déjà à 0/1 sont
|
||||
* intactes.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class Migration14To15Test {
|
||||
|
||||
@Test
|
||||
fun migration_backfill_exists_null_vers_1_sans_toucher_les_lignes_renseignees() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val helper = FrameworkSQLiteOpenHelperFactory().create(
|
||||
SupportSQLiteOpenHelper.Configuration.builder(context)
|
||||
.name(null)
|
||||
.callback(V14Callback())
|
||||
.build(),
|
||||
)
|
||||
val db = helper.writableDatabase
|
||||
db.execSQL(
|
||||
"INSERT INTO `folders` (`resource_id`, `name`, `exists`, `sync_status`, `added_at`, `updated_at`) " +
|
||||
"VALUES ('f-null', 'Null', NULL, 'local', 1, 1), ('f-zero', 'Zero', 0, 'local', 1, 1), ('f-one', 'One', 1, 'local', 1, 1)",
|
||||
)
|
||||
db.execSQL(
|
||||
"INSERT INTO `files` (`resource_id`, `name`, `folder_resource_id`, `size`, `exists`, `added_at`, `updated_at`) " +
|
||||
"VALUES ('d-null', 'n.txt', 'f-one', 10, NULL, 1, 1), ('d-zero', 'z.txt', 'f-one', 10, 0, 1, 1)",
|
||||
)
|
||||
|
||||
val migration = Migrations.ALL.first { it.startVersion == 14 && it.endVersion == 15 }
|
||||
migration.migrate(db)
|
||||
|
||||
db.query("SELECT `resource_id`, `exists` FROM `folders` ORDER BY `resource_id`").use { cursor ->
|
||||
val rows = mutableMapOf<String, Int>()
|
||||
while (cursor.moveToNext()) rows[cursor.getString(0)] = cursor.getInt(1)
|
||||
assertEquals(mapOf("f-null" to 1, "f-one" to 1, "f-zero" to 0), rows)
|
||||
}
|
||||
db.query("SELECT `resource_id`, `exists` FROM `files` ORDER BY `resource_id`").use { cursor ->
|
||||
val rows = mutableMapOf<String, Int>()
|
||||
while (cursor.moveToNext()) rows[cursor.getString(0)] = cursor.getInt(1)
|
||||
assertEquals(mapOf("d-null" to 1, "d-zero" to 0), rows)
|
||||
}
|
||||
helper.close()
|
||||
}
|
||||
|
||||
/** Schéma v14 minimal de `folders`/`files` (colonne `exists` nullable). */
|
||||
private class V14Callback : SupportSQLiteOpenHelper.Callback(14) {
|
||||
override fun onCreate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"CREATE TABLE `folders` (" +
|
||||
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
|
||||
"`resource_id` TEXT NOT NULL, " +
|
||||
"`uri` TEXT, " +
|
||||
"`name` TEXT NOT NULL, " +
|
||||
"`exists` INTEGER, " +
|
||||
"`parent_resource_id` TEXT, " +
|
||||
"`owner_id` TEXT, " +
|
||||
"`sync_status` TEXT NOT NULL, " +
|
||||
"`created_in_app` INTEGER NOT NULL DEFAULT 0, " +
|
||||
"`added_at` INTEGER NOT NULL, " +
|
||||
"`updated_at` INTEGER NOT NULL)",
|
||||
)
|
||||
db.execSQL(
|
||||
"CREATE TABLE `files` (" +
|
||||
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
|
||||
"`resource_id` TEXT NOT NULL, " +
|
||||
"`uri` TEXT, " +
|
||||
"`name` TEXT NOT NULL, " +
|
||||
"`folder_resource_id` TEXT NOT NULL, " +
|
||||
"`extension` TEXT, " +
|
||||
"`size` INTEGER NOT NULL, " +
|
||||
"`mime_type` TEXT, " +
|
||||
"`exists` INTEGER, " +
|
||||
"`added_at` INTEGER NOT NULL, " +
|
||||
"`updated_at` INTEGER NOT NULL)",
|
||||
)
|
||||
}
|
||||
|
||||
override fun onUpgrade(
|
||||
db: SupportSQLiteDatabase,
|
||||
oldVersion: Int,
|
||||
newVersion: Int,
|
||||
) = Unit
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.kazier.mobile.data.local.migration
|
||||
|
||||
import android.content.Context
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import androidx.sqlite.db.SupportSQLiteOpenHelper
|
||||
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* M27 : la migration 15→16 crée la table `resource_permissions` (cache du
|
||||
* snapshot `GET /sync/permissions`, fondement de `canAccess`) + son index
|
||||
* `expires_at`. Une coquille SQL briquerait l'app au démarrage après update.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class Migration15To16Test {
|
||||
|
||||
@Test
|
||||
fun migration_cree_la_table_et_l_index() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val helper = FrameworkSQLiteOpenHelperFactory().create(
|
||||
SupportSQLiteOpenHelper.Configuration.builder(context)
|
||||
.name(null)
|
||||
.callback(EmptyV15Callback())
|
||||
.build(),
|
||||
)
|
||||
val db = helper.writableDatabase
|
||||
|
||||
val migration = Migrations.ALL.first { it.startVersion == 15 && it.endVersion == 16 }
|
||||
migration.migrate(db)
|
||||
|
||||
val tables = mutableListOf<String>()
|
||||
db.query(
|
||||
"SELECT `name` FROM `sqlite_master` WHERE `type` = 'table' AND `name` = 'resource_permissions'",
|
||||
).use { cursor ->
|
||||
while (cursor.moveToNext()) tables += cursor.getString(0)
|
||||
}
|
||||
assertTrue("table resource_permissions manquante", tables.contains("resource_permissions"))
|
||||
|
||||
val columns = mutableListOf<String>()
|
||||
db.query("PRAGMA table_info(`resource_permissions`)").use { cursor ->
|
||||
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||
while (cursor.moveToNext()) columns += cursor.getString(nameIdx)
|
||||
}
|
||||
for (expected in listOf(
|
||||
"resource_id", "resource_type", "effective_access", "owner_id",
|
||||
"shared_by_id", "expires_at", "cached_at", "updated_at",
|
||||
)) {
|
||||
assertTrue("colonne $expected manquante", columns.contains(expected))
|
||||
}
|
||||
|
||||
var indexFound = false
|
||||
db.query("PRAGMA index_list(`resource_permissions`)").use { cursor ->
|
||||
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.getString(nameIdx) == "index_resource_permissions_expires_at") {
|
||||
indexFound = true
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue("index expires_at manquant", indexFound)
|
||||
helper.close()
|
||||
}
|
||||
|
||||
private class EmptyV15Callback : SupportSQLiteOpenHelper.Callback(15) {
|
||||
override fun onCreate(db: SupportSQLiteDatabase) = Unit
|
||||
|
||||
override fun onUpgrade(
|
||||
db: SupportSQLiteDatabase,
|
||||
oldVersion: Int,
|
||||
newVersion: Int,
|
||||
) = Unit
|
||||
}
|
||||
}
|
||||
+19
@@ -11,6 +11,7 @@ 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.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.remote.ApiService
|
||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
@@ -109,6 +110,24 @@ class OcrRepositoryTest {
|
||||
assertEquals("bonjour monde", stored?.ocrText)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `poll_timeout_si_job_bloque_en_processing`() = runTest {
|
||||
// m20 : un job resté `processing` (stale claim serveur) ne tient plus
|
||||
// la coroutine indéfiniment — `OCR_TIMEOUT` au bout du timeout.
|
||||
apiService.jobSequence = listOf(
|
||||
OcrJobDto(id = "job-stuck", status = OcrJobStatus.PROCESSING),
|
||||
)
|
||||
|
||||
var progressCalls = 0
|
||||
val ex = runCatching {
|
||||
repository.poll("job-stuck", timeoutMs = 0) { progressCalls++ }
|
||||
}.exceptionOrNull()
|
||||
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("OCR_TIMEOUT", (ex as ApiException).code)
|
||||
assertEquals(1, progressCalls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `poll_stop_sur_un_job_failed_et_remonte_lerreur`() = runTest {
|
||||
apiService.jobSequence = listOf(
|
||||
|
||||
+143
-16
@@ -232,22 +232,146 @@ class ShareRepositoryTest {
|
||||
assertEquals(1, folderDao.getByResourceId("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")!!.exists)
|
||||
}
|
||||
|
||||
// --- delta / TTL (M27) ---------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun premier_pull_complet_puis_delta() = runTest {
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "viewer", name = "S", parentId = null),
|
||||
)
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
assertNull("premier pull : snapshot complet (after=null)", apiService.lastAfter)
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
assertTrue(
|
||||
"second pull : delta (after=cachedAt)",
|
||||
apiService.lastAfter != null,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forceFull_repasse_en_complet_meme_avec_cache() = runTest {
|
||||
apiService.permissions = emptyList()
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
shareRepository.syncSnapshot(forceFull = true)
|
||||
|
||||
assertNull("forceFull : snapshot complet (after=null)", apiService.lastAfter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun delta_ne_fait_pas_converger_les_absents() = runTest {
|
||||
// Pull complet initial avec une ressource partagée…
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "viewer", name = "S", parentId = null),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
assertEquals(1, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||
|
||||
// …puis delta vide : la ressource NE doit pas être marquée disparue
|
||||
// (un delta ne contient que les changements, pas l'état complet).
|
||||
apiService.permissions = emptyList()
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertEquals(1, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||
}
|
||||
|
||||
// --- expiration (M27) ------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun grant_expire_masque_la_ligne_au_lieu_d_hydrater() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
folderDao.upsert(folder(FOLDER_ID, uri = null, ownerId = OTHER_USER))
|
||||
apiService.permissions = listOf(
|
||||
perm(
|
||||
id = FOLDER_ID, type = "folder", access = "viewer", name = "S", parentId = null,
|
||||
expiresAt = NOW - 1_000L,
|
||||
),
|
||||
)
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertEquals(0, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||
}
|
||||
|
||||
// --- canAccess (M27) ---------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun canAccess_ownership_rang_expiration() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
// Ressource possédée localement → owner implicite.
|
||||
folderDao.upsert(folder(OWNED_ID, uri = null, ownerId = CURRENT_USER))
|
||||
// Grants partagés.
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "editor", name = "E", parentId = null),
|
||||
perm(id = FILE_ID, type = "file", access = "viewer", name = "v.pdf", parentId = FOLDER_ID),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertTrue(shareRepository.canAccess(OWNED_ID, "editor"))
|
||||
assertTrue(shareRepository.canAccess(FOLDER_ID, "editor"))
|
||||
assertTrue("viewer suffit pour viewer", shareRepository.canAccess(FILE_ID, "viewer"))
|
||||
assertFalse("viewer < editor", shareRepository.canAccess(FILE_ID, "editor"))
|
||||
assertFalse("ressource inconnue", shareRepository.canAccess("d".repeat(32), "viewer"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canAccess_grant_expire_refuse() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
apiService.permissions = listOf(
|
||||
perm(
|
||||
id = FOLDER_ID, type = "folder", access = "editor", name = "E", parentId = null,
|
||||
expiresAt = NOW - 1_000L,
|
||||
),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertFalse("grant expiré : pas d'accès", shareRepository.canAccess(FOLDER_ID, "viewer"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canAccess_snapshot_perime_downgrade_lecture_seule() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "editor", name = "E", parentId = null),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
assertTrue(shareRepository.canAccess(FOLDER_ID, "editor"))
|
||||
|
||||
// Simule un cache périmé (TTL 24h dépassé sans reseed).
|
||||
val stale = db.resourcePermissionDao().getByResourceId(FOLDER_ID)!!
|
||||
db.resourcePermissionDao().upsertAll(
|
||||
listOf(stale.copy(cachedAt = System.currentTimeMillis() - ShareRepository.PERMISSION_TTL_MS - 1)),
|
||||
)
|
||||
|
||||
assertTrue("stale : lecture conservée", shareRepository.canAccess(FOLDER_ID, "viewer"))
|
||||
assertFalse("stale : écriture refusée", shareRepository.canAccess(FOLDER_ID, "editor"))
|
||||
}
|
||||
|
||||
// --- fixtures ------------------------------------------------------------
|
||||
|
||||
private fun perm(id: String, type: String, access: String, name: String, parentId: String?) =
|
||||
ResourcePermissionDto(
|
||||
resourceId = id.padEnd(32, '0'),
|
||||
resourceType = type,
|
||||
effectiveAccess = access,
|
||||
inherit = true,
|
||||
ownerId = OTHER_USER,
|
||||
sharedById = OWNER_ID,
|
||||
expiresAt = null,
|
||||
cachedAt = NOW,
|
||||
updatedAt = NOW,
|
||||
name = name,
|
||||
parentId = parentId?.padEnd(32, '0'),
|
||||
)
|
||||
private fun perm(
|
||||
id: String,
|
||||
type: String,
|
||||
access: String,
|
||||
name: String,
|
||||
parentId: String?,
|
||||
expiresAt: Long? = null,
|
||||
) = ResourcePermissionDto(
|
||||
resourceId = id.padEnd(32, '0'),
|
||||
resourceType = type,
|
||||
effectiveAccess = access,
|
||||
inherit = true,
|
||||
ownerId = OTHER_USER,
|
||||
sharedById = OWNER_ID,
|
||||
expiresAt = expiresAt,
|
||||
cachedAt = NOW,
|
||||
updatedAt = NOW,
|
||||
name = name,
|
||||
parentId = parentId?.padEnd(32, '0'),
|
||||
)
|
||||
|
||||
private fun folder(id: String, uri: String?, ownerId: String?) = FolderEntity(
|
||||
resourceId = id.padEnd(32, '0'),
|
||||
@@ -290,6 +414,7 @@ class ShareRepositoryTest {
|
||||
/** Fake `ApiService` — uniquement le snapshot est réellement consommé. */
|
||||
private class FakeApiService : ApiService {
|
||||
var permissions: List<ResourcePermissionDto> = emptyList()
|
||||
var lastAfter: Long? = null
|
||||
|
||||
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
@@ -319,8 +444,10 @@ private class FakeApiService : ApiService {
|
||||
|
||||
override suspend fun syncPermissions(
|
||||
after: Long?,
|
||||
): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||
Response.success(ApiEnvelope(data = permissions))
|
||||
): Response<ApiEnvelope<List<ResourcePermissionDto>>> {
|
||||
lastAfter = after
|
||||
return Response.success(ApiEnvelope(data = permissions))
|
||||
}
|
||||
|
||||
override suspend fun uploadFile(
|
||||
file: MultipartBody.Part,
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
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.dao.PendingOperationDao
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiService
|
||||
import com.kazier.mobile.data.repository.FileRepository
|
||||
import com.kazier.mobile.data.repository.FolderRepository
|
||||
import com.kazier.mobile.data.repository.OutboxRepository
|
||||
import com.kazier.mobile.data.repository.SaveFileInput
|
||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
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.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||
|
||||
/**
|
||||
* M5 : `deleteInCloud` journalise `delete_resource` ET pose la tombstone
|
||||
* locale (`exists = 0`) dans la même transaction — sans ça la ressource
|
||||
* restait affichée et le walk la revoyait (fantôme local vs serveur supprimé).
|
||||
* - fichier déjà poussé (create synced) → `delete_resource` + `exists = 0` ;
|
||||
* - fichier jamais poussé → pas de `delete_resource`, mais `exists = 0` ;
|
||||
* - dossier poussé → dossier + descendance en `exists = 0`, deletes journalisés.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class DeleteInCloudTest {
|
||||
|
||||
private lateinit var context: Context
|
||||
private lateinit var db: AppDatabase
|
||||
private lateinit var opsDao: PendingOperationDao
|
||||
private lateinit var fileRepository: FileRepository
|
||||
private lateinit var folderRepository: FolderRepository
|
||||
private lateinit var outboxRepository: OutboxRepository
|
||||
private lateinit var fileDeleter: FileDeleter
|
||||
private lateinit var folderDeleter: FolderDeleter
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
context = ApplicationProvider.getApplicationContext()
|
||||
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
opsDao = db.pendingOperationDao()
|
||||
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
val apiService = Retrofit.Builder()
|
||||
.baseUrl("http://localhost:1/")
|
||||
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
||||
.build()
|
||||
.create(ApiService::class.java)
|
||||
val apiClient = ApiClient(apiService, moshi)
|
||||
val generateId = GenerateId()
|
||||
val deviceIdentity = DeviceIdentity(db.userPreferenceDao(), generateId)
|
||||
val activeUserStore = ActiveUserStore(db.userPreferenceDao())
|
||||
|
||||
outboxRepository = OutboxRepository(opsDao, generateId, deviceIdentity, moshi)
|
||||
fileRepository = FileRepository(db.fileDao(), db.folderDao(), apiClient, generateId, db, outboxRepository)
|
||||
folderRepository = FolderRepository(db.folderDao(), apiClient, generateId, activeUserStore, db, outboxRepository)
|
||||
val thumbnails = ThumbnailStore(context)
|
||||
fileDeleter = FileDeleter(context, fileRepository, outboxRepository, db, thumbnails)
|
||||
folderDeleter = FolderDeleter(context, folderRepository, fileRepository, outboxRepository, db, thumbnails)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fichier_pousse_delete_cloud_pose_tombstone_et_journalise() = runTest {
|
||||
val folder = folderRepository.saveFolder(SaveFolderInput(uri = FOLDER_URI, name = "R", exists = true))
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(uri = FILE_URI, name = "a.txt", size = 10, resourceId = FILE_ID, processed = true),
|
||||
folderResourceId = folder.resourceId,
|
||||
)
|
||||
markSynced(FILE_ID, PendingOperationType.CREATE_RESOURCE)
|
||||
|
||||
val report = fileDeleter.deleteFiles(
|
||||
listOf(db.fileDao().getByResourceId(FILE_ID)!!),
|
||||
FileDeleter.DeleteMode.IN_CLOUD,
|
||||
)
|
||||
|
||||
assertEquals(1, report.succeeded)
|
||||
assertEquals(0, db.fileDao().getByResourceId(FILE_ID)!!.exists)
|
||||
val deletes = opsDao.selectPending(100).filter {
|
||||
it.resourceId == FILE_ID && it.operation == PendingOperationType.DELETE_RESOURCE
|
||||
}
|
||||
assertEquals(1, deletes.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fichier_jamais_pousse_delete_cloud_sans_delete_resource_mais_masque() = runTest {
|
||||
val folder = folderRepository.saveFolder(SaveFolderInput(uri = FOLDER_URI, name = "R", exists = true))
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(uri = FILE_URI, name = "a.txt", size = 10, resourceId = FILE_ID, processed = false),
|
||||
folderResourceId = folder.resourceId,
|
||||
)
|
||||
|
||||
val report = fileDeleter.deleteFiles(
|
||||
listOf(db.fileDao().getByResourceId(FILE_ID)!!),
|
||||
FileDeleter.DeleteMode.IN_CLOUD,
|
||||
)
|
||||
|
||||
assertEquals(1, report.succeeded)
|
||||
assertEquals(0, db.fileDao().getByResourceId(FILE_ID)!!.exists)
|
||||
val deletes = opsDao.selectPending(100).filter {
|
||||
it.resourceId == FILE_ID && it.operation == PendingOperationType.DELETE_RESOURCE
|
||||
}
|
||||
assertTrue("jamais poussé : aucun delete_resource", deletes.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dossier_pousse_delete_cloud_masque_tout_l_arbre() = runTest {
|
||||
val folder = folderRepository.saveFolder(SaveFolderInput(uri = FOLDER_URI, name = "R", exists = true))
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(uri = FILE_URI, name = "a.txt", size = 10, resourceId = FILE_ID, processed = true),
|
||||
folderResourceId = folder.resourceId,
|
||||
)
|
||||
markSynced(folder.resourceId, PendingOperationType.CREATE_RESOURCE)
|
||||
markSynced(FILE_ID, PendingOperationType.CREATE_RESOURCE)
|
||||
|
||||
val report = folderDeleter.deleteFolders(
|
||||
listOf(db.folderDao().getByResourceId(folder.resourceId)!!),
|
||||
FileDeleter.DeleteMode.IN_CLOUD,
|
||||
)
|
||||
|
||||
assertEquals(1, report.succeeded)
|
||||
assertEquals(0, db.folderDao().getByResourceId(folder.resourceId)!!.exists)
|
||||
assertEquals(0, db.fileDao().getByResourceId(FILE_ID)!!.exists)
|
||||
val deletes = opsDao.selectPending(100).filter {
|
||||
it.operation == PendingOperationType.DELETE_RESOURCE
|
||||
}.map { it.resourceId }.toSet()
|
||||
assertTrue(deletes.contains(folder.resourceId))
|
||||
assertTrue(deletes.contains(FILE_ID))
|
||||
}
|
||||
|
||||
private suspend fun markSynced(resourceId: String, operation: String) {
|
||||
val op = opsDao.selectPending(100).first {
|
||||
it.resourceId == resourceId && it.operation == operation
|
||||
}
|
||||
opsDao.markSynced(op.id, NOW)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val NOW = 1_700_000_000_000L
|
||||
const val FOLDER_URI = "content://tree/root"
|
||||
const val FILE_URI = "content://tree/root/a.txt"
|
||||
const val FILE_ID = "aabbccddeeff11223344556677889900"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user