files_db.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import 'dart:io';
  2. import 'package:logging/logging.dart';
  3. import 'package:photos/models/file_type.dart';
  4. import 'package:photos/models/location.dart';
  5. import 'package:photos/models/file.dart';
  6. import 'package:path/path.dart';
  7. import 'package:sqflite/sqflite.dart';
  8. import 'package:path_provider/path_provider.dart';
  9. class FilesDB {
  10. static final _databaseName = "ente.files.db";
  11. static final _databaseVersion = 1;
  12. static final Logger _logger = Logger("FilesDB");
  13. static final table = 'files';
  14. static final columnGeneratedID = '_id';
  15. static final columnUploadedFileID = 'uploaded_file_id';
  16. static final columnOwnerID = 'owner_id';
  17. static final columnCollectionID = 'collection_id';
  18. static final columnLocalID = 'local_id';
  19. static final columnTitle = 'title';
  20. static final columnDeviceFolder = 'device_folder';
  21. static final columnLatitude = 'latitude';
  22. static final columnLongitude = 'longitude';
  23. static final columnFileType = 'file_type';
  24. static final columnIsEncrypted = 'is_encrypted';
  25. static final columnIsDeleted = 'is_deleted';
  26. static final columnCreationTime = 'creation_time';
  27. static final columnModificationTime = 'modification_time';
  28. static final columnUpdationTime = 'updation_time';
  29. static final columnEncryptedKey = 'encrypted_key';
  30. static final columnKeyDecryptionNonce = 'key_decryption_nonce';
  31. static final columnFileDecryptionHeader = 'file_decryption_header';
  32. static final columnThumbnailDecryptionHeader = 'thumbnail_decryption_header';
  33. static final columnMetadataDecryptionHeader = 'metadata_decryption_header';
  34. // make this a singleton class
  35. FilesDB._privateConstructor();
  36. static final FilesDB instance = FilesDB._privateConstructor();
  37. // only have a single app-wide reference to the database
  38. static Database _database;
  39. Future<Database> get database async {
  40. if (_database != null) return _database;
  41. // lazily instantiate the db the first time it is accessed
  42. _database = await _initDatabase();
  43. return _database;
  44. }
  45. // this opens the database (and creates it if it doesn't exist)
  46. _initDatabase() async {
  47. Directory documentsDirectory = await getApplicationDocumentsDirectory();
  48. String path = join(documentsDirectory.path, _databaseName);
  49. return await openDatabase(path,
  50. version: _databaseVersion, onCreate: _onCreate);
  51. }
  52. // SQL code to create the database table
  53. Future _onCreate(Database db, int version) async {
  54. await db.execute('''
  55. CREATE TABLE $table (
  56. $columnGeneratedID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  57. $columnLocalID TEXT,
  58. $columnUploadedFileID INTEGER,
  59. $columnOwnerID INTEGER,
  60. $columnCollectionID INTEGER,
  61. $columnTitle TEXT NOT NULL,
  62. $columnDeviceFolder TEXT NOT NULL,
  63. $columnLatitude REAL,
  64. $columnLongitude REAL,
  65. $columnFileType INTEGER,
  66. $columnIsEncrypted INTEGER DEFAULT 1,
  67. $columnModificationTime TEXT NOT NULL,
  68. $columnEncryptedKey TEXT,
  69. $columnKeyDecryptionNonce TEXT,
  70. $columnFileDecryptionHeader TEXT,
  71. $columnThumbnailDecryptionHeader TEXT,
  72. $columnMetadataDecryptionHeader TEXT,
  73. $columnIsDeleted INTEGER DEFAULT 0,
  74. $columnCreationTime TEXT NOT NULL,
  75. $columnUpdationTime TEXT,
  76. UNIQUE($columnUploadedFileID, $columnCollectionID)
  77. );
  78. CREATE INDEX collection_id_index ON $table($columnCollectionID);
  79. CREATE INDEX device_folder_index ON $table($columnDeviceFolder);
  80. CREATE INDEX creation_time_index ON $table($columnCreationTime);
  81. CREATE INDEX updation_time_index ON $table($columnUpdationTime);
  82. ''');
  83. }
  84. Future<int> insert(File file) async {
  85. final db = await instance.database;
  86. return await db.insert(table, _getRowForFile(file));
  87. }
  88. Future<List<dynamic>> insertMultiple(List<File> files) async {
  89. final db = await instance.database;
  90. var batch = db.batch();
  91. int batchCounter = 0;
  92. for (File file in files) {
  93. if (batchCounter == 400) {
  94. await batch.commit();
  95. batch = db.batch();
  96. }
  97. batch.insert(
  98. table,
  99. _getRowForFile(file),
  100. conflictAlgorithm: ConflictAlgorithm.replace,
  101. );
  102. batchCounter++;
  103. }
  104. return await batch.commit();
  105. }
  106. Future<File> getFile(int generatedID) async {
  107. final db = await instance.database;
  108. final results = await db.query(table,
  109. where: '$columnGeneratedID = ?', whereArgs: [generatedID]);
  110. if (results.isEmpty) {
  111. return null;
  112. }
  113. return _convertToFiles(results)[0];
  114. }
  115. Future<List<File>> getDeduplicatedFiles() async {
  116. _logger.info("Getting files for collection");
  117. final db = await instance.database;
  118. final results = await db.query(table,
  119. where: '$columnIsDeleted = 0',
  120. orderBy: '$columnCreationTime DESC',
  121. groupBy:
  122. 'IFNULL($columnUploadedFileID, $columnGeneratedID), IFNULL($columnLocalID, $columnGeneratedID)');
  123. return _convertToFiles(results);
  124. }
  125. Future<List<File>> getFiles() async {
  126. final db = await instance.database;
  127. final results = await db.query(
  128. table,
  129. where: '$columnIsDeleted = 0',
  130. orderBy: '$columnCreationTime DESC',
  131. );
  132. return _convertToFiles(results);
  133. }
  134. Future<List<File>> getAllVideos() async {
  135. final db = await instance.database;
  136. final results = await db.query(
  137. table,
  138. where:
  139. '$columnLocalID IS NOT NULL AND $columnFileType = 1 AND $columnIsDeleted = 0',
  140. orderBy: '$columnCreationTime DESC',
  141. );
  142. return _convertToFiles(results);
  143. }
  144. Future<List<File>> getAllInCollectionBeforeCreationTime(
  145. int collectionID, int beforeCreationTime, int limit) async {
  146. final db = await instance.database;
  147. final results = await db.query(
  148. table,
  149. where:
  150. '$columnCollectionID = ? AND $columnIsDeleted = 0 AND $columnCreationTime < ?',
  151. whereArgs: [collectionID, beforeCreationTime],
  152. orderBy: '$columnCreationTime DESC',
  153. limit: limit,
  154. );
  155. return _convertToFiles(results);
  156. }
  157. Future<List<File>> getAllInPathBeforeCreationTime(
  158. String path, int beforeCreationTime, int limit) async {
  159. final db = await instance.database;
  160. final results = await db.query(
  161. table,
  162. where:
  163. '$columnLocalID IS NOT NULL AND $columnDeviceFolder = ? AND $columnIsDeleted = 0 AND $columnCreationTime < ?',
  164. whereArgs: [path, beforeCreationTime],
  165. orderBy: '$columnCreationTime DESC',
  166. groupBy: '$columnLocalID',
  167. limit: limit,
  168. );
  169. return _convertToFiles(results);
  170. }
  171. Future<List<File>> getAllInCollection(int collectionID) async {
  172. final db = await instance.database;
  173. final results = await db.query(
  174. table,
  175. where: '$columnCollectionID = ?',
  176. whereArgs: [collectionID],
  177. orderBy: '$columnCreationTime DESC',
  178. );
  179. return _convertToFiles(results);
  180. }
  181. Future<List<File>> getFilesCreatedWithinDuration(
  182. int startCreationTime, int endCreationTime) async {
  183. final db = await instance.database;
  184. final results = await db.query(
  185. table,
  186. where:
  187. '$columnCreationTime > ? AND $columnCreationTime < ? AND $columnIsDeleted = 0',
  188. whereArgs: [startCreationTime, endCreationTime],
  189. orderBy: '$columnCreationTime ASC',
  190. );
  191. return _convertToFiles(results);
  192. }
  193. Future<List<int>> getDeletedFileIDs() async {
  194. final db = await instance.database;
  195. final rows = await db.query(
  196. table,
  197. columns: [columnUploadedFileID],
  198. distinct: true,
  199. where: '$columnIsDeleted = 1',
  200. orderBy: '$columnCreationTime DESC',
  201. );
  202. final result = List<int>();
  203. for (final row in rows) {
  204. result.add(row[columnUploadedFileID]);
  205. }
  206. return result;
  207. }
  208. Future<List<File>> getFilesToBeUploadedWithinFolders(
  209. Set<String> folders) async {
  210. final db = await instance.database;
  211. String inParam = "";
  212. for (final folder in folders) {
  213. inParam += "'" + folder + "',";
  214. }
  215. inParam = inParam.substring(0, inParam.length - 1);
  216. final results = await db.query(
  217. table,
  218. where:
  219. '$columnUploadedFileID IS NULL AND $columnDeviceFolder IN ($inParam)',
  220. orderBy: '$columnCreationTime DESC',
  221. );
  222. return _convertToFiles(results);
  223. }
  224. Future<Map<int, File>> getLastCreatedFilesInCollections(
  225. List<int> collectionIDs) async {
  226. final db = await instance.database;
  227. final rows = await db.rawQuery('''
  228. SELECT
  229. $columnGeneratedID,
  230. $columnLocalID,
  231. $columnUploadedFileID,
  232. $columnOwnerID,
  233. $columnCollectionID,
  234. $columnTitle,
  235. $columnDeviceFolder,
  236. $columnLatitude,
  237. $columnLongitude,
  238. $columnFileType,
  239. $columnIsEncrypted,
  240. $columnModificationTime,
  241. $columnEncryptedKey,
  242. $columnKeyDecryptionNonce,
  243. $columnFileDecryptionHeader,
  244. $columnThumbnailDecryptionHeader,
  245. $columnMetadataDecryptionHeader,
  246. $columnIsDeleted,
  247. $columnUpdationTime,
  248. MAX($columnCreationTime) as $columnCreationTime
  249. FROM $table
  250. WHERE $columnCollectionID IN (${collectionIDs.join(', ')}) AND $columnIsDeleted = 0
  251. GROUP BY $columnCollectionID
  252. ORDER BY $columnCreationTime DESC;
  253. ''');
  254. final result = Map<int, File>();
  255. final files = _convertToFiles(rows);
  256. for (final file in files) {
  257. result[file.collectionID] = file;
  258. }
  259. return result;
  260. }
  261. Future<Map<int, File>> getLastUpdatedFilesInCollections(
  262. List<int> collectionIDs) async {
  263. final db = await instance.database;
  264. final rows = await db.rawQuery('''
  265. SELECT
  266. $columnGeneratedID,
  267. $columnLocalID,
  268. $columnUploadedFileID,
  269. $columnOwnerID,
  270. $columnCollectionID,
  271. $columnTitle,
  272. $columnDeviceFolder,
  273. $columnLatitude,
  274. $columnLongitude,
  275. $columnFileType,
  276. $columnIsEncrypted,
  277. $columnModificationTime,
  278. $columnEncryptedKey,
  279. $columnKeyDecryptionNonce,
  280. $columnFileDecryptionHeader,
  281. $columnThumbnailDecryptionHeader,
  282. $columnMetadataDecryptionHeader,
  283. $columnIsDeleted,
  284. $columnCreationTime,
  285. MAX($columnUpdationTime) AS $columnUpdationTime
  286. FROM $table
  287. WHERE $columnCollectionID IN (${collectionIDs.join(', ')}) AND $columnIsDeleted = 0
  288. GROUP BY $columnCollectionID
  289. ORDER BY $columnUpdationTime DESC;
  290. ''');
  291. final result = Map<int, File>();
  292. final files = _convertToFiles(rows);
  293. for (final file in files) {
  294. result[file.collectionID] = file;
  295. }
  296. return result;
  297. }
  298. Future<List<File>> getMatchingFiles(
  299. String title, String deviceFolder, int creationTime, int modificationTime,
  300. {String alternateTitle}) async {
  301. final db = await instance.database;
  302. final rows = await db.query(
  303. table,
  304. where: '''($columnTitle=? OR $columnTitle=?) AND
  305. $columnDeviceFolder=? AND $columnCreationTime=? AND
  306. $columnModificationTime=?''',
  307. whereArgs: [
  308. title,
  309. alternateTitle,
  310. deviceFolder,
  311. creationTime,
  312. modificationTime,
  313. ],
  314. );
  315. if (rows.isNotEmpty) {
  316. return _convertToFiles(rows);
  317. } else {
  318. return null;
  319. }
  320. }
  321. Future<File> getMatchingRemoteFile(int uploadedFileID) async {
  322. final db = await instance.database;
  323. final rows = await db.query(
  324. table,
  325. where: '$columnUploadedFileID=?',
  326. whereArgs: [uploadedFileID],
  327. );
  328. if (rows.isNotEmpty) {
  329. return _getFileFromRow(rows[0]);
  330. } else {
  331. throw ("No matching file found");
  332. }
  333. }
  334. Future<int> update(File file) async {
  335. final db = await instance.database;
  336. return await db.update(
  337. table,
  338. _getRowForFile(file),
  339. where: '$columnGeneratedID = ?',
  340. whereArgs: [file.generatedID],
  341. );
  342. }
  343. Future<int> markForDeletion(int uploadedFileID) async {
  344. final db = await instance.database;
  345. final values = new Map<String, dynamic>();
  346. values[columnIsDeleted] = 1;
  347. return db.update(
  348. table,
  349. values,
  350. where: '$columnUploadedFileID =?',
  351. whereArgs: [uploadedFileID],
  352. );
  353. }
  354. Future<int> delete(int uploadedFileID) async {
  355. final db = await instance.database;
  356. return db.delete(
  357. table,
  358. where: '$columnUploadedFileID =?',
  359. whereArgs: [uploadedFileID],
  360. );
  361. }
  362. Future<int> deleteLocalFile(String localID) async {
  363. final db = await instance.database;
  364. return db.delete(
  365. table,
  366. where: '$columnLocalID =?',
  367. whereArgs: [localID],
  368. );
  369. }
  370. Future<int> deleteFromCollection(int uploadedFileID, int collectionID) async {
  371. final db = await instance.database;
  372. return db.delete(
  373. table,
  374. where: '$columnUploadedFileID = ? AND $columnCollectionID = ?',
  375. whereArgs: [uploadedFileID, collectionID],
  376. );
  377. }
  378. Future<int> deleteCollection(int collectionID) async {
  379. final db = await instance.database;
  380. return db.delete(
  381. table,
  382. where: '$columnCollectionID = ?',
  383. whereArgs: [collectionID],
  384. );
  385. }
  386. Future<int> removeFromCollection(int collectionID, List<int> fileIDs) async {
  387. final db = await instance.database;
  388. return db.delete(
  389. table,
  390. where:
  391. '$columnCollectionID =? AND $columnUploadedFileID IN (${fileIDs.join(', ')})',
  392. whereArgs: [collectionID],
  393. );
  394. }
  395. Future<List<String>> getLocalPaths() async {
  396. final db = await instance.database;
  397. final rows = await db.query(
  398. table,
  399. columns: [columnDeviceFolder],
  400. distinct: true,
  401. );
  402. List<String> result = List<String>();
  403. for (final row in rows) {
  404. result.add(row[columnDeviceFolder]);
  405. }
  406. return result;
  407. }
  408. Future<File> getLatestFileInCollection(int collectionID) async {
  409. final db = await instance.database;
  410. final rows = await db.query(
  411. table,
  412. where: '$columnCollectionID = ? AND $columnIsDeleted = 0',
  413. whereArgs: [collectionID],
  414. orderBy: '$columnCreationTime DESC',
  415. limit: 1,
  416. );
  417. if (rows.isNotEmpty) {
  418. return _getFileFromRow(rows[0]);
  419. } else {
  420. return null;
  421. }
  422. }
  423. Future<File> getLastModifiedFileInCollection(int collectionID) async {
  424. final db = await instance.database;
  425. final rows = await db.query(
  426. table,
  427. where: '$columnCollectionID = ? AND $columnIsDeleted = 0',
  428. whereArgs: [collectionID],
  429. orderBy: '$columnUpdationTime DESC',
  430. limit: 1,
  431. );
  432. if (rows.isNotEmpty) {
  433. return _getFileFromRow(rows[0]);
  434. } else {
  435. return null;
  436. }
  437. }
  438. Future<bool> doesFileExistInCollection(
  439. int uploadedFileID, int collectionID) async {
  440. final db = await instance.database;
  441. final rows = await db.query(
  442. table,
  443. where: '$columnUploadedFileID = ? AND $columnCollectionID = ?',
  444. whereArgs: [uploadedFileID, collectionID],
  445. limit: 1,
  446. );
  447. return rows.isNotEmpty;
  448. }
  449. List<File> _convertToFiles(List<Map<String, dynamic>> results) {
  450. final files = List<File>();
  451. for (final result in results) {
  452. files.add(_getFileFromRow(result));
  453. }
  454. return files;
  455. }
  456. Map<String, dynamic> _getRowForFile(File file) {
  457. final row = new Map<String, dynamic>();
  458. row[columnLocalID] = file.localID;
  459. row[columnUploadedFileID] = file.uploadedFileID;
  460. row[columnOwnerID] = file.ownerID;
  461. row[columnCollectionID] = file.collectionID;
  462. row[columnTitle] = file.title;
  463. row[columnDeviceFolder] = file.deviceFolder;
  464. if (file.location != null) {
  465. row[columnLatitude] = file.location.latitude;
  466. row[columnLongitude] = file.location.longitude;
  467. }
  468. switch (file.fileType) {
  469. case FileType.image:
  470. row[columnFileType] = 0;
  471. break;
  472. case FileType.video:
  473. row[columnFileType] = 1;
  474. break;
  475. default:
  476. row[columnFileType] = -1;
  477. }
  478. row[columnIsEncrypted] = file.isEncrypted ? 1 : 0;
  479. row[columnCreationTime] = file.creationTime;
  480. row[columnModificationTime] = file.modificationTime;
  481. row[columnUpdationTime] = file.updationTime;
  482. row[columnEncryptedKey] = file.encryptedKey;
  483. row[columnKeyDecryptionNonce] = file.keyDecryptionNonce;
  484. row[columnFileDecryptionHeader] = file.fileDecryptionHeader;
  485. row[columnThumbnailDecryptionHeader] = file.thumbnailDecryptionHeader;
  486. row[columnMetadataDecryptionHeader] = file.metadataDecryptionHeader;
  487. return row;
  488. }
  489. File _getFileFromRow(Map<String, dynamic> row) {
  490. final file = File();
  491. file.generatedID = row[columnGeneratedID];
  492. file.localID = row[columnLocalID];
  493. file.uploadedFileID = row[columnUploadedFileID];
  494. file.ownerID = row[columnOwnerID];
  495. file.collectionID = row[columnCollectionID];
  496. file.title = row[columnTitle];
  497. file.deviceFolder = row[columnDeviceFolder];
  498. if (row[columnLatitude] != null && row[columnLongitude] != null) {
  499. file.location = Location(row[columnLatitude], row[columnLongitude]);
  500. }
  501. file.fileType = getFileType(row[columnFileType]);
  502. file.isEncrypted = row[columnIsEncrypted] == 1;
  503. file.creationTime = int.parse(row[columnCreationTime]);
  504. file.modificationTime = int.parse(row[columnModificationTime]);
  505. file.updationTime = row[columnUpdationTime] == null
  506. ? -1
  507. : int.parse(row[columnUpdationTime]);
  508. file.encryptedKey = row[columnEncryptedKey];
  509. file.keyDecryptionNonce = row[columnKeyDecryptionNonce];
  510. file.fileDecryptionHeader = row[columnFileDecryptionHeader];
  511. file.thumbnailDecryptionHeader = row[columnThumbnailDecryptionHeader];
  512. file.metadataDecryptionHeader = row[columnMetadataDecryptionHeader];
  513. return file;
  514. }
  515. }