file_uploader.dart 35 KB

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