files_db.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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>> getAllInPath(String path) async {
  158. final db = await instance.database;
  159. final results = await db.query(
  160. table,
  161. where: '$columnLocalID IS NOT NULL AND $columnDeviceFolder = ?',
  162. whereArgs: [path],
  163. orderBy: '$columnCreationTime DESC',
  164. groupBy: '$columnLocalID',
  165. );
  166. return _convertToFiles(results);
  167. }
  168. Future<List<File>> getAllInPathBeforeCreationTime(
  169. String path, int beforeCreationTime, int limit) async {
  170. final db = await instance.database;
  171. final results = await db.query(
  172. table,
  173. where:
  174. '$columnLocalID IS NOT NULL AND $columnDeviceFolder = ? AND $columnIsDeleted = 0 AND $columnCreationTime < ?',
  175. whereArgs: [path, beforeCreationTime],
  176. orderBy: '$columnCreationTime DESC',
  177. groupBy: '$columnLocalID',
  178. limit: limit,
  179. );
  180. return _convertToFiles(results);
  181. }
  182. Future<List<File>> getAllInCollection(int collectionID) async {
  183. final db = await instance.database;
  184. final results = await db.query(
  185. table,
  186. where: '$columnCollectionID = ?',
  187. whereArgs: [collectionID],
  188. orderBy: '$columnCreationTime DESC',
  189. );
  190. return _convertToFiles(results);
  191. }
  192. Future<List<File>> getFilesCreatedWithinDuration(
  193. int startCreationTime, int endCreationTime) async {
  194. final db = await instance.database;
  195. final results = await db.query(
  196. table,
  197. where:
  198. '$columnCreationTime > ? AND $columnCreationTime < ? AND $columnIsDeleted = 0',
  199. whereArgs: [startCreationTime, endCreationTime],
  200. orderBy: '$columnCreationTime ASC',
  201. );
  202. return _convertToFiles(results);
  203. }
  204. Future<List<int>> getDeletedFileIDs() async {
  205. final db = await instance.database;
  206. final rows = await db.query(
  207. table,
  208. columns: [columnUploadedFileID],
  209. distinct: true,
  210. where: '$columnIsDeleted = 1',
  211. orderBy: '$columnCreationTime DESC',
  212. );
  213. final result = List<int>();
  214. for (final row in rows) {
  215. result.add(row[columnUploadedFileID]);
  216. }
  217. return result;
  218. }
  219. Future<List<File>> getFilesToBeUploadedWithinFolders(
  220. Set<String> folders) async {
  221. final db = await instance.database;
  222. String inParam = "";
  223. for (final folder in folders) {
  224. inParam += "'" + folder + "',";
  225. }
  226. inParam = inParam.substring(0, inParam.length - 1);
  227. final results = await db.query(
  228. table,
  229. where:
  230. '$columnUploadedFileID IS NULL AND $columnDeviceFolder IN ($inParam)',
  231. orderBy: '$columnCreationTime DESC',
  232. );
  233. return _convertToFiles(results);
  234. }
  235. Future<Map<int, File>> getLastCreatedFilesInCollections(
  236. List<int> collectionIDs) async {
  237. final db = await instance.database;
  238. final rows = await db.rawQuery('''
  239. SELECT
  240. $columnGeneratedID,
  241. $columnLocalID,
  242. $columnUploadedFileID,
  243. $columnOwnerID,
  244. $columnCollectionID,
  245. $columnTitle,
  246. $columnDeviceFolder,
  247. $columnLatitude,
  248. $columnLongitude,
  249. $columnFileType,
  250. $columnIsEncrypted,
  251. $columnModificationTime,
  252. $columnEncryptedKey,
  253. $columnKeyDecryptionNonce,
  254. $columnFileDecryptionHeader,
  255. $columnThumbnailDecryptionHeader,
  256. $columnMetadataDecryptionHeader,
  257. $columnIsDeleted,
  258. $columnUpdationTime,
  259. MAX($columnCreationTime) as $columnCreationTime
  260. FROM $table
  261. WHERE $columnCollectionID IN (${collectionIDs.join(', ')}) AND $columnIsDeleted = 0
  262. GROUP BY $columnCollectionID
  263. ORDER BY $columnCreationTime DESC;
  264. ''');
  265. final result = Map<int, File>();
  266. final files = _convertToFiles(rows);
  267. for (final file in files) {
  268. result[file.collectionID] = file;
  269. }
  270. return result;
  271. }
  272. Future<Map<int, File>> getLastUpdatedFilesInCollections(
  273. List<int> collectionIDs) async {
  274. final db = await instance.database;
  275. final rows = await db.rawQuery('''
  276. SELECT
  277. $columnGeneratedID,
  278. $columnLocalID,
  279. $columnUploadedFileID,
  280. $columnOwnerID,
  281. $columnCollectionID,
  282. $columnTitle,
  283. $columnDeviceFolder,
  284. $columnLatitude,
  285. $columnLongitude,
  286. $columnFileType,
  287. $columnIsEncrypted,
  288. $columnModificationTime,
  289. $columnEncryptedKey,
  290. $columnKeyDecryptionNonce,
  291. $columnFileDecryptionHeader,
  292. $columnThumbnailDecryptionHeader,
  293. $columnMetadataDecryptionHeader,
  294. $columnIsDeleted,
  295. $columnCreationTime,
  296. MAX($columnUpdationTime) AS $columnUpdationTime
  297. FROM $table
  298. WHERE $columnCollectionID IN (${collectionIDs.join(', ')}) AND $columnIsDeleted = 0
  299. GROUP BY $columnCollectionID
  300. ORDER BY $columnUpdationTime DESC;
  301. ''');
  302. final result = Map<int, File>();
  303. final files = _convertToFiles(rows);
  304. for (final file in files) {
  305. result[file.collectionID] = file;
  306. }
  307. return result;
  308. }
  309. Future<List<File>> getMatchingFiles(
  310. String title, String deviceFolder, int creationTime, int modificationTime,
  311. {String alternateTitle}) async {
  312. final db = await instance.database;
  313. final rows = await db.query(
  314. table,
  315. where: '''($columnTitle=? OR $columnTitle=?) AND
  316. $columnDeviceFolder=? AND $columnCreationTime=? AND
  317. $columnModificationTime=?''',
  318. whereArgs: [
  319. title,
  320. alternateTitle,
  321. deviceFolder,
  322. creationTime,
  323. modificationTime,
  324. ],
  325. );
  326. if (rows.isNotEmpty) {
  327. return _convertToFiles(rows);
  328. } else {
  329. return null;
  330. }
  331. }
  332. Future<File> getMatchingRemoteFile(int uploadedFileID) async {
  333. final db = await instance.database;
  334. final rows = await db.query(
  335. table,
  336. where: '$columnUploadedFileID=?',
  337. whereArgs: [uploadedFileID],
  338. );
  339. if (rows.isNotEmpty) {
  340. return _getFileFromRow(rows[0]);
  341. } else {
  342. throw ("No matching file found");
  343. }
  344. }
  345. Future<int> update(File file) async {
  346. final db = await instance.database;
  347. return await db.update(
  348. table,
  349. _getRowForFile(file),
  350. where: '$columnGeneratedID = ?',
  351. whereArgs: [file.generatedID],
  352. );
  353. }
  354. Future<int> markForDeletion(int uploadedFileID) async {
  355. final db = await instance.database;
  356. final values = new Map<String, dynamic>();
  357. values[columnIsDeleted] = 1;
  358. return db.update(
  359. table,
  360. values,
  361. where: '$columnUploadedFileID =?',
  362. whereArgs: [uploadedFileID],
  363. );
  364. }
  365. Future<int> delete(int uploadedFileID) async {
  366. final db = await instance.database;
  367. return db.delete(
  368. table,
  369. where: '$columnUploadedFileID =?',
  370. whereArgs: [uploadedFileID],
  371. );
  372. }
  373. Future<int> deleteLocalFile(String localID) async {
  374. final db = await instance.database;
  375. return db.delete(
  376. table,
  377. where: '$columnLocalID =?',
  378. whereArgs: [localID],
  379. );
  380. }
  381. Future<int> deleteFromCollection(int uploadedFileID, int collectionID) async {
  382. final db = await instance.database;
  383. return db.delete(
  384. table,
  385. where: '$columnUploadedFileID = ? AND $columnCollectionID = ?',
  386. whereArgs: [uploadedFileID, collectionID],
  387. );
  388. }
  389. Future<int> deleteCollection(int collectionID) async {
  390. final db = await instance.database;
  391. return db.delete(
  392. table,
  393. where: '$columnCollectionID = ?',
  394. whereArgs: [collectionID],
  395. );
  396. }
  397. Future<int> removeFromCollection(int collectionID, List<int> fileIDs) async {
  398. final db = await instance.database;
  399. return db.delete(
  400. table,
  401. where:
  402. '$columnCollectionID =? AND $columnUploadedFileID IN (${fileIDs.join(', ')})',
  403. whereArgs: [collectionID],
  404. );
  405. }
  406. Future<List<String>> getLocalPaths() async {
  407. final db = await instance.database;
  408. final rows = await db.query(
  409. table,
  410. columns: [columnDeviceFolder],
  411. distinct: true,
  412. );
  413. List<String> result = List<String>();
  414. for (final row in rows) {
  415. result.add(row[columnDeviceFolder]);
  416. }
  417. return result;
  418. }
  419. Future<File> getLatestFileInCollection(int collectionID) async {
  420. final db = await instance.database;
  421. final rows = await db.query(
  422. table,
  423. where: '$columnCollectionID = ? AND $columnIsDeleted = 0',
  424. whereArgs: [collectionID],
  425. orderBy: '$columnCreationTime DESC',
  426. limit: 1,
  427. );
  428. if (rows.isNotEmpty) {
  429. return _getFileFromRow(rows[0]);
  430. } else {
  431. return null;
  432. }
  433. }
  434. Future<File> getLastModifiedFileInCollection(int collectionID) async {
  435. final db = await instance.database;
  436. final rows = await db.query(
  437. table,
  438. where: '$columnCollectionID = ? AND $columnIsDeleted = 0',
  439. whereArgs: [collectionID],
  440. orderBy: '$columnUpdationTime DESC',
  441. limit: 1,
  442. );
  443. if (rows.isNotEmpty) {
  444. return _getFileFromRow(rows[0]);
  445. } else {
  446. return null;
  447. }
  448. }
  449. Future<bool> doesFileExistInCollection(
  450. int uploadedFileID, int collectionID) async {
  451. final db = await instance.database;
  452. final rows = await db.query(
  453. table,
  454. where: '$columnUploadedFileID = ? AND $columnCollectionID = ?',
  455. whereArgs: [uploadedFileID, collectionID],
  456. limit: 1,
  457. );
  458. return rows.isNotEmpty;
  459. }
  460. List<File> _convertToFiles(List<Map<String, dynamic>> results) {
  461. final files = List<File>();
  462. for (final result in results) {
  463. files.add(_getFileFromRow(result));
  464. }
  465. return files;
  466. }
  467. Map<String, dynamic> _getRowForFile(File file) {
  468. final row = new Map<String, dynamic>();
  469. row[columnLocalID] = file.localID;
  470. row[columnUploadedFileID] = file.uploadedFileID;
  471. row[columnOwnerID] = file.ownerID;
  472. row[columnCollectionID] = file.collectionID;
  473. row[columnTitle] = file.title;
  474. row[columnDeviceFolder] = file.deviceFolder;
  475. if (file.location != null) {
  476. row[columnLatitude] = file.location.latitude;
  477. row[columnLongitude] = file.location.longitude;
  478. }
  479. switch (file.fileType) {
  480. case FileType.image:
  481. row[columnFileType] = 0;
  482. break;
  483. case FileType.video:
  484. row[columnFileType] = 1;
  485. break;
  486. default:
  487. row[columnFileType] = -1;
  488. }
  489. row[columnIsEncrypted] = file.isEncrypted ? 1 : 0;
  490. row[columnCreationTime] = file.creationTime;
  491. row[columnModificationTime] = file.modificationTime;
  492. row[columnUpdationTime] = file.updationTime;
  493. row[columnEncryptedKey] = file.encryptedKey;
  494. row[columnKeyDecryptionNonce] = file.keyDecryptionNonce;
  495. row[columnFileDecryptionHeader] = file.fileDecryptionHeader;
  496. row[columnThumbnailDecryptionHeader] = file.thumbnailDecryptionHeader;
  497. row[columnMetadataDecryptionHeader] = file.metadataDecryptionHeader;
  498. return row;
  499. }
  500. File _getFileFromRow(Map<String, dynamic> row) {
  501. final file = File();
  502. file.generatedID = row[columnGeneratedID];
  503. file.localID = row[columnLocalID];
  504. file.uploadedFileID = row[columnUploadedFileID];
  505. file.ownerID = row[columnOwnerID];
  506. file.collectionID = row[columnCollectionID];
  507. file.title = row[columnTitle];
  508. file.deviceFolder = row[columnDeviceFolder];
  509. if (row[columnLatitude] != null && row[columnLongitude] != null) {
  510. file.location = Location(row[columnLatitude], row[columnLongitude]);
  511. }
  512. file.fileType = getFileType(row[columnFileType]);
  513. file.isEncrypted = row[columnIsEncrypted] == 1;
  514. file.creationTime = int.parse(row[columnCreationTime]);
  515. file.modificationTime = int.parse(row[columnModificationTime]);
  516. file.updationTime = row[columnUpdationTime] == null
  517. ? -1
  518. : int.parse(row[columnUpdationTime]);
  519. file.encryptedKey = row[columnEncryptedKey];
  520. file.keyDecryptionNonce = row[columnKeyDecryptionNonce];
  521. file.fileDecryptionHeader = row[columnFileDecryptionHeader];
  522. file.thumbnailDecryptionHeader = row[columnThumbnailDecryptionHeader];
  523. file.metadataDecryptionHeader = row[columnMetadataDecryptionHeader];
  524. return file;
  525. }
  526. }