device_files_db.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import 'package:collection/collection.dart';
  2. import 'package:flutter/foundation.dart';
  3. import 'package:logging/logging.dart';
  4. import 'package:photo_manager/photo_manager.dart';
  5. import 'package:photos/db/files_db.dart';
  6. import 'package:photos/models/backup_status.dart';
  7. import 'package:photos/models/device_collection.dart';
  8. import 'package:photos/models/file.dart';
  9. import 'package:photos/models/file_load_result.dart';
  10. import 'package:photos/models/upload_strategy.dart';
  11. import 'package:photos/services/local/local_sync_util.dart';
  12. import 'package:sqflite/sqlite_api.dart';
  13. import 'package:tuple/tuple.dart';
  14. extension DeviceFiles on FilesDB {
  15. static final Logger _logger = Logger("DeviceFilesDB");
  16. static const _sqlBoolTrue = 1;
  17. static const _sqlBoolFalse = 0;
  18. Future<void> insertPathIDToLocalIDMapping(
  19. Map<String, Set<String>> mappingToAdd, {
  20. ConflictAlgorithm conflictAlgorithm = ConflictAlgorithm.ignore,
  21. }) async {
  22. debugPrint("Inserting missing PathIDToLocalIDMapping");
  23. final db = await database;
  24. var batch = db.batch();
  25. int batchCounter = 0;
  26. for (MapEntry e in mappingToAdd.entries) {
  27. final String pathID = e.key;
  28. for (String localID in e.value) {
  29. if (batchCounter == 400) {
  30. await batch.commit(noResult: true);
  31. batch = db.batch();
  32. batchCounter = 0;
  33. }
  34. batch.insert(
  35. "device_files",
  36. {
  37. "id": localID,
  38. "path_id": pathID,
  39. },
  40. conflictAlgorithm: conflictAlgorithm,
  41. );
  42. batchCounter++;
  43. }
  44. }
  45. await batch.commit(noResult: true);
  46. }
  47. Future<void> deletePathIDToLocalIDMapping(
  48. Map<String, Set<String>> mappingsToRemove,
  49. ) async {
  50. debugPrint("removing PathIDToLocalIDMapping");
  51. final db = await database;
  52. var batch = db.batch();
  53. int batchCounter = 0;
  54. for (MapEntry e in mappingsToRemove.entries) {
  55. final String pathID = e.key;
  56. for (String localID in e.value) {
  57. if (batchCounter == 400) {
  58. await batch.commit(noResult: true);
  59. batch = db.batch();
  60. batchCounter = 0;
  61. }
  62. batch.delete(
  63. "device_files",
  64. where: 'id = ? AND path_id = ?',
  65. whereArgs: [localID, pathID],
  66. );
  67. batchCounter++;
  68. }
  69. }
  70. await batch.commit(noResult: true);
  71. }
  72. Future<Map<String, int>> getDevicePathIDToImportedFileCount() async {
  73. try {
  74. final db = await database;
  75. final rows = await db.rawQuery(
  76. '''
  77. SELECT count(*) as count, path_id
  78. FROM device_files
  79. GROUP BY path_id
  80. ''',
  81. );
  82. final result = <String, int>{};
  83. for (final row in rows) {
  84. result[row['path_id'] as String] = row["count"] as int;
  85. }
  86. return result;
  87. } catch (e) {
  88. _logger.severe("failed to getDevicePathIDToImportedFileCount", e);
  89. rethrow;
  90. }
  91. }
  92. Future<Map<String, Set<String>>> getDevicePathIDToLocalIDMap() async {
  93. try {
  94. final db = await database;
  95. final rows = await db.rawQuery(
  96. ''' SELECT id, path_id FROM device_files; ''',
  97. );
  98. final result = <String, Set<String>>{};
  99. for (final row in rows) {
  100. final String pathID = row['path_id'] as String;
  101. if (!result.containsKey(pathID)) {
  102. result[pathID] = <String>{};
  103. }
  104. result[pathID]!.add(row['id'] as String);
  105. }
  106. return result;
  107. } catch (e) {
  108. _logger.severe("failed to getDevicePathIDToLocalIDMap", e);
  109. rethrow;
  110. }
  111. }
  112. Future<Set<String>> getDevicePathIDs() async {
  113. final Database db = await database;
  114. final rows = await db.rawQuery(
  115. '''
  116. SELECT id FROM device_collections
  117. ''',
  118. );
  119. final Set<String> result = <String>{};
  120. for (final row in rows) {
  121. result.add(row['id'] as String);
  122. }
  123. return result;
  124. }
  125. Future<void> insertLocalAssets(
  126. List<LocalPathAsset> localPathAssets, {
  127. bool shouldAutoBackup = false,
  128. }) async {
  129. final Database db = await database;
  130. final Map<String, Set<String>> pathIDToLocalIDsMap = {};
  131. try {
  132. final batch = db.batch();
  133. final Set<String> existingPathIds = await getDevicePathIDs();
  134. for (LocalPathAsset localPathAsset in localPathAssets) {
  135. if (localPathAsset.localIDs.isNotEmpty) {
  136. pathIDToLocalIDsMap[localPathAsset.pathID] = localPathAsset.localIDs;
  137. }
  138. if (existingPathIds.contains(localPathAsset.pathID)) {
  139. batch.rawUpdate(
  140. "UPDATE device_collections SET name = ? where id = "
  141. "?",
  142. [localPathAsset.pathName, localPathAsset.pathID],
  143. );
  144. } else if (localPathAsset.localIDs.isNotEmpty) {
  145. batch.insert(
  146. "device_collections",
  147. {
  148. "id": localPathAsset.pathID,
  149. "name": localPathAsset.pathName,
  150. "should_backup": shouldAutoBackup ? _sqlBoolTrue : _sqlBoolFalse
  151. },
  152. conflictAlgorithm: ConflictAlgorithm.ignore,
  153. );
  154. }
  155. }
  156. await batch.commit(noResult: true);
  157. // add the mappings for localIDs
  158. if (pathIDToLocalIDsMap.isNotEmpty) {
  159. await insertPathIDToLocalIDMapping(pathIDToLocalIDsMap);
  160. }
  161. } catch (e) {
  162. _logger.severe("failed to save path names", e);
  163. rethrow;
  164. }
  165. }
  166. Future<bool> updateDeviceCoverWithCount(
  167. List<Tuple2<AssetPathEntity, String>> devicePathInfo, {
  168. bool shouldBackup = false,
  169. }) async {
  170. bool hasUpdated = false;
  171. try {
  172. final Database db = await database;
  173. final Set<String> existingPathIds = await getDevicePathIDs();
  174. for (Tuple2<AssetPathEntity, String> tup in devicePathInfo) {
  175. final AssetPathEntity pathEntity = tup.item1;
  176. final String localID = tup.item2;
  177. final bool shouldUpdate = existingPathIds.contains(pathEntity.id);
  178. if (shouldUpdate) {
  179. final rowUpdated = await db.rawUpdate(
  180. "UPDATE device_collections SET name = ?, cover_id = ?, count"
  181. " = ? where id = ? AND (name != ? OR cover_id != ? OR count != ?)",
  182. [
  183. pathEntity.name,
  184. localID,
  185. pathEntity.assetCount,
  186. pathEntity.id,
  187. pathEntity.name,
  188. localID,
  189. pathEntity.assetCount,
  190. ],
  191. );
  192. if (rowUpdated > 0) {
  193. _logger.fine("Updated $rowUpdated rows for ${pathEntity.name}");
  194. hasUpdated = true;
  195. }
  196. } else {
  197. hasUpdated = true;
  198. await db.insert(
  199. "device_collections",
  200. {
  201. "id": pathEntity.id,
  202. "name": pathEntity.name,
  203. "count": pathEntity.assetCount,
  204. "cover_id": localID,
  205. "should_backup": shouldBackup ? _sqlBoolTrue : _sqlBoolFalse
  206. },
  207. conflictAlgorithm: ConflictAlgorithm.ignore,
  208. );
  209. }
  210. }
  211. // delete existing pathIDs which are missing on device
  212. existingPathIds.removeAll(devicePathInfo.map((e) => e.item1.id).toSet());
  213. if (existingPathIds.isNotEmpty) {
  214. hasUpdated = true;
  215. _logger.info(
  216. 'Deleting non-backed up pathIds from local '
  217. '$existingPathIds',
  218. );
  219. for (String pathID in existingPathIds) {
  220. // do not delete device collection entries for paths which are
  221. // marked for backup. This is to handle "Free up space"
  222. // feature, where we delete files which are backed up. Deleting such
  223. // entries here result in us losing out on the information that
  224. // those folders were marked for automatic backup.
  225. await db.delete(
  226. "device_collections",
  227. where: 'id = ? and should_backup = $_sqlBoolFalse ',
  228. whereArgs: [pathID],
  229. );
  230. await db.delete(
  231. "device_files",
  232. where: 'path_id = ?',
  233. whereArgs: [pathID],
  234. );
  235. }
  236. }
  237. return hasUpdated;
  238. } catch (e) {
  239. _logger.severe("failed to save path names", e);
  240. rethrow;
  241. }
  242. }
  243. // getDeviceSyncCollectionIDs returns the collectionIDs for the
  244. // deviceCollections which are marked for auto-backup
  245. Future<Set<int>> getDeviceSyncCollectionIDs() async {
  246. final Database db = await database;
  247. final rows = await db.rawQuery(
  248. '''
  249. SELECT collection_id FROM device_collections where should_backup =
  250. $_sqlBoolTrue
  251. and collection_id != -1;
  252. ''',
  253. );
  254. final Set<int> result = <int>{};
  255. for (final row in rows) {
  256. result.add(row['collection_id'] as int);
  257. }
  258. return result;
  259. }
  260. Future<void> updateDevicePathSyncStatus(Map<String, bool> syncStatus) async {
  261. final db = await database;
  262. var batch = db.batch();
  263. int batchCounter = 0;
  264. for (MapEntry e in syncStatus.entries) {
  265. final String pathID = e.key;
  266. if (batchCounter == 400) {
  267. await batch.commit(noResult: true);
  268. batch = db.batch();
  269. batchCounter = 0;
  270. }
  271. batch.update(
  272. "device_collections",
  273. {
  274. "should_backup": e.value ? _sqlBoolTrue : _sqlBoolFalse,
  275. },
  276. where: 'id = ?',
  277. whereArgs: [pathID],
  278. );
  279. batchCounter++;
  280. }
  281. await batch.commit(noResult: true);
  282. }
  283. Future<void> updateDeviceCollection(
  284. String pathID,
  285. int collectionID,
  286. ) async {
  287. final db = await database;
  288. await db.update(
  289. "device_collections",
  290. {"collection_id": collectionID},
  291. where: 'id = ?',
  292. whereArgs: [pathID],
  293. );
  294. return;
  295. }
  296. Future<FileLoadResult> getFilesInDeviceCollection(
  297. DeviceCollection deviceCollection,
  298. int startTime,
  299. int endTime, {
  300. int? limit,
  301. bool? asc,
  302. }) async {
  303. final db = await database;
  304. final order = (asc ?? false ? 'ASC' : 'DESC');
  305. final String rawQuery = '''
  306. SELECT *
  307. FROM ${FilesDB.filesTable}
  308. WHERE ${FilesDB.columnLocalID} IS NOT NULL AND
  309. ${FilesDB.columnCreationTime} >= $startTime AND
  310. ${FilesDB.columnCreationTime} <= $endTime AND
  311. ${FilesDB.columnLocalID} IN
  312. (SELECT id FROM device_files where path_id = '${deviceCollection.id}' )
  313. ORDER BY ${FilesDB.columnCreationTime} $order , ${FilesDB.columnModificationTime} $order
  314. ''' +
  315. (limit != null ? ' limit $limit;' : ';');
  316. final results = await db.rawQuery(rawQuery);
  317. final files = convertToFiles(results);
  318. final dedupe = deduplicateByLocalID(files);
  319. return FileLoadResult(dedupe, files.length == limit);
  320. }
  321. Future<BackedUpFileIDs> getBackedUpForDeviceCollection(
  322. String pathID,
  323. int ownerID,
  324. ) async {
  325. final db = await database;
  326. const String rawQuery = '''
  327. SELECT ${FilesDB.columnLocalID}, ${FilesDB.columnUploadedFileID}
  328. FROM ${FilesDB.filesTable}
  329. WHERE ${FilesDB.columnLocalID} IS NOT NULL AND
  330. (${FilesDB.columnOwnerID} IS NULL OR ${FilesDB.columnOwnerID} = ?)
  331. AND (${FilesDB.columnUploadedFileID} IS NOT NULL AND ${FilesDB.columnUploadedFileID} IS NOT -1)
  332. AND
  333. ${FilesDB.columnLocalID} IN
  334. (SELECT id FROM device_files where path_id = ?)
  335. ''';
  336. final results = await db.rawQuery(rawQuery, [ownerID, pathID]);
  337. final localIDs = <String>{};
  338. final uploadedIDs = <int>{};
  339. for (final result in results) {
  340. // FilesDB.[columnLocalID,columnUploadedFileID] is not null check in query
  341. localIDs.add(result[FilesDB.columnLocalID] as String);
  342. uploadedIDs.add(result[FilesDB.columnUploadedFileID] as int);
  343. }
  344. return BackedUpFileIDs(localIDs.toList(), uploadedIDs.toList());
  345. }
  346. Future<List<DeviceCollection>> getDeviceCollections({
  347. bool includeCoverThumbnail = false,
  348. }) async {
  349. debugPrint(
  350. "Fetching DeviceCollections From DB with thumbnail = "
  351. "$includeCoverThumbnail",
  352. );
  353. try {
  354. final db = await database;
  355. final coverFiles = <File>[];
  356. if (includeCoverThumbnail) {
  357. final fileRows = await db.rawQuery(
  358. '''SELECT * FROM FILES where local_id in (select cover_id from device_collections) group by local_id;
  359. ''',
  360. );
  361. final files = convertToFiles(fileRows);
  362. coverFiles.addAll(files);
  363. }
  364. final deviceCollectionRows = await db.rawQuery(
  365. '''SELECT * from device_collections''',
  366. );
  367. final List<DeviceCollection> deviceCollections = [];
  368. for (var row in deviceCollectionRows) {
  369. final DeviceCollection deviceCollection = DeviceCollection(
  370. row["id"] as String,
  371. (row['name'] ?? '') as String,
  372. count: row['count'] as int,
  373. collectionID: (row["collection_id"] ?? -1) as int,
  374. coverId: row["cover_id"] as String?,
  375. shouldBackup: (row["should_backup"] ?? _sqlBoolFalse) == _sqlBoolTrue,
  376. uploadStrategy: getUploadType((row["upload_strategy"] ?? 0) as int),
  377. );
  378. if (includeCoverThumbnail) {
  379. deviceCollection.thumbnail = coverFiles.firstWhereOrNull(
  380. (element) => element.localID == deviceCollection.coverId,
  381. );
  382. if (deviceCollection.thumbnail == null) {
  383. final File? result =
  384. await getDeviceCollectionThumbnail(deviceCollection.id);
  385. if (result == null) {
  386. _logger.finest(
  387. 'Failed to find coverThumbnail for deviceFolder',
  388. );
  389. continue;
  390. } else {
  391. deviceCollection.thumbnail = result;
  392. }
  393. }
  394. }
  395. deviceCollections.add(deviceCollection);
  396. }
  397. if (includeCoverThumbnail) {
  398. deviceCollections.sort(
  399. (a, b) =>
  400. b.thumbnail!.creationTime!.compareTo(a.thumbnail!.creationTime!),
  401. );
  402. }
  403. return deviceCollections;
  404. } catch (e) {
  405. _logger.severe('Failed to getDeviceCollections', e);
  406. rethrow;
  407. }
  408. }
  409. Future<File?> getDeviceCollectionThumbnail(String pathID) async {
  410. debugPrint("Call fallback method to get potential thumbnail");
  411. final db = await database;
  412. final fileRows = await db.rawQuery(
  413. '''SELECT * FROM FILES f JOIN device_files df on f.local_id = df.id
  414. and df.path_id= ? order by f.creation_time DESC limit 1;
  415. ''',
  416. [pathID],
  417. );
  418. final files = convertToFiles(fileRows);
  419. if (files.isNotEmpty) {
  420. return files.first;
  421. } else {
  422. return null;
  423. }
  424. }
  425. }