file_uploader.dart 36 KB

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