π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Merge remote-tracking branch 'upstream/main' into bg-ml-run
Prateek Sunal79e528776f25
diff --cc mobile/apps/photos/lib/main.dartindex d90cc6d0a1,30549ae1a4..8073b97a8d--- a/mobile/apps/photos/lib/main.dart+++ b/mobile/apps/photos/lib/main.dart@@@ -138,59 -155,76 +155,79 @@@ Future<void> runBackgroundTask}Future<void> _runMinimally(String taskId, TimeLogger tlog) async {- final PackageInfo packageInfo = await PackageInfo.fromPlatform();- final SharedPreferences prefs = await SharedPreferences.getInstance();+ try {+ final PackageInfo packageInfo = await PackageInfo.fromPlatform();+ final SharedPreferences prefs = await SharedPreferences.getInstance();+ await _scheduleHeartBeat(prefs, true);- await Configuration.instance.init();+ _logger.info("(for debugging) Configuration init $tlog");+ await Configuration.instance.init();+ _logger.info("(for debugging) Configuration done $tlog");- // App LifeCycle- AppLifecycleService.instance.init(prefs);- AppLifecycleService.instance.onAppInBackground('init via: WorkManager $tlog');+ // App LifeCycle+ AppLifecycleService.instance.init(prefs);+ AppLifecycleService.instance+ .onAppInBackground('init via: WorkManager $tlog');- // Crypto rel.- await Computer.shared().turnOn(workersCount: 4);- CryptoUtil.init();+ // Crypto rel.+ await Computer.shared().turnOn(workersCount: 4);+ CryptoUtil.init();- // Init Network Utils- await NetworkClient.instance.init(packageInfo);+ // Init Network Utils+ await NetworkClient.instance.init(packageInfo);- // Global Services- ServiceLocator.instance.init(- prefs,- NetworkClient.instance.enteDio,- NetworkClient.instance.getDio(),- packageInfo,- );+ // Global Services+ ServiceLocator.instance.init(+ prefs,+ NetworkClient.instance.enteDio,+ NetworkClient.instance.getDio(),+ packageInfo,+ );++ _logger.info("(for debugging) CollectionsService init $tlog");+ await CollectionsService.instance.init(prefs);+ _logger.info("(for debugging) CollectionsService init done $tlog");++ // Upload & Sync Related+ await FileUploader.instance.init(prefs, true);+ LocalFileUpdateService.instance.init(prefs);+ await LocalSyncService.instance.init(prefs);+ RemoteSyncService.instance.init(prefs);+ await SyncService.instance.init(prefs);- await CollectionsService.instance.init(prefs);-- // Upload & Sync Related- await FileUploader.instance.init(prefs, true);- LocalFileUpdateService.instance.init(prefs);- await LocalSyncService.instance.init(prefs);- RemoteSyncService.instance.init(prefs);- await SyncService.instance.init(prefs);-- // Misc Services- await UserService.instance.init();- NotificationService.instance.init(prefs);-- // Begin Execution- // only runs for android- updateService.showUpdateNotification().ignore();- await _sync('bgTaskActiveProcess');-- final locale = await getLocale();- await initializeDateFormatting(locale?.languageCode ?? "en");- // only runs for android- await _homeWidgetSync(true);-- final isDeviceHealthy = await computeController.isDeviceHealthyFuture();- if (isDeviceHealthy) {- await MLService.instance.init();- await PersonService.init(entityService, MLDataDB.instance, prefs);- await MLService.instance.runAllML(force: true);+ // Misc Services+ await UserService.instance.init();+ NotificationService.instance.init(prefs);+ SocialNotificationCoordinator.instance.init(prefs);+ await NotificationService.instance.initializeForBackground();++ // Begin Execution+ // only runs for android+ _logger.info("[BG TASK] update notification");+ updateService.showUpdateNotification().ignore();+ _logger.info("[BG TASK] sync starting");+ await _sync('bgTaskActiveProcess');+ _logger.info("[BG TASK] sync completed");++ _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");+ await _homeWidgetSync(true);+- // await MLService.instance.init();- // await PersonService.init(entityService, MLDataDB.instance, prefs);- // await MLService.instance.runAllML(force: true);++ final isDeviceHealthy = await computeController.isDeviceHealthyFuture();++ if (isDeviceHealthy) {++ await MLService.instance.init();++ await PersonService.init(entityService, MLDataDB.instance, prefs);++ await MLService.instance.runAllML(force: true);++ }+ _logger.info("[BG TASK] smart albums sync");await smartAlbumsService.syncSmartAlbums();++ _logger.info("[BG TASK] $taskId completed");+ } catch (e, s) {+ _logger.severe("[BG TASK] $taskId error", e, s);}}diff --cc mobile/apps/photos/lib/services/machine_learning/compute_controller.dartindex 54a9801a14,fabad2a55a..fad10341c7--- a/mobile/apps/photos/lib/services/machine_learning/compute_controller.dart+++ b/mobile/apps/photos/lib/services/machine_learning/compute_controller.dart@@@ -8,10 -8,10 +8,11 @@@ import "package:flutter/foundation.dartimport "package:logging/logging.dart";import "package:photos/core/event_bus.dart";import "package:photos/events/compute_control_event.dart";+ import "package:photos/events/device_health_changed_event.dart";+import "package:photos/main.dart";import "package:thermal/thermal.dart";- enum _ComputeRunState {+ enum ComputeRunState {idle,runningML,generatingStream,@@@ -41,31 -48,49 +49,53 @@@ class ComputeControllerbool get isDeviceHealthy => _isDeviceHealthy;+ void _setDeviceHealth(bool healthy) {+ if (_isDeviceHealthy == healthy) return;+ _isDeviceHealthy = healthy;+ Bus.instance.fire(DeviceHealthChangedEvent(healthy));+ }+ComputeController() {_logger.info('ComputeController constructor');+ init();+ _logger.info('init done ');+ }+ // Directly assign the values + Attach listener for compute controller+ Future<void> init() async {+ // we don't need listeners to be initialized in background- if (isProcessBg) {- _logger.info('init done ');- return;- }++ if (isProcessBg) return;+++ // Interaction Timer+_startInteractionTimer(kDefaultInteractionTimeout);++ // Thermal related+ _onThermalStateUpdate(await _thermal.thermalStatus);+ _thermal.onThermalStatusChanged.listen((ThermalStatus thermalState) {+ _onThermalStateUpdate(thermalState);+ });++ // Battery Stateif (Platform.isIOS) {if (kDebugMode) {- _logger.info(+ _logger.fine("iOS battery info stream is not available in simulator, disabling in debug mode",);- // if you need to test on physical device, uncomment this check- return;+ } else {+ // Update Battery state for iOS+ _oniOSBatteryStateUpdate(await BatteryInfoPlugin().iosBatteryInfo);+ BatteryInfoPlugin()+ .iosBatteryInfoStream+ .listen((IosBatteryInfo? batteryInfo) {+ _oniOSBatteryStateUpdate(batteryInfo);+ });}- BatteryInfoPlugin()- .iosBatteryInfoStream- .listen((IosBatteryInfo? batteryInfo) {- _oniOSBatteryStateUpdate(batteryInfo);- });- }- if (Platform.isAndroid) {+ } else if (Platform.isAndroid) {+ // Update Battery state for Android+ _onAndroidBatteryStateUpdate(+ await BatteryInfoPlugin().androidBatteryInfo,+ );BatteryInfoPlugin().androidBatteryInfoStream.listen((AndroidBatteryInfo? batteryInfo) {diff --cc mobile/apps/photos/lib/services/machine_learning/ml_service.dartindex 31942fbe59,1e73bde7f2..9fe96604db--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart@@@ -8,9 -8,10 +8,11 @@@ import "package:logging/logging.dart"import "package:photos/core/event_bus.dart";import "package:photos/db/files_db.dart";import "package:photos/db/ml/db.dart";+ import "package:photos/db/offline_files_db.dart";import "package:photos/events/compute_control_event.dart";import "package:photos/events/people_changed_event.dart";+import "package:photos/main.dart";+ import "package:photos/models/ml/clip.dart";import "package:photos/models/ml/face/face.dart";import "package:photos/models/ml/ml_versions.dart";import "package:photos/service_locator.dart";@@@ -70,38 -95,37 +96,42 @@@ class MLService_logger.info("client: $client");// Listen on ComputeController- Bus.instance.on<ComputeControlEvent>().listen((event) {- if (!hasGrantedMLConsent) {- if (event.shouldRun) {- VideoPreviewService.instance.queueFiles(duration: Duration.zero);+ /// Only listen for events when in foreground,+ /// so we don't waste resources when the app is in background+ /// and we just do things sequentially+ if (!isProcessBg) {+ Bus.instance.on<ComputeControlEvent>().listen((event) {- if (!flagService.hasGrantedMLConsent) {++ if (!hasGrantedMLConsent) {++ if (event.shouldRun) {++ VideoPreviewService.instance.queueFiles(duration: Duration.zero);++ }+ return;}- return;- }- _mlControllerStatus = event.shouldRun;- if (_mlControllerStatus) {- if (_shouldPauseIndexingAndClustering) {- _cancelPauseIndexingAndClustering();- _logger.info(- "MLController allowed running ML, faces indexing undoing previous pause",- );+ _mlControllerStatus = event.shouldRun;+ if (_mlControllerStatus) {+ if (_shouldPauseIndexingAndClustering) {+ _cancelPauseIndexingAndClustering();+ _logger.info(+ "MLController allowed running ML, faces indexing undoing previous pause",+ );+ } else {+ _logger.info(+ "MLController allowed running ML, faces indexing starting",+ );+ }+ unawaited(runAllML());} else {_logger.info(- "MLController allowed running ML, faces indexing starting",+ "MLController stopped running ML, faces indexing will be paused (unless it's fetching embeddings)",);+ pauseIndexingAndClustering();}- unawaited(runAllML());- } else {- _logger.info(- "MLController stopped running ML, faces indexing will be paused (unless it's fetching embeddings)",- );- pauseIndexingAndClustering();- }- });+ });+ }_isInitialized = true;+ unawaited(_maybePredownloadLocalModels());_logger.info('init done');}@@@ -142,7 -192,11 +198,11 @@@);await clusterAllImages();}- if (_mlControllerStatus == true) {+ if (!isProcessBg && _mlControllerStatus == true) {+ if (_hasModeChanged(mode)) {+ _logger.info("App mode changed during ML run, stopping");+ return;+ }// refresh discover sectionmagicCacheService.updateCache(forced: force).ignore();// refresh memories section@@@ -154,7 -212,11 +218,11 @@@if ((await mlDataDB.getUnclusteredFaceCount()) > 0) {await clusterAllImages();}- if (_mlControllerStatus == true) {+ if (!isProcessBg && _mlControllerStatus == true) {+ if (_hasModeChanged(mode)) {+ _logger.info("App mode changed during ML run, stopping");+ return;+ }// refresh discover sectionmagicCacheService.updateCache().ignore();// refresh memories section (only runs if forced is true)@@@ -164,12 -226,10 +232,12 @@@_logger.severe("runAllML failed", e, s);rethrow;} finally {- _logger.severe("ML finished running");+ _logger.info("ML finished running");_isRunningML = false;- computeController.releaseCompute(ml: true);- VideoPreviewService.instance.queueFiles();+ if (!isProcessBg) {+ computeController.releaseCompute(ml: true);+ VideoPreviewService.instance.queueFiles();+ }}}diff --cc mobile/apps/photos/lib/utils/image_ml_util.dartindex 49d95f8bfe,519593b41a..6ac04892fc--- a/mobile/apps/photos/lib/utils/image_ml_util.dart+++ b/mobile/apps/photos/lib/utils/image_ml_util.dart@@@ -54,57 -53,19 +54,63 @@@ Future<DecodedImage> decodeImageFromPatString imagePath, {required bool includeRgbaBytes,required bool includeDartUiImage,+ bool inBackground = false,}) async {+ if (inBackground) {+ if (includeDartUiImage) {+ _logger.severe(+ "Decoding image in background with Dart UI Image is not possible!",+ );+ throw Exception(+ "Decoding image in background with Dart UI Image is not possible!",+ );+ }+ if (!includeRgbaBytes) {+ _logger.severe(+ "Decoding image in background but not returning anything",+ );+ throw Exception(+ "Decoding image in background but not returning anything",+ );+ }+ final image = await img_pkg.decodeImageFile(imagePath);+ final imageData = image?.data;+ if (imageData == null) {+ _logger.severe(+ "Failed to decode image from file: $imagePath using image package",+ );+ throw Exception(+ "Failed to decode image from file: $imagePath using image package",+ );+ }++ Uint8List? bytes;+ for (final order in img_pkg.ChannelOrder.values) {+ bytes = imageData.getBytes(order: order);+ _logger.info("Bytes length is: ${bytes.length}, for order: : $order");+ }+ final dimensions = Dimensions(+ width: image!.width,+ height: image.height,+ );+ _logger.info("Dimensions are: $dimensions");+ return DecodedImage(+ dimensions: dimensions,+ rawRgbaBytes: bytes,+ );+ }final imageData = await File(imagePath).readAsBytes();-- final Map<String, IfdTag> exifData = await readExifFromBytes(imageData);+ final format = imagePath.split('.').last.toLowerCase();+ final bool skipExifRead = Platform.isIOS &&+ format == 'jxl'; // JXL on iOS has issues with EXIF reading+ Map<String, IfdTag> exifData = <String, IfdTag>{};+ if (skipExifRead) {+ _logger.info('Skipping EXIF read for JXL on iOS');+ } else {+ exifData = await readExifFromBytes(imageData);+ }final int orientation =exifData['Image Orientation']?.values.firstAsInt() ?? 1;- final format = imagePath.split('.').last.toLowerCase();if (orientation > 1 && includeRgbaBytes) {if (format == 'heic' || format == 'heif') {_loggerdiff --cc mobile/apps/photos/lib/utils/ml_util.dartindex 2f79fd4231,7ae705f744..e8bb6b54db--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@@ -6,8 -8,7 +8,9 @@@ import "package:logging/logging.dart"import "package:photos/db/files_db.dart";import "package:photos/db/ml/db.dart";import "package:photos/db/ml/filedata.dart";+ import "package:photos/db/offline_files_db.dart";+import "package:photos/extensions/list.dart";+import "package:photos/main.dart";import "package:photos/models/file/extensions/file_props.dart";import "package:photos/models/file/file.dart";import "package:photos/models/file/file_type.dart";