file_uploader.dart 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. import 'dart:async';
  2. import 'dart:collection';
  3. import 'dart:convert';
  4. import 'dart:io' as io;
  5. import 'dart:math';
  6. import 'package:collection/collection.dart';
  7. import 'package:connectivity_plus/connectivity_plus.dart';
  8. import 'package:dio/dio.dart';
  9. import 'package:flutter/foundation.dart';
  10. import 'package:logging/logging.dart';
  11. import 'package:path/path.dart';
  12. import 'package:photos/core/configuration.dart';
  13. import 'package:photos/core/errors.dart';
  14. import 'package:photos/core/event_bus.dart';
  15. import 'package:photos/core/network/network.dart';
  16. import 'package:photos/db/files_db.dart';
  17. import 'package:photos/db/upload_locks_db.dart';
  18. import 'package:photos/events/files_updated_event.dart';
  19. import 'package:photos/events/local_photos_updated_event.dart';
  20. import 'package:photos/events/subscription_purchased_event.dart';
  21. import 'package:photos/main.dart';
  22. import 'package:photos/models/encryption_result.dart';
  23. import 'package:photos/models/file.dart';
  24. import 'package:photos/models/file_type.dart';
  25. import "package:photos/models/metadata/file_magic.dart";
  26. import 'package:photos/models/upload_url.dart';
  27. import 'package:photos/services/collections_service.dart';
  28. import "package:photos/services/file_magic_service.dart";
  29. import 'package:photos/services/local_sync_service.dart';
  30. import 'package:photos/services/sync_service.dart';
  31. import 'package:photos/utils/crypto_util.dart';
  32. import 'package:photos/utils/file_download_util.dart';
  33. import 'package:photos/utils/file_uploader_util.dart';
  34. import 'package:shared_preferences/shared_preferences.dart';
  35. import 'package:tuple/tuple.dart';
  36. class FileUploader {
  37. static const kMaximumConcurrentUploads = 4;
  38. static const kMaximumConcurrentVideoUploads = 2;
  39. static const kMaximumThumbnailCompressionAttempts = 2;
  40. static const kMaximumUploadAttempts = 4;
  41. static const kBlockedUploadsPollFrequency = Duration(seconds: 2);
  42. static const kFileUploadTimeout = Duration(minutes: 50);
  43. final _logger = Logger("FileUploader");
  44. final _dio = NetworkClient.instance.getDio();
  45. final _enteDio = NetworkClient.instance.enteDio;
  46. final LinkedHashMap _queue = LinkedHashMap<String, FileUploadItem>();
  47. final _uploadLocks = UploadLocksDB.instance;
  48. final kSafeBufferForLockExpiry = const Duration(days: 1).inMicroseconds;
  49. final kBGTaskDeathTimeout = const Duration(seconds: 5).inMicroseconds;
  50. final _uploadURLs = Queue<UploadURL>();
  51. // Maintains the count of files in the current upload session.
  52. // Upload session is the period between the first entry into the _queue and last entry out of the _queue
  53. int _totalCountInUploadSession = 0;
  54. // _uploadCounter indicates number of uploads which are currently in progress
  55. int _uploadCounter = 0;
  56. int _videoUploadCounter = 0;
  57. late ProcessType _processType;
  58. late bool _isBackground;
  59. late SharedPreferences _prefs;
  60. FileUploader._privateConstructor() {
  61. Bus.instance.on<SubscriptionPurchasedEvent>().listen((event) {
  62. _uploadURLFetchInProgress = null;
  63. });
  64. }
  65. static FileUploader instance = FileUploader._privateConstructor();
  66. Future<void> init(SharedPreferences preferences, bool isBackground) async {
  67. _prefs = preferences;
  68. _isBackground = isBackground;
  69. _processType =
  70. isBackground ? ProcessType.background : ProcessType.foreground;
  71. final currentTime = DateTime.now().microsecondsSinceEpoch;
  72. await _uploadLocks.releaseLocksAcquiredByOwnerBefore(
  73. _processType.toString(),
  74. currentTime,
  75. );
  76. await _uploadLocks
  77. .releaseAllLocksAcquiredBefore(currentTime - kSafeBufferForLockExpiry);
  78. if (!isBackground) {
  79. await _prefs.reload();
  80. final isBGTaskDead = (_prefs.getInt(kLastBGTaskHeartBeatTime) ?? 0) <
  81. (currentTime - kBGTaskDeathTimeout);
  82. if (isBGTaskDead) {
  83. await _uploadLocks.releaseLocksAcquiredByOwnerBefore(
  84. ProcessType.background.toString(),
  85. currentTime,
  86. );
  87. _logger.info("BG task was found dead, cleared all locks");
  88. }
  89. _pollBackgroundUploadStatus();
  90. }
  91. Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
  92. if (event.type == EventType.deletedFromDevice ||
  93. event.type == EventType.deletedFromEverywhere) {
  94. removeFromQueueWhere(
  95. (file) {
  96. for (final updatedFile in event.updatedFiles) {
  97. if (file.generatedID == updatedFile.generatedID) {
  98. return true;
  99. }
  100. }
  101. return false;
  102. },
  103. InvalidFileError("File already deleted"),
  104. );
  105. }
  106. });
  107. }
  108. // upload future will return null as File when the file entry is deleted
  109. // locally because it's already present in the destination collection.
  110. Future<File> upload(File file, int collectionID) {
  111. if (file.localID == null || file.localID!.isEmpty) {
  112. return Future.error(Exception("file's localID can not be null or empty"));
  113. }
  114. // If the file hasn't been queued yet, queue it
  115. _totalCountInUploadSession++;
  116. if (!_queue.containsKey(file.localID)) {
  117. final completer = Completer<File>();
  118. _queue[file.localID] = FileUploadItem(file, collectionID, completer);
  119. _pollQueue();
  120. return completer.future;
  121. }
  122. // If the file exists in the queue for a matching collectionID,
  123. // return the existing future
  124. final item = _queue[file.localID];
  125. if (item.collectionID == collectionID) {
  126. _totalCountInUploadSession--;
  127. return item.completer.future;
  128. }
  129. debugPrint(
  130. "Wait on another upload on same local ID to finish before "
  131. "adding it to new collection",
  132. );
  133. // Else wait for the existing upload to complete,
  134. // and add it to the relevant collection
  135. return item.completer.future.then((uploadedFile) {
  136. // If the fileUploader completer returned null,
  137. _logger.info(
  138. "original upload completer resolved, try adding the file to another "
  139. "collection",
  140. );
  141. if (uploadedFile == null) {
  142. /* todo: handle this case, ideally during next sync the localId
  143. should be uploaded to this collection ID
  144. */
  145. _logger.severe('unexpected upload state');
  146. return null;
  147. }
  148. return CollectionsService.instance
  149. .addToCollection(collectionID, [uploadedFile]).then((aVoid) {
  150. return uploadedFile as File;
  151. });
  152. });
  153. }
  154. int getCurrentSessionUploadCount() {
  155. return _totalCountInUploadSession;
  156. }
  157. void clearQueue(final Error reason) {
  158. final List<String> uploadsToBeRemoved = [];
  159. _queue.entries
  160. .where((entry) => entry.value.status == UploadStatus.notStarted)
  161. .forEach((pendingUpload) {
  162. uploadsToBeRemoved.add(pendingUpload.key);
  163. });
  164. for (final id in uploadsToBeRemoved) {
  165. _queue.remove(id).completer.completeError(reason);
  166. }
  167. _totalCountInUploadSession = 0;
  168. }
  169. void clearCachedUploadURLs() {
  170. _uploadURLs.clear();
  171. }
  172. void removeFromQueueWhere(final bool Function(File) fn, final Error reason) {
  173. final List<String> uploadsToBeRemoved = [];
  174. _queue.entries
  175. .where((entry) => entry.value.status == UploadStatus.notStarted)
  176. .forEach((pendingUpload) {
  177. if (fn(pendingUpload.value.file)) {
  178. uploadsToBeRemoved.add(pendingUpload.key);
  179. }
  180. });
  181. for (final id in uploadsToBeRemoved) {
  182. _queue.remove(id).completer.completeError(reason);
  183. }
  184. _logger.info(
  185. 'number of enteries removed from queue ${uploadsToBeRemoved.length}',
  186. );
  187. _totalCountInUploadSession -= uploadsToBeRemoved.length;
  188. }
  189. void _pollQueue() {
  190. if (SyncService.instance.shouldStopSync()) {
  191. clearQueue(SyncStopRequestedError());
  192. }
  193. if (_queue.isEmpty) {
  194. // Upload session completed
  195. _totalCountInUploadSession = 0;
  196. return;
  197. }
  198. if (_uploadCounter < kMaximumConcurrentUploads) {
  199. var pendingEntry = _queue.entries
  200. .firstWhereOrNull(
  201. (entry) => entry.value.status == UploadStatus.notStarted,
  202. )
  203. ?.value;
  204. if (pendingEntry != null &&
  205. pendingEntry.file.fileType == FileType.video &&
  206. _videoUploadCounter >= kMaximumConcurrentVideoUploads) {
  207. // check if there's any non-video entry which can be queued for upload
  208. pendingEntry = _queue.entries
  209. .firstWhereOrNull(
  210. (entry) =>
  211. entry.value.status == UploadStatus.notStarted &&
  212. entry.value.file.fileType != FileType.video,
  213. )
  214. ?.value;
  215. }
  216. if (pendingEntry != null) {
  217. pendingEntry.status = UploadStatus.inProgress;
  218. _encryptAndUploadFileToCollection(
  219. pendingEntry.file,
  220. pendingEntry.collectionID,
  221. );
  222. }
  223. }
  224. }
  225. Future<File?> _encryptAndUploadFileToCollection(
  226. File file,
  227. int collectionID, {
  228. bool forcedUpload = false,
  229. }) async {
  230. _uploadCounter++;
  231. if (file.fileType == FileType.video) {
  232. _videoUploadCounter++;
  233. }
  234. final localID = file.localID;
  235. try {
  236. final uploadedFile =
  237. await _tryToUpload(file, collectionID, forcedUpload).timeout(
  238. kFileUploadTimeout,
  239. onTimeout: () {
  240. final message = "Upload timed out for file " + file.toString();
  241. _logger.severe(message);
  242. throw TimeoutException(message);
  243. },
  244. );
  245. _queue.remove(localID).completer.complete(uploadedFile);
  246. return uploadedFile;
  247. } catch (e) {
  248. if (e is LockAlreadyAcquiredError) {
  249. _queue[localID].status = UploadStatus.inBackground;
  250. return _queue[localID].completer.future;
  251. } else {
  252. _queue.remove(localID).completer.completeError(e);
  253. return null;
  254. }
  255. } finally {
  256. _uploadCounter--;
  257. if (file.fileType == FileType.video) {
  258. _videoUploadCounter--;
  259. }
  260. _pollQueue();
  261. }
  262. }
  263. Future<void> checkNetworkForUpload({bool isForceUpload = false}) async {
  264. // Note: We don't support force uploading currently. During force upload,
  265. // network check is skipped completely
  266. if (isForceUpload) {
  267. return;
  268. }
  269. final connectivityResult = await (Connectivity().checkConnectivity());
  270. bool canUploadUnderCurrentNetworkConditions = true;
  271. if (connectivityResult == ConnectivityResult.mobile) {
  272. canUploadUnderCurrentNetworkConditions =
  273. Configuration.instance.shouldBackupOverMobileData();
  274. }
  275. if (!canUploadUnderCurrentNetworkConditions) {
  276. throw WiFiUnavailableError();
  277. }
  278. }
  279. Future<File> _tryToUpload(
  280. File file,
  281. int collectionID,
  282. bool forcedUpload,
  283. ) async {
  284. await checkNetworkForUpload(isForceUpload: forcedUpload);
  285. final fileOnDisk = await FilesDB.instance.getFile(file.generatedID!);
  286. final wasAlreadyUploaded = fileOnDisk != null &&
  287. fileOnDisk.uploadedFileID != null &&
  288. (fileOnDisk.updationTime ?? -1) != -1 &&
  289. (fileOnDisk.collectionID ?? -1) == collectionID;
  290. if (wasAlreadyUploaded) {
  291. debugPrint("File is already uploaded ${fileOnDisk.tag}");
  292. return fileOnDisk;
  293. }
  294. if ((file.localID ?? '') == '') {
  295. _logger.severe('Trying to upload file with missing localID');
  296. return file;
  297. }
  298. final String lockKey = file.localID!;
  299. try {
  300. await _uploadLocks.acquireLock(
  301. lockKey,
  302. _processType.toString(),
  303. DateTime.now().microsecondsSinceEpoch,
  304. );
  305. } catch (e) {
  306. _logger.warning("Lock was already taken for " + file.toString());
  307. throw LockAlreadyAcquiredError();
  308. }
  309. final tempDirectory = Configuration.instance.getTempDirectory();
  310. final encryptedFilePath = tempDirectory +
  311. file.generatedID.toString() +
  312. (_isBackground ? "_bg" : "") +
  313. ".encrypted";
  314. final encryptedThumbnailPath = tempDirectory +
  315. file.generatedID.toString() +
  316. "_thumbnail" +
  317. (_isBackground ? "_bg" : "") +
  318. ".encrypted";
  319. MediaUploadData? mediaUploadData;
  320. var uploadCompleted = false;
  321. // This flag is used to decide whether to clear the iOS origin file cache
  322. // or not.
  323. var uploadHardFailure = false;
  324. try {
  325. _logger.info(
  326. "Trying to upload " +
  327. file.toString() +
  328. ", isForced: " +
  329. forcedUpload.toString(),
  330. );
  331. try {
  332. mediaUploadData = await getUploadDataFromEnteFile(file);
  333. } catch (e) {
  334. if (e is InvalidFileError) {
  335. await _onInvalidFileError(file, e);
  336. } else {
  337. rethrow;
  338. }
  339. }
  340. Uint8List? key;
  341. final bool isUpdatedFile =
  342. file.uploadedFileID != null && file.updationTime == -1;
  343. if (isUpdatedFile) {
  344. _logger.info("File was updated " + file.toString());
  345. key = getFileKey(file);
  346. } else {
  347. key = null;
  348. // check if the file is already uploaded and can be mapped to existing
  349. // uploaded file. If map is found, it also returns the corresponding
  350. // mapped or update file entry.
  351. final result = await _mapToExistingUploadWithSameHash(
  352. mediaUploadData!,
  353. file,
  354. collectionID,
  355. );
  356. final isMappedToExistingUpload = result.item1;
  357. if (isMappedToExistingUpload) {
  358. debugPrint(
  359. "File success mapped to existing uploaded ${file.toString()}",
  360. );
  361. // return the mapped file
  362. return result.item2;
  363. }
  364. }
  365. if (io.File(encryptedFilePath).existsSync()) {
  366. await io.File(encryptedFilePath).delete();
  367. }
  368. final encryptedFile = io.File(encryptedFilePath);
  369. final EncryptionResult fileAttributes = await CryptoUtil.encryptFile(
  370. mediaUploadData!.sourceFile!.path,
  371. encryptedFilePath,
  372. key: key,
  373. );
  374. final thumbnailData = mediaUploadData.thumbnail;
  375. final EncryptionResult encryptedThumbnailData =
  376. await CryptoUtil.encryptChaCha(
  377. thumbnailData!,
  378. fileAttributes.key!,
  379. );
  380. if (io.File(encryptedThumbnailPath).existsSync()) {
  381. await io.File(encryptedThumbnailPath).delete();
  382. }
  383. final encryptedThumbnailFile = io.File(encryptedThumbnailPath);
  384. await encryptedThumbnailFile
  385. .writeAsBytes(encryptedThumbnailData.encryptedData!);
  386. final thumbnailUploadURL = await _getUploadURL();
  387. final String thumbnailObjectKey =
  388. await _putFile(thumbnailUploadURL, encryptedThumbnailFile);
  389. final fileUploadURL = await _getUploadURL();
  390. final String fileObjectKey = await _putFile(fileUploadURL, encryptedFile);
  391. final metadata = await file.getMetadataForUpload(mediaUploadData);
  392. final encryptedMetadataResult = await CryptoUtil.encryptChaCha(
  393. utf8.encode(jsonEncode(metadata)) as Uint8List,
  394. fileAttributes.key!,
  395. );
  396. final fileDecryptionHeader =
  397. CryptoUtil.bin2base64(fileAttributes.header!);
  398. final thumbnailDecryptionHeader =
  399. CryptoUtil.bin2base64(encryptedThumbnailData.header!);
  400. final encryptedMetadata = CryptoUtil.bin2base64(
  401. encryptedMetadataResult.encryptedData!,
  402. );
  403. final metadataDecryptionHeader =
  404. CryptoUtil.bin2base64(encryptedMetadataResult.header!);
  405. if (SyncService.instance.shouldStopSync()) {
  406. throw SyncStopRequestedError();
  407. }
  408. File remoteFile;
  409. if (isUpdatedFile) {
  410. remoteFile = await _updateFile(
  411. file,
  412. fileObjectKey,
  413. fileDecryptionHeader,
  414. await encryptedFile.length(),
  415. thumbnailObjectKey,
  416. thumbnailDecryptionHeader,
  417. await encryptedThumbnailFile.length(),
  418. encryptedMetadata,
  419. metadataDecryptionHeader,
  420. );
  421. // Update across all collections
  422. await FilesDB.instance.updateUploadedFileAcrossCollections(remoteFile);
  423. } else {
  424. final encryptedFileKeyData = CryptoUtil.encryptSync(
  425. fileAttributes.key!,
  426. CollectionsService.instance.getCollectionKey(collectionID),
  427. );
  428. final encryptedKey =
  429. CryptoUtil.bin2base64(encryptedFileKeyData.encryptedData!);
  430. final keyDecryptionNonce =
  431. CryptoUtil.bin2base64(encryptedFileKeyData.nonce!);
  432. MetadataRequest? pubMetadataRequest;
  433. if ((mediaUploadData.height ?? 0) != 0 &&
  434. (mediaUploadData.width ?? 0) != 0) {
  435. final pubMetadata = {
  436. heightKey: mediaUploadData.height,
  437. widthKey: mediaUploadData.width
  438. };
  439. if (mediaUploadData.motionPhotoStartIndex != null) {
  440. pubMetadata[motionVideoIndexKey] =
  441. mediaUploadData.motionPhotoStartIndex;
  442. }
  443. pubMetadataRequest = await getPubMetadataRequest(
  444. file,
  445. pubMetadata,
  446. fileAttributes.key!,
  447. );
  448. }
  449. remoteFile = await _uploadFile(
  450. file,
  451. collectionID,
  452. encryptedKey,
  453. keyDecryptionNonce,
  454. fileAttributes,
  455. fileObjectKey,
  456. fileDecryptionHeader,
  457. await encryptedFile.length(),
  458. thumbnailObjectKey,
  459. thumbnailDecryptionHeader,
  460. await encryptedThumbnailFile.length(),
  461. encryptedMetadata,
  462. metadataDecryptionHeader,
  463. pubMetadata: pubMetadataRequest,
  464. );
  465. if (mediaUploadData.isDeleted) {
  466. _logger.info("File found to be deleted");
  467. remoteFile.localID = null;
  468. }
  469. await FilesDB.instance.update(remoteFile);
  470. }
  471. if (!_isBackground) {
  472. Bus.instance.fire(
  473. LocalPhotosUpdatedEvent(
  474. [remoteFile],
  475. source: "downloadComplete",
  476. ),
  477. );
  478. }
  479. _logger.info("File upload complete for " + remoteFile.toString());
  480. uploadCompleted = true;
  481. return remoteFile;
  482. } catch (e, s) {
  483. if (!(e is NoActiveSubscriptionError ||
  484. e is StorageLimitExceededError ||
  485. e is WiFiUnavailableError ||
  486. e is SilentlyCancelUploadsError ||
  487. e is FileTooLargeForPlanError)) {
  488. _logger.severe("File upload failed for " + file.toString(), e, s);
  489. }
  490. if ((e is StorageLimitExceededError ||
  491. e is FileTooLargeForPlanError ||
  492. e is NoActiveSubscriptionError)) {
  493. // file upload can be be retried in such cases without user intervention
  494. uploadHardFailure = false;
  495. }
  496. rethrow;
  497. } finally {
  498. await _onUploadDone(
  499. mediaUploadData,
  500. uploadCompleted,
  501. uploadHardFailure,
  502. file,
  503. encryptedFilePath,
  504. encryptedThumbnailPath,
  505. lockKey: lockKey,
  506. );
  507. }
  508. }
  509. /*
  510. _mapToExistingUpload links the fileToUpload with the existing uploaded
  511. files. if the link is successful, it returns true otherwise false.
  512. When false, we should go ahead and re-upload or update the file.
  513. It performs following checks:
  514. a) Uploaded file with same localID and destination collection. Delete the
  515. fileToUpload entry
  516. b) Uploaded file in any collection but with missing localID.
  517. Update the localID for uploadedFile and delete the fileToUpload entry
  518. c) A uploaded file exist with same localID but in a different collection.
  519. Add a symlink in the destination collection and update the fileToUpload
  520. d) File already exists but different localID. Re-upload
  521. In case the existing files already have local identifier, which is
  522. different from the {fileToUpload}, then most probably device has
  523. duplicate files.
  524. */
  525. Future<Tuple2<bool, File>> _mapToExistingUploadWithSameHash(
  526. MediaUploadData mediaUploadData,
  527. File fileToUpload,
  528. int toCollectionID,
  529. ) async {
  530. if (fileToUpload.uploadedFileID != null) {
  531. // ideally this should never happen, but because the code below this case
  532. // can do unexpected mapping, we are adding this additional check
  533. _logger.severe(
  534. 'Critical: file is already uploaded, skipped mapping',
  535. );
  536. return Tuple2(false, fileToUpload);
  537. }
  538. final List<File> existingUploadedFiles =
  539. await FilesDB.instance.getUploadedFilesWithHashes(
  540. mediaUploadData.hashData!,
  541. fileToUpload.fileType,
  542. Configuration.instance.getUserID()!,
  543. );
  544. if (existingUploadedFiles.isEmpty) {
  545. // continueUploading this file
  546. return Tuple2(false, fileToUpload);
  547. }
  548. // case a
  549. final File? sameLocalSameCollection =
  550. existingUploadedFiles.firstWhereOrNull(
  551. (e) =>
  552. e.collectionID == toCollectionID && e.localID == fileToUpload.localID,
  553. );
  554. if (sameLocalSameCollection != null) {
  555. _logger.fine(
  556. "sameLocalSameCollection: \n toUpload ${fileToUpload.tag} "
  557. "\n existing: ${sameLocalSameCollection.tag}",
  558. );
  559. // should delete the fileToUploadEntry
  560. await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);
  561. Bus.instance.fire(
  562. LocalPhotosUpdatedEvent(
  563. [fileToUpload],
  564. type: EventType.deletedFromEverywhere,
  565. source: "sameLocalSameCollection", //
  566. ),
  567. );
  568. return Tuple2(true, sameLocalSameCollection);
  569. }
  570. // case b
  571. final File? fileMissingLocal = existingUploadedFiles.firstWhereOrNull(
  572. (e) => e.localID == null,
  573. );
  574. if (fileMissingLocal != null) {
  575. // update the local id of the existing file and delete the fileToUpload
  576. // entry
  577. _logger.fine(
  578. "fileMissingLocal: \n toUpload ${fileToUpload.tag} "
  579. "\n existing: ${fileMissingLocal.tag}",
  580. );
  581. fileMissingLocal.localID = fileToUpload.localID;
  582. // set localID for the given uploadedID across collections
  583. await FilesDB.instance.updateLocalIDForUploaded(
  584. fileMissingLocal.uploadedFileID!,
  585. fileToUpload.localID!,
  586. );
  587. await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);
  588. Bus.instance.fire(
  589. LocalPhotosUpdatedEvent(
  590. [fileToUpload],
  591. source: "fileMissingLocal",
  592. type: EventType.deletedFromEverywhere, //
  593. ),
  594. );
  595. return Tuple2(true, fileMissingLocal);
  596. }
  597. // case c
  598. final File? fileExistsButDifferentCollection =
  599. existingUploadedFiles.firstWhereOrNull(
  600. (e) =>
  601. e.collectionID != toCollectionID && e.localID == fileToUpload.localID,
  602. );
  603. if (fileExistsButDifferentCollection != null) {
  604. _logger.fine(
  605. "fileExistsButDifferentCollection: \n toUpload ${fileToUpload.tag} "
  606. "\n existing: ${fileExistsButDifferentCollection.tag}",
  607. );
  608. final linkedFile = await CollectionsService.instance
  609. .linkLocalFileToExistingUploadedFileInAnotherCollection(
  610. toCollectionID,
  611. localFileToUpload: fileToUpload,
  612. existingUploadedFile: fileExistsButDifferentCollection,
  613. );
  614. return Tuple2(true, linkedFile);
  615. }
  616. final Set<String> matchLocalIDs = existingUploadedFiles
  617. .where(
  618. (e) => e.localID != null,
  619. )
  620. .map((e) => e.localID!)
  621. .toSet();
  622. _logger.fine(
  623. "Found hashMatch but probably with diff localIDs "
  624. "$matchLocalIDs",
  625. );
  626. // case d
  627. return Tuple2(false, fileToUpload);
  628. }
  629. Future<void> _onUploadDone(
  630. MediaUploadData? mediaUploadData,
  631. bool uploadCompleted,
  632. bool uploadHardFailure,
  633. File file,
  634. String encryptedFilePath,
  635. String encryptedThumbnailPath, {
  636. required String lockKey,
  637. }) async {
  638. if (mediaUploadData != null && mediaUploadData.sourceFile != null) {
  639. // delete the file from app's internal cache if it was copied to app
  640. // for upload. On iOS, only remove the file from photo_manager/app cache
  641. // when upload is either completed or there's a tempFailure
  642. // Shared Media should only be cleared when the upload
  643. // succeeds.
  644. if ((io.Platform.isIOS && (uploadCompleted || uploadHardFailure)) ||
  645. (uploadCompleted && file.isSharedMediaToAppSandbox)) {
  646. await mediaUploadData.sourceFile?.delete();
  647. }
  648. }
  649. if (io.File(encryptedFilePath).existsSync()) {
  650. await io.File(encryptedFilePath).delete();
  651. }
  652. if (io.File(encryptedThumbnailPath).existsSync()) {
  653. await io.File(encryptedThumbnailPath).delete();
  654. }
  655. await _uploadLocks.releaseLock(lockKey, _processType.toString());
  656. }
  657. Future _onInvalidFileError(File file, InvalidFileError e) async {
  658. final String ext = file.title == null ? "no title" : extension(file.title!);
  659. _logger.severe(
  660. "Invalid file: (ext: $ext) encountered: " + file.toString(),
  661. e,
  662. );
  663. await FilesDB.instance.deleteLocalFile(file);
  664. await LocalSyncService.instance.trackInvalidFile(file);
  665. throw e;
  666. }
  667. Future<File> _uploadFile(
  668. File file,
  669. int collectionID,
  670. String encryptedKey,
  671. String keyDecryptionNonce,
  672. EncryptionResult fileAttributes,
  673. String fileObjectKey,
  674. String fileDecryptionHeader,
  675. int fileSize,
  676. String thumbnailObjectKey,
  677. String thumbnailDecryptionHeader,
  678. int thumbnailSize,
  679. String encryptedMetadata,
  680. String metadataDecryptionHeader, {
  681. MetadataRequest? pubMetadata,
  682. int attempt = 1,
  683. }) async {
  684. final request = {
  685. "collectionID": collectionID,
  686. "encryptedKey": encryptedKey,
  687. "keyDecryptionNonce": keyDecryptionNonce,
  688. "file": {
  689. "objectKey": fileObjectKey,
  690. "decryptionHeader": fileDecryptionHeader,
  691. "size": fileSize,
  692. },
  693. "thumbnail": {
  694. "objectKey": thumbnailObjectKey,
  695. "decryptionHeader": thumbnailDecryptionHeader,
  696. "size": thumbnailSize,
  697. },
  698. "metadata": {
  699. "encryptedData": encryptedMetadata,
  700. "decryptionHeader": metadataDecryptionHeader,
  701. }
  702. };
  703. if (pubMetadata != null) {
  704. request["pubMagicMetadata"] = pubMetadata;
  705. }
  706. try {
  707. final response = await _enteDio.post("/files", data: request);
  708. final data = response.data;
  709. file.uploadedFileID = data["id"];
  710. file.collectionID = collectionID;
  711. file.updationTime = data["updationTime"];
  712. file.ownerID = data["ownerID"];
  713. file.encryptedKey = encryptedKey;
  714. file.keyDecryptionNonce = keyDecryptionNonce;
  715. file.fileDecryptionHeader = fileDecryptionHeader;
  716. file.thumbnailDecryptionHeader = thumbnailDecryptionHeader;
  717. file.metadataDecryptionHeader = metadataDecryptionHeader;
  718. return file;
  719. } on DioError catch (e) {
  720. if (e.response?.statusCode == 413) {
  721. throw FileTooLargeForPlanError();
  722. } else if (e.response?.statusCode == 426) {
  723. _onStorageLimitExceeded();
  724. } else if (attempt < kMaximumUploadAttempts) {
  725. _logger.info("Upload file failed, will retry in 3 seconds");
  726. await Future.delayed(const Duration(seconds: 3));
  727. return _uploadFile(
  728. file,
  729. collectionID,
  730. encryptedKey,
  731. keyDecryptionNonce,
  732. fileAttributes,
  733. fileObjectKey,
  734. fileDecryptionHeader,
  735. fileSize,
  736. thumbnailObjectKey,
  737. thumbnailDecryptionHeader,
  738. thumbnailSize,
  739. encryptedMetadata,
  740. metadataDecryptionHeader,
  741. attempt: attempt + 1,
  742. pubMetadata: pubMetadata,
  743. );
  744. }
  745. rethrow;
  746. }
  747. }
  748. Future<File> _updateFile(
  749. File file,
  750. String fileObjectKey,
  751. String fileDecryptionHeader,
  752. int fileSize,
  753. String thumbnailObjectKey,
  754. String thumbnailDecryptionHeader,
  755. int thumbnailSize,
  756. String encryptedMetadata,
  757. String metadataDecryptionHeader, {
  758. int attempt = 1,
  759. }) async {
  760. final request = {
  761. "id": file.uploadedFileID,
  762. "file": {
  763. "objectKey": fileObjectKey,
  764. "decryptionHeader": fileDecryptionHeader,
  765. "size": fileSize,
  766. },
  767. "thumbnail": {
  768. "objectKey": thumbnailObjectKey,
  769. "decryptionHeader": thumbnailDecryptionHeader,
  770. "size": thumbnailSize,
  771. },
  772. "metadata": {
  773. "encryptedData": encryptedMetadata,
  774. "decryptionHeader": metadataDecryptionHeader,
  775. }
  776. };
  777. try {
  778. final response = await _enteDio.put("/files/update", data: request);
  779. final data = response.data;
  780. file.uploadedFileID = data["id"];
  781. file.updationTime = data["updationTime"];
  782. file.fileDecryptionHeader = fileDecryptionHeader;
  783. file.thumbnailDecryptionHeader = thumbnailDecryptionHeader;
  784. file.metadataDecryptionHeader = metadataDecryptionHeader;
  785. return file;
  786. } on DioError catch (e) {
  787. if (e.response?.statusCode == 426) {
  788. _onStorageLimitExceeded();
  789. } else if (attempt < kMaximumUploadAttempts) {
  790. _logger.info("Update file failed, will retry in 3 seconds");
  791. await Future.delayed(const Duration(seconds: 3));
  792. return _updateFile(
  793. file,
  794. fileObjectKey,
  795. fileDecryptionHeader,
  796. fileSize,
  797. thumbnailObjectKey,
  798. thumbnailDecryptionHeader,
  799. thumbnailSize,
  800. encryptedMetadata,
  801. metadataDecryptionHeader,
  802. attempt: attempt + 1,
  803. );
  804. }
  805. rethrow;
  806. }
  807. }
  808. Future<UploadURL> _getUploadURL() async {
  809. if (_uploadURLs.isEmpty) {
  810. await fetchUploadURLs(_queue.length);
  811. }
  812. try {
  813. return _uploadURLs.removeFirst();
  814. } catch (e) {
  815. if (e is StateError && e.message == 'No element' && _queue.isEmpty) {
  816. _logger.warning("Oops, uploadUrls has no element now, fetching again");
  817. return _getUploadURL();
  818. } else {
  819. rethrow;
  820. }
  821. }
  822. }
  823. Future<void>? _uploadURLFetchInProgress;
  824. Future<void> fetchUploadURLs(int fileCount) async {
  825. _uploadURLFetchInProgress ??= Future<void>(() async {
  826. try {
  827. final response = await _enteDio.get(
  828. "/files/upload-urls",
  829. queryParameters: {
  830. "count": min(42, fileCount * 2), // m4gic number
  831. },
  832. );
  833. final urls = (response.data["urls"] as List)
  834. .map((e) => UploadURL.fromMap(e))
  835. .toList();
  836. _uploadURLs.addAll(urls);
  837. } on DioError catch (e, s) {
  838. if (e.response != null) {
  839. if (e.response!.statusCode == 402) {
  840. final error = NoActiveSubscriptionError();
  841. clearQueue(error);
  842. throw error;
  843. } else if (e.response!.statusCode == 426) {
  844. final error = StorageLimitExceededError();
  845. clearQueue(error);
  846. throw error;
  847. } else {
  848. _logger.severe("Could not fetch upload URLs", e, s);
  849. }
  850. }
  851. rethrow;
  852. } finally {
  853. _uploadURLFetchInProgress = null;
  854. }
  855. });
  856. return _uploadURLFetchInProgress;
  857. }
  858. void _onStorageLimitExceeded() {
  859. clearQueue(StorageLimitExceededError());
  860. throw StorageLimitExceededError();
  861. }
  862. Future<String> _putFile(
  863. UploadURL uploadURL,
  864. io.File file, {
  865. int? contentLength,
  866. int attempt = 1,
  867. }) async {
  868. final fileSize = contentLength ?? await file.length();
  869. _logger.info(
  870. "Putting object for " +
  871. file.toString() +
  872. " of size: " +
  873. fileSize.toString(),
  874. );
  875. final startTime = DateTime.now().millisecondsSinceEpoch;
  876. try {
  877. await _dio.put(
  878. uploadURL.url,
  879. data: file.openRead(),
  880. options: Options(
  881. headers: {
  882. Headers.contentLengthHeader: fileSize,
  883. },
  884. ),
  885. );
  886. _logger.info(
  887. "Upload speed : " +
  888. (fileSize / (DateTime.now().millisecondsSinceEpoch - startTime))
  889. .toString() +
  890. " kilo bytes per second",
  891. );
  892. return uploadURL.objectKey;
  893. } on DioError catch (e) {
  894. if (e.message.startsWith(
  895. "HttpException: Content size exceeds specified contentLength.",
  896. ) &&
  897. attempt == 1) {
  898. return _putFile(
  899. uploadURL,
  900. file,
  901. contentLength: (await file.readAsBytes()).length,
  902. attempt: 2,
  903. );
  904. } else if (attempt < kMaximumUploadAttempts) {
  905. final newUploadURL = await _getUploadURL();
  906. return _putFile(
  907. newUploadURL,
  908. file,
  909. contentLength: (await file.readAsBytes()).length,
  910. attempt: attempt + 1,
  911. );
  912. } else {
  913. _logger.info(
  914. "Upload failed for file with size " + fileSize.toString(),
  915. e,
  916. );
  917. rethrow;
  918. }
  919. }
  920. }
  921. Future<void> _pollBackgroundUploadStatus() async {
  922. final blockedUploads = _queue.entries
  923. .where((e) => e.value.status == UploadStatus.inBackground)
  924. .toList();
  925. for (final upload in blockedUploads) {
  926. final file = upload.value.file;
  927. final isStillLocked = await _uploadLocks.isLocked(
  928. file.localID,
  929. ProcessType.background.toString(),
  930. );
  931. if (!isStillLocked) {
  932. final completer = _queue.remove(upload.key).completer;
  933. final dbFile =
  934. await FilesDB.instance.getFile(upload.value.file.generatedID);
  935. if (dbFile?.uploadedFileID != null) {
  936. _logger.info("Background upload success detected");
  937. completer.complete(dbFile);
  938. } else {
  939. _logger.info("Background upload failure detected");
  940. completer.completeError(SilentlyCancelUploadsError());
  941. }
  942. }
  943. }
  944. Future.delayed(kBlockedUploadsPollFrequency, () async {
  945. await _pollBackgroundUploadStatus();
  946. });
  947. }
  948. }
  949. class FileUploadItem {
  950. final File file;
  951. final int collectionID;
  952. final Completer<File> completer;
  953. UploadStatus status;
  954. FileUploadItem(
  955. this.file,
  956. this.collectionID,
  957. this.completer, {
  958. this.status = UploadStatus.notStarted,
  959. });
  960. }
  961. enum UploadStatus {
  962. notStarted,
  963. inProgress,
  964. inBackground,
  965. completed,
  966. }
  967. enum ProcessType {
  968. background,
  969. foreground,
  970. }