fix validJsonFromString

This commit is contained in:
Jonatas Antunes Messias 2024-06-20 11:08:16 -03:00
parent f3b85a39d9
commit bb0a950415
3 changed files with 80 additions and 75 deletions

File diff suppressed because one or more lines are too long

View File

@ -26,7 +26,7 @@ class PushNotificationService {
_listenToForegroundMessages(context); _listenToForegroundMessages(context);
_listenToBackgroundMessages(); _listenToBackgroundMessages();
_listenToNotificationClicks(context); _listenToNotificationClicks(context);
await _updateDeviceToken(); await updateDeviceToken();
} }
Future<void> _requestPermissions() async { Future<void> _requestPermissions() async {
@ -42,18 +42,45 @@ class PushNotificationService {
} }
} }
Map<String, dynamic> validJsonFromString(String? string) { Map<String, dynamic> validJsonFromString(String? jsonString) {
// Switch(string != null || string.isNotEmpty) { if (jsonString == null || jsonString.isEmpty) {
// case true: return {};
// debugPrint() }
// break;
// } // Passo 1 e 2: Adiciona aspas duplas em torno das chaves e valores que não estão corretamente delimitados
String stringValidate = string! String correctedJson = jsonString.replaceAllMapped(
.replaceAllMapped(RegExp(r'(\w+):'), RegExp(r'([a-zA-Z0-9_]+)\s*:\s*([^",\}\]]+)'), (match) {
(match) => '"${match[1]}":') // Enclose keys in double quotes var key = '"${match[1]!}"'; // Chaves sempre recebem aspas
.replaceAllMapped(RegExp(r':\s*(\w+)'), (match) => ': "${match[1]}"'); var value = match[2]!.trim();
Map<String, dynamic> json = jsonDecode(stringValidate);
return json; // Verifica se o valor é uma string (não numérica, booleana, nula ou objeto JSON)
bool isStringValue = !RegExp(r'^-?\d+(\.\d+)?$').hasMatch(value) &&
value != 'true' &&
value != 'false' &&
value != 'null' &&
!value.startsWith('{') &&
!value.endsWith('}');
// Adiciona aspas duplas em torno do valor se for uma string
String quotedValue = isStringValue ? '"$value"' : value;
return '$key: $quotedValue';
});
// Passo 3: Tratar corretamente strings JSON aninhadas
correctedJson =
correctedJson.replaceAllMapped(RegExp(r'"{([^"]+)}"'), (match) {
// Remove as aspas duplas extras em torno de objetos JSON aninhados
return '{${match[1]!}}';
});
try {
// Passo 4: Decodificar o JSON corrigido
return jsonDecode(correctedJson);
} catch (e) {
print('Error decoding JSON: $e');
return {};
}
} }
void _initializeLocalNotifications( void _initializeLocalNotifications(
@ -78,17 +105,9 @@ class PushNotificationService {
onDidReceiveNotificationResponse: (NotificationResponse response) async { onDidReceiveNotificationResponse: (NotificationResponse response) async {
debugPrint('Response payload:${response.payload}'); debugPrint('Response payload:${response.payload}');
if (response.payload != null) { if (response.payload != null) {
// Preprocess the payload to ensure it's in a valid JSON format
String validJsonPayload = response.payload!
.replaceAllMapped(RegExp(r'(\w+):'),
(match) => '"${match[1]}":') // Enclose keys in double quotes
.replaceAllMapped(
RegExp(r':\s*(\w+)'),
(match) =>
': "${match[1]}"'); // Enclose string values in double quotes
try { try {
Map<String, dynamic> message = jsonDecode(validJsonPayload); Map<String, dynamic> message =
validJsonFromString(response.payload!);
debugPrint('Notification payload: $message'); debugPrint('Notification payload: $message');
_handleNotificationClick(message); _handleNotificationClick(message);
} catch (e) { } catch (e) {
@ -136,48 +155,58 @@ class PushNotificationService {
}); });
} }
Future<void> _updateDeviceToken() async { void configureTokenRefresh() {
_firebaseMessaging.onTokenRefresh.listen(_handleTokenUpdate).onError((err) {
debugPrint("Error refreshing token: $err");
});
}
Future<void> _updateToken(String token) async {
FFAppState().token = token;
final ApiCallResponse? response = await _updateTokenOnServer(token);
if (_isTokenUpdateSuccessful(response)) {
debugPrint('Token updated successfully on server. Token: $token');
} else {
debugPrint('Error updating token on server');
}
}
Future<void> _handleTokenUpdate(String newToken) async {
debugPrint('Token refreshed: $newToken');
await _updateToken(newToken);
}
Future<void> updateDeviceToken() async {
configureTokenRefresh();
final NotificationSettings settings = final NotificationSettings settings =
await _requestNotificationPermission(); await _requestNotificationPermission();
await _fetchAndLogApnsToken(settings); await _fetchAndLogApnsToken(settings);
final String? deviceToken = await FirebaseMessaging.instance.getToken(); final String? deviceToken = await _firebaseMessaging.getToken();
if (deviceToken == null) { if (deviceToken != null) {
debugPrint('Failed to get Firebase Messaging token');
return;
}
debugPrint('Push Messaging token: $deviceToken'); debugPrint('Push Messaging token: $deviceToken');
FFAppState().token = deviceToken; await _updateToken(deviceToken);
final ApiCallResponse? updTokenResponse =
await _updateTokenOnServer(deviceToken);
if (_isTokenUpdateSuccessful(updTokenResponse)) {
debugPrint('Token updated successfully');
} else { } else {
debugPrint('Error updating token'); debugPrint('Failed to get Firebase Messaging token');
} }
} }
Future<NotificationSettings> _requestNotificationPermission() async { Future<NotificationSettings> _requestNotificationPermission() async {
final NotificationSettings settings = final NotificationSettings settings =
await _firebaseMessaging.requestPermission(); await _firebaseMessaging.requestPermission();
if (settings.authorizationStatus == AuthorizationStatus.authorized) { debugPrint(settings.authorizationStatus == AuthorizationStatus.authorized
debugPrint('User granted permission'); ? 'User granted permission'
} else { : 'User declined or has not accepted permission');
debugPrint('User declined or has not accepted permission');
}
return settings; return settings;
} }
Future<void> _fetchAndLogApnsToken(NotificationSettings settings) async { Future<void> _fetchAndLogApnsToken(NotificationSettings settings) async {
if (settings.authorizationStatus == AuthorizationStatus.authorized) { if (settings.authorizationStatus == AuthorizationStatus.authorized) {
final String? apnsToken = await _firebaseMessaging.getAPNSToken(); final String? apnsToken = await _firebaseMessaging.getAPNSToken();
if (apnsToken != null) { debugPrint(apnsToken != null
debugPrint('APNS Token: $apnsToken'); ? 'APNS Token: $apnsToken'
} else { : 'Failed to get APNS token');
debugPrint('Failed to get APNS token');
}
} }
} }
@ -251,6 +280,7 @@ class NotificationHandler {
break; break;
default: default:
debugPrint('Notification type not recognized'); debugPrint('Notification type not recognized');
_showVisitRequestDialog(message, context);
} }
} }
@ -262,7 +292,7 @@ class NotificationHandler {
return Dialog( return Dialog(
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
child: VisitRequestTemplateComponentWidget( child: VisitRequestTemplateComponentWidget(
name: message['nome'] ?? 'Unknown', name: message['nomevisita'] ?? 'Unknown',
reason: message['motivo'] ?? 'Unknown', reason: message['motivo'] ?? 'Unknown',
message: message['mensagem'] ?? 'Unknown', message: message['mensagem'] ?? 'Unknown',
document: message['documento'] ?? 'Unknown', document: message['documento'] ?? 'Unknown',

View File

@ -37,33 +37,8 @@ class _HomePageWidgetState extends State<HomePageWidget> {
_model = createModel(context, () => HomePageModel()); _model = createModel(context, () => HomePageModel());
SchedulerBinding.instance.addPostFrameCallback((_) async { SchedulerBinding.instance.addPostFrameCallback((_) async {
// final pushNotificationService = PushNotificationService();
// await pushNotificationService.initialize(context);
// NotificationHandler().listenToNotifications(context);
// Inicializa o serviço de notificação
await PushNotificationService().initialize(context); await PushNotificationService().initialize(context);
// Opcional: Defina ações específicas quando uma notificação é recebida
// PushNotificationService().onMessage.listen((message) {
// // Implemente sua lógica aqui, por exemplo, navegar para uma nova página
// // ou mostrar um diálogo com a mensagem da notificação
// showDialog(
// context: context,
// builder: (context) => AlertDialog(
// title: Text("Notificação Recebida"),
// content: Text(message),
// actions: [
// TextButton(
// onPressed: () => Navigator.of(context).pop(),
// child: Text("OK"),
// ),
// ],
// ),
// );
// });
// });
if (FFAppState().cliUUID == '') { if (FFAppState().cliUUID == '') {
showModalBottomSheet( showModalBottomSheet(
isScrollControlled: true, isScrollControlled: true,