file_uploader.dart 44 KB

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