file_uploader.dart 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. final fileNameToLastAttempt =
  312. await _uploadLocks.getFileNameToLastAttemptedAtMap();
  313. for (final file in filesToDelete) {
  314. final fileName = file.path.split('/').last;
  315. final lastAttemptTime = fileNameToLastAttempt[fileName] != null
  316. ? DateTime.fromMillisecondsSinceEpoch(
  317. fileNameToLastAttempt[fileName]!,
  318. )
  319. : null;
  320. if (lastAttemptTime == null ||
  321. DateTime.now().difference(lastAttemptTime).inDays > 1) {
  322. await file.delete();
  323. } else {
  324. _logger.info(
  325. 'Skipping file $fileName as it was attempted recently on $lastAttemptTime',
  326. );
  327. }
  328. }
  329. }
  330. if (Platform.isAndroid) {
  331. final sharedMediaDir =
  332. Configuration.instance.getSharedMediaDirectory() + "/";
  333. final sharedFiles = await Directory(sharedMediaDir).list().toList();
  334. if (sharedFiles.isNotEmpty) {
  335. _logger.info('Shared media directory cleanup ${sharedFiles.length}');
  336. final int ownerID = Configuration.instance.getUserID()!;
  337. final existingLocalFileIDs =
  338. await FilesDB.instance.getExistingLocalFileIDs(ownerID);
  339. final Set<String> trackedSharedFilePaths = {};
  340. for (String localID in existingLocalFileIDs) {
  341. if (localID.contains(sharedMediaIdentifier)) {
  342. trackedSharedFilePaths
  343. .add(getSharedMediaPathFromLocalID(localID));
  344. }
  345. }
  346. for (final file in sharedFiles) {
  347. if (!trackedSharedFilePaths.contains(file.path)) {
  348. _logger.info('Deleting stale shared media file ${file.path}');
  349. await file.delete();
  350. }
  351. }
  352. }
  353. }
  354. } catch (e, s) {
  355. _logger.severe("Failed to remove stale files", e, s);
  356. }
  357. }
  358. Future<void> checkNetworkForUpload({bool isForceUpload = false}) async {
  359. // Note: We don't support force uploading currently. During force upload,
  360. // network check is skipped completely
  361. if (isForceUpload) {
  362. return;
  363. }
  364. final List<ConnectivityResult> connections =
  365. await (Connectivity().checkConnectivity());
  366. bool canUploadUnderCurrentNetworkConditions = true;
  367. if (!Configuration.instance.shouldBackupOverMobileData()) {
  368. if (connections.any((element) => element == ConnectivityResult.mobile)) {
  369. canUploadUnderCurrentNetworkConditions = false;
  370. } else {
  371. _logger.info(
  372. "mobileBackupDisabled, backing up with connections: ${connections.map((e) => e.name).toString()}",
  373. );
  374. }
  375. }
  376. if (!canUploadUnderCurrentNetworkConditions) {
  377. throw WiFiUnavailableError();
  378. }
  379. }
  380. Future<void> verifyMediaLocationAccess() async {
  381. if (Platform.isAndroid) {
  382. final bool hasPermission = await Permission.accessMediaLocation.isGranted;
  383. if (!hasPermission) {
  384. final permissionStatus = await Permission.accessMediaLocation.request();
  385. if (!permissionStatus.isGranted) {
  386. _logger.severe(
  387. "Media location access denied with permission status: ${permissionStatus.name}",
  388. );
  389. throw NoMediaLocationAccessError();
  390. }
  391. }
  392. }
  393. }
  394. Future<EnteFile> forceUpload(EnteFile file, int collectionID) async {
  395. _hasInitiatedForceUpload = true;
  396. return _tryToUpload(file, collectionID, true);
  397. }
  398. Future<EnteFile> _tryToUpload(
  399. EnteFile file,
  400. int collectionID,
  401. bool forcedUpload,
  402. ) async {
  403. await checkNetworkForUpload(isForceUpload: forcedUpload);
  404. if (!forcedUpload) {
  405. final fileOnDisk = await FilesDB.instance.getFile(file.generatedID!);
  406. final wasAlreadyUploaded = fileOnDisk != null &&
  407. fileOnDisk.uploadedFileID != null &&
  408. (fileOnDisk.updationTime ?? -1) != -1 &&
  409. (fileOnDisk.collectionID ?? -1) == collectionID;
  410. if (wasAlreadyUploaded) {
  411. _logger.info("File is already uploaded ${fileOnDisk.tag}");
  412. return fileOnDisk;
  413. }
  414. }
  415. if ((file.localID ?? '') == '') {
  416. _logger.severe('Trying to upload file with missing localID');
  417. return file;
  418. }
  419. if (!CollectionsService.instance.allowUpload(collectionID)) {
  420. _logger.warning(
  421. 'Upload not allowed for collection $collectionID',
  422. );
  423. if (!file.isUploaded && file.generatedID != null) {
  424. _logger.info("Deleting file entry for " + file.toString());
  425. await FilesDB.instance.deleteByGeneratedID(file.generatedID!);
  426. }
  427. return file;
  428. }
  429. final String lockKey = file.localID!;
  430. bool _isMultipartUpload = false;
  431. try {
  432. await _uploadLocks.acquireLock(
  433. lockKey,
  434. _processType.toString(),
  435. DateTime.now().microsecondsSinceEpoch,
  436. );
  437. } catch (e) {
  438. _logger.warning("Lock was already taken for " + file.toString());
  439. throw LockAlreadyAcquiredError();
  440. }
  441. final tempDirectory = Configuration.instance.getTempDirectory();
  442. MediaUploadData? mediaUploadData;
  443. mediaUploadData = await getUploadDataFromEnteFile(file);
  444. final String? existingMultipartEncFileName =
  445. mediaUploadData.hashData?.fileHash != null
  446. ? await _uploadLocks.getEncryptedFileName(
  447. lockKey,
  448. mediaUploadData.hashData!.fileHash!,
  449. collectionID,
  450. )
  451. : null;
  452. bool multipartEntryExists = existingMultipartEncFileName != null;
  453. final String uniqueID = const Uuid().v4().toString();
  454. final encryptedFilePath = multipartEntryExists
  455. ? '$tempDirectory$existingMultipartEncFileName'
  456. : '$tempDirectory$uploadTempFilePrefix${uniqueID}_file.encrypted';
  457. final encryptedThumbnailPath =
  458. '$tempDirectory$uploadTempFilePrefix${uniqueID}_thumb.encrypted';
  459. var uploadCompleted = false;
  460. // This flag is used to decide whether to clear the iOS origin file cache
  461. // or not.
  462. var uploadHardFailure = false;
  463. try {
  464. final bool isUpdatedFile =
  465. file.uploadedFileID != null && file.updationTime == -1;
  466. _logger.info(
  467. 'starting ${forcedUpload ? 'forced' : ''} '
  468. '${isUpdatedFile ? 're-upload' : 'upload'} of ${file.toString()}',
  469. );
  470. Uint8List? key;
  471. EncryptionResult? multiPartFileEncResult = multipartEntryExists
  472. ? await _multiPartUploader.getEncryptionResult(
  473. lockKey,
  474. mediaUploadData.hashData!.fileHash!,
  475. collectionID,
  476. )
  477. : null;
  478. if (isUpdatedFile) {
  479. key = getFileKey(file);
  480. } else {
  481. key = multiPartFileEncResult?.key;
  482. // check if the file is already uploaded and can be mapped to existing
  483. // uploaded file. If map is found, it also returns the corresponding
  484. // mapped or update file entry.
  485. final result = await _mapToExistingUploadWithSameHash(
  486. mediaUploadData,
  487. file,
  488. collectionID,
  489. );
  490. final isMappedToExistingUpload = result.item1;
  491. if (isMappedToExistingUpload) {
  492. debugPrint(
  493. "File success mapped to existing uploaded ${file.toString()}",
  494. );
  495. // return the mapped file
  496. return result.item2;
  497. }
  498. }
  499. final encryptedFileExists = File(encryptedFilePath).existsSync();
  500. // If the multipart entry exists but the encrypted file doesn't, it means
  501. // that we'll have to reupload as the nonce is lost
  502. if (multipartEntryExists) {
  503. final bool updateWithDiffKey = isUpdatedFile &&
  504. multiPartFileEncResult != null &&
  505. !listEquals(key, multiPartFileEncResult.key);
  506. if (!encryptedFileExists || updateWithDiffKey) {
  507. if (updateWithDiffKey) {
  508. _logger.severe('multiPart update resumed with differentKey');
  509. } else {
  510. _logger.warning(
  511. 'multiPart EncryptedFile missing, discard multipart entry',
  512. );
  513. }
  514. await _uploadLocks.deleteMultipartTrack(lockKey);
  515. multipartEntryExists = false;
  516. multiPartFileEncResult = null;
  517. }
  518. } else if (encryptedFileExists) {
  519. // otherwise just delete the file for singlepart upload
  520. await File(encryptedFilePath).delete();
  521. }
  522. await _checkIfWithinStorageLimit(mediaUploadData.sourceFile!);
  523. final encryptedFile = File(encryptedFilePath);
  524. final EncryptionResult fileAttributes = multiPartFileEncResult ??
  525. await CryptoUtil.encryptFile(
  526. mediaUploadData.sourceFile!.path,
  527. encryptedFilePath,
  528. key: key,
  529. );
  530. late final Uint8List? thumbnailData;
  531. if (mediaUploadData.thumbnail == null &&
  532. file.fileType == FileType.video) {
  533. thumbnailData = base64Decode(blackThumbnailBase64);
  534. } else {
  535. thumbnailData = mediaUploadData.thumbnail;
  536. }
  537. final EncryptionResult encryptedThumbnailData =
  538. await CryptoUtil.encryptChaCha(
  539. thumbnailData!,
  540. fileAttributes.key!,
  541. );
  542. if (File(encryptedThumbnailPath).existsSync()) {
  543. await File(encryptedThumbnailPath).delete();
  544. }
  545. final encryptedThumbnailFile = File(encryptedThumbnailPath);
  546. await encryptedThumbnailFile
  547. .writeAsBytes(encryptedThumbnailData.encryptedData!);
  548. // Calculate the number of parts for the file.
  549. final count = await _multiPartUploader.calculatePartCount(
  550. await encryptedFile.length(),
  551. );
  552. late String fileObjectKey;
  553. late String thumbnailObjectKey;
  554. if (count <= 1) {
  555. final thumbnailUploadURL = await _getUploadURL();
  556. thumbnailObjectKey =
  557. await _putFile(thumbnailUploadURL, encryptedThumbnailFile);
  558. final fileUploadURL = await _getUploadURL();
  559. fileObjectKey = await _putFile(fileUploadURL, encryptedFile);
  560. } else {
  561. _isMultipartUpload = true;
  562. _logger.finest(
  563. "Init multipartUpload $multipartEntryExists, isUpdate $isUpdatedFile",
  564. );
  565. if (multipartEntryExists) {
  566. fileObjectKey = await _multiPartUploader.putExistingMultipartFile(
  567. encryptedFile,
  568. lockKey,
  569. mediaUploadData.hashData!.fileHash!,
  570. collectionID,
  571. );
  572. } else {
  573. final fileUploadURLs =
  574. await _multiPartUploader.getMultipartUploadURLs(count);
  575. final encFileName = encryptedFile.path.split('/').last;
  576. await _multiPartUploader.createTableEntry(
  577. lockKey,
  578. mediaUploadData.hashData!.fileHash!,
  579. collectionID,
  580. fileUploadURLs,
  581. encFileName,
  582. await encryptedFile.length(),
  583. fileAttributes.key!,
  584. fileAttributes.header!,
  585. );
  586. fileObjectKey = await _multiPartUploader.putMultipartFile(
  587. fileUploadURLs,
  588. encryptedFile,
  589. );
  590. }
  591. // in case of multipart, upload the thumbnail towards the end to avoid
  592. // re-uploading the thumbnail in case of failure.
  593. // In regular upload, always upload the thumbnail first to keep existing behaviour
  594. //
  595. final thumbnailUploadURL = await _getUploadURL();
  596. thumbnailObjectKey =
  597. await _putFile(thumbnailUploadURL, encryptedThumbnailFile);
  598. }
  599. final metadata = await file.getMetadataForUpload(mediaUploadData);
  600. final encryptedMetadataResult = await CryptoUtil.encryptChaCha(
  601. utf8.encode(jsonEncode(metadata)),
  602. fileAttributes.key!,
  603. );
  604. final fileDecryptionHeader =
  605. CryptoUtil.bin2base64(fileAttributes.header!);
  606. final thumbnailDecryptionHeader =
  607. CryptoUtil.bin2base64(encryptedThumbnailData.header!);
  608. final encryptedMetadata = CryptoUtil.bin2base64(
  609. encryptedMetadataResult.encryptedData!,
  610. );
  611. final metadataDecryptionHeader =
  612. CryptoUtil.bin2base64(encryptedMetadataResult.header!);
  613. if (SyncService.instance.shouldStopSync()) {
  614. throw SyncStopRequestedError();
  615. }
  616. EnteFile remoteFile;
  617. if (isUpdatedFile) {
  618. remoteFile = await _updateFile(
  619. file,
  620. fileObjectKey,
  621. fileDecryptionHeader,
  622. await encryptedFile.length(),
  623. thumbnailObjectKey,
  624. thumbnailDecryptionHeader,
  625. await encryptedThumbnailFile.length(),
  626. encryptedMetadata,
  627. metadataDecryptionHeader,
  628. );
  629. // Update across all collections
  630. await FilesDB.instance.updateUploadedFileAcrossCollections(remoteFile);
  631. } else {
  632. final encryptedFileKeyData = CryptoUtil.encryptSync(
  633. fileAttributes.key!,
  634. CollectionsService.instance.getCollectionKey(collectionID),
  635. );
  636. final encryptedKey =
  637. CryptoUtil.bin2base64(encryptedFileKeyData.encryptedData!);
  638. final keyDecryptionNonce =
  639. CryptoUtil.bin2base64(encryptedFileKeyData.nonce!);
  640. final Map<String, dynamic> pubMetadata = {};
  641. MetadataRequest? pubMetadataRequest;
  642. if ((mediaUploadData.height ?? 0) != 0 &&
  643. (mediaUploadData.width ?? 0) != 0) {
  644. pubMetadata[heightKey] = mediaUploadData.height;
  645. pubMetadata[widthKey] = mediaUploadData.width;
  646. }
  647. if (mediaUploadData.motionPhotoStartIndex != null) {
  648. pubMetadata[motionVideoIndexKey] =
  649. mediaUploadData.motionPhotoStartIndex;
  650. }
  651. if (mediaUploadData.thumbnail == null) {
  652. pubMetadata[noThumbKey] = true;
  653. }
  654. if (pubMetadata.isNotEmpty) {
  655. pubMetadataRequest = await getPubMetadataRequest(
  656. file,
  657. pubMetadata,
  658. fileAttributes.key!,
  659. );
  660. }
  661. remoteFile = await _uploadFile(
  662. file,
  663. collectionID,
  664. encryptedKey,
  665. keyDecryptionNonce,
  666. fileAttributes,
  667. fileObjectKey,
  668. fileDecryptionHeader,
  669. await encryptedFile.length(),
  670. thumbnailObjectKey,
  671. thumbnailDecryptionHeader,
  672. await encryptedThumbnailFile.length(),
  673. encryptedMetadata,
  674. metadataDecryptionHeader,
  675. pubMetadata: pubMetadataRequest,
  676. );
  677. if (mediaUploadData.isDeleted) {
  678. _logger.info("File found to be deleted");
  679. remoteFile.localID = null;
  680. }
  681. await FilesDB.instance.update(remoteFile);
  682. }
  683. await UploadLocksDB.instance.deleteMultipartTrack(lockKey);
  684. if (!_isBackground) {
  685. Bus.instance.fire(
  686. LocalPhotosUpdatedEvent(
  687. [remoteFile],
  688. source: "downloadComplete",
  689. ),
  690. );
  691. }
  692. _logger.info("File upload complete for " + remoteFile.toString());
  693. uploadCompleted = true;
  694. Bus.instance.fire(FileUploadedEvent(remoteFile));
  695. return remoteFile;
  696. } catch (e, s) {
  697. if (!(e is NoActiveSubscriptionError ||
  698. e is StorageLimitExceededError ||
  699. e is WiFiUnavailableError ||
  700. e is SilentlyCancelUploadsError ||
  701. e is InvalidFileError ||
  702. e is FileTooLargeForPlanError)) {
  703. _logger.severe("File upload failed for " + file.toString(), e, s);
  704. }
  705. if (e is InvalidFileError) {
  706. _logger.severe("File upload ignored for " + file.toString(), e);
  707. await _onInvalidFileError(file, e);
  708. }
  709. if ((e is StorageLimitExceededError ||
  710. e is FileTooLargeForPlanError ||
  711. e is NoActiveSubscriptionError)) {
  712. // file upload can be be retried in such cases without user intervention
  713. uploadHardFailure = false;
  714. }
  715. rethrow;
  716. } finally {
  717. await _onUploadDone(
  718. mediaUploadData,
  719. uploadCompleted,
  720. uploadHardFailure,
  721. file,
  722. encryptedFilePath,
  723. encryptedThumbnailPath,
  724. lockKey: lockKey,
  725. isMultiPartUpload: _isMultipartUpload,
  726. );
  727. }
  728. }
  729. /*
  730. _mapToExistingUpload links the fileToUpload with the existing uploaded
  731. files. if the link is successful, it returns true otherwise false.
  732. When false, we should go ahead and re-upload or update the file.
  733. It performs following checks:
  734. a) Uploaded file with same localID and destination collection. Delete the
  735. fileToUpload entry
  736. b) Uploaded file in any collection but with missing localID.
  737. Update the localID for uploadedFile and delete the fileToUpload entry
  738. c) A uploaded file exist with same localID but in a different collection.
  739. Add a symlink in the destination collection and update the fileToUpload
  740. d) File already exists but different localID. Re-upload
  741. In case the existing files already have local identifier, which is
  742. different from the {fileToUpload}, then most probably device has
  743. duplicate files.
  744. */
  745. Future<Tuple2<bool, EnteFile>> _mapToExistingUploadWithSameHash(
  746. MediaUploadData mediaUploadData,
  747. EnteFile fileToUpload,
  748. int toCollectionID,
  749. ) async {
  750. if (fileToUpload.uploadedFileID != null) {
  751. // ideally this should never happen, but because the code below this case
  752. // can do unexpected mapping, we are adding this additional check
  753. _logger.severe(
  754. 'Critical: file is already uploaded, skipped mapping',
  755. );
  756. return Tuple2(false, fileToUpload);
  757. }
  758. final List<EnteFile> existingUploadedFiles =
  759. await FilesDB.instance.getUploadedFilesWithHashes(
  760. mediaUploadData.hashData!,
  761. fileToUpload.fileType,
  762. Configuration.instance.getUserID()!,
  763. );
  764. if (existingUploadedFiles.isEmpty) {
  765. // continueUploading this file
  766. return Tuple2(false, fileToUpload);
  767. }
  768. // case a
  769. final EnteFile? sameLocalSameCollection =
  770. existingUploadedFiles.firstWhereOrNull(
  771. (e) =>
  772. e.collectionID == toCollectionID && e.localID == fileToUpload.localID,
  773. );
  774. if (sameLocalSameCollection != null) {
  775. _logger.fine(
  776. "sameLocalSameCollection: \n toUpload ${fileToUpload.tag} "
  777. "\n existing: ${sameLocalSameCollection.tag}",
  778. );
  779. // should delete the fileToUploadEntry
  780. if (fileToUpload.generatedID != null) {
  781. await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);
  782. }
  783. Bus.instance.fire(
  784. LocalPhotosUpdatedEvent(
  785. [fileToUpload],
  786. type: EventType.deletedFromEverywhere,
  787. source: "sameLocalSameCollection", //
  788. ),
  789. );
  790. return Tuple2(true, sameLocalSameCollection);
  791. }
  792. // case b
  793. final EnteFile? fileMissingLocal = existingUploadedFiles.firstWhereOrNull(
  794. (e) => e.localID == null,
  795. );
  796. if (fileMissingLocal != null) {
  797. // update the local id of the existing file and delete the fileToUpload
  798. // entry
  799. _logger.fine(
  800. "fileMissingLocal: \n toUpload ${fileToUpload.tag} "
  801. "\n existing: ${fileMissingLocal.tag}",
  802. );
  803. fileMissingLocal.localID = fileToUpload.localID;
  804. // set localID for the given uploadedID across collections
  805. await FilesDB.instance.updateLocalIDForUploaded(
  806. fileMissingLocal.uploadedFileID!,
  807. fileToUpload.localID!,
  808. );
  809. // For files selected from device, during collaborative upload, we don't
  810. // insert entries in the FilesDB. So, we don't need to delete the entry
  811. if (fileToUpload.generatedID != null) {
  812. await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);
  813. }
  814. Bus.instance.fire(
  815. LocalPhotosUpdatedEvent(
  816. [fileToUpload],
  817. source: "fileMissingLocal",
  818. type: EventType.deletedFromEverywhere, //
  819. ),
  820. );
  821. return Tuple2(true, fileMissingLocal);
  822. }
  823. // case c
  824. final EnteFile? fileExistsButDifferentCollection =
  825. existingUploadedFiles.firstWhereOrNull(
  826. (e) =>
  827. e.collectionID != toCollectionID && e.localID == fileToUpload.localID,
  828. );
  829. if (fileExistsButDifferentCollection != null) {
  830. _logger.fine(
  831. "fileExistsButDifferentCollection: \n toUpload ${fileToUpload.tag} "
  832. "\n existing: ${fileExistsButDifferentCollection.tag}",
  833. );
  834. final linkedFile = await CollectionsService.instance
  835. .linkLocalFileToExistingUploadedFileInAnotherCollection(
  836. toCollectionID,
  837. localFileToUpload: fileToUpload,
  838. existingUploadedFile: fileExistsButDifferentCollection,
  839. );
  840. return Tuple2(true, linkedFile);
  841. }
  842. final Set<String> matchLocalIDs = existingUploadedFiles
  843. .where(
  844. (e) => e.localID != null,
  845. )
  846. .map((e) => e.localID!)
  847. .toSet();
  848. _logger.fine(
  849. "Found hashMatch but probably with diff localIDs "
  850. "$matchLocalIDs",
  851. );
  852. // case d
  853. return Tuple2(false, fileToUpload);
  854. }
  855. Future<void> _onUploadDone(
  856. MediaUploadData? mediaUploadData,
  857. bool uploadCompleted,
  858. bool uploadHardFailure,
  859. EnteFile file,
  860. String encryptedFilePath,
  861. String encryptedThumbnailPath, {
  862. required String lockKey,
  863. bool isMultiPartUpload = false,
  864. }) async {
  865. if (mediaUploadData != null && mediaUploadData.sourceFile != null) {
  866. // delete the file from app's internal cache if it was copied to app
  867. // for upload. On iOS, only remove the file from photo_manager/app cache
  868. // when upload is either completed or there's a tempFailure
  869. // Shared Media should only be cleared when the upload
  870. // succeeds.
  871. if ((Platform.isIOS && (uploadCompleted || uploadHardFailure)) ||
  872. (uploadCompleted && file.isSharedMediaToAppSandbox)) {
  873. await mediaUploadData.sourceFile?.delete();
  874. }
  875. }
  876. if (File(encryptedFilePath).existsSync()) {
  877. if (isMultiPartUpload && !uploadCompleted) {
  878. _logger.fine(
  879. "skip delete for multipart encrypted file $encryptedFilePath",
  880. );
  881. } else {
  882. _logger.fine("deleting encrypted file $encryptedFilePath");
  883. await File(encryptedFilePath).delete();
  884. }
  885. }
  886. if (File(encryptedThumbnailPath).existsSync()) {
  887. await File(encryptedThumbnailPath).delete();
  888. }
  889. await _uploadLocks.releaseLock(lockKey, _processType.toString());
  890. }
  891. /*
  892. _checkIfWithinStorageLimit verifies if the file size for encryption and upload
  893. is within the storage limit. It throws StorageLimitExceededError if the limit
  894. is exceeded. This check is best effort and may not be completely accurate
  895. due to UserDetail cache. It prevents infinite loops when clients attempt to
  896. upload files that exceed the server's storage limit + buffer.
  897. Note: Local storageBuffer is 20MB, server storageBuffer is 50MB, and an
  898. additional 30MB is reserved for thumbnails and encryption overhead.
  899. */
  900. Future<void> _checkIfWithinStorageLimit(File fileToBeUploaded) async {
  901. try {
  902. final UserDetails? userDetails =
  903. UserService.instance.getCachedUserDetails();
  904. if (userDetails == null) {
  905. return;
  906. }
  907. // add k20MBStorageBuffer to the free storage
  908. final num freeStorage = userDetails.getFreeStorage() + k20MBStorageBuffer;
  909. final num fileSize = await fileToBeUploaded.length();
  910. if (fileSize > freeStorage) {
  911. _logger.warning('Storage limit exceeded fileSize $fileSize and '
  912. 'freeStorage $freeStorage');
  913. throw StorageLimitExceededError();
  914. }
  915. if (fileSize > kMaxFileSize5Gib) {
  916. _logger.warning('File size exceeds 5GiB fileSize $fileSize');
  917. throw InvalidFileError(
  918. 'file size above 5GiB',
  919. InvalidReason.tooLargeFile,
  920. );
  921. }
  922. } catch (e) {
  923. if (e is StorageLimitExceededError || e is InvalidFileError) {
  924. rethrow;
  925. } else {
  926. _logger.severe('Error checking storage limit', e);
  927. }
  928. }
  929. }
  930. Future _onInvalidFileError(EnteFile file, InvalidFileError e) async {
  931. try {
  932. final bool canIgnoreFile = file.localID != null &&
  933. file.deviceFolder != null &&
  934. file.title != null &&
  935. !file.isSharedMediaToAppSandbox;
  936. // If the file is not uploaded yet and either it can not be ignored or the
  937. // err is related to live photo media, delete the local entry
  938. final bool deleteEntry =
  939. !file.isUploaded && (!canIgnoreFile || e.reason.isLivePhotoErr);
  940. if (e.reason != InvalidReason.thumbnailMissing || !canIgnoreFile) {
  941. _logger.severe(
  942. "Invalid file, localDelete: $deleteEntry, ignored: $canIgnoreFile",
  943. e,
  944. );
  945. }
  946. if (deleteEntry) {
  947. await FilesDB.instance.deleteLocalFile(file);
  948. }
  949. if (canIgnoreFile) {
  950. await LocalSyncService.instance.ignoreUpload(file, e);
  951. }
  952. } catch (e, s) {
  953. _logger.severe("Failed to handle invalid file error", e, s);
  954. }
  955. }
  956. Future<EnteFile> _uploadFile(
  957. EnteFile file,
  958. int collectionID,
  959. String encryptedKey,
  960. String keyDecryptionNonce,
  961. EncryptionResult fileAttributes,
  962. String fileObjectKey,
  963. String fileDecryptionHeader,
  964. int fileSize,
  965. String thumbnailObjectKey,
  966. String thumbnailDecryptionHeader,
  967. int thumbnailSize,
  968. String encryptedMetadata,
  969. String metadataDecryptionHeader, {
  970. MetadataRequest? pubMetadata,
  971. int attempt = 1,
  972. }) async {
  973. final request = {
  974. "collectionID": collectionID,
  975. "encryptedKey": encryptedKey,
  976. "keyDecryptionNonce": keyDecryptionNonce,
  977. "file": {
  978. "objectKey": fileObjectKey,
  979. "decryptionHeader": fileDecryptionHeader,
  980. "size": fileSize,
  981. },
  982. "thumbnail": {
  983. "objectKey": thumbnailObjectKey,
  984. "decryptionHeader": thumbnailDecryptionHeader,
  985. "size": thumbnailSize,
  986. },
  987. "metadata": {
  988. "encryptedData": encryptedMetadata,
  989. "decryptionHeader": metadataDecryptionHeader,
  990. },
  991. };
  992. if (pubMetadata != null) {
  993. request["pubMagicMetadata"] = pubMetadata;
  994. }
  995. try {
  996. final response = await _enteDio.post("/files", data: request);
  997. final data = response.data;
  998. file.uploadedFileID = data["id"];
  999. file.collectionID = collectionID;
  1000. file.updationTime = data["updationTime"];
  1001. file.ownerID = data["ownerID"];
  1002. file.encryptedKey = encryptedKey;
  1003. file.keyDecryptionNonce = keyDecryptionNonce;
  1004. file.fileDecryptionHeader = fileDecryptionHeader;
  1005. file.thumbnailDecryptionHeader = thumbnailDecryptionHeader;
  1006. file.metadataDecryptionHeader = metadataDecryptionHeader;
  1007. return file;
  1008. } on DioError catch (e) {
  1009. if (e.response?.statusCode == 413) {
  1010. throw FileTooLargeForPlanError();
  1011. } else if (e.response?.statusCode == 426) {
  1012. _onStorageLimitExceeded();
  1013. } else if (attempt < kMaximumUploadAttempts) {
  1014. _logger.info("Upload file failed, will retry in 3 seconds");
  1015. await Future.delayed(const Duration(seconds: 3));
  1016. return _uploadFile(
  1017. file,
  1018. collectionID,
  1019. encryptedKey,
  1020. keyDecryptionNonce,
  1021. fileAttributes,
  1022. fileObjectKey,
  1023. fileDecryptionHeader,
  1024. fileSize,
  1025. thumbnailObjectKey,
  1026. thumbnailDecryptionHeader,
  1027. thumbnailSize,
  1028. encryptedMetadata,
  1029. metadataDecryptionHeader,
  1030. attempt: attempt + 1,
  1031. pubMetadata: pubMetadata,
  1032. );
  1033. }
  1034. rethrow;
  1035. }
  1036. }
  1037. Future<EnteFile> _updateFile(
  1038. EnteFile file,
  1039. String fileObjectKey,
  1040. String fileDecryptionHeader,
  1041. int fileSize,
  1042. String thumbnailObjectKey,
  1043. String thumbnailDecryptionHeader,
  1044. int thumbnailSize,
  1045. String encryptedMetadata,
  1046. String metadataDecryptionHeader, {
  1047. int attempt = 1,
  1048. }) async {
  1049. final request = {
  1050. "id": file.uploadedFileID,
  1051. "file": {
  1052. "objectKey": fileObjectKey,
  1053. "decryptionHeader": fileDecryptionHeader,
  1054. "size": fileSize,
  1055. },
  1056. "thumbnail": {
  1057. "objectKey": thumbnailObjectKey,
  1058. "decryptionHeader": thumbnailDecryptionHeader,
  1059. "size": thumbnailSize,
  1060. },
  1061. "metadata": {
  1062. "encryptedData": encryptedMetadata,
  1063. "decryptionHeader": metadataDecryptionHeader,
  1064. },
  1065. };
  1066. try {
  1067. final response = await _enteDio.put("/files/update", data: request);
  1068. final data = response.data;
  1069. file.uploadedFileID = data["id"];
  1070. file.updationTime = data["updationTime"];
  1071. file.fileDecryptionHeader = fileDecryptionHeader;
  1072. file.thumbnailDecryptionHeader = thumbnailDecryptionHeader;
  1073. file.metadataDecryptionHeader = metadataDecryptionHeader;
  1074. return file;
  1075. } on DioError catch (e) {
  1076. if (e.response?.statusCode == 426) {
  1077. _onStorageLimitExceeded();
  1078. } else if (attempt < kMaximumUploadAttempts) {
  1079. _logger.info("Update file failed, will retry in 3 seconds");
  1080. await Future.delayed(const Duration(seconds: 3));
  1081. return _updateFile(
  1082. file,
  1083. fileObjectKey,
  1084. fileDecryptionHeader,
  1085. fileSize,
  1086. thumbnailObjectKey,
  1087. thumbnailDecryptionHeader,
  1088. thumbnailSize,
  1089. encryptedMetadata,
  1090. metadataDecryptionHeader,
  1091. attempt: attempt + 1,
  1092. );
  1093. }
  1094. rethrow;
  1095. }
  1096. }
  1097. Future<UploadURL> _getUploadURL() async {
  1098. if (_uploadURLs.isEmpty) {
  1099. // the queue is empty, fetch at least for one file to handle force uploads
  1100. // that are not in the queue. This is to also avoid
  1101. await fetchUploadURLs(math.max(_queue.length, 1));
  1102. }
  1103. try {
  1104. return _uploadURLs.removeFirst();
  1105. } catch (e) {
  1106. if (e is StateError && e.message == 'No element' && _queue.isEmpty) {
  1107. _logger.warning("Oops, uploadUrls has no element now, fetching again");
  1108. return _getUploadURL();
  1109. } else {
  1110. rethrow;
  1111. }
  1112. }
  1113. }
  1114. Future<void>? _uploadURLFetchInProgress;
  1115. Future<void> fetchUploadURLs(int fileCount) async {
  1116. _uploadURLFetchInProgress ??= Future<void>(() async {
  1117. try {
  1118. final response = await _enteDio.get(
  1119. "/files/upload-urls",
  1120. queryParameters: {
  1121. "count": math.min(42, fileCount * 2), // m4gic number
  1122. },
  1123. );
  1124. final urls = (response.data["urls"] as List)
  1125. .map((e) => UploadURL.fromMap(e))
  1126. .toList();
  1127. _uploadURLs.addAll(urls);
  1128. } on DioError catch (e, s) {
  1129. if (e.response != null) {
  1130. if (e.response!.statusCode == 402) {
  1131. final error = NoActiveSubscriptionError();
  1132. clearQueue(error);
  1133. throw error;
  1134. } else if (e.response!.statusCode == 426) {
  1135. final error = StorageLimitExceededError();
  1136. clearQueue(error);
  1137. throw error;
  1138. } else {
  1139. _logger.severe("Could not fetch upload URLs", e, s);
  1140. }
  1141. }
  1142. rethrow;
  1143. } finally {
  1144. _uploadURLFetchInProgress = null;
  1145. }
  1146. });
  1147. return _uploadURLFetchInProgress;
  1148. }
  1149. void _onStorageLimitExceeded() {
  1150. clearQueue(StorageLimitExceededError());
  1151. throw StorageLimitExceededError();
  1152. }
  1153. Future<String> _putFile(
  1154. UploadURL uploadURL,
  1155. File file, {
  1156. int? contentLength,
  1157. int attempt = 1,
  1158. }) async {
  1159. final fileSize = contentLength ?? await file.length();
  1160. _logger.info(
  1161. "Putting object for " +
  1162. file.toString() +
  1163. " of size: " +
  1164. fileSize.toString(),
  1165. );
  1166. final startTime = DateTime.now().millisecondsSinceEpoch;
  1167. try {
  1168. await _dio.put(
  1169. uploadURL.url,
  1170. data: file.openRead(),
  1171. options: Options(
  1172. headers: {
  1173. Headers.contentLengthHeader: fileSize,
  1174. },
  1175. ),
  1176. );
  1177. _logger.info(
  1178. "Upload speed : " +
  1179. (fileSize / (DateTime.now().millisecondsSinceEpoch - startTime))
  1180. .toString() +
  1181. " kilo bytes per second",
  1182. );
  1183. return uploadURL.objectKey;
  1184. } on DioError catch (e) {
  1185. if (e.message.startsWith(
  1186. "HttpException: Content size exceeds specified contentLength.",
  1187. ) &&
  1188. attempt == 1) {
  1189. return _putFile(
  1190. uploadURL,
  1191. file,
  1192. contentLength: (await file.readAsBytes()).length,
  1193. attempt: 2,
  1194. );
  1195. } else if (attempt < kMaximumUploadAttempts) {
  1196. final newUploadURL = await _getUploadURL();
  1197. return _putFile(
  1198. newUploadURL,
  1199. file,
  1200. contentLength: (await file.readAsBytes()).length,
  1201. attempt: attempt + 1,
  1202. );
  1203. } else {
  1204. _logger.info(
  1205. "Upload failed for file with size " + fileSize.toString(),
  1206. e,
  1207. );
  1208. rethrow;
  1209. }
  1210. }
  1211. }
  1212. Future<void> _pollBackgroundUploadStatus() async {
  1213. final blockedUploads = _queue.entries
  1214. .where((e) => e.value.status == UploadStatus.inBackground)
  1215. .toList();
  1216. for (final upload in blockedUploads) {
  1217. final file = upload.value.file;
  1218. final isStillLocked = await _uploadLocks.isLocked(
  1219. file.localID!,
  1220. ProcessType.background.toString(),
  1221. );
  1222. if (!isStillLocked) {
  1223. final completer = _queue.remove(upload.key)?.completer;
  1224. final dbFile =
  1225. await FilesDB.instance.getFile(upload.value.file.generatedID!);
  1226. if (dbFile?.uploadedFileID != null) {
  1227. _logger.info("Background upload success detected");
  1228. completer?.complete(dbFile);
  1229. } else {
  1230. _logger.info("Background upload failure detected");
  1231. completer?.completeError(SilentlyCancelUploadsError());
  1232. }
  1233. }
  1234. }
  1235. Future.delayed(kBlockedUploadsPollFrequency, () async {
  1236. await _pollBackgroundUploadStatus();
  1237. });
  1238. }
  1239. }
  1240. class FileUploadItem {
  1241. final EnteFile file;
  1242. final int collectionID;
  1243. final Completer<EnteFile> completer;
  1244. UploadStatus status;
  1245. FileUploadItem(
  1246. this.file,
  1247. this.collectionID,
  1248. this.completer, {
  1249. this.status = UploadStatus.notStarted,
  1250. });
  1251. }
  1252. enum UploadStatus {
  1253. notStarted,
  1254. inProgress,
  1255. inBackground,
  1256. completed,
  1257. }
  1258. enum ProcessType {
  1259. background,
  1260. foreground,
  1261. }