Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][photos] Enable Android push registration and background sync (#13397)

aman-pilot4d9955678321
diff --git a/mobile/apps/photos/android/app/build.gradle b/mobile/apps/photos/android/app/build.gradle
index d988621c70..26afc77233 100644
--- a/mobile/apps/photos/android/app/build.gradle
+++ b/mobile/apps/photos/android/app/build.gradle
@@ -1,10 +1,15 @@
plugins {
+ id "com.google.gms.google-services" version "4.4.4" apply false
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.20'
}
+if (file("google-services.json").exists()) {
+ apply plugin: "com.google.gms.google-services"
+}
+
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
diff --git a/mobile/apps/photos/android/app/google-services.json b/mobile/apps/photos/android/app/google-services.json
new file mode 100644
index 0000000000..b61bba338b
--- /dev/null
+++ b/mobile/apps/photos/android/app/google-services.json
@@ -0,0 +1,143 @@
+{
+ "project_info": {
+ "project_number": "817308839677",
+ "firebase_url": "https://ente-photos-d38a3.firebaseio.com",
+ "project_id": "ente-photos-d38a3",
+ "storage_bucket": "ente-photos-d38a3.firebasestorage.app"
+ },
+ "client": [
+ {
+ "client_info": {
+ "mobilesdk_app_id": "1:817308839677:android:3718b21f6652c7fc185894",
+ "android_client_info": {
+ "package_name": "io.ente.photos"
+ }
+ },
+ "oauth_client": [],
+ "api_key": [
+ {
+ "current_key": "AIzaSyBZ8nli5jpqFTv7p5saSyGrUck34PC2DpQ"
+ },
+ {
+ "current_key": "AIzaSyDoyvjcoP88P956UKJCepTbhqZAoks6ntM"
+ }
+ ],
+ "services": {
+ "appinvite_service": {
+ "other_platform_oauth_client": []
+ }
+ }
+ },
+ {
+ "client_info": {
+ "mobilesdk_app_id": "1:817308839677:android:26cd5d62e19fc0cf185894",
+ "android_client_info": {
+ "package_name": "io.ente.photos.debug"
+ }
+ },
+ "oauth_client": [],
+ "api_key": [
+ {
+ "current_key": "AIzaSyBZ8nli5jpqFTv7p5saSyGrUck34PC2DpQ"
+ },
+ {
+ "current_key": "AIzaSyDoyvjcoP88P956UKJCepTbhqZAoks6ntM"
+ }
+ ],
+ "services": {
+ "appinvite_service": {
+ "other_platform_oauth_client": []
+ }
+ }
+ },
+ {
+ "client_info": {
+ "mobilesdk_app_id": "1:817308839677:android:4f8b2f6c6e32c400185894",
+ "android_client_info": {
+ "package_name": "io.ente.photos.dev"
+ }
+ },
+ "oauth_client": [],
+ "api_key": [
+ {
+ "current_key": "AIzaSyBZ8nli5jpqFTv7p5saSyGrUck34PC2DpQ"
+ },
+ {
+ "current_key": "AIzaSyDoyvjcoP88P956UKJCepTbhqZAoks6ntM"
+ }
+ ],
+ "services": {
+ "appinvite_service": {
+ "other_platform_oauth_client": []
+ }
+ }
+ },
+ {
+ "client_info": {
+ "mobilesdk_app_id": "1:817308839677:android:f21cf722b3adc034185894",
+ "android_client_info": {
+ "package_name": "io.ente.photos.dev.debug"
+ }
+ },
+ "oauth_client": [],
+ "api_key": [
+ {
+ "current_key": "AIzaSyBZ8nli5jpqFTv7p5saSyGrUck34PC2DpQ"
+ },
+ {
+ "current_key": "AIzaSyDoyvjcoP88P956UKJCepTbhqZAoks6ntM"
+ }
+ ],
+ "services": {
+ "appinvite_service": {
+ "other_platform_oauth_client": []
+ }
+ }
+ },
+ {
+ "client_info": {
+ "mobilesdk_app_id": "1:817308839677:android:f795d06b3347b5fc185894",
+ "android_client_info": {
+ "package_name": "io.ente.photos.independent"
+ }
+ },
+ "oauth_client": [],
+ "api_key": [
+ {
+ "current_key": "AIzaSyBZ8nli5jpqFTv7p5saSyGrUck34PC2DpQ"
+ },
+ {
+ "current_key": "AIzaSyDoyvjcoP88P956UKJCepTbhqZAoks6ntM"
+ }
+ ],
+ "services": {
+ "appinvite_service": {
+ "other_platform_oauth_client": []
+ }
+ }
+ },
+ {
+ "client_info": {
+ "mobilesdk_app_id": "1:817308839677:android:863c6d1bc426a3cf185894",
+ "android_client_info": {
+ "package_name": "io.ente.photos.independent.debug"
+ }
+ },
+ "oauth_client": [],
+ "api_key": [
+ {
+ "current_key": "AIzaSyBZ8nli5jpqFTv7p5saSyGrUck34PC2DpQ"
+ },
+ {
+ "current_key": "AIzaSyDoyvjcoP88P956UKJCepTbhqZAoks6ntM"
+ }
+ ],
+ "services": {
+ "appinvite_service": {
+ "other_platform_oauth_client": []
+ }
+ }
+ }
+ ],
+ "configuration_version": "1"
+}
diff --git a/mobile/apps/photos/changes/android-push-refresh.md b/mobile/apps/photos/changes/android-push-refresh.md
new file mode 100644
index 0000000000..716cba6d1d
--- /dev/null
+++ b/mobile/apps/photos/changes/android-push-refresh.md
@@ -0,0 +1 @@
+- Added support for push-triggered background refresh on Android.
diff --git a/mobile/apps/photos/lib/gateways/push/push_gateway.dart b/mobile/apps/photos/lib/gateways/push/push_gateway.dart
index 86a7732825..58faca4186 100644
--- a/mobile/apps/photos/lib/gateways/push/push_gateway.dart
+++ b/mobile/apps/photos/lib/gateways/push/push_gateway.dart
@@ -7,11 +7,16 @@ class PushGateway {
Future<void> registerToken({
required String fcmToken,
+ required String platform,
String? apnsToken,
}) async {
await _enteDio.post(
"/push/token",
- data: {"fcmToken": fcmToken, "apnsToken": apnsToken},
+ data: {
+ "fcmToken": fcmToken,
+ "platform": platform,
+ "apnsToken": apnsToken,
+ },
);
}
}
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 6f5a2d0b5b..8ebfe04e6f 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -580,11 +580,7 @@ Future<void> _init(
await _scheduleFGHomeWidgetSync();
}
- if (Platform.isIOS) {
- PushService.instance
- .init(onBackgroundPush: _handleBackgroundPush)
- .ignore();
- }
+ PushService.instance.init(onBackgroundPush: _handleBackgroundPush).ignore();
_logger.info("PushService/HomeWidget done $tlog");
unawaited(MLService.instance.init());
try {
diff --git a/mobile/apps/photos/lib/services/push_service.dart b/mobile/apps/photos/lib/services/push_service.dart
index a6be0f83d9..f5fe489c56 100644
--- a/mobile/apps/photos/lib/services/push_service.dart
+++ b/mobile/apps/photos/lib/services/push_service.dart
@@ -1,7 +1,9 @@
import "dart:async";
+import "dart:io";
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
+import 'package:flutter/widgets.dart';
import 'package:logging/logging.dart';
import 'package:photos/core/configuration.dart';
import 'package:photos/core/constants.dart';
@@ -9,6 +11,7 @@ import 'package:photos/core/event_bus.dart';
import 'package:photos/events/signed_in_event.dart';
import 'package:photos/service_locator.dart';
import 'package:photos/services/sync/sync_service.dart';
+import 'package:photos/utils/bg_task_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';
typedef BackgroundPushHandler = Future<void> Function(Object message);
@@ -26,13 +29,16 @@ class PushService {
late SharedPreferences _prefs;
StreamSubscription<RemoteMessage>? _foregroundMessageSubscription;
StreamSubscription<SignedInEvent>? _signedInSubscription;
+ StreamSubscription<String>? _tokenRefreshSubscription;
PushService._privateConstructor();
Future<void> init({BackgroundPushHandler? onBackgroundPush}) async {
_prefs = await SharedPreferences.getInstance();
await Firebase.initializeApp();
- if (onBackgroundPush != null) {
+ if (Platform.isAndroid) {
+ FirebaseMessaging.onBackgroundMessage(handleAndroidBackgroundPush);
+ } else if (onBackgroundPush != null) {
FirebaseMessaging.onBackgroundMessage(onBackgroundPush);
}
if (_foregroundMessageSubscription != null) {
@@ -44,54 +50,71 @@ class PushService {
_logger.info("Got a message whilst in the foreground!");
_handleForegroundPushMessage(message);
});
- try {
- if (_signedInSubscription != null) {
- await _signedInSubscription!.cancel();
- }
- if (Configuration.instance.hasConfiguredAccount()) {
- await _configurePushToken();
- } else {
- _signedInSubscription = Bus.instance.on<SignedInEvent>().listen((
- _,
- ) async {
- // ignore: unawaited_futures
- _configurePushToken();
- });
- }
- } catch (e, s) {
- _logger.severe("Could not configure push token", e, s);
+ if (_signedInSubscription != null) {
+ await _signedInSubscription!.cancel();
}
+ _signedInSubscription = Bus.instance.on<SignedInEvent>().listen((_) {
+ unawaited(_configurePushToken());
+ });
+ await _tokenRefreshSubscription?.cancel();
+ _tokenRefreshSubscription = FirebaseMessaging.instance.onTokenRefresh
+ .listen(
+ (_) => unawaited(_configurePushToken()),
+ onError: (Object error, StackTrace stack) {
+ _logPushError("Could not refresh push token", error, stack);
+ },
+ );
+ await _configurePushToken();
}
Future<void> _configurePushToken() async {
- final String? fcmToken = await FirebaseMessaging.instance.getToken();
- final shouldForceRefreshServerToken =
- DateTime.now().microsecondsSinceEpoch -
- (_prefs.getInt(kLastFCMTokenUpdationTime) ?? 0) >
- kFCMTokenUpdationIntervalInMicroSeconds;
- if (fcmToken != null &&
- (_prefs.getString(kFCMPushToken) != fcmToken ||
- shouldForceRefreshServerToken)) {
- final String? apnsToken = await FirebaseMessaging.instance.getAPNSToken();
- try {
+ final sessionToken = Configuration.instance.getToken();
+ if (sessionToken == null) return;
+ try {
+ final String? fcmToken = await FirebaseMessaging.instance.getToken();
+ final shouldForceRefreshServerToken =
+ DateTime.now().microsecondsSinceEpoch -
+ (_prefs.getInt(kLastFCMTokenUpdationTime) ?? 0) >
+ kFCMTokenUpdationIntervalInMicroSeconds;
+ if (fcmToken != null &&
+ (_prefs.getString(kFCMPushToken) != fcmToken ||
+ shouldForceRefreshServerToken)) {
+ final String? apnsToken = Platform.isIOS
+ ? await FirebaseMessaging.instance.getAPNSToken()
+ : null;
_logger.info("Updating token on server");
await _setPushTokenOnServer(fcmToken, apnsToken);
+ if (_prefs.getString(Configuration.tokenKey) != sessionToken) return;
await _prefs.setString(kFCMPushToken, fcmToken);
await _prefs.setInt(
kLastFCMTokenUpdationTime,
DateTime.now().microsecondsSinceEpoch,
);
_logger.info("Push token updated on server");
- } catch (e) {
- _logger.severe("Could not set push token", e, StackTrace.current);
+ } else {
+ _logger.info("Skipping token update");
}
- } else {
- _logger.info("Skipping token update");
+ } catch (e, s) {
+ _logPushError("Could not configure push token", e, s);
}
}
Future<void> _setPushTokenOnServer(String fcmToken, String? apnsToken) async {
- await pushGateway.registerToken(fcmToken: fcmToken, apnsToken: apnsToken);
+ await pushGateway.registerToken(
+ fcmToken: fcmToken,
+ platform: Platform.operatingSystem,
+ apnsToken: apnsToken,
+ );
+ }
+
+ void _logPushError(String message, Object error, StackTrace stack) {
+ if (error is FirebaseException &&
+ (error.message?.contains("MISSING_INSTANCEID_SERVICE") == true ||
+ error.message?.contains("SERVICE_NOT_AVAILABLE") == true)) {
+ _logger.warning("$message: $error");
+ } else {
+ _logger.warning(message, error, stack);
+ }
}
void _handleForegroundPushMessage(RemoteMessage message) {
@@ -114,3 +137,13 @@ class PushService {
message.data[kPushAction] == kSync;
}
}
+
+@pragma('vm:entry-point')
+Future<void> handleAndroidBackgroundPush(RemoteMessage message) async {
+ if (!PushService.shouldSync(message)) return;
+ WidgetsFlutterBinding.ensureInitialized();
+ await Firebase.initializeApp().timeout(const Duration(seconds: 10));
+ await BgTaskUtils.scheduleAndroidBackgroundRefresh().timeout(
+ const Duration(seconds: 10),
+ );
+}
diff --git a/mobile/apps/photos/lib/utils/bg_task_utils.dart b/mobile/apps/photos/lib/utils/bg_task_utils.dart
index d30b5f40d5..fddfdc27fb 100644
--- a/mobile/apps/photos/lib/utils/bg_task_utils.dart
+++ b/mobile/apps/photos/lib/utils/bg_task_utils.dart
@@ -25,6 +25,7 @@ void callbackDispatcher() {
String? failure = "Task didn't run";
bool timedOut = false;
bool ownsPipeline = false;
+ final isPushRefresh = taskName == BgTaskUtils.androidPushRefreshTask;
final isIOSProcessingTask =
Platform.isIOS && taskName == BgTaskUtils.iOSBackgroundProcessingTask;
final prefs = await SharedPreferences.getInstance();
@@ -38,7 +39,7 @@ void callbackDispatcher() {
() async {
try {
BgTaskUtils.$.info('Task started $tlog');
- if (await BackgroundTasks.nativeEnabled(prefs)) {
+ if (!isPushRefresh && await BackgroundTasks.nativeEnabled(prefs)) {
await BackgroundTasks.configure();
failure = null;
return;
@@ -56,7 +57,7 @@ void callbackDispatcher() {
failure = null;
return;
}
- if (await BackgroundTasks.nativeEnabled(prefs)) {
+ if (!isPushRefresh && await BackgroundTasks.nativeEnabled(prefs)) {
await BackgroundTasks.configure();
failure = null;
return;
@@ -114,7 +115,8 @@ void callbackDispatcher() {
return;
});
- if (ownsPipeline &&
+ if (!isPushRefresh &&
+ ownsPipeline &&
!timedOut &&
await BackgroundTasks.nativeEnabled(prefs)) {
await BackgroundTasks.configure().catchError((Object _) {});
@@ -135,6 +137,7 @@ class BgTaskUtils {
static const iOSBackgroundProcessingTask =
"io.ente.frame.iOSBackgroundProcessing";
static const androidPeriodicTask = "io.ente.photos.androidPeriodicTask";
+ static const androidPushRefreshTask = "io.ente.photos.androidPushRefresh";
static const androidBackgroundProcessingTask =
"io.ente.photos.androidBackgroundProcessing";
@@ -145,7 +148,8 @@ class BgTaskUtils {
static bool isRefreshTask(String taskName) =>
taskName == iOSBackgroundAppRefreshTask ||
- taskName == androidPeriodicTask;
+ taskName == androidPeriodicTask ||
+ taskName == androidPushRefreshTask;
static Duration taskStartupElapsedFor(
String taskName,
@@ -283,6 +287,18 @@ class BgTaskUtils {
await prefs.remove(kLastBGTaskHeartBeatTime);
}
+ static Future<void> scheduleAndroidBackgroundRefresh() async {
+ await workmanager.Workmanager().initialize(callbackDispatcher);
+ await workmanager.Workmanager().registerOneOffTask(
+ androidPushRefreshTask,
+ androidPushRefreshTask,
+ constraints: workmanager.Constraints(
+ networkType: workmanager.NetworkType.connected,
+ ),
+ existingWorkPolicy: workmanager.ExistingWorkPolicy.keep,
+ );
+ }
+
static Future<void> configureWorkmanager() async {
try {
await workmanager.Workmanager().initialize(callbackDispatcher);
diff --git a/mobile/apps/photos/scripts/prepare_fdroid_source.sh b/mobile/apps/photos/scripts/prepare_fdroid_source.sh
index 965224a5a6..68727e3dcb 100755
--- a/mobile/apps/photos/scripts/prepare_fdroid_source.sh
+++ b/mobile/apps/photos/scripts/prepare_fdroid_source.sh
@@ -17,6 +17,9 @@ remove_direct_dependencies() {
remove_playstore_sources() {
../../packages/install_source/scripts/prepare_fdroid_source.sh
+ sed -i.bak '/com.google.gms.google-services/d' android/app/build.gradle
+ rm android/app/build.gradle.bak
+ rm -f android/app/google-services.json
}
copy_fdroid_overlay() {