import 'dart:convert'; import 'dart:developer'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:hub/app_state.dart'; import 'package:hub/backend/api_requests/api_calls.dart'; import 'package:hub/backend/api_requests/api_manager.dart'; import 'package:hub/components/templates_components/message_notificaion_modal_template_component/message_notification_widget.dart'; import 'package:hub/shared/utils/log_util.dart'; class PushNotification { static final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance; static final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); Future initialize() async { await _requestPermissions(); // Mensagens _backgroundMessage(); _forgroundMessage(); _openMessage(); // Token _refreshToken(); _updateDeviceToken(); } Future _updateDeviceToken() async { try { final String? deviceToken = await _firebaseMessaging.getToken(); if (deviceToken != null) { AppState().token = deviceToken; final ApiCallResponse? response = await PhpGroup.updToken.call(token: AppState().token, devid: AppState().devUUID, useruuid: AppState().userUUID); if (PhpGroup.updToken.error((response?.jsonBody ?? '')) == false) { log('Token Atualizado com Sucesso!'); } else { log('Falha ao Atualizar Token: ${response?.jsonBody}'); } } else { log('Falha ao Pegar Token do Firebase'); } } catch (e, s) { LogUtil.requestAPIFailed("updToken.php", "", "Atualizar Token", e, s); } } Future _requestPermissions() async { NotificationSettings settings = await _firebaseMessaging.requestPermission( alert: true, badge: true, sound: true, provisional: true, criticalAlert: false, carPlay: false, announcement: false ); log('Permisão de Notificação: ${settings.authorizationStatus == AuthorizationStatus.authorized ? "Liberado" : "Negado"}'); } void _backgroundMessage() { FirebaseMessaging.onBackgroundMessage((RemoteMessage message) => _printNotification(message, 'background')); } void _forgroundMessage() { FirebaseMessaging.onMessage.listen((RemoteMessage message) => _printNotification(message, 'forground')); } void _openMessage() { FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) => _processNotification(message)); } void _refreshToken() { _firebaseMessaging.onTokenRefresh.listen((token) => log('Novo Token: $token')); } Future _printNotification(RemoteMessage message, String type) async { print("Tipo da Notificação: $type"); print("Mensagem: $message"); } Future _processNotification(RemoteMessage message) async { switch (message.category) { case 'mensagem': _showMessageNotificationDialog(message.data, AppState().context!, message.notification?.body ?? ''); } } void _showMessageNotificationDialog(Map message, BuildContext context, String extra) { showDialog( useSafeArea: true, barrierDismissible: true, context: context, builder: (BuildContext context) { String localId = ''; try { localId = jsonDecode(message['local'])['CLI_ID']; } catch (e) { localId = message['local']['CLI_ID'].toString(); } return GestureDetector( onTap: () => Navigator.of(context).pop(), child: SizedBox( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: Dialog( backgroundColor: Colors.transparent, child: GestureDetector( onTap: () => Navigator.of(context).pop(), child: SizedBox( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: MessageNotificationModalTemplateComponentWidget( id: localId, from: message['remetente'].toString(), to: message['destinatario'].toString() == 'O' ? 'Morador' : 'Visitante', message: extra.isEmpty ? 'Unknown' : extra.toString(), ), ), ), ), ), ); }, ); } Future _showMessage(RemoteMessage message) async { print("Dados: ${message.data}"); print("From: ${message.from}"); print("Notification: ${message.notification?.body}"); print("Category: ${message.category}"); showDialog( context: AppState().context!, builder: (context) => Dialog( child: Container( child: Text("Notificação"), ), ) ); } }