local_sync_util.dart 11 KB

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