local_sync_util.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // @dart = 2.9
  2. import 'dart:io';
  3. import 'dart:math';
  4. import 'package:computer/computer.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:photo_manager/photo_manager.dart';
  8. import 'package:photos/core/event_bus.dart';
  9. import 'package:photos/events/local_import_progress.dart';
  10. import 'package:photos/models/file.dart';
  11. import 'package:tuple/tuple.dart';
  12. final _logger = Logger("FileSyncUtil");
  13. const ignoreSizeConstraint = SizeConstraint(ignoreSize: true);
  14. const assetFetchPageSize = 2000;
  15. Future<Tuple2<List<LocalPathAsset>, List<File>>> getLocalPathAssetsAndFiles(
  16. int fromTime,
  17. int toTime,
  18. Computer computer,
  19. ) async {
  20. final pathEntities = await _getGalleryList(
  21. updateFromTime: fromTime,
  22. updateToTime: toTime,
  23. );
  24. final List<LocalPathAsset> localPathAssets = [];
  25. // alreadySeenLocalIDs is used to track and ignore file with particular
  26. // localID if it's already present in another album. This only impacts iOS
  27. // devices where a file can belong to multiple
  28. final Set<String> alreadySeenLocalIDs = {};
  29. final List<File> uniqueFiles = [];
  30. for (AssetPathEntity pathEntity in pathEntities) {
  31. final List<AssetEntity> assetsInPath = await _getAllAssetLists(pathEntity);
  32. final Tuple2<Set<String>, List<File>> result = await computer.compute(
  33. _getLocalIDsAndFilesFromAssets,
  34. param: <String, dynamic>{
  35. "pathEntity": pathEntity,
  36. "fromTime": fromTime,
  37. "alreadySeenLocalIDs": alreadySeenLocalIDs,
  38. "assetList": assetsInPath,
  39. },
  40. );
  41. alreadySeenLocalIDs.addAll(result.item1);
  42. uniqueFiles.addAll(result.item2);
  43. localPathAssets.add(
  44. LocalPathAsset(
  45. localIDs: result.item1,
  46. pathName: pathEntity.name,
  47. pathID: pathEntity.id,
  48. ),
  49. );
  50. }
  51. return Tuple2(localPathAssets, uniqueFiles);
  52. }
  53. // getDeviceFolderWithCountAndLatestFile returns a tuple of AssetPathEntity and
  54. // latest file's localID in the assetPath, along with modifiedPath time and
  55. // total count of assets in a Asset Path.
  56. // We use this result to update the latest thumbnail for deviceFolder and
  57. // identify (in future) which AssetPath needs to be re-synced again.
  58. Future<List<Tuple2<AssetPathEntity, String>>>
  59. getDeviceFolderWithCountAndCoverID() async {
  60. final List<Tuple2<AssetPathEntity, String>> result = [];
  61. final pathEntities = await _getGalleryList(
  62. needsTitle: false,
  63. containsModifiedPath: true,
  64. orderOption:
  65. const OrderOption(type: OrderOptionType.createDate, asc: false),
  66. );
  67. for (AssetPathEntity pathEntity in pathEntities) {
  68. //todo: test and handle empty album case
  69. final latestEntity = await pathEntity.getAssetListPaged(
  70. page: 0,
  71. size: 1,
  72. );
  73. final String localCoverID = latestEntity.first.id;
  74. result.add(Tuple2(pathEntity, localCoverID));
  75. }
  76. return result;
  77. }
  78. Future<List<LocalPathAsset>> getAllLocalAssets() async {
  79. final filterOptionGroup = FilterOptionGroup();
  80. filterOptionGroup.setOption(
  81. AssetType.image,
  82. const FilterOption(sizeConstraint: ignoreSizeConstraint),
  83. );
  84. filterOptionGroup.setOption(
  85. AssetType.video,
  86. const FilterOption(sizeConstraint: ignoreSizeConstraint),
  87. );
  88. filterOptionGroup.createTimeCond = DateTimeCond.def().copyWith(ignore: true);
  89. final assetPaths = await PhotoManager.getAssetPathList(
  90. hasAll: !Platform.isAndroid,
  91. type: RequestType.common,
  92. filterOption: filterOptionGroup,
  93. );
  94. final List<LocalPathAsset> localPathAssets = [];
  95. for (final assetPath in assetPaths) {
  96. final Set<String> localIDs = <String>{};
  97. for (final asset in await _getAllAssetLists(assetPath)) {
  98. localIDs.add(asset.id);
  99. }
  100. localPathAssets.add(
  101. LocalPathAsset(
  102. localIDs: localIDs,
  103. pathName: assetPath.name,
  104. pathID: assetPath.id,
  105. ),
  106. );
  107. }
  108. return localPathAssets;
  109. }
  110. Future<LocalDiffResult> getDiffWithLocal(
  111. List<LocalPathAsset> assets,
  112. // current set of assets available on device
  113. Set<String> existingIDs, // localIDs of files already imported in app
  114. Map<String, Set<String>> pathToLocalIDs,
  115. Set<String> invalidIDs,
  116. Computer computer,
  117. ) async {
  118. final Map<String, dynamic> args = <String, dynamic>{};
  119. args['assets'] = assets;
  120. args['existingIDs'] = existingIDs;
  121. args['invalidIDs'] = invalidIDs;
  122. args['pathToLocalIDs'] = pathToLocalIDs;
  123. final LocalDiffResult diffResult =
  124. await computer.compute(_getLocalAssetsDiff, param: args);
  125. diffResult.uniqueLocalFiles =
  126. await _convertLocalAssetsToUniqueFiles(diffResult.localPathAssets);
  127. return diffResult;
  128. }
  129. // _getLocalAssetsDiff compares local db with the file system and compute
  130. // the files which needs to be added or removed from device collection.
  131. LocalDiffResult _getLocalAssetsDiff(Map<String, dynamic> args) {
  132. final List<LocalPathAsset> onDeviceLocalPathAsset = args['assets'];
  133. final Set<String> existingIDs = args['existingIDs'];
  134. final Set<String> invalidIDs = args['invalidIDs'];
  135. final Map<String, Set<String>> pathToLocalIDs = args['pathToLocalIDs'];
  136. final Map<String, Set<String>> newPathToLocalIDs = <String, Set<String>>{};
  137. final Map<String, Set<String>> removedPathToLocalIDs =
  138. <String, Set<String>>{};
  139. final List<LocalPathAsset> unsyncedAssets = [];
  140. for (final localPathAsset in onDeviceLocalPathAsset) {
  141. final String pathID = localPathAsset.pathID;
  142. // Start identifying pathID to localID mapping changes which needs to be
  143. // synced
  144. final Set<String> candidateLocalIDsForRemoval =
  145. pathToLocalIDs[pathID] ?? <String>{};
  146. final Set<String> missingLocalIDsInPath = <String>{};
  147. for (final String localID in localPathAsset.localIDs) {
  148. if (candidateLocalIDsForRemoval.contains(localID)) {
  149. // remove the localID after checking. Any pending existing ID indicates
  150. // the the local file was removed from the path.
  151. candidateLocalIDsForRemoval.remove(localID);
  152. } else {
  153. missingLocalIDsInPath.add(localID);
  154. }
  155. }
  156. if (candidateLocalIDsForRemoval.isNotEmpty) {
  157. removedPathToLocalIDs[pathID] = candidateLocalIDsForRemoval;
  158. }
  159. if (missingLocalIDsInPath.isNotEmpty) {
  160. newPathToLocalIDs[pathID] = missingLocalIDsInPath;
  161. }
  162. // End
  163. localPathAsset.localIDs.removeAll(existingIDs);
  164. localPathAsset.localIDs.removeAll(invalidIDs);
  165. if (localPathAsset.localIDs.isNotEmpty) {
  166. unsyncedAssets.add(localPathAsset);
  167. }
  168. }
  169. return LocalDiffResult(
  170. localPathAssets: unsyncedAssets,
  171. newPathToLocalIDs: newPathToLocalIDs,
  172. deletePathToLocalIDs: removedPathToLocalIDs,
  173. );
  174. }
  175. Future<List<File>> _convertLocalAssetsToUniqueFiles(
  176. List<LocalPathAsset> assets,
  177. ) async {
  178. final Set<String> alreadySeenLocalIDs = <String>{};
  179. final List<File> files = [];
  180. for (LocalPathAsset localPathAsset in assets) {
  181. final String localPathName = localPathAsset.pathName;
  182. for (final String localID in localPathAsset.localIDs) {
  183. if (!alreadySeenLocalIDs.contains(localID)) {
  184. final assetEntity = await AssetEntity.fromId(localID);
  185. files.add(
  186. await File.fromAsset(localPathName, assetEntity),
  187. );
  188. alreadySeenLocalIDs.add(localID);
  189. }
  190. }
  191. }
  192. return files;
  193. }
  194. /// returns a list of AssetPathEntity with relevant filter operations.
  195. /// [needTitle] impacts the performance for fetching the actual [AssetEntity]
  196. /// in iOS. Same is true for [containsModifiedPath]
  197. Future<List<AssetPathEntity>> _getGalleryList({
  198. final int updateFromTime,
  199. final int updateToTime,
  200. final bool containsModifiedPath = false,
  201. // in iOS fetching the AssetEntity title impacts performance
  202. final bool needsTitle = true,
  203. final OrderOption orderOption,
  204. }) async {
  205. final filterOptionGroup = FilterOptionGroup();
  206. filterOptionGroup.setOption(
  207. AssetType.image,
  208. FilterOption(needTitle: needsTitle, sizeConstraint: ignoreSizeConstraint),
  209. );
  210. filterOptionGroup.setOption(
  211. AssetType.video,
  212. FilterOption(needTitle: needsTitle, sizeConstraint: ignoreSizeConstraint),
  213. );
  214. if (orderOption != null) {
  215. filterOptionGroup.addOrderOption(orderOption);
  216. }
  217. if (updateFromTime != null && updateToTime != null) {
  218. filterOptionGroup.updateTimeCond = DateTimeCond(
  219. min: DateTime.fromMillisecondsSinceEpoch(updateFromTime ~/ 1000),
  220. max: DateTime.fromMillisecondsSinceEpoch(updateToTime ~/ 1000),
  221. );
  222. }
  223. filterOptionGroup.containsPathModified = containsModifiedPath;
  224. final galleryList = await PhotoManager.getAssetPathList(
  225. hasAll: !Platform.isAndroid,
  226. type: RequestType.common,
  227. filterOption: filterOptionGroup,
  228. );
  229. galleryList.sort((s1, s2) {
  230. if (s1.isAll) {
  231. return 1;
  232. }
  233. return 0;
  234. });
  235. return galleryList;
  236. }
  237. Future<List<AssetEntity>> _getAllAssetLists(AssetPathEntity pathEntity) async {
  238. final List<AssetEntity> result = [];
  239. int currentPage = 0;
  240. List<AssetEntity> currentPageResult = [];
  241. do {
  242. currentPageResult = await pathEntity.getAssetListPaged(
  243. page: currentPage,
  244. size: assetFetchPageSize,
  245. );
  246. Bus.instance.fire(
  247. LocalImportProgressEvent(pathEntity.name,
  248. currentPage * assetFetchPageSize + currentPageResult.length),
  249. );
  250. result.addAll(currentPageResult);
  251. currentPage = currentPage + 1;
  252. } while (currentPageResult.length >= assetFetchPageSize);
  253. return result;
  254. }
  255. // review: do we need to run this inside compute, after making File.FromAsset
  256. // sync. If yes, update the method documentation with reason.
  257. Future<Tuple2<Set<String>, List<File>>> _getLocalIDsAndFilesFromAssets(
  258. Map<String, dynamic> args,
  259. ) async {
  260. final pathEntity = args["pathEntity"] as AssetPathEntity;
  261. final assetList = args["assetList"];
  262. final fromTime = args["fromTime"];
  263. final alreadySeenLocalIDs = args["alreadySeenLocalIDs"] as Set<String>;
  264. final List<File> files = [];
  265. final Set<String> localIDs = {};
  266. for (AssetEntity entity in assetList) {
  267. localIDs.add(entity.id);
  268. final bool assetCreatedOrUpdatedAfterGivenTime = max(
  269. entity.createDateTime.millisecondsSinceEpoch,
  270. entity.modifiedDateTime.millisecondsSinceEpoch,
  271. ) >=
  272. (fromTime / ~1000);
  273. if (!alreadySeenLocalIDs.contains(entity.id) &&
  274. assetCreatedOrUpdatedAfterGivenTime) {
  275. try {
  276. final file = await File.fromAsset(pathEntity.name, entity);
  277. files.add(file);
  278. } catch (e) {
  279. _logger.severe(e);
  280. }
  281. }
  282. }
  283. return Tuple2(localIDs, files);
  284. }
  285. class LocalPathAsset {
  286. final Set<String> localIDs;
  287. final String pathID;
  288. final String pathName;
  289. LocalPathAsset({
  290. @required this.localIDs,
  291. @required this.pathName,
  292. @required this.pathID,
  293. });
  294. }
  295. class LocalDiffResult {
  296. // unique localPath Assets.
  297. final List<LocalPathAsset> localPathAssets;
  298. // set of File object created from localPathAssets
  299. List<File> uniqueLocalFiles;
  300. // newPathToLocalIDs represents new entries which needs to be synced to
  301. // the local db
  302. final Map<String, Set<String>> newPathToLocalIDs;
  303. final Map<String, Set<String>> deletePathToLocalIDs;
  304. LocalDiffResult({
  305. this.uniqueLocalFiles,
  306. this.localPathAssets,
  307. this.newPathToLocalIDs,
  308. this.deletePathToLocalIDs,
  309. });
  310. }