file_uploader.dart 37 KB

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