You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mohemm-flutter-app/lib/classes/notifications.dart

257 lines
9.7 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
// import 'package:huawei_hmsavailability/huawei_hmsavailability.dart';
import 'package:huawei_push/huawei_push.dart' as huawei_push;
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/chat_call_kit.dart';
import 'package:mohem_flutter_app/classes/date_uitl.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/models/get_notifications_response_model.dart';
import 'package:mohem_flutter_app/ui/notifications/notification_details_page.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:uuid/uuid.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
class AppNotifications {
static final AppNotifications _instance = AppNotifications._internal();
AppNotifications._internal();
factory AppNotifications() => _instance;
// late HmsApiAvailability hmsApiAvailability;
String _huaweiToken = '';
late BuildContext context;
Future<void> requestPermissions() async {
if (Platform.isIOS) {
await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(alert: true, badge: true, sound: true);
} else if (Platform.isAndroid) {
AndroidFlutterLocalNotificationsPlugin? androidImplementation = flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
bool? granted = await androidImplementation?.requestPermission();
if (granted == false) {
if (kDebugMode) {
print("-------------------- Permission Granted ------------------------");
print(granted);
}
await Permission.notification.request();
}
}
}
void init(String? firebaseToken, BuildContext context) async {
this.context = context;
debugPrint("Firebase init");
await requestPermissions();
AppState().setDeviceToken = firebaseToken;
await Permission.notification.isDenied.then((bool value) {
if (value) {
Permission.notification.request();
}
});
await FirebaseMessaging.instance.setAutoInitEnabled(true);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(alert: true, badge: true, sound: true);
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) _handleMessage(initialMessage);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
_handleMessage(message);
});
FirebaseMessaging.onMessageOpenedApp.listen(_handleOpenApp);
FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler);
FirebaseMessaging.instance.onTokenRefresh.listen((String token) {
AppState().setDeviceToken = token;
});
// if (Platform.isAndroid) {
// // await hmsApiAvailability.isHMSAvailable().then((value) async {
// if (!(await Utils.isGoogleServicesAvailable())) {
// huawei_push.Push.enableLogger();
// var result = await huawei_push.Push.setAutoInitEnabled(true);
//
// huawei_push.Push.onNotificationOpenedApp.listen((message) {
// print("onNotificationOpenedApp");
// print(message);
// // newMessage(toFirebaseRemoteMessage(message));
// }, onError: (e) => print(e.toString()));
//
// huawei_push.Push.onMessageReceivedStream.listen((message) {
// print("onMessageReceivedStream");
// print(message);
// // newMessage(toFirebaseRemoteMessage(message));
// }, onError: (e) => print(e.toString()));
// }
// // }).catchError((err) {
// // print(err);
// // });
// }
}
Future<void> initHuaweiPush(Function loginCallback) async {
AppState().setIsHuawei = true;
huawei_push.Push.enableLogger();
huawei_push.Push.getToken("");
var result = await huawei_push.Push.setAutoInitEnabled(true);
debugPrint("HUAWEI PUSH TOKEN RESULT: $result");
huawei_push.Push.onMessageReceivedStream.listen(onMessageReceived);
//huawei_push.Push.registerBackgroundMessageHandler(huaweiBackgroundMessage);
bool backgroundMessageHandler = await huawei_push.Push.registerBackgroundMessageHandler(huaweiBackgroundMessage);
debugPrint("Huawei Background Message Handler Registered: $backgroundMessageHandler");
initTokenStream(loginCallback);
}
void onMessageReceived(huawei_push.RemoteMessage remoteMessage) {
dynamic data = remoteMessage.data;
if (data != null) {
huawei_push.Push.localNotification(
<String, String>{
huawei_push.HMSLocalNotificationAttr.TITLE: 'DataMessage Received',
huawei_push.HMSLocalNotificationAttr.MESSAGE: data,
},
);
print('onMessageReceived' + 'Data: $data');
RemoteMessage message = RemoteMessage(
data: jsonDecode(remoteMessage.data!),
);
_handleMessage(message);
} else {
print('onMessageReceived' + 'No data is present.');
}
}
// HUAWEI PUSH TOKEN IMPLEMENTATION
void _onTokenEvent(String event) {
_huaweiToken = event;
AppState().setHuaweiPushToken = _huaweiToken;
debugPrint("HUAWEI PUSH TOKEN: $_huaweiToken");
}
void _onTokenError(Object error) {
debugPrint("HUAWEI PUSH TOKEN ERROR: $error");
Utils.hideLoading(context);
}
void initTokenStream(Function loginCallback) {
huawei_push.Push.getTokenStream.listen(_onTokenEvent, onError: _onTokenError).onData((data) async {
AppState().setHuaweiPushToken = data;
debugPrint("HUAWEI PUSH TOKEN: $data");
loginCallback();
});
}
void _handleMessage(RemoteMessage message) {
Utils.saveStringFromPrefs("isAppOpendByChat", "false");
GetNotificationsResponseModel notification = GetNotificationsResponseModel();
if (message.notification != null) {
notification.createdOn = DateUtil.getMonthDayYearDateFormatted(DateTime.now());
notification.messageTypeData = message.data['picture'];
notification.message = message.data['message'];
notification.notificationType = message.data["NotificationType"].toString();
if (message.data["NotificationType"] == "2") {
notification.videoURL = message.data["VideoUrl"];
}
Future.delayed(Duration(seconds: 5), () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => NotificationsDetailsPage(
notification: notification,
),
),
);
});
}
if (message.data.isNotEmpty && message.data["messageType"] == 'chat') {
Utils.saveStringFromPrefs("isAppOpendByChat", "true");
Utils.saveStringFromPrefs("notificationData", message.data["user_chat_history_response"].toString());
} else if (message.data.isNotEmpty && message.data["messageType"] == 'call') {
if (Platform.isAndroid) {
ChatVoipCall().showCallkitIncoming(uuid: const Uuid().v4(), data: message);
}
}
}
void _handleOpenApp(RemoteMessage message) {
if (message.data.isNotEmpty && message.data["type"] == 'chat') {
Utils.saveStringFromPrefs("isAppOpendByChat", "true");
Utils.saveStringFromPrefs("notificationData", message.data["user_chat_history_response"].toString());
} else {
GetNotificationsResponseModel notification = GetNotificationsResponseModel();
notification.createdOn = DateUtil.getMonthDayYearDateFormatted(DateTime.now());
notification.messageTypeData = message.data['picture'];
notification.message = message.data['message'];
notification.notificationType = message.data["NotificationType"].toString();
if (message.data["NotificationType"] == "2") {
notification.videoURL = message.data["VideoUrl"];
}
Future.delayed(Duration(seconds: 5), () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => NotificationsDetailsPage(
notification: notification,
),
),
);
});
}
}
}
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description: 'This channel is used for important notifications.', // description
importance: Importance.high,
);
@pragma('vm:entry-point')
Future<void> backgroundMessageHandler(RemoteMessage message) async {
await Firebase.initializeApp();
if (message.data.isNotEmpty && message.data["messageType"] == 'chat') {
Utils.saveStringFromPrefs("isAppOpendByChat", "false");
Utils.saveStringFromPrefs("notificationData", message.data["user_chat_history_response"].toString());
} else if (message.data.isNotEmpty && message.data["messageType"] == 'call') {
if (Platform.isAndroid) {
ChatVoipCall().showCallkitIncoming(uuid: const Uuid().v4(), data: message, background: true);
}
}
}
void huaweiBackgroundMessage(huawei_push.RemoteMessage remoteMessage) async {
dynamic data = remoteMessage.data;
if (data != null) {
print(
'Background message is received, sending local notification.',
);
huawei_push.Push.localNotification(
<String, String>{
huawei_push.HMSLocalNotificationAttr.TITLE: '[Headless] DataMessage Received',
huawei_push.HMSLocalNotificationAttr.MESSAGE: data,
},
);
} else {
print(
'Background message is received. There is no data in the message.',
);
}
}