59 lines
1.6 KiB
Dart
59 lines
1.6 KiB
Dart
import 'package:firebase_messaging/firebase_messaging.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
import 'package:hoshan/core/routes/route_generator.dart';
|
|
import 'package:hoshan/data/model/ai/bots_model.dart';
|
|
import 'package:hoshan/data/model/chat_args.dart';
|
|
import 'package:hoshan/main.dart';
|
|
|
|
class FirebasApi {
|
|
static final _firebaseMessaging = FirebaseMessaging.instance;
|
|
static Bots? bot;
|
|
static String? fcmToken;
|
|
|
|
static Future<void> initialNotifications() async {
|
|
await refreshToken();
|
|
|
|
initPushNotification();
|
|
}
|
|
|
|
static Future refreshToken() async {
|
|
await _firebaseMessaging.requestPermission();
|
|
|
|
fcmToken = await _firebaseMessaging.getToken();
|
|
|
|
if (kDebugMode) {
|
|
print('fCMToken: $fcmToken');
|
|
}
|
|
}
|
|
|
|
static Future deleteToken() async {
|
|
try {
|
|
await _firebaseMessaging.deleteToken();
|
|
} catch (e) {
|
|
if (kDebugMode) {
|
|
print('Error while firebaseMessaging deleteToken: $e');
|
|
}
|
|
}
|
|
}
|
|
|
|
static void handleMessage(RemoteMessage? message) async {
|
|
if (message == null) return;
|
|
bot = Bots.fromNotification(message.data);
|
|
if (navigatorKey.currentState != null) {
|
|
if (bot!.tool ?? false) {
|
|
navigatorKey.currentContext?.go(Routes.assistant, extra: bot!.id);
|
|
} else {
|
|
navigatorKey.currentContext
|
|
?.go(Routes.chat, extra: ChatArgs(bot: bot!));
|
|
}
|
|
bot = null;
|
|
}
|
|
}
|
|
|
|
static Future initPushNotification() async {
|
|
FirebaseMessaging.instance.getInitialMessage().then(handleMessage);
|
|
FirebaseMessaging.onMessageOpenedApp.listen(handleMessage);
|
|
}
|
|
}
|