file_uploader.dart 32 KB

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