TF-1202: Config Podfile for FCM

This commit is contained in:
ManhNTX
2022-11-18 12:09:07 +07:00
committed by Dat H. Pham
parent 972402bc59
commit 11e17c3b4d
13 changed files with 116 additions and 200 deletions
+1 -7
View File
@@ -1,8 +1,6 @@
import 'package:contact/contact/model/capability_contact.dart';
import 'package:core/core.dart';
import 'package:dartz/dartz.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:forward/forward/capability_forward.dart';
@@ -21,8 +19,6 @@ import 'package:tmail_ui_user/features/manage_account/presentation/email_rules/b
import 'package:tmail_ui_user/features/manage_account/presentation/forward/bindings/forwarding_interactors_bindings.dart';
import 'package:tmail_ui_user/features/push_notification/domain/model/capability_push_notification.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/firebase_bindings.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/firebase_options.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/notification_service.dart';
import 'package:tmail_ui_user/main/error/capability_validator.dart';
import 'package:tmail_ui_user/main/exceptions/remote_exception.dart';
import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
@@ -147,11 +143,9 @@ abstract class BaseController extends GetxController
}
}
Future<void> injectFirebaseBindings(Session? session, AccountId? accountId) async {
void injectFirebaseBindings(Session? session, AccountId? accountId) {
try {
requireCapability(session!, accountId!, [capabilityPushNotification]);
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
FireBaseBindings().dependencies();
} catch(e) {
logError('BaseController::injectFirebaseBindings(): exception: $e');
@@ -358,10 +358,9 @@ class MailboxDashBoardController extends ReloadableController {
@override
Future<void> injectFirebaseBindings(Session? session, AccountId? accountId) async {
try {
await super.injectFirebaseBindings(session, accountId);
super.injectFirebaseBindings(session, accountId);
_saveFirebaseCacheInteractor = Get.find<SaveFirebaseCacheInteractor>();
NotificationService.initializeNotificationService(
onDidReceiveNotificationResponse);
await NotificationService.initializeNotificationService();
NotificationService.onTokenRefresh.listen((token) {
_saveFirebaseCacheInteractor?.execute(FirebaseDto(token));
});
@@ -18,17 +18,17 @@ class DefaultFirebaseOptions {
case TargetPlatform.macOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for macos - '
'you can reconfigure this by running the FlutterFire CLI again.',
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
@@ -66,4 +66,4 @@ class DefaultFirebaseOptions {
iosClientId: dotenv.get('FIREBASE_IOS_CLIENT_ID', fallback: ''),
iosBundleId: dotenv.get('FIREBASE_IOS_BUNDLE_ID', fallback: ''),
);
}
}
@@ -1,36 +1,19 @@
import 'dart:async';
import 'dart:io';
import 'package:core/utils/app_logger.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:model/firebase/firebase_dto.dart';
import 'package:tmail_ui_user/features/push_notification/domain/usecases/save_firebase_cache_interactor.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/firebase_options.dart';
import 'notification_strings.dart';
final StreamController<NotificationResponse?> selectNotificationStream =
StreamController<NotificationResponse?>.broadcast();
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await dotenv.load(fileName: 'env.file');
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await NotificationService.displayPushNotification(message);
}
@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {
//handle action
}
void onDidReceiveNotificationResponse(
NotificationResponse details,
) {
selectNotificationStream.add(details);
log('firebaseMessagingBackgroundHandler: ${message.data}');
}
class NotificationService {
@@ -42,53 +25,20 @@ class NotificationService {
static get _firebaseMessaging => FirebaseMessaging.instance;
static get _flutterLocalNotificationsPlugin =>
FlutterLocalNotificationsPlugin();
static Stream<String> get onTokenRefresh => _firebaseMessaging.onTokenRefresh;
static bool _isFlutterLocalNotificationsInitialized = false;
static Future<void> initializeNotificationService(
Function(NotificationResponse)? onDidReceiveNotificationResponse,
) async {
static Future<void> initializeNotificationService() async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
if (_isFlutterLocalNotificationsInitialized) return;
final _saveFirebaseCacheInteractor = Get.find<SaveFirebaseCacheInteractor>();
final token = await _firebaseMessaging.getToken();
_saveFirebaseCacheInteractor.execute(FirebaseDto(token));
await _initFirebaseMessaging();
await _flutterLocalNotificationsPlugin.initialize(
InitializationSettings(
android: androidInitializationSettings,
iOS: iosInitializationSettings,
),
onDidReceiveNotificationResponse: onDidReceiveNotificationResponse,
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
);
await _requestPermissions();
await _createNotificationChannels();
_listenNotificationActionStream();
_isFlutterLocalNotificationsInitialized = true;
}
static Future<void> displayPushNotification(
RemoteMessage notification,
) async {
try {
await _flutterLocalNotificationsPlugin.show(
createUniqueId,
channelName,
notification.data.toString(),
pushNotificationDetails,
);
} catch (e) {
debugPrint(e.toString());
}
}
static Future<void> cancelAllNotifications() async {
await _flutterLocalNotificationsPlugin.cancelAll();
}
static Future<void> _initFirebaseMessaging() async {
FirebaseMessaging.onMessage.listen(_handleIncomingForegroundNotification);
FirebaseMessaging.onMessageOpenedApp.listen(_handleOpenedAppNotification);
@@ -97,52 +47,11 @@ class NotificationService {
static Future<void> _handleIncomingForegroundNotification(
RemoteMessage remoteMessage,
) async {
await displayPushNotification(remoteMessage);
log('firebaseMessagingForegroundHandler: ${remoteMessage.data}');
}
static void _handleOpenedAppNotification(RemoteMessage remoteMessage) {}
static Future<void> _requestPermissions() async {
if (Platform.isAndroid) {
await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.requestPermission();
} else {
await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
}
static Future<void> _listenNotificationActionStream() async {
selectNotificationStream.stream
.listen((event) => event)
.onData((data) async {
switch (data?.notificationResponseType) {
case NotificationResponseType.selectedNotification:
break;
case NotificationResponseType.selectedNotificationAction:
break;
default:
}
});
}
static Future<void> _createNotificationChannels() async {
await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(androidChannel);
}
static Future<void> deleteToken() async => _firebaseMessaging.deleteToken();
}
int get createUniqueId =>
DateTime.now().millisecondsSinceEpoch.remainder(100000);
@@ -1,54 +0,0 @@
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
const channelId = 'team_mail_channel_id';
const channelKey = 'team_mail_channel_key';
const channelName = 'Team Mail notifications';
const channelDescription = 'Team Mail notifications';
final iosInitializationSettings = DarwinInitializationSettings(
notificationCategories: [
DarwinNotificationCategory(
channelId,
actions: <DarwinNotificationAction>[
DarwinNotificationAction.plain(
channelKey,
channelName,
options: {
DarwinNotificationActionOption.foreground,
},
),
],
),
],
onDidReceiveLocalNotification:
(int id, String? title, String? body, String? payload) {},
);
const androidInitializationSettings =
AndroidInitializationSettings('background');
const androidChannel = AndroidNotificationChannel(
channelId,
channelName,
description: channelDescription,
importance: Importance.max,
enableLights: true,
);
const pushNotificationDetails = NotificationDetails(
android: AndroidNotificationDetails(
channelId,
channelName,
channelDescription: channelDescription,
visibility: NotificationVisibility.public,
importance: Importance.max,
ledOnMs: 100,
ledOffMs: 1000,
category: AndroidNotificationCategory.message,
),
iOS: DarwinNotificationDetails(
presentSound: true,
presentAlert: true,
presentBadge: true,
),
);