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