local_sync_util.dart 11 KB

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