Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[locker] Refactor: Use single db for files & trash

Neeraj Guptac5dec5f67d35
diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dart
index 7ab3ef98ae..f03323e144 100644
--- a/mobile/apps/locker/lib/main.dart
+++ b/mobile/apps/locker/lib/main.dart
@@ -23,14 +23,13 @@ import 'package:locker/app.dart';
import 'package:locker/core/locale.dart';
import 'package:locker/l10n/app_localizations.dart';
import 'package:locker/services/collections/collections_api_client.dart';
-import "package:locker/services/collections/collections_db.dart";
import 'package:locker/services/collections/collections_service.dart';
import 'package:locker/services/configuration.dart';
+import "package:locker/services/db/locker_db.dart";
import 'package:locker/services/favorites_service.dart';
import 'package:locker/services/files/download/service_locator.dart';
import "package:locker/services/files/links/links_client.dart";
import "package:locker/services/files/links/links_service.dart";
-import "package:locker/services/trash/trash_db.dart";
import 'package:locker/services/trash/trash_service.dart';
import 'package:locker/ui/pages/home_page.dart';
import 'package:package_info_plus/package_info_plus.dart';
@@ -162,12 +161,10 @@ Future<void> _init(bool bool, {String? via}) async {
await CryptoUtil.init();
- await CollectionDB.instance.init();
- await TrashDB.instance.init();
+ await LockerDB.instance.init();
await Configuration.instance.init([
- CollectionDB.instance,
- TrashDB.instance,
+ LockerDB.instance,
]);
await Network.instance.init(Configuration.instance);
diff --git a/mobile/apps/locker/lib/services/collections/collections_api_client.dart b/mobile/apps/locker/lib/services/collections/collections_api_client.dart
index 17a41d6d22..43e0b6d1b7 100644
--- a/mobile/apps/locker/lib/services/collections/collections_api_client.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_api_client.dart
@@ -11,7 +11,6 @@ import "package:ente_sharing/collection_sharing_service.dart";
import "package:ente_sharing/models/user.dart";
import 'package:locker/core/errors.dart';
import "package:locker/events/collections_updated_event.dart";
-import "package:locker/services/collections/collections_db.dart";
import "package:locker/services/collections/collections_service.dart";
import 'package:locker/services/collections/models/collection.dart';
import 'package:locker/services/collections/models/collection_file_item.dart';
@@ -19,6 +18,7 @@ import 'package:locker/services/collections/models/collection_magic.dart';
import 'package:locker/services/collections/models/diff.dart';
import "package:locker/services/collections/models/public_url.dart";
import 'package:locker/services/configuration.dart';
+import "package:locker/services/db/locker_db.dart";
import "package:locker/services/files/sync/metadata_updater_service.dart";
import 'package:locker/services/files/sync/models/file.dart';
import 'package:locker/services/files/sync/models/file_magic.dart';
@@ -36,10 +36,10 @@ class CollectionApiClient {
final _enteDio = Network.instance.enteDio;
final _config = Configuration.instance;
- late CollectionDB _db;
+ late LockerDB _db;
Future<void> init() async {
- _db = CollectionDB.instance;
+ _db = LockerDB.instance;
}
Future<List<Collection>> getCollections(int sinceTime) async {
diff --git a/mobile/apps/locker/lib/services/collections/collections_service.dart b/mobile/apps/locker/lib/services/collections/collections_service.dart
index 05dec54fbb..149c70f873 100644
--- a/mobile/apps/locker/lib/services/collections/collections_service.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_service.dart
@@ -15,12 +15,12 @@ import 'package:locker/events/collections_updated_event.dart';
import 'package:locker/events/trigger_logout_event.dart';
import 'package:locker/events/user_details_refresh_event.dart';
import "package:locker/services/collections/collections_api_client.dart";
-import "package:locker/services/collections/collections_db.dart";
import 'package:locker/services/collections/models/collection.dart';
import "package:locker/services/collections/models/collection_items.dart";
import "package:locker/services/collections/models/files_split.dart";
import "package:locker/services/collections/models/public_url.dart";
import 'package:locker/services/configuration.dart';
+import "package:locker/services/db/locker_db.dart";
import 'package:locker/services/files/sync/models/file.dart';
import 'package:locker/services/trash/models/trash_item_request.dart';
import "package:locker/services/trash/trash_service.dart";
@@ -48,19 +48,19 @@ class CollectionService {
final _logger = Logger("CollectionService");
late CollectionApiClient _apiClient;
- late CollectionDB _db;
+ late LockerDB _db;
final _collectionIDToCollections = <int, Collection>{};
CollectionService._privateConstructor();
Future<void> init() async {
- _db = CollectionDB.instance;
+ _db = LockerDB.instance;
_apiClient = CollectionApiClient.instance;
- Bus.instance.on<SignedInEvent>().listen((event) {
+ Bus.instance.on<SignedInEvent>().listen((event) async {
_logger.info("User signed in, starting initial sync.");
- _init();
+ await _init();
});
if (Configuration.instance.hasConfiguredAccount()) {
@@ -260,11 +260,7 @@ class CollectionService {
}
}
- /// Removes orphaned files that exist in files table but have no collection mappings.
- /// This is a one-time cleanup for files deleted from trash before the fix was applied.
- ///
- /// This migration fix can be removed after a year or so (around Nov 2026)
- /// once all users have had the corrected trash deletion logic applied.
+ /// Removes orphaned files that exist in files but have no collection mappings.
Future<void> cleanupOrphanedFiles() async {
try {
await _db.cleanupOrphanedFiles();
diff --git a/mobile/apps/locker/lib/services/collections/collections_db.dart b/mobile/apps/locker/lib/services/db/locker_db.dart
similarity index 56%
rename from mobile/apps/locker/lib/services/collections/collections_db.dart
rename to mobile/apps/locker/lib/services/db/locker_db.dart
index a9fd586a0d..89c230a249 100644
--- a/mobile/apps/locker/lib/services/collections/collections_db.dart
+++ b/mobile/apps/locker/lib/services/db/locker_db.dart
@@ -1,31 +1,41 @@
import 'dart:convert';
+import 'dart:io';
import "package:ente_base/models/database.dart";
+import 'package:ente_crypto_api/ente_crypto_api.dart';
import "package:ente_sharing/models/user.dart";
+import 'package:flutter/foundation.dart';
import 'package:locker/models/file_type.dart';
import 'package:locker/services/collections/models/collection.dart';
import 'package:locker/services/collections/models/public_url.dart';
import 'package:locker/services/files/sync/models/file.dart';
+import 'package:locker/utils/crypto_helper.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
-class CollectionDB extends EnteBaseDatabase {
- CollectionDB._privateConstructor();
+class LockerDB extends EnteBaseDatabase {
+ LockerDB._privateConstructor();
- static final CollectionDB instance = CollectionDB._privateConstructor();
+ static final LockerDB instance = LockerDB._privateConstructor();
Database? _database;
int _collectionSyncTime = 0;
final Map<int, int> _collectionSyncTimesCache = {};
+ static const String databaseName = 'locker.db';
static const String _collectionsTable = 'collections';
static const String _filesTable = 'files';
+ static const String trashTable = 'trash_files';
static const String _collectionFilesTable = 'collection_files';
static const String _syncTimesTable = 'sync_times';
+ static const int _collectionPayloadVersion = 1;
+ static const int _filePayloadVersion = 1;
+ static const int _trashPayloadVersion = 1;
Future<void> init() async {
_database = await _initDatabase();
+ await _createTables(_db, 1);
await _loadCaches();
}
@@ -51,7 +61,11 @@ class CollectionDB extends EnteBaseDatabase {
Future<Database> _initDatabase() async {
final documentsDirectory = await getApplicationDocumentsDirectory();
- final path = join(documentsDirectory.path, 'collection_store.db');
+ await _deleteObsoleteDatabases(documentsDirectory.path);
+ final path = join(documentsDirectory.path, databaseName);
+ if (kDebugMode) {
+ debugPrint('LockerDB path: $path');
+ }
return await openDatabase(
path,
@@ -62,61 +76,25 @@ class CollectionDB extends EnteBaseDatabase {
Future<void> _createTables(Database db, int version) async {
await db.execute('''
- CREATE TABLE $_collectionsTable (
+ CREATE TABLE IF NOT EXISTS $_collectionsTable (
id INTEGER PRIMARY KEY,
owner_id INTEGER,
- owner_email TEXT,
- owner_name TEXT,
- encrypted_key TEXT,
- key_decryption_nonce TEXT,
- name TEXT,
type TEXT,
- attributes_version INTEGER,
- attributes_encrypted_path TEXT,
- attributes_path_decryption_nonce TEXT,
- sharees TEXT,
- public_urls TEXT,
updation_time INTEGER,
is_deleted INTEGER DEFAULT 0,
- decrypted_path TEXT,
- m_md_encoded_json TEXT,
- m_md_pub_encoded_json TEXT,
- shared_mmd_json TEXT,
- m_md_version INTEGER DEFAULT 0,
- m_mb_pub_version INTEGER DEFAULT 0,
- shared_mmd_version INTEGER DEFAULT 0
- )
- ''');
-
- await db.execute('''
- CREATE TABLE $_filesTable (
- uploaded_file_id INTEGER PRIMARY KEY,
- local_path TEXT,
- owner_id INTEGER,
- collection_id INTEGER,
- title TEXT,
- creation_time INTEGER,
- modification_time INTEGER,
- updation_time INTEGER,
- added_time INTEGER,
- hash TEXT,
- metadata_version INTEGER,
encrypted_key TEXT,
key_decryption_nonce TEXT,
- file_decryption_header TEXT,
- thumbnail_decryption_header TEXT,
- metadata_decryption_header TEXT,
- file_size INTEGER,
- file_type INTEGER,
- m_md_encoded_json TEXT,
- m_md_version INTEGER DEFAULT 0,
- pub_mmd_encoded_json TEXT,
- pub_mmd_version INTEGER DEFAULT 1
+ payload_encrypted_data TEXT NOT NULL,
+ payload_decryption_nonce TEXT NOT NULL,
+ payload_version INTEGER DEFAULT $_collectionPayloadVersion
)
''');
+ await _createFilesTable(db);
+ await _createTrashTable(db);
+
await db.execute('''
- CREATE TABLE $_collectionFilesTable (
+ CREATE TABLE IF NOT EXISTS $_collectionFilesTable (
collection_id INTEGER,
uploaded_file_id INTEGER,
PRIMARY KEY (collection_id, uploaded_file_id)
@@ -124,29 +102,102 @@ class CollectionDB extends EnteBaseDatabase {
''');
await db.execute('''
- CREATE TABLE $_syncTimesTable (
+ CREATE TABLE IF NOT EXISTS $_syncTimesTable (
key TEXT PRIMARY KEY,
value INTEGER NOT NULL
)
''');
await db.execute('''
- CREATE INDEX idx_files_collection_id ON $_filesTable (collection_id)
+ CREATE INDEX IF NOT EXISTS idx_files_collection_id ON $_filesTable (collection_id)
''');
await db.execute('''
- CREATE INDEX idx_files_uploaded_file_id ON $_filesTable (uploaded_file_id)
+ CREATE INDEX IF NOT EXISTS idx_files_uploaded_file_id ON $_filesTable (uploaded_file_id)
''');
await db.execute('''
- CREATE INDEX idx_collection_files_uploaded_file_id ON $_collectionFilesTable (uploaded_file_id)
+ CREATE INDEX IF NOT EXISTS idx_collection_files_uploaded_file_id ON $_collectionFilesTable (uploaded_file_id)
''');
await db.execute('''
- CREATE INDEX idx_collections_updation_time ON $_collectionsTable (updation_time)
+ CREATE INDEX IF NOT EXISTS idx_collections_updation_time ON $_collectionsTable (updation_time)
''');
}
+ Future<void> _createFilesTable(Database db) async {
+ await db.execute('''
+ CREATE TABLE IF NOT EXISTS $_filesTable (
+ uploaded_file_id INTEGER PRIMARY KEY,
+ collection_id INTEGER,
+ owner_id INTEGER,
+ updation_time INTEGER,
+ encrypted_key TEXT,
+ key_decryption_nonce TEXT,
+ file_decryption_header TEXT,
+ thumbnail_decryption_header TEXT,
+ metadata_decryption_header TEXT,
+ file_size INTEGER,
+ payload_encrypted_data TEXT NOT NULL,
+ payload_decryption_header TEXT NOT NULL,
+ payload_version INTEGER DEFAULT $_filePayloadVersion
+ )
+ ''');
+ }
+
+ Future<void> _createTrashTable(Database db) async {
+ await db.execute('''
+ CREATE TABLE IF NOT EXISTS ${LockerDB.trashTable} (
+ uploaded_file_id INTEGER PRIMARY KEY,
+ collection_id INTEGER,
+ owner_id INTEGER,
+ updation_time INTEGER,
+ encrypted_key TEXT,
+ key_decryption_nonce TEXT,
+ file_decryption_header TEXT,
+ thumbnail_decryption_header TEXT,
+ metadata_decryption_header TEXT,
+ file_size INTEGER,
+ created_at INTEGER,
+ update_at INTEGER,
+ delete_by INTEGER,
+ payload_encrypted_data TEXT NOT NULL,
+ payload_decryption_header TEXT NOT NULL,
+ payload_version INTEGER DEFAULT $_trashPayloadVersion
+ )
+ ''');
+ }
+
+ Future<void> _deleteObsoleteDatabases(String baseDir) async {
+ const obsoleteNames = <String>[
+ 'collection_store.db',
+ 'trash.db',
+ ];
+ for (final name in obsoleteNames) {
+ final obsoletePath = join(baseDir, name);
+ if (obsoletePath == join(baseDir, databaseName)) {
+ continue;
+ }
+ try {
+ await deleteDatabase(obsoletePath);
+ } catch (_) {
+ // Ignore cleanup errors; the app can continue with the new DB.
+ }
+ try {
+ final walFile = File('$obsoletePath-wal');
+ if (await walFile.exists()) {
+ await walFile.delete();
+ }
+ final shmFile = File('$obsoletePath-shm');
+ if (await shmFile.exists()) {
+ await shmFile.delete();
+ }
+ } catch (_) {
+ // Ignore sidecar cleanup failures.
+ }
+ }
+ }
+
Database get _db {
if (_database == null) {
throw Exception('Database not initialized. Call init() first.');
@@ -154,6 +205,8 @@ class CollectionDB extends EnteBaseDatabase {
return _database!;
}
+ Database get database => _db;
+
Future<void> setSyncTime(int lastSyncTime) async {
_collectionSyncTime = lastSyncTime;
await _db.insert(
@@ -297,9 +350,10 @@ class CollectionDB extends EnteBaseDatabase {
final batch = _db.batch();
for (final file in files) {
+ final fileMap = await _fileToMap(file);
batch.insert(
_filesTable,
- _fileToMap(file),
+ fileMap,
conflictAlgorithm: ConflictAlgorithm.replace,
);
@@ -386,7 +440,7 @@ class CollectionDB extends EnteBaseDatabase {
final List<EnteFile> uniqueFiles = [];
for (final row in result) {
- final file = _mapToFile(row);
+ final file = await _mapFromRow(row);
if (!seenFileIds.contains(file.uploadedFileID)) {
seenFileIds.add(file.uploadedFileID!);
@@ -437,7 +491,8 @@ class CollectionDB extends EnteBaseDatabase {
// Group files by collection ID
for (final row in result) {
final collectionId = row['mapping_collection_id'] as int;
- final file = _mapToFile(row)..collectionID = collectionId;
+ final file = await _mapFromRow(row)
+ ..collectionID = collectionId;
collectionToFilesMap.putIfAbsent(collectionId, () => []);
collectionToFilesMap[collectionId]!.add(file);
@@ -448,15 +503,18 @@ class CollectionDB extends EnteBaseDatabase {
Future<List<EnteFile>> getAllFiles() async {
final result = await _db.query(_filesTable);
- return result.map((row) => _mapToFile(row)).toList();
+ final files = <EnteFile>[];
+ for (final row in result) {
+ files.add(await _mapFromRow(row));
+ }
+ return files;
}
- /// Removes orphaned files that exist in files table but have no collection mappings.
- /// This can happen if files were deleted from trash before the cleanup fix was applied.
+ /// Removes orphaned files that exist in files but have no collection mappings.
Future<void> cleanupOrphanedFiles() async {
final orphanedFiles = await _db.rawQuery(
'''
- SELECT f.uploaded_file_id, f.title
+ SELECT f.uploaded_file_id
FROM $_filesTable f
LEFT JOIN $_collectionFilesTable cf ON f.uploaded_file_id = cf.uploaded_file_id
WHERE cf.uploaded_file_id IS NULL
@@ -481,25 +539,40 @@ class CollectionDB extends EnteBaseDatabase {
}
Map<String, dynamic> _collectionToMap(Collection collection) {
+ final collectionKey = CryptoHelper.instance.getCollectionKey(collection);
+ final encryptedPayload = CryptoUtil.encryptSync(
+ utf8.encode(jsonEncode(_collectionPayloadToMap(collection))),
+ collectionKey,
+ );
+
return {
'id': collection.id,
'owner_id': collection.owner.id,
- 'owner_email': collection.owner.email,
- 'owner_name': collection.owner.name,
+ 'type': typeToString(collection.type),
+ 'updation_time': collection.updationTime,
+ 'is_deleted': collection.isDeleted ? 1 : 0,
'encrypted_key': collection.encryptedKey,
'key_decryption_nonce': collection.keyDecryptionNonce,
+ 'payload_encrypted_data':
+ CryptoUtil.bin2base64(encryptedPayload.encryptedData!),
+ 'payload_decryption_nonce':
+ CryptoUtil.bin2base64(encryptedPayload.nonce!),
+ 'payload_version': _collectionPayloadVersion,
+ };
+ }
+
+ Map<String, dynamic> _collectionPayloadToMap(Collection collection) {
+ return {
+ 'owner_email': collection.owner.email,
+ // ignore: deprecated_member_use
+ 'owner_name': collection.owner.name,
'name': collection.name,
- 'type': typeToString(collection.type),
'attributes_version': collection.attributes.version,
'attributes_encrypted_path': collection.attributes.encryptedPath,
'attributes_path_decryption_nonce':
collection.attributes.pathDecryptionNonce,
- 'sharees':
- jsonEncode(collection.sharees.map((user) => user.toMap()).toList()),
- 'public_urls':
- jsonEncode(collection.publicURLs.map((url) => url.toMap()).toList()),
- 'updation_time': collection.updationTime,
- 'is_deleted': collection.isDeleted ? 1 : 0,
+ 'sharees': collection.sharees.map((user) => user.toMap()).toList(),
+ 'public_urls': collection.publicURLs.map((url) => url.toMap()).toList(),
'decrypted_path': collection.decryptedPath,
'm_md_encoded_json': collection.mMdEncodedJson,
'm_md_pub_encoded_json': collection.mMdPubEncodedJson,
@@ -511,28 +584,29 @@ class CollectionDB extends EnteBaseDatabase {
}
Collection _mapToCollection(Map<String, dynamic> map) {
+ final payload = _collectionPayloadFromRow(map);
+
final owner = User(
id: map['owner_id'] as int?,
- email: map['owner_email'] as String,
- name: map['owner_name'] as String?,
+ email: payload['owner_email'] as String? ?? '',
+ name: payload['owner_name'] as String?,
);
final attributes = CollectionAttributes(
- version: map['attributes_version'] as int? ?? 0,
- encryptedPath: map['attributes_encrypted_path'] as String?,
- pathDecryptionNonce: map['attributes_path_decryption_nonce'] as String?,
+ version: payload['attributes_version'] as int? ?? 0,
+ encryptedPath: payload['attributes_encrypted_path'] as String?,
+ pathDecryptionNonce:
+ payload['attributes_path_decryption_nonce'] as String?,
);
- final shareesJson = map['sharees'] as String? ?? '[]';
- final shareesData = jsonDecode(shareesJson) as List<dynamic>;
+ final shareesData = payload['sharees'] as List<dynamic>? ?? const [];
final sharees = shareesData
.map((shareeeMap) => User.fromMap(shareeeMap as Map<String, dynamic>))
.where((user) => user != null)
.cast<User>()
.toList();
- final publicUrlsJson = map['public_urls'] as String? ?? '[]';
- final publicURLsData = jsonDecode(publicUrlsJson) as List<dynamic>;
+ final publicURLsData = payload['public_urls'] as List<dynamic>? ?? const [];
final publicURLs = publicURLsData
.map((urlMap) => PublicURL.fromMap(urlMap as Map<String, dynamic>))
.where((url) => url != null)
@@ -544,7 +618,7 @@ class CollectionDB extends EnteBaseDatabase {
owner,
map['encrypted_key'] as String,
map['key_decryption_nonce'] as String?,
- map['name'] as String?,
+ payload['name'] as String?,
null,
null,
typeFromString(map['type'] as String),
@@ -555,36 +629,122 @@ class CollectionDB extends EnteBaseDatabase {
isDeleted: (map['is_deleted'] as int? ?? 0) == 1,
);
- collection.decryptedPath = map['decrypted_path'] as String?;
- collection.mMdEncodedJson = map['m_md_encoded_json'] as String?;
- collection.mMdPubEncodedJson = map['m_md_pub_encoded_json'] as String?;
- collection.sharedMmdJson = map['shared_mmd_json'] as String?;
- collection.mMdVersion = map['m_md_version'] as int? ?? 0;
- collection.mMbPubVersion = map['m_mb_pub_version'] as int? ?? 0;
- collection.sharedMmdVersion = map['shared_mmd_version'] as int? ?? 0;
+ collection.decryptedPath = payload['decrypted_path'] as String?;
+ collection.mMdEncodedJson = payload['m_md_encoded_json'] as String?;
+ collection.mMdPubEncodedJson = payload['m_md_pub_encoded_json'] as String?;
+ collection.sharedMmdJson = payload['shared_mmd_json'] as String?;
+ collection.mMdVersion = payload['m_md_version'] as int? ?? 0;
+ collection.mMbPubVersion = payload['m_mb_pub_version'] as int? ?? 0;
+ collection.sharedMmdVersion = payload['shared_mmd_version'] as int? ?? 0;
return collection;
}
- Map<String, dynamic> _fileToMap(EnteFile file) {
+ Map<String, dynamic> _collectionPayloadFromRow(Map<String, dynamic> map) {
+ final encryptedPayloadData = map['payload_encrypted_data'] as String?;
+ final payloadDecryptionNonce = map['payload_decryption_nonce'] as String?;
+ if (encryptedPayloadData == null || payloadDecryptionNonce == null) {
+ return _legacyCollectionPayloadFromRow(map);
+ }
+
+ final collectionKey = _getCollectionKeyFromRow(map);
+ final decryptedPayload = CryptoUtil.decryptSync(
+ CryptoUtil.base642bin(encryptedPayloadData),
+ collectionKey,
+ CryptoUtil.base642bin(payloadDecryptionNonce),
+ );
+ return jsonDecode(utf8.decode(decryptedPayload)) as Map<String, dynamic>;
+ }
+
+ Map<String, dynamic> _legacyCollectionPayloadFromRow(
+ Map<String, dynamic> map,
+ ) {
+ final shareesJson = map['sharees'] as String? ?? '[]';
+ final publicUrlsJson = map['public_urls'] as String? ?? '[]';
+
+ return {
+ 'owner_email': map['owner_email'],
+ 'owner_name': map['owner_name'],
+ 'name': map['name'],
+ 'attributes_version': map['attributes_version'],
+ 'attributes_encrypted_path': map['attributes_encrypted_path'],
+ 'attributes_path_decryption_nonce':
+ map['attributes_path_decryption_nonce'],
+ 'sharees': jsonDecode(shareesJson) as List<dynamic>,
+ 'public_urls': jsonDecode(publicUrlsJson) as List<dynamic>,
+ 'decrypted_path': map['decrypted_path'],
+ 'm_md_encoded_json': map['m_md_encoded_json'],
+ 'm_md_pub_encoded_json': map['m_md_pub_encoded_json'],
+ 'shared_mmd_json': map['shared_mmd_json'],
+ 'm_md_version': map['m_md_version'],
+ 'm_mb_pub_version': map['m_mb_pub_version'],
+ 'shared_mmd_version': map['shared_mmd_version'],
+ };
+ }
+
+ Uint8List _getCollectionKeyFromRow(Map<String, dynamic> map) {
+ final encryptedKey = map['encrypted_key'] as String?;
+ if (encryptedKey == null) {
+ throw Exception('Invalid collections row: missing encrypted key');
+ }
+
+ final owner = User(
+ id: map['owner_id'] as int?,
+ email: '',
+ );
+ final collection = Collection(
+ map['id'] as int,
+ owner,
+ encryptedKey,
+ map['key_decryption_nonce'] as String?,
+ null,
+ null,
+ null,
+ typeFromString(map['type'] as String),
+ CollectionAttributes(),
+ <User>[],
+ <PublicURL>[],
+ map['updation_time'] as int? ?? 0,
+ isDeleted: (map['is_deleted'] as int? ?? 0) == 1,
+ );
+ return CryptoHelper.instance.getCollectionKey(collection);
+ }
+
+ Future<Map<String, dynamic>> _fileToMap(EnteFile file) async {
+ final fileKey = await _getFileKey(file);
+ final encryptedPayload = await CryptoUtil.encryptData(
+ utf8.encode(jsonEncode(_filePayloadToMap(file))),
+ fileKey,
+ );
+
return {
'uploaded_file_id': file.uploadedFileID,
- 'local_path': file.localPath,
- 'owner_id': file.ownerID,
'collection_id': file.collectionID,
- 'title': file.title,
- 'creation_time': file.creationTime,
- 'modification_time': file.modificationTime,
+ 'owner_id': file.ownerID,
'updation_time': file.updationTime,
- 'added_time': file.addedTime,
- 'hash': file.hash,
- 'metadata_version': file.metadataVersion,
'encrypted_key': file.encryptedKey,
'key_decryption_nonce': file.keyDecryptionNonce,
'file_decryption_header': file.fileDecryptionHeader,
'thumbnail_decryption_header': file.thumbnailDecryptionHeader,
'metadata_decryption_header': file.metadataDecryptionHeader,
'file_size': file.fileSize,
+ 'payload_encrypted_data':
+ CryptoUtil.bin2base64(encryptedPayload.encryptedData!),
+ 'payload_decryption_header':
+ CryptoUtil.bin2base64(encryptedPayload.header!),
+ 'payload_version': _filePayloadVersion,
+ };
+ }
+
+ Map<String, dynamic> _filePayloadToMap(EnteFile file) {
+ return {
+ 'local_path': file.localPath,
+ 'title': file.title,
+ 'creation_time': file.creationTime,
+ 'modification_time': file.modificationTime,
+ 'added_time': file.addedTime,
+ 'hash': file.hash,
+ 'metadata_version': file.metadataVersion,
'file_type': file.fileType?.index,
'm_md_encoded_json': file.mMdEncodedJson,
'm_md_version': file.mMdVersion,
@@ -593,37 +753,94 @@ class CollectionDB extends EnteBaseDatabase {
};
}
- EnteFile _mapToFile(Map<String, dynamic> map) {
- final file = EnteFile();
+ Future<EnteFile> _mapFromRow(Map<String, dynamic> map) async {
+ final encryptedPayloadData = map['payload_encrypted_data'] as String?;
+ final payloadDecryptionHeader = map['payload_decryption_header'] as String?;
+ if (encryptedPayloadData == null || payloadDecryptionHeader == null) {
+ throw Exception('Invalid files row: missing encrypted payload');
+ }
+
+ final fileKey = await _getFileKeyFromRow(map);
+ final decryptedPayload = await CryptoUtil.decryptData(
+ CryptoUtil.base642bin(encryptedPayloadData),
+ fileKey,
+ CryptoUtil.base642bin(payloadDecryptionHeader),
+ );
- file.localPath = map['local_path'];
+ final payload =
+ jsonDecode(utf8.decode(decryptedPayload)) as Map<String, dynamic>;
+
+ final file = EnteFile();
file.uploadedFileID = map['uploaded_file_id'];
- file.ownerID = map['owner_id'];
file.collectionID = map['collection_id'];
- file.title = map['title'];
- file.creationTime = map['creation_time'];
- file.modificationTime = map['modification_time'];
- file.updationTime = map['updation_time'];
- file.addedTime = map['added_time'];
- file.hash = map['hash'];
- file.metadataVersion = map['metadata_version'];
file.encryptedKey = map['encrypted_key'];
file.keyDecryptionNonce = map['key_decryption_nonce'];
- file.fileDecryptionHeader = map['file_decryption_header'];
- file.thumbnailDecryptionHeader = map['thumbnail_decryption_header'];
- file.metadataDecryptionHeader = map['metadata_decryption_header'];
- file.fileSize = map['file_size'];
- if (map['file_type'] != null) {
- file.fileType = getFileType(map['file_type']);
+
+ file.localPath = payload['local_path'];
+ file.ownerID = map['owner_id'] ?? payload['owner_id'];
+ file.title = payload['title'];
+ file.creationTime = payload['creation_time'];
+ file.modificationTime = payload['modification_time'];
+ file.updationTime = map['updation_time'] ?? payload['updation_time'];
+ file.addedTime = payload['added_time'];
+ file.hash = payload['hash'];
+ file.metadataVersion = payload['metadata_version'];
+ file.fileDecryptionHeader =
+ map['file_decryption_header'] ?? payload['file_decryption_header'];
+ file.thumbnailDecryptionHeader = map['thumbnail_decryption_header'] ??
+ payload['thumbnail_decryption_header'];
+ file.metadataDecryptionHeader = map['metadata_decryption_header'] ??
+ payload['metadata_decryption_header'];
+ file.fileSize = map['file_size'] ?? payload['file_size'];
+ if (payload['file_type'] != null) {
+ file.fileType = getFileType(payload['file_type']);
}
- file.mMdEncodedJson = map['m_md_encoded_json'];
- file.mMdVersion = map['m_md_version'] ?? 0;
- file.pubMmdEncodedJson = map['pub_mmd_encoded_json'];
- file.pubMmdVersion = map['pub_mmd_version'] ?? 1;
+ file.mMdEncodedJson = payload['m_md_encoded_json'];
+ file.mMdVersion = payload['m_md_version'] ?? 0;
+ file.pubMmdEncodedJson = payload['pub_mmd_encoded_json'];
+ file.pubMmdVersion = payload['pub_mmd_version'] ?? 1;
return file;
}
+ Future<Uint8List> _getFileKey(EnteFile file) async {
+ if (file.collectionID == null ||
+ file.encryptedKey == null ||
+ file.keyDecryptionNonce == null) {
+ throw Exception('Missing file key data for file ${file.uploadedFileID}');
+ }
+
+ final collection = await getCollection(file.collectionID!);
+ final collectionKey = CryptoHelper.instance.getCollectionKey(collection);
+ return CryptoHelper.instance.getFileKey(
+ file.encryptedKey!,
+ file.keyDecryptionNonce!,
+ collectionKey,
+ );
+ }
+
+ Future<Uint8List> _getFileKeyFromRow(Map<String, dynamic> map) async {
+ final collectionID = map['collection_id'] as int?;
+ final encryptedKey = map['encrypted_key'] as String?;
+ final keyDecryptionNonce = map['key_decryption_nonce'] as String?;
+
+ if (collectionID == null ||
+ encryptedKey == null ||
+ keyDecryptionNonce == null) {
+ throw Exception(
+ 'Missing key fields in files for file ${map['uploaded_file_id']}',
+ );
+ }
+
+ final collection = await getCollection(collectionID);
+ final collectionKey = CryptoHelper.instance.getCollectionKey(collection);
+ return CryptoHelper.instance.getFileKey(
+ encryptedKey,
+ keyDecryptionNonce,
+ collectionKey,
+ );
+ }
+
Future<void> close() async {
await _database?.close();
_database = null;
@@ -633,6 +850,7 @@ class CollectionDB extends EnteBaseDatabase {
Future<void> clearTable() async {
await _database?.delete(_collectionsTable);
await _database?.delete(_filesTable);
+ await _database?.delete(LockerDB.trashTable);
await _database?.delete(_collectionFilesTable);
await _database?.delete(_syncTimesTable);
_collectionSyncTimesCache.clear();
diff --git a/mobile/apps/locker/lib/services/db/trash_table.dart b/mobile/apps/locker/lib/services/db/trash_table.dart
new file mode 100644
index 0000000000..1449230102
--- /dev/null
+++ b/mobile/apps/locker/lib/services/db/trash_table.dart
@@ -0,0 +1,199 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import "package:ente_crypto_api/ente_crypto_api.dart";
+import 'package:locker/services/db/locker_db.dart';
+import 'package:locker/services/trash/models/trash_file.dart';
+import 'package:locker/utils/crypto_helper.dart';
+import 'package:sqflite/sqflite.dart';
+
+const int _trashPayloadVersion = 1;
+
+extension TrashTable on LockerDB {
+ Future<void> insertTrashFiles(List<TrashFile> trashFiles) async {
+ final batch = database.batch();
+
+ for (final trashFile in trashFiles) {
+ final map = await _trashFileToMap(this, trashFile);
+ batch.insert(
+ LockerDB.trashTable,
+ map,
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ await batch.commit();
+ }
+
+ Future<void> deleteTrashFiles(List<int> uploadedFileIDs) async {
+ final batch = database.batch();
+
+ for (final uploadedFileID in uploadedFileIDs) {
+ batch.delete(
+ LockerDB.trashTable,
+ where: 'uploaded_file_id = ?',
+ whereArgs: [uploadedFileID],
+ );
+ }
+
+ await batch.commit();
+ }
+
+ Future<List<TrashFile>> getTrashFiles() async {
+ final rows = await database.query(LockerDB.trashTable);
+ final files = <TrashFile>[];
+ for (final row in rows) {
+ files.add(await _trashFileFromRow(this, row));
+ }
+ return files;
+ }
+
+ Future<void> clearTrashFilesTable() async {
+ await database.delete(LockerDB.trashTable);
+ }
+}
+
+Future<Map<String, dynamic>> _trashFileToMap(
+ LockerDB db,
+ TrashFile trashFile,
+) async {
+ final fileKey = await _getTrashFileKey(db, trashFile);
+ final encryptedPayload = await CryptoUtil.encryptData(
+ utf8.encode(jsonEncode(_trashPayloadToMap(trashFile))),
+ fileKey,
+ );
+
+ return {
+ 'uploaded_file_id': trashFile.uploadedFileID!,
+ 'collection_id': trashFile.collectionID,
+ 'owner_id': trashFile.ownerID,
+ 'updation_time': trashFile.updationTime,
+ 'encrypted_key': trashFile.encryptedKey,
+ 'key_decryption_nonce': trashFile.keyDecryptionNonce,
+ 'file_decryption_header': trashFile.fileDecryptionHeader,
+ 'thumbnail_decryption_header': trashFile.thumbnailDecryptionHeader,
+ 'metadata_decryption_header': trashFile.metadataDecryptionHeader,
+ 'file_size': trashFile.fileSize,
+ 'created_at': trashFile.createdAt,
+ 'update_at': trashFile.updateAt,
+ 'delete_by': trashFile.deleteBy,
+ 'payload_encrypted_data':
+ CryptoUtil.bin2base64(encryptedPayload.encryptedData!),
+ 'payload_decryption_header':
+ CryptoUtil.bin2base64(encryptedPayload.header!),
+ 'payload_version': _trashPayloadVersion,
+ };
+}
+
+Map<String, dynamic> _trashPayloadToMap(TrashFile trashFile) {
+ return {
+ 'local_path': trashFile.localPath,
+ 'title': trashFile.title,
+ 'creation_time': trashFile.creationTime,
+ 'modification_time': trashFile.modificationTime,
+ 'added_time': trashFile.addedTime,
+ 'hash': trashFile.hash,
+ 'metadata_version': trashFile.metadataVersion,
+ 'm_md_encoded_json': trashFile.mMdEncodedJson,
+ 'm_md_version': trashFile.mMdVersion,
+ 'pub_mmd_encoded_json': trashFile.pubMmdEncodedJson,
+ 'pub_mmd_version': trashFile.pubMmdVersion,
+ };
+}
+
+Future<TrashFile> _trashFileFromRow(
+ LockerDB db,
+ Map<String, dynamic> row,
+) async {
+ final encryptedPayloadData = row['payload_encrypted_data'] as String?;
+ final payloadDecryptionHeader = row['payload_decryption_header'] as String?;
+ if (encryptedPayloadData == null || payloadDecryptionHeader == null) {
+ throw Exception('Invalid trash_files row: missing encrypted payload');
+ }
+
+ final fileKey = await _getTrashFileKeyFromRow(db, row);
+ final decryptedPayload = await CryptoUtil.decryptData(
+ CryptoUtil.base642bin(encryptedPayloadData),
+ fileKey,
+ CryptoUtil.base642bin(payloadDecryptionHeader),
+ );
+ final payload = jsonDecode(utf8.decode(decryptedPayload));
+
+ final trashFile = TrashFile();
+ trashFile.uploadedFileID = row['uploaded_file_id'];
+ trashFile.collectionID = row['collection_id'];
+ trashFile.encryptedKey = row['encrypted_key'];
+ trashFile.keyDecryptionNonce = row['key_decryption_nonce'];
+
+ trashFile.localPath = payload['local_path'];
+ trashFile.ownerID = row['owner_id'] ?? payload['owner_id'];
+ trashFile.title = payload['title'];
+ trashFile.creationTime = payload['creation_time'];
+ trashFile.modificationTime = payload['modification_time'];
+ trashFile.updationTime = row['updation_time'] ?? payload['updation_time'];
+ trashFile.addedTime = payload['added_time'];
+ trashFile.hash = payload['hash'];
+ trashFile.metadataVersion = payload['metadata_version'];
+ trashFile.fileDecryptionHeader =
+ row['file_decryption_header'] ?? payload['file_decryption_header'];
+ trashFile.thumbnailDecryptionHeader = row['thumbnail_decryption_header'] ??
+ payload['thumbnail_decryption_header'];
+ trashFile.metadataDecryptionHeader = row['metadata_decryption_header'] ??
+ payload['metadata_decryption_header'];
+ trashFile.fileSize = row['file_size'] ?? payload['file_size'];
+ trashFile.mMdEncodedJson = payload['m_md_encoded_json'];
+ trashFile.mMdVersion = payload['m_md_version'] ?? 0;
+ trashFile.pubMmdEncodedJson = payload['pub_mmd_encoded_json'];
+ trashFile.pubMmdVersion = payload['pub_mmd_version'] ?? 1;
+ trashFile.createdAt = row['created_at'] ?? payload['created_at'];
+ trashFile.updateAt = row['update_at'] ?? payload['update_at'];
+ trashFile.deleteBy = row['delete_by'] ?? payload['delete_by'];
+
+ return trashFile;
+}
+
+Future<Uint8List> _getTrashFileKey(
+ LockerDB db,
+ TrashFile file,
+) async {
+ if (file.collectionID == null ||
+ file.encryptedKey == null ||
+ file.keyDecryptionNonce == null) {
+ throw Exception(
+ 'Missing file key fields for trash file ${file.uploadedFileID}',
+ );
+ }
+
+ final collection = await db.getCollection(file.collectionID!);
+ final collectionKey = CryptoHelper.instance.getCollectionKey(collection);
+ return CryptoHelper.instance.getFileKey(
+ file.encryptedKey!,
+ file.keyDecryptionNonce!,
+ collectionKey,
+ );
+}
+
+Future<Uint8List> _getTrashFileKeyFromRow(
+ LockerDB db,
+ Map<String, dynamic> row,
+) async {
+ final collectionID = row['collection_id'] as int?;
+ final encryptedKey = row['encrypted_key'] as String?;
+ final keyDecryptionNonce = row['key_decryption_nonce'] as String?;
+
+ if (collectionID == null ||
+ encryptedKey == null ||
+ keyDecryptionNonce == null) {
+ throw Exception(
+ 'Missing key fields in trash_files for file ${row['uploaded_file_id']}',
+ );
+ }
+
+ final collection = await db.getCollection(collectionID);
+ final collectionKey = CryptoHelper.instance.getCollectionKey(collection);
+ return CryptoHelper.instance.getFileKey(
+ encryptedKey,
+ keyDecryptionNonce,
+ collectionKey,
+ );
+}
diff --git a/mobile/apps/locker/lib/services/favorites_service.dart b/mobile/apps/locker/lib/services/favorites_service.dart
index 56de864e1e..02ccb52797 100644
--- a/mobile/apps/locker/lib/services/favorites_service.dart
+++ b/mobile/apps/locker/lib/services/favorites_service.dart
@@ -3,10 +3,10 @@ import 'dart:async';
import 'package:ente_events/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:locker/events/collections_updated_event.dart';
-import 'package:locker/services/collections/collections_db.dart';
import 'package:locker/services/collections/collections_service.dart';
import 'package:locker/services/collections/models/collection.dart';
import 'package:locker/services/configuration.dart';
+import 'package:locker/services/db/locker_db.dart';
import 'package:locker/services/files/sync/models/file.dart';
import 'package:logging/logging.dart';
@@ -14,7 +14,7 @@ class FavoritesService {
late Configuration _config;
late CollectionService _collectionService;
- late CollectionDB _db;
+ late LockerDB _db;
int? _cachedFavoritesCollectionID;
final Set<int> _cachedFavUploadedIDs = {};
final Map<String, int> _cachedFavFileHashes = {};
@@ -30,7 +30,7 @@ class FavoritesService {
Future<void> init() async {
_config = Configuration.instance;
_collectionService = CollectionService.instance;
- _db = CollectionDB.instance;
+ _db = LockerDB.instance;
_collectionUpdatesSubscription =
Bus.instance.on<CollectionsUpdatedEvent>().listen((event) {
// When collections are updated, refresh our cache
diff --git a/mobile/apps/locker/lib/services/trash/trash_db.dart b/mobile/apps/locker/lib/services/trash/trash_db.dart
deleted file mode 100644
index 7557e3426a..0000000000
--- a/mobile/apps/locker/lib/services/trash/trash_db.dart
+++ /dev/null
@@ -1,173 +0,0 @@
-import "package:ente_base/models/database.dart";
-import 'package:locker/services/trash/models/trash_file.dart';
-import 'package:path/path.dart';
-import 'package:path_provider/path_provider.dart';
-import 'package:sqflite/sqflite.dart';
-
-class TrashDB extends EnteBaseDatabase {
- TrashDB._privateConstructor();
-
- static final TrashDB instance = TrashDB._privateConstructor();
-
- Database? _database;
-
- static const String _trashTable = 'trash_files';
-
- Future<void> init() async {
- _database = await _initDatabase();
- }
-
- Future<Database> _initDatabase() async {
- final documentsDirectory = await getApplicationDocumentsDirectory();
- final path = join(documentsDirectory.path, 'trash.db');
-
- return await openDatabase(
- path,
- version: 1,
- onCreate: _createTables,
- );
- }
-
- Future<void> _createTables(Database db, int version) async {
- await db.execute('''
- CREATE TABLE $_trashTable (
- uploaded_file_id INTEGER PRIMARY KEY,
- local_path TEXT,
- owner_id INTEGER,
- collection_id INTEGER,
- title TEXT,
- creation_time INTEGER,
- modification_time INTEGER,
- updation_time INTEGER,
- added_time INTEGER,
- hash TEXT,
- metadata_version INTEGER,
- encrypted_key TEXT,
- key_decryption_nonce TEXT,
- file_decryption_header TEXT,
- thumbnail_decryption_header TEXT,
- metadata_decryption_header TEXT,
- file_size INTEGER,
- m_md_encoded_json TEXT,
- m_md_version INTEGER,
- pub_mmd_encoded_json TEXT,
- pub_mmd_version INTEGER,
- created_at INTEGER NOT NULL,
- update_at INTEGER NOT NULL,
- delete_by INTEGER NOT NULL
- )
- ''');
- }
-
- Database get _db {
- if (_database == null) {
- throw Exception('TrashDB not initialized. Call init() first.');
- }
- return _database!;
- }
-
- Future<void> insertMultiple(List<TrashFile> trashFiles) async {
- final batch = _db.batch();
-
- for (final trashFile in trashFiles) {
- batch.insert(
- _trashTable,
- _trashFileToMap(trashFile),
- conflictAlgorithm: ConflictAlgorithm.replace,
- );
- }
-
- await batch.commit();
- }
-
- Future<void> delete(List<int> uploadedFileIDs) async {
- final batch = _db.batch();
-
- for (final uploadedFileID in uploadedFileIDs) {
- batch.delete(
- _trashTable,
- where: 'uploaded_file_id = ?',
- whereArgs: [uploadedFileID],
- );
- }
-
- await batch.commit();
- }
-
- Future<List<TrashFile>> getAllTrashFiles() async {
- final result = await _db.query(_trashTable);
- return result.map((row) => _mapToTrashFile(row)).toList();
- }
-
- @override
- Future<void> clearTable() async {
- await _db.delete(_trashTable);
- }
-
- Map<String, dynamic> _trashFileToMap(TrashFile trashFile) {
- return {
- 'uploaded_file_id': trashFile.uploadedFileID!,
- 'local_path': trashFile.localPath,
- 'owner_id': trashFile.ownerID,
- 'collection_id': trashFile.collectionID,
- 'title': trashFile.title,
- 'creation_time': trashFile.creationTime,
- 'modification_time': trashFile.modificationTime,
- 'updation_time': trashFile.updationTime,
- 'added_time': trashFile.addedTime,
- 'hash': trashFile.hash,
- 'metadata_version': trashFile.metadataVersion,
- 'encrypted_key': trashFile.encryptedKey,
- 'key_decryption_nonce': trashFile.keyDecryptionNonce,
- 'file_decryption_header': trashFile.fileDecryptionHeader,
- 'thumbnail_decryption_header': trashFile.thumbnailDecryptionHeader,
- 'metadata_decryption_header': trashFile.metadataDecryptionHeader,
- 'file_size': trashFile.fileSize,
- 'm_md_encoded_json': trashFile.mMdEncodedJson,
- 'm_md_version': trashFile.mMdVersion,
- 'pub_mmd_encoded_json': trashFile.pubMmdEncodedJson,
- 'pub_mmd_version': trashFile.pubMmdVersion,
- 'created_at': trashFile.createdAt,
- 'update_at': trashFile.updateAt,
- 'delete_by': trashFile.deleteBy,
- };
- }
-
- TrashFile _mapToTrashFile(Map<String, dynamic> map) {
- final trashFile = TrashFile();
-
- trashFile.localPath = map['local_path'];
- trashFile.uploadedFileID = map['uploaded_file_id'];
- trashFile.ownerID = map['owner_id'];
- trashFile.collectionID = map['collection_id'];
- trashFile.title = map['title'];
- trashFile.creationTime = map['creation_time'];
- trashFile.modificationTime = map['modification_time'];
- trashFile.updationTime = map['updation_time'];
- trashFile.addedTime = map['added_time'];
- trashFile.hash = map['hash'];
- trashFile.metadataVersion = map['metadata_version'];
- trashFile.encryptedKey = map['encrypted_key'];
- trashFile.keyDecryptionNonce = map['key_decryption_nonce'];
- trashFile.fileDecryptionHeader = map['file_decryption_header'];
- trashFile.thumbnailDecryptionHeader = map['thumbnail_decryption_header'];
- trashFile.metadataDecryptionHeader = map['metadata_decryption_header'];
- trashFile.fileSize = map['file_size'];
- trashFile.mMdEncodedJson = map['m_md_encoded_json'];
- trashFile.mMdVersion = map['m_md_version'] ?? 0;
- trashFile.pubMmdEncodedJson = map['pub_mmd_encoded_json'];
- trashFile.pubMmdVersion = map['pub_mmd_version'] ?? 1;
-
- // TrashFile specific fields
- trashFile.createdAt = map['created_at'];
- trashFile.updateAt = map['update_at'];
- trashFile.deleteBy = map['delete_by'];
-
- return trashFile;
- }
-
- Future<void> close() async {
- await _database?.close();
- _database = null;
- }
-}
diff --git a/mobile/apps/locker/lib/services/trash/trash_service.dart b/mobile/apps/locker/lib/services/trash/trash_service.dart
index c24039b3a6..29329d8314 100644
--- a/mobile/apps/locker/lib/services/trash/trash_service.dart
+++ b/mobile/apps/locker/lib/services/trash/trash_service.dart
@@ -9,15 +9,15 @@ import "package:ente_events/models/signed_in_event.dart";
import 'package:ente_network/network.dart';
import "package:locker/events/collections_updated_event.dart";
import "package:locker/events/user_details_refresh_event.dart";
-import 'package:locker/services/collections/collections_db.dart';
import 'package:locker/services/collections/collections_service.dart';
import 'package:locker/services/collections/models/collection.dart';
import 'package:locker/services/collections/models/collection_file_item.dart';
import "package:locker/services/configuration.dart";
+import 'package:locker/services/db/locker_db.dart';
+import 'package:locker/services/db/trash_table.dart';
import 'package:locker/services/files/sync/models/file.dart';
import 'package:locker/services/files/sync/models/file_magic.dart';
import 'package:locker/services/trash/models/trash_file.dart';
-import 'package:locker/services/trash/trash_db.dart';
import "package:locker/utils/crypto_helper.dart";
import 'package:logging/logging.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -26,20 +26,18 @@ class TrashService {
TrashService._privateConstructor();
static final TrashService instance = TrashService._privateConstructor();
- static const kLastTrashSyncTime = "last_trash_sync_time";
+ static const kLastTrashSyncTime = "last_trash_sync_time_locker_db";
final _logger = Logger("TrashService");
late SharedPreferences _prefs;
late Dio _enteDio;
- late TrashDB _trashDB;
- late CollectionDB _collectionDB;
+ late LockerDB _db;
Future<void> init(SharedPreferences preferences) async {
_prefs = preferences;
_enteDio = Network.instance.enteDio;
- _trashDB = TrashDB.instance;
- _collectionDB = CollectionDB.instance;
+ _db = LockerDB.instance;
- Bus.instance.on<SignedInEvent>().listen((event) {
+ Bus.instance.on<SignedInEvent>().listen((event) async {
_logger.info("User signed in, starting initial trash sync.");
unawaited(syncTrash());
});
@@ -55,16 +53,17 @@ class TrashService {
final diff = await getTrashFilesDiff(lastSyncTime);
if (diff.trashedFiles.isNotEmpty) {
_logger.fine("inserting ${diff.trashedFiles.length} items in trash");
- await _trashDB.insertMultiple(diff.trashedFiles);
+ await _db.insertTrashFiles(diff.trashedFiles);
}
if (diff.deletedUploadIDs.isNotEmpty) {
_logger.fine("discard ${diff.deletedUploadIDs.length} deleted items");
- await _trashDB.delete(diff.deletedUploadIDs);
+ await _db.deleteTrashFiles(diff.deletedUploadIDs);
}
if (diff.restoredFiles.isNotEmpty) {
_logger.fine("discard ${diff.restoredFiles.length} restored items");
- await _trashDB
- .delete(diff.restoredFiles.map((e) => e.uploadedFileID!).toList());
+ await _db.deleteTrashFiles(
+ diff.restoredFiles.map((e) => e.uploadedFileID!).toList(),
+ );
}
if (diff.lastSyncedTimeStamp != 0) {
@@ -76,7 +75,7 @@ class TrashService {
}
Future<List<TrashFile>> getTrashFiles() async {
- return await _trashDB.getAllTrashFiles();
+ return await _db.getTrashFiles();
}
Future<bool> _setSyncTime(int time) async {
@@ -209,8 +208,8 @@ class TrashService {
"/trash/delete",
data: params,
);
- await _trashDB.delete(uniqueFileIds);
- await _collectionDB.deleteFilesByUploadedFileIDs(uniqueFileIds);
+ await _db.deleteTrashFiles(uniqueFileIds);
+ await _db.deleteFilesByUploadedFileIDs(uniqueFileIds);
// no need to await on syncing trash from remote
unawaited(syncTrash());
}
@@ -218,7 +217,7 @@ class TrashService {
Future<void> emptyTrash() async {
final params = <String, dynamic>{};
params["lastUpdatedAt"] = _getSyncTime();
- final trashFiles = await _trashDB.getAllTrashFiles();
+ final trashFiles = await _db.getTrashFiles();
final fileIDs =
trashFiles.map((trashFile) => trashFile.uploadedFileID!).toList();
@@ -227,8 +226,8 @@ class TrashService {
data: params,
);
- await _trashDB.clearTable();
- await _collectionDB.deleteFilesByUploadedFileIDs(fileIDs);
+ await _db.clearTrashFilesTable();
+ await _db.deleteFilesByUploadedFileIDs(fileIDs);
unawaited(syncTrash());
_logger.info("Successfully emptied trash");
}
@@ -258,7 +257,7 @@ class TrashService {
"/collections/restore-files",
data: params,
);
- await _trashDB.delete(files.map((e) => e.uploadedFileID!).toList());
+ await _db.deleteTrashFiles(files.map((e) => e.uploadedFileID!).toList());
// Refresh collections so restored files are immediately available in UI
await CollectionService.instance.sync();
Bus.instance.fire(CollectionsUpdatedEvent("file_restore"));