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);
_listenToBackgroundMessages();
_listenToNotificationClicks(context);
await _updateDeviceToken();
await updateDeviceToken();
}
Future<void> _requestPermissions() async {
@ -42,18 +42,45 @@ class PushNotificationService {
}
}
Map<String, dynamic> validJsonFromString(String? string) {
// Switch(string != null || string.isNotEmpty) {
// case true:
// debugPrint()
// break;
// }
String stringValidate = string!
.replaceAllMapped(RegExp(r'(\w+):'),
(match) => '"${match[1]}":') // Enclose keys in double quotes
.replaceAllMapped(RegExp(r':\s*(\w+)'), (match) => ': "${match[1]}"');
Map<String, dynamic> json = jsonDecode(stringValidate);
return json;
Map<String, dynamic> validJsonFromString(String? jsonString) {
if (jsonString == null || jsonString.isEmpty) {
return {};
}
// Passo 1 e 2: Adiciona aspas duplas em torno das chaves e valores que não estão corretamente delimitados
String correctedJson = jsonString.replaceAllMapped(
RegExp(r'([a-zA-Z0-9_]+)\s*:\s*([^",\}\]]+)'), (match) {
var key = '"${match[1]!}"'; // Chaves sempre recebem aspas
var value = match[2]!.trim();
// 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(
@ -78,17 +105,9 @@ class PushNotificationService {
onDidReceiveNotificationResponse: (NotificationResponse response) async {
debugPrint('Response payload:${response.payload}');
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 {
Map<String, dynamic> message = jsonDecode(validJsonPayload);
Map<String, dynamic> message =
validJsonFromString(response.payload!);
debugPrint('Notification payload: $message');
_handleNotificationClick(message);
} 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 =
await _requestNotificationPermission();
await _fetchAndLogApnsToken(settings);
final String? deviceToken = await FirebaseMessaging.instance.getToken();
if (deviceToken == null) {
debugPrint('Failed to get Firebase Messaging token');
return;
}
debugPrint('Push Messaging token: $deviceToken');
FFAppState().token = deviceToken;
final ApiCallResponse? updTokenResponse =
await _updateTokenOnServer(deviceToken);
if (_isTokenUpdateSuccessful(updTokenResponse)) {
debugPrint('Token updated successfully');
final String? deviceToken = await _firebaseMessaging.getToken();
if (deviceToken != null) {
debugPrint('Push Messaging token: $deviceToken');
await _updateToken(deviceToken);
} else {
debugPrint('Error updating token');
debugPrint('Failed to get Firebase Messaging token');
}
}
Future<NotificationSettings> _requestNotificationPermission() async {
final NotificationSettings settings =
await _firebaseMessaging.requestPermission();
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
debugPrint('User granted permission');
} else {
debugPrint('User declined or has not accepted permission');
}
debugPrint(settings.authorizationStatus == AuthorizationStatus.authorized
? 'User granted permission'
: 'User declined or has not accepted permission');
return settings;
}
Future<void> _fetchAndLogApnsToken(NotificationSettings settings) async {
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
final String? apnsToken = await _firebaseMessaging.getAPNSToken();
if (apnsToken != null) {
debugPrint('APNS Token: $apnsToken');
} else {
debugPrint('Failed to get APNS token');
}
debugPrint(apnsToken != null
? 'APNS Token: $apnsToken'
: 'Failed to get APNS token');
}
}
@ -251,6 +280,7 @@ class NotificationHandler {
break;
default:
debugPrint('Notification type not recognized');
_showVisitRequestDialog(message, context);
}
}
@ -262,7 +292,7 @@ class NotificationHandler {
return Dialog(
backgroundColor: Colors.transparent,
child: VisitRequestTemplateComponentWidget(
name: message['nome'] ?? 'Unknown',
name: message['nomevisita'] ?? 'Unknown',
reason: message['motivo'] ?? 'Unknown',
message: message['mensagem'] ?? 'Unknown',
document: message['documento'] ?? 'Unknown',

View File

@ -37,33 +37,8 @@ class _HomePageWidgetState extends State<HomePageWidget> {
_model = createModel(context, () => HomePageModel());
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);
// 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 == '') {
showModalBottomSheet(
isScrollControlled: true,