π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
restrict debug logging to internal users only
Prateek Sunal683ac9e442bb
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dartindex 69068352ac..d315365164 100644--- a/mobile/apps/photos/lib/main.dart+++ b/mobile/apps/photos/lib/main.dart@@ -177,54 +177,76 @@ Future<void> _runMinimally(String taskId, TimeLogger tlog) async {// Begin Execution// only runs for android- _logger.info("[BG TASK] update notification");+ if (flagService.internalUser) {+ _logger.info("[BG TASK] update notification");+ }updateService.showUpdateNotification().ignore();// Wrap _sync() with timeout and error handling to prevent indefinite hanging// and allow background tasks to complete even if sync failstry {- _logger.info("[BG TASK] sync starting with 5-minute timeout");+ if (flagService.internalUser) {+ _logger.info("[BG TASK] sync starting with 5-minute timeout");+ }await _sync('bgTaskActiveProcess').timeout(const Duration(minutes: 5),onTimeout: () {- _logger.severe(- "[BG TASK] Sync timed out after 5 minutes! "- "Continuing with home widget and smart albums sync.",- );+ if (flagService.internalUser) {+ _logger.severe(+ "[BG TASK] Sync timed out after 5 minutes! "+ "Continuing with home widget and smart albums sync.",+ );+ }throw TimeoutException('Background sync exceeded 5-minute timeout',const Duration(minutes: 5),);},);- _logger.info("[BG TASK] sync completed successfully");+ if (flagService.internalUser) {+ _logger.info("[BG TASK] sync completed successfully");+ }} on TimeoutException catch (e) {- _logger.severe("[BG TASK] Sync timeout caught, continuing...", e);+ if (flagService.internalUser) {+ _logger.severe("[BG TASK] Sync timeout caught, continuing...", e);+ }} catch (e, s) {- _logger.severe(- "[BG TASK] Sync failed with error. "- "Continuing with home widget and smart albums sync.",- e,- s,- );+ if (flagService.internalUser) {+ _logger.severe(+ "[BG TASK] Sync failed with error. "+ "Continuing with home widget and smart albums sync.",+ e,+ s,+ );+ }}- _logger.info("[BG TASK] locale fetch");+ if (flagService.internalUser) {+ _logger.info("[BG TASK] locale fetch");+ }final locale = await getLocale();await initializeDateFormatting(locale?.languageCode ?? "en");// only runs for android- _logger.info("[BG TASK] home widget sync");+ if (flagService.internalUser) {+ _logger.info("[BG TASK] home widget sync");+ }await _homeWidgetSync(true);// await MLService.instance.init();// await PersonService.init(entityService, MLDataDB.instance, prefs);// await MLService.instance.runAllML(force: true);- _logger.info("[BG TASK] smart albums sync");+ if (flagService.internalUser) {+ _logger.info("[BG TASK] smart albums sync");+ }await smartAlbumsService.syncSmartAlbums();- _logger.info("[BG TASK] $taskId completed");+ if (flagService.internalUser) {+ _logger.info("[BG TASK] $taskId completed");+ }} catch (e, s) {- _logger.severe("[BG TASK] $taskId error", e, s);+ if (flagService.internalUser) {+ _logger.severe("[BG TASK] $taskId error", e, s);+ }}}diff --git a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart b/mobile/apps/photos/lib/services/sync/remote_sync_service.dartindex 1580a8dd64..73744f9454 100644--- a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart+++ b/mobile/apps/photos/lib/services/sync/remote_sync_service.dart@@ -604,168 +604,221 @@ class RemoteSyncService {bool preUploadChecksPassed = false;if (toBeUploaded > 0) {- _logger.info(- "[UPLOAD-DEBUG] Preparing to upload $toBeUploaded files "- "(${filesToBeUploaded.length} new, ${updatedFileIDs.length} updated) "- "in ${isProcessBg ? 'BACKGROUND' : 'FOREGROUND'} mode",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Preparing to upload $toBeUploaded files "+ "(${filesToBeUploaded.length} new, ${updatedFileIDs.length} updated) "+ "in ${isProcessBg ? 'BACKGROUND' : 'FOREGROUND'} mode",+ );+ }// Add random delay to detect if OS is killing background tasksfinal randomDelaySeconds = 3 + Random().nextInt(6); // 3-8 seconds- _logger.info(- "[UPLOAD-DEBUG] Adding random delay of $randomDelaySeconds seconds "- "before preparingForUpload to detect potential OS kills...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Adding random delay of $randomDelaySeconds seconds "+ "before preparingForUpload to detect potential OS kills...",+ );+ }final delayStartTime = DateTime.now();await Future.delayed(Duration(seconds: randomDelaySeconds));final delayEndTime = DateTime.now();final actualDelayMs =delayEndTime.difference(delayStartTime).inMilliseconds;- _logger.info(- "[UPLOAD-DEBUG] Random delay completed successfully! "- "Expected: ${randomDelaySeconds}s, Actual: ${actualDelayMs}ms. "- "Task was NOT killed by OS during delay.",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Random delay completed successfully! "+ "Expected: ${randomDelaySeconds}s, Actual: ${actualDelayMs}ms. "+ "Task was NOT killed by OS during delay.",+ );+ }Bus.instance.fire(SyncStatusUpdate(SyncStatus.preparingForUpload, total: toBeUploaded),);- _logger.info("[UPLOAD-DEBUG] Fired preparingForUpload status update");+ if (flagService.internalUser) {+ _logger.info("[UPLOAD-DEBUG] Fired preparingForUpload status update");+ }// Wrap all pre-upload checks in try-catch to handle failures gracefully// This allows sync to complete and background tasks to continue to home widget/smart albumstry {// Step 1: Verify media location access permission- _logger.info(- "[UPLOAD-DEBUG] Step 1/3: Checking media location access permission...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Step 1/3: Checking media location access permission...",+ );+ }await _uploader.verifyMediaLocationAccess();- _logger- .info("[UPLOAD-DEBUG] Step 1/3: Media location access verified β");+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Step 1/3: Media location access verified β",+ );+ }// Step 2: Check network availability for upload- _logger.info(- "[UPLOAD-DEBUG] Step 2/3: Checking network availability for upload...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Step 2/3: Checking network availability for upload...",+ );+ }await _uploader.checkNetworkForUpload();- _logger.info("[UPLOAD-DEBUG] Step 2/3: Network check passed β");+ if (flagService.internalUser) {+ _logger.info("[UPLOAD-DEBUG] Step 2/3: Network check passed β");+ }// Step 3: Fetch upload URLs from server- _logger.info(- "[UPLOAD-DEBUG] Step 3/3: Fetching upload URLs from server for $toBeUploaded files...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Step 3/3: Fetching upload URLs from server for $toBeUploaded files...",+ );+ }await _uploader.fetchUploadURLs(toBeUploaded);- _logger.info(- "[UPLOAD-DEBUG] Step 3/3: Upload URLs fetched successfully β",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Step 3/3: Upload URLs fetched successfully β",+ );+ }preUploadChecksPassed = true;- _logger.info(- "[UPLOAD-DEBUG] All pre-upload checks completed successfully! "- "Proceeding to queue individual file uploads...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] All pre-upload checks completed successfully! "+ "Proceeding to queue individual file uploads...",+ );+ }} catch (e, s) {- _logger.severe(- "[UPLOAD-DEBUG] Pre-upload checks FAILED. "- "Skipping upload phase but allowing sync to complete gracefully. "- "This ensures home widget and smart albums can still sync.",- e,- s,- );+ if (flagService.internalUser) {+ _logger.severe(+ "[UPLOAD-DEBUG] Pre-upload checks FAILED. "+ "Skipping upload phase but allowing sync to complete gracefully. "+ "This ensures home widget and smart albums can still sync.",+ e,+ s,+ );+ }// Don't rethrow - allow sync to complete without uploads}if (!preUploadChecksPassed) {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Skipping file upload queue due to failed pre-upload checks. "+ "Sync will complete without uploading $toBeUploaded files.",+ );+ }+ }+ } else {+ if (flagService.internalUser) {_logger.info(- "[UPLOAD-DEBUG] Skipping file upload queue due to failed pre-upload checks. "- "Sync will complete without uploading $toBeUploaded files.",+ "[UPLOAD-DEBUG] No files to upload, skipping upload preparation",);}- } else {- _logger.info(- "[UPLOAD-DEBUG] No files to upload, skipping upload preparation",- );}final List<Future> futures = [];// Only proceed with queueing uploads if pre-upload checks passedif (preUploadChecksPassed) {- _logger.info(- "[UPLOAD-DEBUG] Starting to queue ${filesToBeUploaded.length} new files for upload...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Starting to queue ${filesToBeUploaded.length} new files for upload...",+ );+ }int queuedCount = 0;for (final file in filesToBeUploaded) {if (shouldThrottleUpload &&futures.length >= kMaximumPermissibleUploadsInThrottledMode) {- _logger.info(- "[UPLOAD-DEBUG] Throttle limit reached (${futures.length} files queued). "- "Skipping remaining ${filesToBeUploaded.length - queuedCount} files.",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Throttle limit reached (${futures.length} files queued). "+ "Skipping remaining ${filesToBeUploaded.length - queuedCount} files.",+ );+ }break;}// prefer existing collection ID for manually uploaded files.// See https://github.com/ente-io/photos-app/pull/187- _logger.info(- "[UPLOAD-DEBUG] Queueing file ${queuedCount + 1}/${filesToBeUploaded.length}: "- "${file.title} (localID: ${file.localID}, generatedID: ${file.generatedID})",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Queueing file ${queuedCount + 1}/${filesToBeUploaded.length}: "+ "${file.title} (localID: ${file.localID}, generatedID: ${file.generatedID})",+ );+ }try {final collectionID = file.collectionID ??(await _collectionsService.getOrCreateForPath(file.deviceFolder ?? 'Unknown Folder',)).id;- _logger.info(- "[UPLOAD-DEBUG] Resolved collectionID: $collectionID for file ${file.title}",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Resolved collectionID: $collectionID for file ${file.title}",+ );+ }_uploadFile(file, collectionID, futures);queuedCount++;- _logger.info(- "[UPLOAD-DEBUG] Successfully queued file ${file.title} ($queuedCount queued so far)",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Successfully queued file ${file.title} ($queuedCount queued so far)",+ );+ }} catch (e, s) {- _logger.severe(- "[UPLOAD-DEBUG] Failed to queue file ${file.title}",- e,- s,- );+ if (flagService.internalUser) {+ _logger.severe(+ "[UPLOAD-DEBUG] Failed to queue file ${file.title}",+ e,+ s,+ );+ }}}- _logger.info(- "[UPLOAD-DEBUG] Finished queueing new files. Total queued: $queuedCount/${filesToBeUploaded.length}",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Finished queueing new files. Total queued: $queuedCount/${filesToBeUploaded.length}",+ );+ }- _logger.info(- "[UPLOAD-DEBUG] Starting to queue ${updatedFileIDs.length} updated files for re-upload...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Starting to queue ${updatedFileIDs.length} updated files for re-upload...",+ );+ }int reuploadQueuedCount = 0;for (final uploadedFileID in updatedFileIDs) {if (shouldThrottleUpload &&futures.length >= kMaximumPermissibleUploadsInThrottledMode) {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Throttle limit reached for re-uploads (${futures.length} total queued). "+ "Skipping remaining ${updatedFileIDs.length - reuploadQueuedCount} updated files.",+ );+ }+ break;+ }+ if (flagService.internalUser) {_logger.info(- "[UPLOAD-DEBUG] Throttle limit reached for re-uploads (${futures.length} total queued). "- "Skipping remaining ${updatedFileIDs.length - reuploadQueuedCount} updated files.",+ "[UPLOAD-DEBUG] Processing updated file ${reuploadQueuedCount + 1}/${updatedFileIDs.length} "+ "(uploadedFileID: $uploadedFileID)",);- break;}- _logger.info(- "[UPLOAD-DEBUG] Processing updated file ${reuploadQueuedCount + 1}/${updatedFileIDs.length} "- "(uploadedFileID: $uploadedFileID)",- );try {final allFiles = await _db.getFilesInAllCollection(uploadedFileID,ownerID,);if (allFiles.isEmpty) {- _logger.warning(- "[UPLOAD-DEBUG] No files found for uploadedFileID $uploadedFileID, skipping",- );+ if (flagService.internalUser) {+ _logger.warning(+ "[UPLOAD-DEBUG] No files found for uploadedFileID $uploadedFileID, skipping",+ );+ }continue;}- _logger.info(- "[UPLOAD-DEBUG] Found ${allFiles.length} file(s) for uploadedFileID $uploadedFileID",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Found ${allFiles.length} file(s) for uploadedFileID $uploadedFileID",+ );+ }EnteFile? fileInCollectionOwnedByUser;for (final file in allFiles) {if (file.canReUpload(ownerID)) {@@ -774,144 +827,182 @@ class RemoteSyncService {}}if (fileInCollectionOwnedByUser != null) {- _logger.info(- "[UPLOAD-DEBUG] Queueing re-upload for ${fileInCollectionOwnedByUser.title}",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Queueing re-upload for ${fileInCollectionOwnedByUser.title}",+ );+ }_uploadFile(fileInCollectionOwnedByUser,fileInCollectionOwnedByUser.collectionID!,futures,);reuploadQueuedCount++;- _logger.info(- "[UPLOAD-DEBUG] Successfully queued re-upload ($reuploadQueuedCount re-uploads queued)",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Successfully queued re-upload ($reuploadQueuedCount re-uploads queued)",+ );+ }} else {- _logger.warning(- "[UPLOAD-DEBUG] No re-uploadable file found for uploadedFileID $uploadedFileID",- );+ if (flagService.internalUser) {+ _logger.warning(+ "[UPLOAD-DEBUG] No re-uploadable file found for uploadedFileID $uploadedFileID",+ );+ }}} catch (e, s) {- _logger.severe(- "[UPLOAD-DEBUG] Failed to queue re-upload for uploadedFileID $uploadedFileID",- e,- s,- );+ if (flagService.internalUser) {+ _logger.severe(+ "[UPLOAD-DEBUG] Failed to queue re-upload for uploadedFileID $uploadedFileID",+ e,+ s,+ );+ }}}- _logger.info(- "[UPLOAD-DEBUG] Finished queueing updated files. Total re-uploads queued: "- "$reuploadQueuedCount/${updatedFileIDs.length}",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Finished queueing updated files. Total re-uploads queued: "+ "$reuploadQueuedCount/${updatedFileIDs.length}",+ );+ }- _logger.info(- "[UPLOAD-DEBUG] βββββββββββββββββββββββββββββββββββββββββββββββββββββββ",- );- _logger.info(- "[UPLOAD-DEBUG] SUMMARY: Total ${futures.length} upload futures queued",- );- _logger.info(- "[UPLOAD-DEBUG] - New files queued: $queuedCount/${filesToBeUploaded.length}",- );- _logger.info(- "[UPLOAD-DEBUG] - Re-uploads queued: $reuploadQueuedCount/${updatedFileIDs.length}",- );- _logger.info(- "[UPLOAD-DEBUG] - Process mode: ${isProcessBg ? 'BACKGROUND' : 'FOREGROUND'}",- );- _logger.info(- "[UPLOAD-DEBUG] Now waiting for all ${futures.length} upload futures to complete...",- );- _logger.info(- "[UPLOAD-DEBUG] βββββββββββββββββββββββββββββββββββββββββββββββββββββββ",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] βββββββββββββββββββββββββββββββββββββββββββββββββββββββ",+ );+ _logger.info(+ "[UPLOAD-DEBUG] SUMMARY: Total ${futures.length} upload futures queued",+ );+ _logger.info(+ "[UPLOAD-DEBUG] - New files queued: $queuedCount/${filesToBeUploaded.length}",+ );+ _logger.info(+ "[UPLOAD-DEBUG] - Re-uploads queued: $reuploadQueuedCount/${updatedFileIDs.length}",+ );+ _logger.info(+ "[UPLOAD-DEBUG] - Process mode: ${isProcessBg ? 'BACKGROUND' : 'FOREGROUND'}",+ );+ _logger.info(+ "[UPLOAD-DEBUG] Now waiting for all ${futures.length} upload futures to complete...",+ );+ _logger.info(+ "[UPLOAD-DEBUG] βββββββββββββββββββββββββββββββββββββββββββββββββββββββ",+ );+ }try {await Future.wait(futures);- _logger.info(- "[UPLOAD-DEBUG] All upload futures completed successfully! "- "Completed: $_completedUploads, Ignored: $_ignoredUploads",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] All upload futures completed successfully! "+ "Completed: $_completedUploads, Ignored: $_ignoredUploads",+ );+ }} on InvalidFileError catch (e, s) {- _logger.warning(- "[UPLOAD-DEBUG] InvalidFileError caught (ignored)",- e,- s,- );+ if (flagService.internalUser) {+ _logger.warning(+ "[UPLOAD-DEBUG] InvalidFileError caught (ignored)",+ e,+ s,+ );+ }// Do nothing} on FileSystemException catch (e, s) {- _logger.warning(- "[UPLOAD-DEBUG] FileSystemException caught (ignored - likely concurrency issue)",- e,- s,- );+ if (flagService.internalUser) {+ _logger.warning(+ "[UPLOAD-DEBUG] FileSystemException caught (ignored - likely concurrency issue)",+ e,+ s,+ );+ }// Do nothing since it's caused mostly due to concurrency issues// when the foreground app deletes temporary files, interrupting a background// upload} on LockAlreadyAcquiredError catch (e, s) {- _logger.warning(- "[UPLOAD-DEBUG] LockAlreadyAcquiredError caught (ignored)",- e,- s,- );+ if (flagService.internalUser) {+ _logger.warning(+ "[UPLOAD-DEBUG] LockAlreadyAcquiredError caught (ignored)",+ e,+ s,+ );+ }// Do nothing} on SilentlyCancelUploadsError catch (e, s) {- _logger.warning(- "[UPLOAD-DEBUG] SilentlyCancelUploadsError caught (ignored)",- e,- s,- );+ if (flagService.internalUser) {+ _logger.warning(+ "[UPLOAD-DEBUG] SilentlyCancelUploadsError caught (ignored)",+ e,+ s,+ );+ }// Do nothing} on UserCancelledUploadError catch (e, s) {- _logger.warning(- "[UPLOAD-DEBUG] UserCancelledUploadError caught (ignored)",- e,- s,- );+ if (flagService.internalUser) {+ _logger.warning(+ "[UPLOAD-DEBUG] UserCancelledUploadError caught (ignored)",+ e,+ s,+ );+ }// Do nothing} catch (e, s) {- _logger.severe("[UPLOAD-DEBUG] Unexpected error during upload", e, s);+ if (flagService.internalUser) {+ _logger.severe("[UPLOAD-DEBUG] Unexpected error during upload", e, s);+ }rethrow;}} else {- _logger.info(- "[UPLOAD-DEBUG] Skipped upload queueing because pre-upload checks failed. "- "Sync completing without uploads to allow background task to continue.",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Skipped upload queueing because pre-upload checks failed. "+ "Sync completing without uploads to allow background task to continue.",+ );+ }}final hasUploaded = _completedUploads > 0;- _logger.info(- "[UPLOAD-DEBUG] Upload process finished. Returning hasUploaded=$hasUploaded "- "(completedUploads: $_completedUploads)",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Upload process finished. Returning hasUploaded=$hasUploaded "+ "(completedUploads: $_completedUploads)",+ );+ }return hasUploaded;}void _uploadFile(EnteFile file, int collectionID, List<Future> futures) {- _logger.info(- "[UPLOAD-DEBUG] _uploadFile() called for ${file.title} "- "(localID: ${file.localID}, collectionID: $collectionID). "- "Calling FileUploader.upload()...",- );- final future = _uploader.upload(file, collectionID).then((uploadedFile) {+ if (flagService.internalUser) {_logger.info(- "[UPLOAD-DEBUG] Upload completed successfully for ${uploadedFile.title}",+ "[UPLOAD-DEBUG] _uploadFile() called for ${file.title} "+ "(localID: ${file.localID}, collectionID: $collectionID). "+ "Calling FileUploader.upload()...",);+ }+ final future = _uploader.upload(file, collectionID).then((uploadedFile) {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Upload completed successfully for ${uploadedFile.title}",+ );+ }return _onFileUploaded(uploadedFile);}).onError((error, stackTrace) {- _logger.severe(- "[UPLOAD-DEBUG] Upload failed for ${file.title}",- error,- stackTrace,- );+ if (flagService.internalUser) {+ _logger.severe(+ "[UPLOAD-DEBUG] Upload failed for ${file.title}",+ error,+ stackTrace,+ );+ }return _onFileUploadError(error, stackTrace, file);});futures.add(future);- _logger.info(- "[UPLOAD-DEBUG] Upload future added to futures list for ${file.title} "- "(futures count: ${futures.length})",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Upload future added to futures list for ${file.title} "+ "(futures count: ${futures.length})",+ );+ }}Future<void> _onFileUploaded(EnteFile file) async {diff --git a/mobile/apps/photos/lib/utils/file_uploader.dart b/mobile/apps/photos/lib/utils/file_uploader.dartindex 607971b9c9..1872678a7f 100644--- a/mobile/apps/photos/lib/utils/file_uploader.dart+++ b/mobile/apps/photos/lib/utils/file_uploader.dart@@ -164,26 +164,32 @@ class FileUploader {// upload future will return null as File when the file entry is deleted// locally because it's already present in the destination collection.Future<EnteFile> upload(EnteFile file, int collectionID) {- _logger.info(- "[UPLOAD-DEBUG] FileUploader.upload() called for ${file.title} "- "(localID: ${file.localID}, collectionID: $collectionID, "- "isProcessBg: $isProcessBg)",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] FileUploader.upload() called for ${file.title} "+ "(localID: ${file.localID}, collectionID: $collectionID, "+ "isProcessBg: $isProcessBg)",+ );+ }if (file.localID == null || file.localID!.isEmpty) {- _logger.severe(- "[UPLOAD-DEBUG] Upload rejected - file's localID is null or empty for ${file.title}",- );+ if (flagService.internalUser) {+ _logger.severe(+ "[UPLOAD-DEBUG] Upload rejected - file's localID is null or empty for ${file.title}",+ );+ }return Future.error(Exception("file's localID can not be null or empty"));}// If the file hasn't been queued yet, queue it for upload_totalCountInUploadSession++;final String localID = file.localID!;if (!_queue.containsKey(localID)) {- _logger.info(- "[UPLOAD-DEBUG] File ${file.title} not in queue. Adding to upload queue... "- "(queue size before: ${_queue.length})",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] File ${file.title} not in queue. Adding to upload queue... "+ "(queue size before: ${_queue.length})",+ );+ }final completer = Completer<EnteFile>();_queue[localID] = FileUploadItem(file, collectionID, completer);_allBackups[localID] = BackupItem(@@ -193,33 +199,43 @@ class FileUploader {completer: completer,);Bus.instance.fire(BackupUpdatedEvent(_allBackups));- _logger.info(- "[UPLOAD-DEBUG] File ${file.title} added to queue (queue size: ${_queue.length}). "- "Calling _pollQueue()...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] File ${file.title} added to queue (queue size: ${_queue.length}). "+ "Calling _pollQueue()...",+ );+ }_pollQueue();- _logger.info(- "[UPLOAD-DEBUG] _pollQueue() called for ${file.title}. Returning completer.future",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] _pollQueue() called for ${file.title}. Returning completer.future",+ );+ }return completer.future;}// If the file exists in the queue for a matching collectionID,// return the existing future- _logger.info(- "[UPLOAD-DEBUG] File ${file.title} already in queue with localID $localID",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] File ${file.title} already in queue with localID $localID",+ );+ }final FileUploadItem item = _queue[localID]!;if (item.collectionID == collectionID) {_totalCountInUploadSession--;+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Same collectionID ($collectionID) - returning existing future",+ );+ }+ return item.completer.future;+ }+ if (flagService.internalUser) {_logger.info(- "[UPLOAD-DEBUG] Same collectionID ($collectionID) - returning existing future",+ "[UPLOAD-DEBUG] Different collectionID (existing: ${item.collectionID}, new: $collectionID) "+ "- waiting for existing upload to complete",);- return item.completer.future;}- _logger.info(- "[UPLOAD-DEBUG] Different collectionID (existing: ${item.collectionID}, new: $collectionID) "- "- waiting for existing upload to complete",- );debugPrint("Wait on another upload on same local ID to finish before ""adding it to new collection",@@ -291,53 +307,65 @@ class FileUploader {}void _pollQueue() {- _logger.info(- "[UPLOAD-DEBUG] _pollQueue() called. Queue size: ${_queue.length}, "- "uploadCounter: $_uploadCounter/$kMaximumConcurrentUploads, "- "isProcessBg: $isProcessBg",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] _pollQueue() called. Queue size: ${_queue.length}, "+ "uploadCounter: $_uploadCounter/$kMaximumConcurrentUploads, "+ "isProcessBg: $isProcessBg",+ );+ }if (SyncService.instance.shouldStopSync()) {- _logger.warning("[UPLOAD-DEBUG] Sync stop requested - clearing queue");+ if (flagService.internalUser) {+ _logger.warning("[UPLOAD-DEBUG] Sync stop requested - clearing queue");+ }clearQueue(SyncStopRequestedError());return;}if (_queue.isEmpty) {// Upload session completed- _logger.info(- "[UPLOAD-DEBUG] Queue is empty - upload session completed. "- "Resetting totalCountInUploadSession",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Queue is empty - upload session completed. "+ "Resetting totalCountInUploadSession",+ );+ }_totalCountInUploadSession = 0;return;}if (_uploadCounter < kMaximumConcurrentUploads) {- _logger.info(- "[UPLOAD-DEBUG] Upload capacity available ($_uploadCounter < $kMaximumConcurrentUploads). "- "Searching for pending entry...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Upload capacity available ($_uploadCounter < $kMaximumConcurrentUploads). "+ "Searching for pending entry...",+ );+ }var pendingEntry = _queue.entries.firstWhereOrNull((entry) => entry.value.status == UploadStatus.notStarted,)?.value;- if (pendingEntry != null) {- _logger.info(- "[UPLOAD-DEBUG] Found pending entry: ${pendingEntry.file.title} "- "(fileType: ${pendingEntry.file.fileType})",- );- } else {- _logger.info("[UPLOAD-DEBUG] No pending entry found in queue");+ if (flagService.internalUser) {+ if (pendingEntry != null) {+ _logger.info(+ "[UPLOAD-DEBUG] Found pending entry: ${pendingEntry.file.title} "+ "(fileType: ${pendingEntry.file.fileType})",+ );+ } else {+ _logger.info("[UPLOAD-DEBUG] No pending entry found in queue");+ }}if (pendingEntry != null &&pendingEntry.file.fileType == FileType.video &&_videoUploadCounter >= kMaximumConcurrentVideoUploads) {- _logger.info(- "[UPLOAD-DEBUG] Video upload limit reached ($_videoUploadCounter >= $kMaximumConcurrentVideoUploads). "- "Looking for non-video entry...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Video upload limit reached ($_videoUploadCounter >= $kMaximumConcurrentVideoUploads). "+ "Looking for non-video entry...",+ );+ }// check if there's any non-video entry which can be queued for uploadpendingEntry = _queue.entries.firstWhereOrNull(@@ -346,19 +374,23 @@ class FileUploader {entry.value.file.fileType != FileType.video,)?.value;- if (pendingEntry != null) {- _logger.info(- "[UPLOAD-DEBUG] Found non-video entry: ${pendingEntry.file.title}",- );- } else {- _logger.info("[UPLOAD-DEBUG] No non-video entry available");+ if (flagService.internalUser) {+ if (pendingEntry != null) {+ _logger.info(+ "[UPLOAD-DEBUG] Found non-video entry: ${pendingEntry.file.title}",+ );+ } else {+ _logger.info("[UPLOAD-DEBUG] No non-video entry available");+ }}}if (pendingEntry != null) {- _logger.info(- "[UPLOAD-DEBUG] Starting upload for ${pendingEntry.file.title}. "- "Marking as inProgress and calling _encryptAndUploadFileToCollection()...",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Starting upload for ${pendingEntry.file.title}. "+ "Marking as inProgress and calling _encryptAndUploadFileToCollection()...",+ );+ }pendingEntry.status = UploadStatus.inProgress;_allBackups[pendingEntry.file.localID!] =_allBackups[pendingEntry.file.localID]!@@ -368,20 +400,26 @@ class FileUploader {pendingEntry.file,pendingEntry.collectionID,);- _logger.info(- "[UPLOAD-DEBUG] _encryptAndUploadFileToCollection() initiated for ${pendingEntry.file.title}",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] _encryptAndUploadFileToCollection() initiated for ${pendingEntry.file.title}",+ );+ }} else {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] No pending entry to process at this time "+ "(either all uploads in progress or video limit reached)",+ );+ }+ }+ } else {+ if (flagService.internalUser) {_logger.info(- "[UPLOAD-DEBUG] No pending entry to process at this time "- "(either all uploads in progress or video limit reached)",+ "[UPLOAD-DEBUG] Upload capacity full ($_uploadCounter >= $kMaximumConcurrentUploads). "+ "Waiting for uploads to complete...",);}- } else {- _logger.info(- "[UPLOAD-DEBUG] Upload capacity full ($_uploadCounter >= $kMaximumConcurrentUploads). "- "Waiting for uploads to complete...",- );}}@@ -390,36 +428,46 @@ class FileUploader {int collectionID, {bool forcedUpload = false,}) async {- _logger.info(- "[UPLOAD-DEBUG] _encryptAndUploadFileToCollection() started for ${file.title} "- "(collectionID: $collectionID, forcedUpload: $forcedUpload, "- "isProcessBg: $isProcessBg)",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] _encryptAndUploadFileToCollection() started for ${file.title} "+ "(collectionID: $collectionID, forcedUpload: $forcedUpload, "+ "isProcessBg: $isProcessBg)",+ );+ }_uploadCounter++;if (file.fileType == FileType.video) {_videoUploadCounter++;}- _logger.info(- "[UPLOAD-DEBUG] Upload counters updated: uploadCounter=$_uploadCounter, "- "videoUploadCounter=$_videoUploadCounter",- );- final localID = file.localID!;- try {+ if (flagService.internalUser) {_logger.info(- "[UPLOAD-DEBUG] Calling _tryToUpload() for ${file.title} with ${kFileUploadTimeout.inSeconds}s timeout...",+ "[UPLOAD-DEBUG] Upload counters updated: uploadCounter=$_uploadCounter, "+ "videoUploadCounter=$_videoUploadCounter",);+ }+ final localID = file.localID!;+ try {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Calling _tryToUpload() for ${file.title} with ${kFileUploadTimeout.inSeconds}s timeout...",+ );+ }final uploadedFile =await _tryToUpload(file, collectionID, forcedUpload).timeout(kFileUploadTimeout,onTimeout: () {final message = "Upload timed out for file " + file.toString();- _logger.warning("[UPLOAD-DEBUG] $message");+ if (flagService.internalUser) {+ _logger.warning("[UPLOAD-DEBUG] $message");+ }throw TimeoutException(message);},);- _logger.info(- "[UPLOAD-DEBUG] _tryToUpload() completed successfully for ${file.title}",- );+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] _tryToUpload() completed successfully for ${file.title}",+ );+ }_queue.remove(localID)!.completer.complete(uploadedFile);_allBackups[localID] =_allBackups[localID]!.copyWith(status: BackupItemStatus.uploaded);@@ -779,15 +827,40 @@ class FileUploader {late String thumbnailObjectKey;if (count <= 1) {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Non-multipart upload: Getting thumbnail upload URL...",+ );+ }final thumbnailUploadURL = await _getUploadURL();+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Thumbnail URL obtained, uploading thumbnail (size: ${formatBytes(encThumbSize)})...",+ );+ }thumbnailObjectKey = await _putFile(thumbnailUploadURL,encryptedThumbnailFile,encThumbSize,);+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Thumbnail uploaded successfully! Now getting file upload URL...",+ );+ }final fileUploadURL = await _getUploadURL();+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] File URL obtained, uploading actual file (size: ${formatBytes(encFileSize)})...",+ );+ }fileObjectKey =await _putFile(fileUploadURL, encryptedFile, encFileSize);+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Actual file uploaded successfully!",+ );+ }} else {isMultipartUpload = true;_logger.info(@@ -1404,13 +1477,34 @@ class FileUploader {}Future<UploadURL> _getUploadURL() async {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] _getUploadURL() called. URL queue size: ${_uploadURLs.length}, Upload queue size: ${_queue.length}",+ );+ }if (_uploadURLs.isEmpty) {+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] URL queue is empty, fetching new upload URLs from server...",+ );+ }// the queue is empty, fetch at least for one file to handle force uploads// that are not in the queue. This is to also avoidawait fetchUploadURLs(math.max(_queue.length, 1));+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Successfully fetched upload URLs. New queue size: ${_uploadURLs.length}",+ );+ }}try {- return _uploadURLs.removeFirst();+ final url = _uploadURLs.removeFirst();+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] Returning upload URL. Remaining URLs in queue: ${_uploadURLs.length}",+ );+ }+ return url;} catch (e) {if (e is StateError && e.message == 'No element' && _queue.isEmpty) {_logger.warning("Oops, uploadUrls has no element now, fetching again");@@ -1426,16 +1520,32 @@ class FileUploader {Future<void> fetchUploadURLs(int fileCount) async {_uploadURLFetchInProgress ??= Future<void>(() async {try {+ final requestCount = math.min(42, fileCount * 2);+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] fetchUploadURLs() starting HTTP GET to /files/upload-urls with count=$requestCount",+ );+ }final response = await _enteDio.get("/files/upload-urls",queryParameters: {- "count": math.min(42, fileCount * 2), // m4gic number+ "count": requestCount, // m4gic number},);+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] HTTP GET completed, parsing ${(response.data["urls"] as List).length} URLs...",+ );+ }final urls = (response.data["urls"] as List).map((e) => UploadURL.fromMap(e)).toList();_uploadURLs.addAll(urls);+ if (flagService.internalUser) {+ _logger.info(+ "[UPLOAD-DEBUG] fetchUploadURLs() completed. Added ${urls.length} URLs to queue.",+ );+ }} on DioException catch (e, s) {if (e.response != null) {if (e.response!.statusCode == 402) {diff --git a/mobile/apps/photos/scripts/internal_changes.txt b/mobile/apps/photos/scripts/internal_changes.txtindex 741ddd49da..7303f7d3e1 100644--- a/mobile/apps/photos/scripts/internal_changes.txt+++ b/mobile/apps/photos/scripts/internal_changes.txt@@ -7,4 +7,5 @@- Prateek: Fix CronetException during background sync by disabling NativeAdapter on Android- Laurens: Change similar images labels copy- Laurens: Fix flipped thumbnails issue by removing use of ColorFiltered widget-- Prateek: Add comprehensive debug logging and timeout/error handling to track and fix background sync issues\ No newline at end of file+- Prateek: Add comprehensive debug logging and timeout/error handling to track and fix background sync issues+- Prateek: Add detailed logging to upload URL fetching and file upload phases to identify background task hang point\ No newline at end of file