Skip to content

Commit

Permalink
feat: Switch to firebase messaging package
Browse files Browse the repository at this point in the history
  • Loading branch information
krille-chan committed Dec 22, 2023
1 parent 5794bb7 commit 07f6794
Show file tree
Hide file tree
Showing 17 changed files with 212 additions and 148 deletions.
7 changes: 2 additions & 5 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,10 @@ android {
buildTypes {
debug {
signingConfig signingConfigs.debug
applicationIdSuffix ".debug"
versionNameSuffix "-debug"
}
release {
signingConfig signingConfigs.release
}
}
}
// https://stackoverflow.com/a/77494454/8222484
packagingOptions {
Expand All @@ -87,8 +85,7 @@ flutter {

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
//implementation 'com.google.firebase:firebase-messaging:19.0.1' // Workaround for https://github.com/microg/android_packages_apps_GmsCore/issues/313#issuecomment-617651698
implementation 'androidx.multidex:multidex:2.0.1'
}

//apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.gms.google-services'
7 changes: 0 additions & 7 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,6 @@
</intent-filter>
</activity>

<service android:name=".FcmPushService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>

<service android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
android:foregroundServiceType="camera|microphone|mediaProjection">
</service>
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ import android.content.Context
import androidx.multidex.MultiDex

class MainActivity : FlutterActivity() {

override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
}


override fun provideFlutterEngine(context: Context): FlutterEngine? {
return provideEngine(this)
}
Expand Down
2 changes: 1 addition & 1 deletion android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
//classpath 'com.google.gms:google-services:4.3.8'
classpath 'com.google.gms:google-services:4.3.8'
}
}

Expand Down
1 change: 1 addition & 0 deletions firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"flutter":{"platforms":{"android":{"default":{"projectId":"fluffychat-ef3e8","appId":"1:865731724731:android:ec427b3b1dcd4a1e64309e","fileOutput":"android/app/google-services.json"}},"ios":{"default":{"projectId":"fluffychat-ef3e8","appId":"1:865731724731:ios:79fd983ce46cb40c64309e","uploadDebugSymbols":false,"fileOutput":"ios/Runner/GoogleService-Info.plist"}},"macos":{"default":{"projectId":"fluffychat-ef3e8","appId":"1:865731724731:ios:6fb777cf513cdb6264309e","uploadDebugSymbols":false,"fileOutput":"macos/Runner/GoogleService-Info.plist"}},"dart":{"lib/firebase_options.dart":{"projectId":"fluffychat-ef3e8","configurations":{"android":"1:865731724731:android:ec427b3b1dcd4a1e64309e","ios":"1:865731724731:ios:79fd983ce46cb40c64309e","macos":"1:865731724731:ios:6fb777cf513cdb6264309e","web":"1:865731724731:web:d367990bc625c24864309e"}}}}}}
3 changes: 3 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

import 'package:collection/collection.dart';
Expand All @@ -21,6 +22,8 @@ void main() async {
// widget bindings are initialized already.
WidgetsFlutterBinding.ensureInitialized();

await Firebase.initializeApp();

Logs().nativeColors = !PlatformInfos.isIOS;
final store = await SharedPreferences.getInstance();
final clients = await ClientManager.getClients(store: store);
Expand Down
23 changes: 10 additions & 13 deletions lib/utils/background_push.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

Expand All @@ -39,8 +40,6 @@ import '../config/setting_keys.dart';
import '../widgets/matrix.dart';
import 'platform_infos.dart';

//import 'package:fcm_shared_isolate/fcm_shared_isolate.dart';

class NoTokenException implements Exception {
String get cause => 'Cannot get firebase token';
}
Expand All @@ -64,7 +63,7 @@ class BackgroundPush {

final pendingTests = <String, Completer<void>>{};

final dynamic firebase = null; //FcmSharedIsolate();
final firebase = FirebaseMessaging.instance;

DateTime? lastReceivedPush;

Expand All @@ -74,17 +73,16 @@ class BackgroundPush {
onRoomSync ??= client.onSync.stream
.where((s) => s.hasRoomUpdate)
.listen((s) => _onClearingPush(getFromServer: false));
firebase?.setListeners(
onMessage: (message) => pushHelper(
PushNotification.fromJson(
Map<String, dynamic>.from(message['data'] ?? message),
),
FirebaseMessaging.onMessage.listen(
(message) => pushHelper(
PushNotification.fromJson(Map<String, dynamic>.from(message.data)),
client: client,
l10n: l10n,
activeRoomId: matrix?.activeRoomId,
onSelectNotification: goToRoom,
),
);
FirebaseMessaging.onBackgroundMessage(pushHelperBackground);
if (Platform.isAndroid) {
UnifiedPush.initialize(
onNewEndpoint: _newUpEndpoint,
Expand Down Expand Up @@ -138,9 +136,8 @@ class BackgroundPush {
Set<String?>? oldTokens,
bool useDeviceSpecificAppId = false,
}) async {
if (PlatformInfos.isIOS) {
await firebase?.requestPermission();
}
await firebase.requestPermission();

final clientName = PlatformInfos.clientName;
oldTokens ??= <String>{};
final pushers = await (client.getPushers().catchError((e) {
Expand Down Expand Up @@ -291,7 +288,7 @@ class BackgroundPush {
Logs().v('Setup firebase');
if (_fcmToken?.isEmpty ?? true) {
try {
_fcmToken = await firebase?.getToken();
_fcmToken = await firebase.getToken();
if (_fcmToken == null) throw ('PushToken is null');
} catch (e, s) {
Logs().w('[Push] cannot get token', e, e is String ? null : s);
Expand Down Expand Up @@ -363,7 +360,7 @@ class BackgroundPush {
Logs().i('[Push] UnifiedPush using endpoint $endpoint');
final oldTokens = <String?>{};
try {
final fcmToken = await firebase?.getToken();
final fcmToken = await firebase.getToken();
oldTokens.add(fcmToken);
} catch (_) {}
await setupPusher(
Expand Down
46 changes: 23 additions & 23 deletions lib/utils/client_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import 'matrix_sdk_extensions/flutter_matrix_sdk_database_builder.dart';
abstract class ClientManager {
static const String clientNamespace = 'im.fluffychat.store.clients';
static Future<List<Client>> getClients({
bool initialize = true,
bool isBackgroundClient = false,
required SharedPreferences store,
}) async {
if (PlatformInfos.isLinux) {
Expand All @@ -44,28 +44,28 @@ abstract class ClientManager {
await store.setStringList(clientNamespace, clientNames.toList());
}
final clients = clientNames.map(createClient).toList();
if (initialize) {
FlutterLocalNotificationsPlugin? flutterLocalNotificationsPlugin;
await Future.wait(
clients.map(
(client) => client
.init(
waitForFirstSync: false,
waitUntilLoadCompletedLoaded: false,
onMigration: () {
sendMigrationNotification(
flutterLocalNotificationsPlugin ??=
FlutterLocalNotificationsPlugin(),
);
},
)
.catchError(
(e, s) => Logs().e('Unable to initialize client', e, s),
),
),
);
flutterLocalNotificationsPlugin?.cancel(0);
}
FlutterLocalNotificationsPlugin? flutterLocalNotificationsPlugin;
await Future.wait(
clients.map(
(client) => client
.init(
waitForFirstSync: false,
waitUntilLoadCompletedLoaded: false,
isBackgroundClient: isBackgroundClient,
onMigration: () {
sendMigrationNotification(
flutterLocalNotificationsPlugin ??=
FlutterLocalNotificationsPlugin(),
);
},
)
.catchError(
(e, s) => Logs().e('Unable to initialize client', e, s),
),
),
);
flutterLocalNotificationsPlugin?.cancel(0);

if (clients.length > 1 && clients.any((c) => !c.isLogged())) {
final loggedOutClients = clients.where((c) => !c.isLogged()).toList();
for (final client in loggedOutClients) {
Expand Down
13 changes: 10 additions & 3 deletions lib/utils/push_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
Expand All @@ -17,6 +18,10 @@ import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart';
import 'package:fluffychat/utils/platform_infos.dart';
import 'package:fluffychat/utils/voip/callkeep_manager.dart';

Future<void> pushHelperBackground(RemoteMessage message) => pushHelper(
PushNotification.fromJson(message.data),
);

Future<void> pushHelper(
PushNotification notification, {
Client? client,
Expand Down Expand Up @@ -52,7 +57,7 @@ Future<void> pushHelper(
l10n.newMessageInFluffyChat,
l10n.openAppToReadMessages,
NotificationDetails(
iOS: const DarwinNotificationDetails(),
iOS: const DarwinNotificationDetails(sound: 'notification.caf'),
android: AndroidNotificationDetails(
AppConfig.pushNotificationsChannelId,
AppConfig.pushNotificationsChannelName,
Expand Down Expand Up @@ -101,7 +106,7 @@ Future<void> _tryPushHelper(
);

client ??= (await ClientManager.getClients(
initialize: false,
isBackgroundClient: true,
store: await SharedPreferences.getInstance(),
))
.first;
Expand Down Expand Up @@ -246,7 +251,9 @@ Future<void> _tryPushHelper(
groupKey: notificationGroupId,
fullScreenIntent: true, // To show notification popup
);
const iOSPlatformChannelSpecifics = DarwinNotificationDetails();
const iOSPlatformChannelSpecifics = DarwinNotificationDetails(
sound: "notification.caf",
);
final platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics,
Expand Down
4 changes: 4 additions & 0 deletions macos/Flutter/GeneratedPluginRegistrant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import device_info_plus
import dynamic_color
import emoji_picker_flutter
import file_selector_macos
import firebase_core
import firebase_messaging
import flutter_app_badger
import flutter_local_notifications
import flutter_secure_storage_macos
Expand Down Expand Up @@ -43,6 +45,8 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
DynamicColorPlugin.register(with: registry.registrar(forPlugin: "DynamicColorPlugin"))
EmojiPickerFlutterPlugin.register(with: registry.registrar(forPlugin: "EmojiPickerFlutterPlugin"))
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin"))
FLTFirebaseMessagingPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseMessagingPlugin"))
FlutterAppBadgerPlugin.register(with: registry.registrar(forPlugin: "FlutterAppBadgerPlugin"))
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin"))
Expand Down
10 changes: 7 additions & 3 deletions macos/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
3AF44CC3D61A8332019AFCDE /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 5AEFA815523969D4ADFBE7E8 /* GoogleService-Info.plist */; };
9CAF203E1D098383F2EDFFCB /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B3C62FEBAA272B5A33AFFC95 /* Pods_Runner.framework */; };
/* End PBXBuildFile section */

Expand Down Expand Up @@ -69,6 +70,7 @@
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
35E6B919318905352ECC7D69 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = "<group>"; };
5AEFA815523969D4ADFBE7E8 /* GoogleService-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; name = "GoogleService-Info.plist"; path = "Runner/GoogleService-Info.plist"; sourceTree = "<group>"; };
5CDC3DD55F4AC23D2067B292 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
Expand Down Expand Up @@ -110,6 +112,7 @@
33CC10EE2044A3C60003C045 /* Products */,
D73912EC22F37F3D000D13A0 /* Frameworks */,
F9F203356080D460FB6D4567 /* Pods */,
5AEFA815523969D4ADFBE7E8 /* GoogleService-Info.plist */,
);
sourceTree = "<group>";
};
Expand Down Expand Up @@ -255,6 +258,7 @@
files = (
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */,
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */,
3AF44CC3D61A8332019AFCDE /* GoogleService-Info.plist in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down Expand Up @@ -447,7 +451,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "FluffyChat";
PRODUCT_NAME = FluffyChat;
};
name = Profile;
};
Expand Down Expand Up @@ -601,15 +605,15 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "FluffyChat";
PRODUCT_NAME = FluffyChat;
};
name = Debug;
};
33CC111D2044C6BA0003C045 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "FluffyChat";
PRODUCT_NAME = FluffyChat;
};
name = Release;
};
Expand Down
Loading

0 comments on commit 07f6794

Please sign in to comment.