file_uploader.dart 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. _logger.info(
  330. "Trying to upload " +
  331. file.toString() +
  332. ", isForced: " +
  333. forcedUpload.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. final bool isUpdatedFile =
  346. file.uploadedFileID != null && file.updationTime == -1;
  347. if (isUpdatedFile) {
  348. _logger.info("File was updated " + file.toString());
  349. key = getFileKey(file);
  350. } else {
  351. key = null;
  352. // check if the file is already uploaded and can be mapped to existing
  353. // uploaded file. If map is found, it also returns the corresponding
  354. // mapped or update file entry.
  355. final result = await _mapToExistingUploadWithSameHash(
  356. mediaUploadData!,
  357. file,
  358. collectionID,
  359. );
  360. final isMappedToExistingUpload = result.item1;
  361. if (isMappedToExistingUpload) {
  362. debugPrint(
  363. "File success mapped to existing uploaded ${file.toString()}",
  364. );
  365. // return the mapped file
  366. return result.item2;
  367. }
  368. }
  369. if (io.File(encryptedFilePath).existsSync()) {
  370. await io.File(encryptedFilePath).delete();
  371. }
  372. await _checkIfWithinStorageLimit(mediaUploadData!.sourceFile!);
  373. final encryptedFile = io.File(encryptedFilePath);
  374. final EncryptionResult fileAttributes = await CryptoUtil.encryptFile(
  375. mediaUploadData.sourceFile!.path,
  376. encryptedFilePath,
  377. key: key,
  378. );
  379. final thumbnailData = mediaUploadData.thumbnail;
  380. final EncryptionResult encryptedThumbnailData =
  381. await CryptoUtil.encryptChaCha(
  382. thumbnailData!,
  383. fileAttributes.key!,
  384. );
  385. if (io.File(encryptedThumbnailPath).existsSync()) {
  386. await io.File(encryptedThumbnailPath).delete();
  387. }
  388. final encryptedThumbnailFile = io.File(encryptedThumbnailPath);
  389. await encryptedThumbnailFile
  390. .writeAsBytes(encryptedThumbnailData.encryptedData!);
  391. final thumbnailUploadURL = await _getUploadURL();
  392. final String thumbnailObjectKey =
  393. await _putFile(thumbnailUploadURL, encryptedThumbnailFile);
  394. final fileUploadURL = await _getUploadURL();
  395. final String fileObjectKey = await _putFile(fileUploadURL, encryptedFile);
  396. final metadata = await file.getMetadataForUpload(mediaUploadData);
  397. final encryptedMetadataResult = await CryptoUtil.encryptChaCha(
  398. utf8.encode(jsonEncode(metadata)) as Uint8List,
  399. fileAttributes.key!,
  400. );
  401. final fileDecryptionHeader =
  402. CryptoUtil.bin2base64(fileAttributes.header!);
  403. final thumbnailDecryptionHeader =
  404. CryptoUtil.bin2base64(encryptedThumbnailData.header!);
  405. final encryptedMetadata = CryptoUtil.bin2base64(
  406. encryptedMetadataResult.encryptedData!,
  407. );
  408. final metadataDecryptionHeader =
  409. CryptoUtil.bin2base64(encryptedMetadataResult.header!);
  410. if (SyncService.instance.shouldStopSync()) {
  411. throw SyncStopRequestedError();
  412. }
  413. File remoteFile;
  414. if (isUpdatedFile) {
  415. remoteFile = await _updateFile(
  416. file,
  417. fileObjectKey,
  418. fileDecryptionHeader,
  419. await encryptedFile.length(),
  420. thumbnailObjectKey,
  421. thumbnailDecryptionHeader,
  422. await encryptedThumbnailFile.length(),
  423. encryptedMetadata,
  424. metadataDecryptionHeader,
  425. );
  426. // Update across all collections
  427. await FilesDB.instance.updateUploadedFileAcrossCollections(remoteFile);
  428. } else {
  429. final encryptedFileKeyData = CryptoUtil.encryptSync(
  430. fileAttributes.key!,
  431. CollectionsService.instance.getCollectionKey(collectionID),
  432. );
  433. final encryptedKey =
  434. CryptoUtil.bin2base64(encryptedFileKeyData.encryptedData!);
  435. final keyDecryptionNonce =
  436. CryptoUtil.bin2base64(encryptedFileKeyData.nonce!);
  437. MetadataRequest? pubMetadataRequest;
  438. if ((mediaUploadData.height ?? 0) != 0 &&
  439. (mediaUploadData.width ?? 0) != 0) {
  440. final pubMetadata = {
  441. heightKey: mediaUploadData.height,
  442. widthKey: mediaUploadData.width,
  443. };
  444. if (mediaUploadData.motionPhotoStartIndex != null) {
  445. pubMetadata[motionVideoIndexKey] =
  446. mediaUploadData.motionPhotoStartIndex;
  447. }
  448. pubMetadataRequest = await getPubMetadataRequest(
  449. file,
  450. pubMetadata,
  451. fileAttributes.key!,
  452. );
  453. }
  454. remoteFile = await _uploadFile(
  455. file,
  456. collectionID,
  457. encryptedKey,
  458. keyDecryptionNonce,
  459. fileAttributes,
  460. fileObjectKey,
  461. fileDecryptionHeader,
  462. await encryptedFile.length(),
  463. thumbnailObjectKey,
  464. thumbnailDecryptionHeader,
  465. await encryptedThumbnailFile.length(),
  466. encryptedMetadata,
  467. metadataDecryptionHeader,
  468. pubMetadata: pubMetadataRequest,
  469. );
  470. if (mediaUploadData.isDeleted) {
  471. _logger.info("File found to be deleted");
  472. remoteFile.localID = null;
  473. }
  474. await FilesDB.instance.update(remoteFile);
  475. }
  476. if (!_isBackground) {
  477. Bus.instance.fire(
  478. LocalPhotosUpdatedEvent(
  479. [remoteFile],
  480. source: "downloadComplete",
  481. ),
  482. );
  483. }
  484. _logger.info("File upload complete for " + remoteFile.toString());
  485. uploadCompleted = true;
  486. return remoteFile;
  487. } catch (e, s) {
  488. if (!(e is NoActiveSubscriptionError ||
  489. e is StorageLimitExceededError ||
  490. e is WiFiUnavailableError ||
  491. e is SilentlyCancelUploadsError ||
  492. e is FileTooLargeForPlanError)) {
  493. _logger.severe("File upload failed for " + file.toString(), e, s);
  494. }
  495. if ((e is StorageLimitExceededError ||
  496. e is FileTooLargeForPlanError ||
  497. e is NoActiveSubscriptionError)) {
  498. // file upload can be be retried in such cases without user intervention
  499. uploadHardFailure = false;
  500. }
  501. rethrow;
  502. } finally {
  503. await _onUploadDone(
  504. mediaUploadData,
  505. uploadCompleted,
  506. uploadHardFailure,
  507. file,
  508. encryptedFilePath,
  509. encryptedThumbnailPath,
  510. lockKey: lockKey,
  511. );
  512. }
  513. }
  514. /*
  515. _mapToExistingUpload links the fileToUpload with the existing uploaded
  516. files. if the link is successful, it returns true otherwise false.
  517. When false, we should go ahead and re-upload or update the file.
  518. It performs following checks:
  519. a) Uploaded file with same localID and destination collection. Delete the
  520. fileToUpload entry
  521. b) Uploaded file in any collection but with missing localID.
  522. Update the localID for uploadedFile and delete the fileToUpload entry
  523. c) A uploaded file exist with same localID but in a different collection.
  524. Add a symlink in the destination collection and update the fileToUpload
  525. d) File already exists but different localID. Re-upload
  526. In case the existing files already have local identifier, which is
  527. different from the {fileToUpload}, then most probably device has
  528. duplicate files.
  529. */
  530. Future<Tuple2<bool, File>> _mapToExistingUploadWithSameHash(
  531. MediaUploadData mediaUploadData,
  532. File fileToUpload,
  533. int toCollectionID,
  534. ) async {
  535. if (fileToUpload.uploadedFileID != null) {
  536. // ideally this should never happen, but because the code below this case
  537. // can do unexpected mapping, we are adding this additional check
  538. _logger.severe(
  539. 'Critical: file is already uploaded, skipped mapping',
  540. );
  541. return Tuple2(false, fileToUpload);
  542. }
  543. final List<File> existingUploadedFiles =
  544. await FilesDB.instance.getUploadedFilesWithHashes(
  545. mediaUploadData.hashData!,
  546. fileToUpload.fileType,
  547. Configuration.instance.getUserID()!,
  548. );
  549. if (existingUploadedFiles.isEmpty) {
  550. // continueUploading this file
  551. return Tuple2(false, fileToUpload);
  552. }
  553. // case a
  554. final File? sameLocalSameCollection =
  555. existingUploadedFiles.firstWhereOrNull(
  556. (e) =>
  557. e.collectionID == toCollectionID && e.localID == fileToUpload.localID,
  558. );
  559. if (sameLocalSameCollection != null) {
  560. _logger.fine(
  561. "sameLocalSameCollection: \n toUpload ${fileToUpload.tag} "
  562. "\n existing: ${sameLocalSameCollection.tag}",
  563. );
  564. // should delete the fileToUploadEntry
  565. if (fileToUpload.generatedID != null) {
  566. await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);
  567. }
  568. Bus.instance.fire(
  569. LocalPhotosUpdatedEvent(
  570. [fileToUpload],
  571. type: EventType.deletedFromEverywhere,
  572. source: "sameLocalSameCollection", //
  573. ),
  574. );
  575. return Tuple2(true, sameLocalSameCollection);
  576. }
  577. // case b
  578. final File? fileMissingLocal = existingUploadedFiles.firstWhereOrNull(
  579. (e) => e.localID == null,
  580. );
  581. if (fileMissingLocal != null) {
  582. // update the local id of the existing file and delete the fileToUpload
  583. // entry
  584. _logger.fine(
  585. "fileMissingLocal: \n toUpload ${fileToUpload.tag} "
  586. "\n existing: ${fileMissingLocal.tag}",
  587. );
  588. fileMissingLocal.localID = fileToUpload.localID;
  589. // set localID for the given uploadedID across collections
  590. await FilesDB.instance.updateLocalIDForUploaded(
  591. fileMissingLocal.uploadedFileID!,
  592. fileToUpload.localID!,
  593. );
  594. // For files selected from device, during collaborative upload, we don't
  595. // insert entries in the FilesDB. So, we don't need to delete the entry
  596. if (fileToUpload.generatedID != null) {
  597. await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);
  598. }
  599. Bus.instance.fire(
  600. LocalPhotosUpdatedEvent(
  601. [fileToUpload],
  602. source: "fileMissingLocal",
  603. type: EventType.deletedFromEverywhere, //
  604. ),
  605. );
  606. return Tuple2(true, fileMissingLocal);
  607. }
  608. // case c
  609. final File? fileExistsButDifferentCollection =
  610. existingUploadedFiles.firstWhereOrNull(
  611. (e) =>
  612. e.collectionID != toCollectionID && e.localID == fileToUpload.localID,
  613. );
  614. if (fileExistsButDifferentCollection != null) {
  615. _logger.fine(
  616. "fileExistsButDifferentCollection: \n toUpload ${fileToUpload.tag} "
  617. "\n existing: ${fileExistsButDifferentCollection.tag}",
  618. );
  619. final linkedFile = await CollectionsService.instance
  620. .linkLocalFileToExistingUploadedFileInAnotherCollection(
  621. toCollectionID,
  622. localFileToUpload: fileToUpload,
  623. existingUploadedFile: fileExistsButDifferentCollection,
  624. );
  625. return Tuple2(true, linkedFile);
  626. }
  627. final Set<String> matchLocalIDs = existingUploadedFiles
  628. .where(
  629. (e) => e.localID != null,
  630. )
  631. .map((e) => e.localID!)
  632. .toSet();
  633. _logger.fine(
  634. "Found hashMatch but probably with diff localIDs "
  635. "$matchLocalIDs",
  636. );
  637. // case d
  638. return Tuple2(false, fileToUpload);
  639. }
  640. Future<void> _onUploadDone(
  641. MediaUploadData? mediaUploadData,
  642. bool uploadCompleted,
  643. bool uploadHardFailure,
  644. File file,
  645. String encryptedFilePath,
  646. String encryptedThumbnailPath, {
  647. required String lockKey,
  648. }) async {
  649. if (mediaUploadData != null && mediaUploadData.sourceFile != null) {
  650. // delete the file from app's internal cache if it was copied to app
  651. // for upload. On iOS, only remove the file from photo_manager/app cache
  652. // when upload is either completed or there's a tempFailure
  653. // Shared Media should only be cleared when the upload
  654. // succeeds.
  655. if ((io.Platform.isIOS && (uploadCompleted || uploadHardFailure)) ||
  656. (uploadCompleted && file.isSharedMediaToAppSandbox)) {
  657. await mediaUploadData.sourceFile?.delete();
  658. }
  659. }
  660. if (io.File(encryptedFilePath).existsSync()) {
  661. await io.File(encryptedFilePath).delete();
  662. }
  663. if (io.File(encryptedThumbnailPath).existsSync()) {
  664. await io.File(encryptedThumbnailPath).delete();
  665. }
  666. await _uploadLocks.releaseLock(lockKey, _processType.toString());
  667. }
  668. /*
  669. _checkIfWithinStorageLimit verifies if the file size for encryption and upload
  670. is within the storage limit. It throws StorageLimitExceededError if the limit
  671. is exceeded. This check is best effort and may not be completely accurate
  672. due to UserDetail cache. It prevents infinite loops when clients attempt to
  673. upload files that exceed the server's storage limit + buffer.
  674. Note: Local storageBuffer is 20MB, server storageBuffer is 50MB, and an
  675. additional 30MB is reserved for thumbnails and encryption overhead.
  676. */
  677. Future<void> _checkIfWithinStorageLimit(io.File fileToBeUploaded) async {
  678. try {
  679. final UserDetails? userDetails =
  680. UserService.instance.getCachedUserDetails();
  681. if (userDetails == null) {
  682. return;
  683. }
  684. // add k20MBStorageBuffer to the free storage
  685. final num freeStorage = userDetails.getFreeStorage() + k20MBStorageBuffer;
  686. final num fileSize = await fileToBeUploaded.length();
  687. if (fileSize > freeStorage) {
  688. _logger.warning('Storage limit exceeded fileSize $fileSize and '
  689. 'freeStorage $freeStorage');
  690. throw StorageLimitExceededError();
  691. }
  692. } catch (e) {
  693. if (e is StorageLimitExceededError) {
  694. rethrow;
  695. } else {
  696. _logger.severe('Error checking storage limit', e);
  697. }
  698. }
  699. }
  700. Future _onInvalidFileError(File file, InvalidFileError e) async {
  701. final String ext = file.title == null ? "no title" : extension(file.title!);
  702. _logger.severe(
  703. "Invalid file: (ext: $ext) encountered: " + file.toString(),
  704. e,
  705. );
  706. await FilesDB.instance.deleteLocalFile(file);
  707. await LocalSyncService.instance.trackInvalidFile(file);
  708. throw e;
  709. }
  710. Future<File> _uploadFile(
  711. File file,
  712. int collectionID,
  713. String encryptedKey,
  714. String keyDecryptionNonce,
  715. EncryptionResult fileAttributes,
  716. String fileObjectKey,
  717. String fileDecryptionHeader,
  718. int fileSize,
  719. String thumbnailObjectKey,
  720. String thumbnailDecryptionHeader,
  721. int thumbnailSize,
  722. String encryptedMetadata,
  723. String metadataDecryptionHeader, {
  724. MetadataRequest? pubMetadata,
  725. int attempt = 1,
  726. }) async {
  727. final request = {
  728. "collectionID": collectionID,
  729. "encryptedKey": encryptedKey,
  730. "keyDecryptionNonce": keyDecryptionNonce,
  731. "file": {
  732. "objectKey": fileObjectKey,
  733. "decryptionHeader": fileDecryptionHeader,
  734. "size": fileSize,
  735. },
  736. "thumbnail": {
  737. "objectKey": thumbnailObjectKey,
  738. "decryptionHeader": thumbnailDecryptionHeader,
  739. "size": thumbnailSize,
  740. },
  741. "metadata": {
  742. "encryptedData": encryptedMetadata,
  743. "decryptionHeader": metadataDecryptionHeader,
  744. },
  745. };
  746. if (pubMetadata != null) {
  747. request["pubMagicMetadata"] = pubMetadata;
  748. }
  749. try {
  750. final response = await _enteDio.post("/files", data: request);
  751. final data = response.data;
  752. file.uploadedFileID = data["id"];
  753. file.collectionID = collectionID;
  754. file.updationTime = data["updationTime"];
  755. file.ownerID = data["ownerID"];
  756. file.encryptedKey = encryptedKey;
  757. file.keyDecryptionNonce = keyDecryptionNonce;
  758. file.fileDecryptionHeader = fileDecryptionHeader;
  759. file.thumbnailDecryptionHeader = thumbnailDecryptionHeader;
  760. file.metadataDecryptionHeader = metadataDecryptionHeader;
  761. return file;
  762. } on DioError catch (e) {
  763. if (e.response?.statusCode == 413) {
  764. throw FileTooLargeForPlanError();
  765. } else if (e.response?.statusCode == 426) {
  766. _onStorageLimitExceeded();
  767. } else if (attempt < kMaximumUploadAttempts) {
  768. _logger.info("Upload file failed, will retry in 3 seconds");
  769. await Future.delayed(const Duration(seconds: 3));
  770. return _uploadFile(
  771. file,
  772. collectionID,
  773. encryptedKey,
  774. keyDecryptionNonce,
  775. fileAttributes,
  776. fileObjectKey,
  777. fileDecryptionHeader,
  778. fileSize,
  779. thumbnailObjectKey,
  780. thumbnailDecryptionHeader,
  781. thumbnailSize,
  782. encryptedMetadata,
  783. metadataDecryptionHeader,
  784. attempt: attempt + 1,
  785. pubMetadata: pubMetadata,
  786. );
  787. }
  788. rethrow;
  789. }
  790. }
  791. Future<File> _updateFile(
  792. File file,
  793. String fileObjectKey,
  794. String fileDecryptionHeader,
  795. int fileSize,
  796. String thumbnailObjectKey,
  797. String thumbnailDecryptionHeader,
  798. int thumbnailSize,
  799. String encryptedMetadata,
  800. String metadataDecryptionHeader, {
  801. int attempt = 1,
  802. }) async {
  803. final request = {
  804. "id": file.uploadedFileID,
  805. "file": {
  806. "objectKey": fileObjectKey,
  807. "decryptionHeader": fileDecryptionHeader,
  808. "size": fileSize,
  809. },
  810. "thumbnail": {
  811. "objectKey": thumbnailObjectKey,
  812. "decryptionHeader": thumbnailDecryptionHeader,
  813. "size": thumbnailSize,
  814. },
  815. "metadata": {
  816. "encryptedData": encryptedMetadata,
  817. "decryptionHeader": metadataDecryptionHeader,
  818. },
  819. };
  820. try {
  821. final response = await _enteDio.put("/files/update", data: request);
  822. final data = response.data;
  823. file.uploadedFileID = data["id"];
  824. file.updationTime = data["updationTime"];
  825. file.fileDecryptionHeader = fileDecryptionHeader;
  826. file.thumbnailDecryptionHeader = thumbnailDecryptionHeader;
  827. file.metadataDecryptionHeader = metadataDecryptionHeader;
  828. return file;
  829. } on DioError catch (e) {
  830. if (e.response?.statusCode == 426) {
  831. _onStorageLimitExceeded();
  832. } else if (attempt < kMaximumUploadAttempts) {
  833. _logger.info("Update file failed, will retry in 3 seconds");
  834. await Future.delayed(const Duration(seconds: 3));
  835. return _updateFile(
  836. file,
  837. fileObjectKey,
  838. fileDecryptionHeader,
  839. fileSize,
  840. thumbnailObjectKey,
  841. thumbnailDecryptionHeader,
  842. thumbnailSize,
  843. encryptedMetadata,
  844. metadataDecryptionHeader,
  845. attempt: attempt + 1,
  846. );
  847. }
  848. rethrow;
  849. }
  850. }
  851. Future<UploadURL> _getUploadURL() async {
  852. if (_uploadURLs.isEmpty) {
  853. // the queue is empty, fetch at least for one file to handle force uploads
  854. // that are not in the queue. This is to also avoid
  855. await fetchUploadURLs(max(_queue.length, 1));
  856. }
  857. try {
  858. return _uploadURLs.removeFirst();
  859. } catch (e) {
  860. if (e is StateError && e.message == 'No element' && _queue.isEmpty) {
  861. _logger.warning("Oops, uploadUrls has no element now, fetching again");
  862. return _getUploadURL();
  863. } else {
  864. rethrow;
  865. }
  866. }
  867. }
  868. Future<void>? _uploadURLFetchInProgress;
  869. Future<void> fetchUploadURLs(int fileCount) async {
  870. _uploadURLFetchInProgress ??= Future<void>(() async {
  871. try {
  872. final response = await _enteDio.get(
  873. "/files/upload-urls",
  874. queryParameters: {
  875. "count": min(42, fileCount * 2), // m4gic number
  876. },
  877. );
  878. final urls = (response.data["urls"] as List)
  879. .map((e) => UploadURL.fromMap(e))
  880. .toList();
  881. _uploadURLs.addAll(urls);
  882. } on DioError catch (e, s) {
  883. if (e.response != null) {
  884. if (e.response!.statusCode == 402) {
  885. final error = NoActiveSubscriptionError();
  886. clearQueue(error);
  887. throw error;
  888. } else if (e.response!.statusCode == 426) {
  889. final error = StorageLimitExceededError();
  890. clearQueue(error);
  891. throw error;
  892. } else {
  893. _logger.severe("Could not fetch upload URLs", e, s);
  894. }
  895. }
  896. rethrow;
  897. } finally {
  898. _uploadURLFetchInProgress = null;
  899. }
  900. });
  901. return _uploadURLFetchInProgress;
  902. }
  903. void _onStorageLimitExceeded() {
  904. clearQueue(StorageLimitExceededError());
  905. throw StorageLimitExceededError();
  906. }
  907. Future<String> _putFile(
  908. UploadURL uploadURL,
  909. io.File file, {
  910. int? contentLength,
  911. int attempt = 1,
  912. }) async {
  913. final fileSize = contentLength ?? await file.length();
  914. _logger.info(
  915. "Putting object for " +
  916. file.toString() +
  917. " of size: " +
  918. fileSize.toString(),
  919. );
  920. final startTime = DateTime.now().millisecondsSinceEpoch;
  921. try {
  922. await _dio.put(
  923. uploadURL.url,
  924. data: file.openRead(),
  925. options: Options(
  926. headers: {
  927. Headers.contentLengthHeader: fileSize,
  928. },
  929. ),
  930. );
  931. _logger.info(
  932. "Upload speed : " +
  933. (fileSize / (DateTime.now().millisecondsSinceEpoch - startTime))
  934. .toString() +
  935. " kilo bytes per second",
  936. );
  937. return uploadURL.objectKey;
  938. } on DioError catch (e) {
  939. if (e.message.startsWith(
  940. "HttpException: Content size exceeds specified contentLength.",
  941. ) &&
  942. attempt == 1) {
  943. return _putFile(
  944. uploadURL,
  945. file,
  946. contentLength: (await file.readAsBytes()).length,
  947. attempt: 2,
  948. );
  949. } else if (attempt < kMaximumUploadAttempts) {
  950. final newUploadURL = await _getUploadURL();
  951. return _putFile(
  952. newUploadURL,
  953. file,
  954. contentLength: (await file.readAsBytes()).length,
  955. attempt: attempt + 1,
  956. );
  957. } else {
  958. _logger.info(
  959. "Upload failed for file with size " + fileSize.toString(),
  960. e,
  961. );
  962. rethrow;
  963. }
  964. }
  965. }
  966. Future<void> _pollBackgroundUploadStatus() async {
  967. final blockedUploads = _queue.entries
  968. .where((e) => e.value.status == UploadStatus.inBackground)
  969. .toList();
  970. for (final upload in blockedUploads) {
  971. final file = upload.value.file;
  972. final isStillLocked = await _uploadLocks.isLocked(
  973. file.localID,
  974. ProcessType.background.toString(),
  975. );
  976. if (!isStillLocked) {
  977. final completer = _queue.remove(upload.key).completer;
  978. final dbFile =
  979. await FilesDB.instance.getFile(upload.value.file.generatedID);
  980. if (dbFile?.uploadedFileID != null) {
  981. _logger.info("Background upload success detected");
  982. completer.complete(dbFile);
  983. } else {
  984. _logger.info("Background upload failure detected");
  985. completer.completeError(SilentlyCancelUploadsError());
  986. }
  987. }
  988. }
  989. Future.delayed(kBlockedUploadsPollFrequency, () async {
  990. await _pollBackgroundUploadStatus();
  991. });
  992. }
  993. }
  994. class FileUploadItem {
  995. final File file;
  996. final int collectionID;
  997. final Completer<File> completer;
  998. UploadStatus status;
  999. FileUploadItem(
  1000. this.file,
  1001. this.collectionID,
  1002. this.completer, {
  1003. this.status = UploadStatus.notStarted,
  1004. });
  1005. }
  1006. enum UploadStatus {
  1007. notStarted,
  1008. inProgress,
  1009. inBackground,
  1010. completed,
  1011. }
  1012. enum ProcessType {
  1013. background,
  1014. foreground,
  1015. }