files_db.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 columnRemoteFolderID = 'remote_folder_id';
  25. static final columnIsEncrypted = 'is_encrypted';
  26. static final columnIsDeleted = 'is_deleted';
  27. static final columnCreationTime = 'creation_time';
  28. static final columnModificationTime = 'modification_time';
  29. static final columnUpdationTime = 'updation_time';
  30. static final columnEncryptedKey = 'encrypted_key';
  31. static final columnKeyDecryptionNonce = 'key_decryption_nonce';
  32. static final columnFileDecryptionHeader = 'file_decryption_header';
  33. static final columnThumbnailDecryptionHeader = 'thumbnail_decryption_header';
  34. static final columnMetadataDecryptionHeader = 'metadata_decryption_header';
  35. // make this a singleton class
  36. FilesDB._privateConstructor();
  37. static final FilesDB instance = FilesDB._privateConstructor();
  38. // only have a single app-wide reference to the database
  39. static Database _database;
  40. Future<Database> get database async {
  41. if (_database != null) return _database;
  42. // lazily instantiate the db the first time it is accessed
  43. _database = await _initDatabase();
  44. return _database;
  45. }
  46. // this opens the database (and creates it if it doesn't exist)
  47. _initDatabase() async {
  48. Directory documentsDirectory = await getApplicationDocumentsDirectory();
  49. String path = join(documentsDirectory.path, _databaseName);
  50. return await openDatabase(path,
  51. version: _databaseVersion, onCreate: _onCreate);
  52. }
  53. // SQL code to create the database table
  54. Future _onCreate(Database db, int version) async {
  55. await db.execute('''
  56. CREATE TABLE $table (
  57. $columnGeneratedID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  58. $columnLocalID TEXT,
  59. $columnUploadedFileID INTEGER,
  60. $columnOwnerID INTEGER,
  61. $columnCollectionID INTEGER,
  62. $columnTitle TEXT NOT NULL,
  63. $columnDeviceFolder TEXT NOT NULL,
  64. $columnLatitude REAL,
  65. $columnLongitude REAL,
  66. $columnFileType INTEGER,
  67. $columnRemoteFolderID INTEGER,
  68. $columnIsEncrypted INTEGER DEFAULT 1,
  69. $columnModificationTime TEXT NOT NULL,
  70. $columnEncryptedKey TEXT,
  71. $columnKeyDecryptionNonce TEXT,
  72. $columnFileDecryptionHeader TEXT,
  73. $columnThumbnailDecryptionHeader TEXT,
  74. $columnMetadataDecryptionHeader TEXT,
  75. $columnIsDeleted INTEGER DEFAULT 0,
  76. $columnCreationTime TEXT NOT NULL,
  77. $columnUpdationTime TEXT,
  78. UNIQUE($columnUploadedFileID, $columnCollectionID)
  79. )
  80. ''');
  81. }
  82. Future<int> insert(File file) async {
  83. final db = await instance.database;
  84. return await db.insert(table, _getRowForFile(file));
  85. }
  86. Future<List<dynamic>> insertMultiple(List<File> files) async {
  87. final db = await instance.database;
  88. var batch = db.batch();
  89. int batchCounter = 0;
  90. for (File file in files) {
  91. if (batchCounter == 400) {
  92. await batch.commit();
  93. batch = db.batch();
  94. }
  95. batch.insert(
  96. table,
  97. _getRowForFile(file),
  98. conflictAlgorithm: ConflictAlgorithm.replace,
  99. );
  100. batchCounter++;
  101. }
  102. return await batch.commit();
  103. }
  104. Future<File> getFile(int generatedID) async {
  105. final db = await instance.database;
  106. final results = await db.query(table,
  107. where: '$columnGeneratedID = ?', whereArgs: [generatedID]);
  108. return _convertToFiles(results)[0];
  109. }
  110. Future<List<File>> getOwnedFiles(int ownerID) async {
  111. final db = await instance.database;
  112. final whereArgs = List<dynamic>();
  113. if (ownerID != null) {
  114. whereArgs.add(ownerID);
  115. }
  116. final results = await db.query(
  117. table,
  118. where: '$columnIsDeleted = 0' +
  119. (ownerID == null
  120. ? ''
  121. : ' AND ($columnOwnerID IS NULL OR $columnOwnerID = ?)'),
  122. whereArgs: whereArgs,
  123. orderBy: '$columnCreationTime DESC',
  124. );
  125. return _convertToFiles(results);
  126. }
  127. Future<List<File>> getAllVideos() async {
  128. final db = await instance.database;
  129. final results = await db.query(
  130. table,
  131. where:
  132. '$columnLocalID IS NOT NULL AND $columnFileType = 1 AND $columnIsDeleted = 0',
  133. orderBy: '$columnCreationTime DESC',
  134. );
  135. return _convertToFiles(results);
  136. }
  137. Future<List<File>> getAllInFolder(
  138. int folderID, int beforeCreationTime, int limit) async {
  139. final db = await instance.database;
  140. final results = await db.query(
  141. table,
  142. where:
  143. '$columnRemoteFolderID = ? AND $columnIsDeleted = 0 AND $columnCreationTime < ?',
  144. whereArgs: [folderID, beforeCreationTime],
  145. orderBy: '$columnCreationTime DESC',
  146. limit: limit,
  147. );
  148. return _convertToFiles(results);
  149. }
  150. Future<List<File>> getAllInCollectionBeforeCreationTime(
  151. int collectionID, int beforeCreationTime, int limit) async {
  152. final db = await instance.database;
  153. final results = await db.query(
  154. table,
  155. where:
  156. '$columnCollectionID = ? AND $columnIsDeleted = 0 AND $columnCreationTime < ?',
  157. whereArgs: [collectionID, beforeCreationTime],
  158. orderBy: '$columnCreationTime DESC',
  159. limit: limit,
  160. );
  161. return _convertToFiles(results);
  162. }
  163. Future<List<File>> getAllInCollection(int collectionID) async {
  164. final db = await instance.database;
  165. final results = await db.query(
  166. table,
  167. where: '$columnCollectionID = ?',
  168. whereArgs: [collectionID],
  169. orderBy: '$columnCreationTime DESC',
  170. );
  171. return _convertToFiles(results);
  172. }
  173. Future<List<File>> getFilesCreatedWithinDuration(
  174. int startCreationTime, int endCreationTime) async {
  175. final db = await instance.database;
  176. final results = await db.query(
  177. table,
  178. where:
  179. '$columnCreationTime > ? AND $columnCreationTime < ? AND $columnIsDeleted = 0',
  180. whereArgs: [startCreationTime, endCreationTime],
  181. orderBy: '$columnCreationTime ASC',
  182. );
  183. return _convertToFiles(results);
  184. }
  185. Future<List<File>> getAllDeleted() async {
  186. final db = await instance.database;
  187. final results = await db.query(
  188. table,
  189. where: '$columnIsDeleted = 1',
  190. orderBy: '$columnCreationTime DESC',
  191. );
  192. return _convertToFiles(results);
  193. }
  194. Future<List<File>> getFilesToBeUploadedWithinFolders(
  195. Set<String> folders) async {
  196. final db = await instance.database;
  197. String inParam = "";
  198. for (final folder in folders) {
  199. inParam += "'" + folder + "',";
  200. }
  201. inParam = inParam.substring(0, inParam.length - 1);
  202. final results = await db.query(
  203. table,
  204. where:
  205. '$columnUploadedFileID IS NULL AND $columnDeviceFolder IN ($inParam)',
  206. orderBy: '$columnCreationTime DESC',
  207. );
  208. return _convertToFiles(results);
  209. }
  210. Future<File> getMatchingFile(String localID, String title,
  211. String deviceFolder, int creationTime, int modificationTime,
  212. {String alternateTitle}) async {
  213. final db = await instance.database;
  214. final rows = await db.query(
  215. table,
  216. where: '''$columnLocalID=? AND ($columnTitle=? OR $columnTitle=?) AND
  217. $columnDeviceFolder=? AND $columnCreationTime=? AND
  218. $columnModificationTime=?''',
  219. whereArgs: [
  220. localID,
  221. title,
  222. alternateTitle,
  223. deviceFolder,
  224. creationTime,
  225. modificationTime,
  226. ],
  227. );
  228. if (rows.isNotEmpty) {
  229. return _getFileFromRow(rows[0]);
  230. } else {
  231. throw ("No matching file found");
  232. }
  233. }
  234. Future<File> getMatchingRemoteFile(int uploadedFileID) async {
  235. final db = await instance.database;
  236. final rows = await db.query(
  237. table,
  238. where: '$columnUploadedFileID=?',
  239. whereArgs: [uploadedFileID],
  240. );
  241. if (rows.isNotEmpty) {
  242. return _getFileFromRow(rows[0]);
  243. } else {
  244. throw ("No matching file found");
  245. }
  246. }
  247. Future<int> update(File file) async {
  248. final db = await instance.database;
  249. return await db.update(
  250. table,
  251. _getRowForFile(file),
  252. where: '$columnGeneratedID = ?',
  253. whereArgs: [file.generatedID],
  254. );
  255. }
  256. // TODO: Remove deleted files on remote
  257. Future<int> markForDeletion(File file) async {
  258. final db = await instance.database;
  259. final values = new Map<String, dynamic>();
  260. values[columnIsDeleted] = 1;
  261. return db.update(
  262. table,
  263. values,
  264. where: '$columnGeneratedID =?',
  265. whereArgs: [file.generatedID],
  266. );
  267. }
  268. Future<int> delete(File file) async {
  269. final db = await instance.database;
  270. return db.delete(
  271. table,
  272. where: '$columnGeneratedID =?',
  273. whereArgs: [file.generatedID],
  274. );
  275. }
  276. Future<int> deleteFromCollection(int uploadedFileID, int collectionID) async {
  277. final db = await instance.database;
  278. return db.delete(
  279. table,
  280. where: '$columnUploadedFileID = ? AND $columnCollectionID = ?',
  281. whereArgs: [uploadedFileID, collectionID],
  282. );
  283. }
  284. Future<int> deleteFilesInRemoteFolder(int folderID) async {
  285. final db = await instance.database;
  286. return db.delete(
  287. table,
  288. where: '$columnRemoteFolderID =?',
  289. whereArgs: [folderID],
  290. );
  291. }
  292. Future<List<String>> getLocalPaths() async {
  293. final db = await instance.database;
  294. final rows = await db.query(
  295. table,
  296. columns: [columnDeviceFolder],
  297. distinct: true,
  298. where: '$columnRemoteFolderID IS NULL',
  299. );
  300. List<String> result = List<String>();
  301. for (final row in rows) {
  302. result.add(row[columnDeviceFolder]);
  303. }
  304. return result;
  305. }
  306. Future<File> getLatestFileInPath(String path) async {
  307. final db = await instance.database;
  308. final rows = await db.query(
  309. table,
  310. where: '$columnDeviceFolder =?',
  311. whereArgs: [path],
  312. orderBy: '$columnCreationTime DESC',
  313. limit: 1,
  314. );
  315. if (rows.isNotEmpty) {
  316. return _getFileFromRow(rows[0]);
  317. } else {
  318. throw ("No file found in path");
  319. }
  320. }
  321. Future<File> getLatestFileInRemoteFolder(int folderID) async {
  322. final db = await instance.database;
  323. final rows = await db.query(
  324. table,
  325. where: '$columnRemoteFolderID =?',
  326. whereArgs: [folderID],
  327. orderBy: '$columnCreationTime DESC',
  328. limit: 1,
  329. );
  330. if (rows.isNotEmpty) {
  331. return _getFileFromRow(rows[0]);
  332. } else {
  333. throw ("No file found in remote folder " + folderID.toString());
  334. }
  335. }
  336. Future<File> getLatestFileInCollection(int collectionID) async {
  337. final db = await instance.database;
  338. final rows = await db.query(
  339. table,
  340. where: '$columnCollectionID =?',
  341. whereArgs: [collectionID],
  342. orderBy: '$columnCreationTime DESC',
  343. limit: 1,
  344. );
  345. if (rows.isNotEmpty) {
  346. return _getFileFromRow(rows[0]);
  347. } else {
  348. throw ("No file found in collection " + collectionID.toString());
  349. }
  350. }
  351. Future<File> getLastSyncedFileInRemoteFolder(int folderID) async {
  352. final db = await instance.database;
  353. final rows = await db.query(
  354. table,
  355. where: '$columnRemoteFolderID =?',
  356. whereArgs: [folderID],
  357. orderBy: '$columnUpdationTime DESC',
  358. limit: 1,
  359. );
  360. if (rows.isNotEmpty) {
  361. return _getFileFromRow(rows[0]);
  362. } else {
  363. throw ("No file found in remote folder " + folderID.toString());
  364. }
  365. }
  366. Future<File> getLatestFileAmongGeneratedIDs(List<String> generatedIDs) async {
  367. final db = await instance.database;
  368. final rows = await db.query(
  369. table,
  370. where: '$columnGeneratedID IN (${generatedIDs.join(",")})',
  371. orderBy: '$columnCreationTime DESC',
  372. limit: 1,
  373. );
  374. if (rows.isNotEmpty) {
  375. return _getFileFromRow(rows[0]);
  376. } else {
  377. throw ("No file found with ids " + generatedIDs.join(", ").toString());
  378. }
  379. }
  380. List<File> _convertToFiles(List<Map<String, dynamic>> results) {
  381. final files = List<File>();
  382. for (final result in results) {
  383. files.add(_getFileFromRow(result));
  384. }
  385. return files;
  386. }
  387. Map<String, dynamic> _getRowForFile(File file) {
  388. final row = new Map<String, dynamic>();
  389. row[columnLocalID] = file.localID;
  390. row[columnUploadedFileID] = file.uploadedFileID;
  391. row[columnOwnerID] = file.ownerID;
  392. row[columnCollectionID] = file.collectionID;
  393. row[columnTitle] = file.title;
  394. row[columnDeviceFolder] = file.deviceFolder;
  395. if (file.location != null) {
  396. row[columnLatitude] = file.location.latitude;
  397. row[columnLongitude] = file.location.longitude;
  398. }
  399. switch (file.fileType) {
  400. case FileType.image:
  401. row[columnFileType] = 0;
  402. break;
  403. case FileType.video:
  404. row[columnFileType] = 1;
  405. break;
  406. default:
  407. row[columnFileType] = -1;
  408. }
  409. row[columnIsEncrypted] = file.isEncrypted ? 1 : 0;
  410. row[columnRemoteFolderID] = file.remoteFolderID;
  411. row[columnCreationTime] = file.creationTime;
  412. row[columnModificationTime] = file.modificationTime;
  413. row[columnUpdationTime] = file.updationTime;
  414. row[columnEncryptedKey] = file.encryptedKey;
  415. row[columnKeyDecryptionNonce] = file.keyDecryptionNonce;
  416. row[columnFileDecryptionHeader] = file.fileDecryptionHeader;
  417. row[columnThumbnailDecryptionHeader] = file.thumbnailDecryptionHeader;
  418. row[columnMetadataDecryptionHeader] = file.metadataDecryptionHeader;
  419. return row;
  420. }
  421. File _getFileFromRow(Map<String, dynamic> row) {
  422. final file = File();
  423. file.generatedID = row[columnGeneratedID];
  424. file.localID = row[columnLocalID];
  425. file.uploadedFileID = row[columnUploadedFileID];
  426. file.ownerID = row[columnOwnerID];
  427. file.collectionID = row[columnCollectionID];
  428. file.title = row[columnTitle];
  429. file.deviceFolder = row[columnDeviceFolder];
  430. if (row[columnLatitude] != null && row[columnLongitude] != null) {
  431. file.location = Location(row[columnLatitude], row[columnLongitude]);
  432. }
  433. file.fileType = getFileType(row[columnFileType]);
  434. file.remoteFolderID = row[columnRemoteFolderID];
  435. file.isEncrypted = row[columnIsEncrypted] == 1;
  436. file.creationTime = int.parse(row[columnCreationTime]);
  437. file.modificationTime = int.parse(row[columnModificationTime]);
  438. file.updationTime = row[columnUpdationTime] == null
  439. ? -1
  440. : int.parse(row[columnUpdationTime]);
  441. file.encryptedKey = row[columnEncryptedKey];
  442. file.keyDecryptionNonce = row[columnKeyDecryptionNonce];
  443. file.fileDecryptionHeader = row[columnFileDecryptionHeader];
  444. file.thumbnailDecryptionHeader = row[columnThumbnailDecryptionHeader];
  445. file.metadataDecryptionHeader = row[columnMetadataDecryptionHeader];
  446. return file;
  447. }
  448. }