25-10-6/1

This commit is contained in:
Hamza-Ayed
2025-10-05 23:45:18 +03:00
parent f5dfe2c0fe
commit de84662e02
18 changed files with 590 additions and 451 deletions

View File

@@ -25,6 +25,7 @@ import '../functions/audio_record1.dart';
import '../home/map_passenger_controller.dart';
import 'access_token.dart';
import 'local_notification.dart';
import 'notification_service.dart';
class FirebaseMessagesController extends GetxController {
final fcmToken = FirebaseMessaging.instance;
@@ -73,29 +74,6 @@ class FirebaseMessagesController extends GetxController {
? Get.find<NotificationController>()
: Get.put(NotificationController());
Future getTokens() async {
String? basicAuthCredentials =
await storage.read(key: BoxName.basicAuthCredentials);
var res = await http.post(
Uri.parse(AppLink.getTokens),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
body: {},
);
var jsonResponse = jsonDecode(res.body);
if (jsonResponse['status'] == 'success') {
dataTokens = jsonResponse['data'];
for (var i = 0; i < dataTokens.length; i++) {
tokens.add(jsonResponse['data'][i]['token']);
}
box.write(BoxName.tokens, tokens);
} else {
Get.defaultDialog(title: "Warning", middleText: "Server Error");
}
}
Future getToken() async {
fcmToken.getToken().then((token) {
// Log.print('fcmToken: ${token}');
@@ -202,7 +180,7 @@ class FirebaseMessagesController extends GetxController {
passengerDialog(message.notification!.body!);
update();
} else if (message.notification!.title! == 'Trip is Begin'.tr) {
} else if (message.notification!.title! == 'Trip is Begin') {
if (Platform.isAndroid) {
notificationController.showNotification(
'Trip is Begin'.tr, ''.tr, 'start');
@@ -256,33 +234,60 @@ class FirebaseMessagesController extends GetxController {
// .searchNewDriverAfterRejectingFromDriver();
);
} else if (message.notification!.title! == 'Driver Finish Trip'.tr) {
var myListString = message.data['DriverList'];
Log.print('myListString: ${myListString}');
var driverList = jsonDecode(myListString) as List<dynamic>;
Log.print('driverList: ${driverList}');
if (Platform.isAndroid) {
notificationController.showNotification(
"Driver Finish Trip".tr,
'you will pay to Driver'.tr + ' ${driverList[3].toString()} \$'.tr,
'tone1');
// الخطوة 1: استقبل البيانات وتحقق من وجودها
final rawData = message.data['DriverList'];
List<dynamic> driverList = []; // ابدأ بقائمة فارغة كإجراء وقائي
// الخطوة 2: قم بفك تشفير البيانات بأمان
if (rawData != null && rawData is String) {
try {
driverList = jsonDecode(rawData);
Log.print('Successfully decoded DriverList: $driverList');
} catch (e) {
Log.print('Error decoding DriverList JSON: $e');
// اترك القائمة فارغة في حالة حدوث خطأ
}
} else {
Log.print('Error: DriverList data is null or not a String.');
}
Get.find<AudioRecorderController>().stopRecording();
if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
box.write(BoxName.passengerWalletTotal, 0);
// الخطوة 3: استخدم البيانات فقط إذا كانت القائمة تحتوي على العناصر المطلوبة
// هذا يمنع خطأ "RangeError" إذا كانت القائمة أقصر من المتوقع
if (driverList.length >= 4) {
if (Platform.isAndroid) {
notificationController.showNotification(
"Driver Finish Trip".tr,
'${'you will pay to Driver'.tr} ${driverList[3].toString()} \$', // تم تحسين طريقة عرض النص
'tone1');
}
Get.find<AudioRecorderController>().stopRecording();
if ((double.tryParse(
box.read(BoxName.passengerWalletTotal).toString()) ??
0) <
0) {
box.write(BoxName.passengerWalletTotal, 0);
}
Get.find<MapPassengerController>().tripFinishedFromDriver();
NotificationController().showNotification(
'Dont forget your personal belongings.'.tr,
'Please make sure you have all your personal belongings and that any remaining fare, if applicable, has been added to your wallet before leaving. Thank you for choosing the Intaleq app'
.tr,
'ding');
Get.to(() => RateDriverFromPassenger(), arguments: {
'driverId': driverList[0].toString(),
'rideId': driverList[1].toString(),
'price': driverList[3].toString()
});
} else {
Log.print(
'Error: Decoded driverList does not have enough elements. Received: $driverList');
// هنا يمكنك عرض رسالة خطأ للمستخدم إذا لزم الأمر
}
print(333);
Get.find<MapPassengerController>().tripFinishedFromDriver();
NotificationController().showNotification(
'Dont forget your personal belongings.'.tr,
'Please make sure you have all your personal belongings and that any remaining fare, if applicable, has been added to your wallet before leaving. Thank you for choosing the Intaleq app'
.tr,
'ding');
print(267);
Get.to(() => RateDriverFromPassenger(), arguments: {
'driverId': driverList[0].toString(),
'rideId': driverList[1].toString(),
'price': driverList[3].toString()
});
} else if (message.notification!.title! == "Finish Monitor".tr) {
Get.defaultDialog(
titleStyle: AppStyle.title,
@@ -423,12 +428,21 @@ class FirebaseMessagesController extends GetxController {
confirm: MyElevatedButton(
title: 'Ok I will go now.'.tr,
onPressed: () {
sendNotificationToPassengerToken(
'Hi ,I will go now',
'I will go now'.tr,
Get.find<MapPassengerController>().driverToken,
[],
'ding.wav');
// sendNotificationToPassengerToken(
// 'Hi ,I will go now',
// 'I will go now'.tr,
// Get.find<MapPassengerController>().driverToken,
// [],
// 'ding');
NotificationService.sendNotification(
target:
Get.find<MapPassengerController>().driverToken.toString(),
title: 'Hi ,I will go now'.tr,
body: 'I will go now'.tr,
isTopic: false, // Important: this is a token
tone: 'ding',
driverList: [],
);
Get.find<MapPassengerController>()
.startTimerDriverWaitPassenger5Minute();
@@ -487,57 +501,57 @@ class FirebaseMessagesController extends GetxController {
));
}
void sendNotificationAll(String title, body, tone) async {
// Get the token you want to subtract.
String token = box.read(BoxName.tokenFCM);
tokens = box.read(BoxName.tokens);
// Subtract the token from the list of tokens.
tokens.remove(token);
// void sendNotificationAll(String title, body, tone) async {
// // Get the token you want to subtract.
// String token = box.read(BoxName.tokenFCM);
// tokens = box.read(BoxName.tokens);
// // Subtract the token from the list of tokens.
// tokens.remove(token);
// Save the list of tokens back to the box.
// box.write(BoxName.tokens, tokens);
tokens = box.read(BoxName.tokens);
for (var i = 0; i < tokens.length; i++) {
http
.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=${AK.serverAPI}'
},
body: jsonEncode({
'message': {
'token': token,
'notification': {
'title': title,
'body': body,
},
// 'data': {
// 'DriverList': jsonEncode(data),
// },
'android': {
'priority': 'HIGH ', // Set priority to high
'notification': {
'sound': tone,
},
},
'apns': {
'headers': {
'apns-priority': '10', // Set APNs priority to 10
},
'payload': {
'aps': {
'sound': tone,
},
},
},
},
}),
)
.whenComplete(() {})
.catchError((e) {});
}
}
// // Save the list of tokens back to the box.
// // box.write(BoxName.tokens, tokens);
// tokens = box.read(BoxName.tokens);
// for (var i = 0; i < tokens.length; i++) {
// http
// .post(
// Uri.parse('https://fcm.googleapis.com/fcm/send'),
// headers: <String, String>{
// 'Content-Type': 'application/json',
// 'Authorization': 'key=${AK.serverAPI}'
// },
// body: jsonEncode({
// 'message': {
// 'token': token,
// 'notification': {
// 'title': title,
// 'body': body,
// },
// // 'data': {
// // 'DriverList': jsonEncode(data),
// // },
// 'android': {
// 'priority': 'HIGH ', // Set priority to high
// 'notification': {
// 'sound': tone,
// },
// },
// 'apns': {
// 'headers': {
// 'apns-priority': '10', // Set APNs priority to 10
// },
// 'payload': {
// 'aps': {
// 'sound': tone,
// },
// },
// },
// },
// }),
// )
// .whenComplete(() {})
// .catchError((e) {});
// }
// }
// for (var i = 0; i < tokens.length; i++) {
// http
@@ -566,166 +580,166 @@ class FirebaseMessagesController extends GetxController {
// }
// }
late String serviceAccountKeyJson;
// late String serviceAccountKeyJson;
// '{"type": "service_account", "project_id": "intaleq-d48a7", "private_key_id": "d63a627dad96d0050c08a76c2920b1e48ddc4d38", "private_key": "-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHgHWUIlGskFWT\\nkjBvSiAYzXz51NbyMtqlvq1rZaiokd/yzqcEsjgxcAEGap93gRu72cuJ7QzDOpec\\nXSmhQwaGrdDyGyuS5x8nBa9ea3QEUGKjk975OhgIDoaIX2YHjah+jf/p3CPvwovC\\n+qypLsErv5DtcFfKtHkL+Z8gKJojU3p0gP2cVLHlhodGG4767w1f70fIv5LmQRHh\\nE0x5GgjO7MfA1CJewgHDWzj9GTuTd9o3G5nF6ojn8H1EOWminNDrsHAagsplY7iV\\nNmdvGoIAg2kRt66y5k4Li7EiH3e2ILvomGvUe3ahxBTc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lbv3zJUQCVUxUQWxvNduaCT44qhnAV\\nv13TKR78xGwqcxyQZHXo+VrYmaRMTn1bGcQrb/WvAoGAIWUnnGQsvf6SwPQ/7gXC\\nVAq4i3E+coLStVyPK552HVorKa7J+TQnNBGHjCaQhxfCgp59/4qeT5AizzQaMhuS\\noGiUwGeo4RY4A1EEGoUpUk3zWZfC+bAjHVDyIjfN0YfxobL6Sh/97N68PMzb6ppq\\nybvddSGGsqZgucSxkEhIdTw=\\n-----END PRIVATE KEY-----\\n", "client_email": "firebase-adminsdk-fbsvc@intaleq-d48a7.iam.gserviceaccount.com", "client_id": "100558924056484926665", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40intaleq-d48a7.iam.gserviceaccount.com", "universe_domain": "googleapis.com"}';
@override
Future<void> onInit() async {
super.onInit();
try {
var encryptedKey = Env.privateKeyFCM;
// Log.print('encryptedKey: ${encryptedKey}');
serviceAccountKeyJson =
EncryptionHelper.instance.decryptData(encryptedKey);
// Log.print('serviceAccountKeyJson: ${serviceAccountKeyJson}');
} catch (e) {
print('🔴 Error decrypting FCM key: $e');
}
// try {
// // var encryptedKey = Env.privateKeyFCM;
// // // Log.print('encryptedKey: ${encryptedKey}');
// // serviceAccountKeyJson =
// // EncryptionHelper.instance.decryptData(encryptedKey);
// // Log.print('serviceAccountKeyJson: ${serviceAccountKeyJson}');
// } catch (e) {
// print('🔴 Error decrypting FCM key: $e');
// }
}
Future<void> sendNotificationToDriverMAP(
String title, String body, String token, List<String> data, String tone,
{int retryCount = 1}) async {
try {
if (serviceAccountKeyJson.isEmpty) {
print("🔴 Error: Service Account Key is empty");
return;
}
// Future<void> sendNotificationToDriverMAP(
// String title, String body, String token, List<String> data, String tone,
// {int retryCount = 1}) async {
// try {
// if (serviceAccountKeyJson.isEmpty) {
// print("🔴 Error: Service Account Key is empty");
// return;
// }
// Initialize AccessTokenManager
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// Log.print(
// 'accessTokenManager: ${accessTokenManager.serviceAccountJsonKey}');
// // Initialize AccessTokenManager
// final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// // Log.print(
// // 'accessTokenManager: ${accessTokenManager.serviceAccountJsonKey}');
// Obtain an OAuth 2.0 access token
final accessToken = await accessTokenManager.getAccessToken();
// Log.print('accessToken: ${accessToken}');
// // Obtain an OAuth 2.0 access token
// final accessToken = await accessTokenManager.getAccessToken();
// // Log.print('accessToken: ${accessToken}');
// Send the notification
final response = await http.post(
Uri.parse(
'https://fcm.googleapis.com/v1/projects/intaleq-d48a7/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode({
'message': {
'token': token,
'notification': {
'title': title,
'body': body,
},
'data': {
'DriverList': jsonEncode(data),
},
'android': {
'priority': 'HIGH ', // Set priority to high
'notification': {
'sound': tone,
},
},
'apns': {
'headers': {
'apns-priority': '10', // Set APNs priority to 10
},
'payload': {
'aps': {
'sound': tone,
},
},
},
},
}),
);
// // Send the notification
// final response = await http.post(
// Uri.parse(
// 'https://fcm.googleapis.com/v1/projects/intaleq-d48a7/messages:send'),
// headers: <String, String>{
// 'Content-Type': 'application/json',
// 'Authorization': 'Bearer $accessToken',
// },
// body: jsonEncode({
// 'message': {
// 'token': token,
// 'notification': {
// 'title': title,
// 'body': body,
// },
// 'data': {
// 'DriverList': jsonEncode(data),
// },
// 'android': {
// 'priority': 'HIGH ', // Set priority to high
// 'notification': {
// 'sound': tone,
// },
// },
// 'apns': {
// 'headers': {
// 'apns-priority': '10', // Set APNs priority to 10
// },
// 'payload': {
// 'aps': {
// 'sound': tone,
// },
// },
// },
// },
// }),
// );
if (response.statusCode == 200) {
print(
'Notification sent successfully. Status code: ${response.statusCode}');
// print('Response token: ${token}');
} else {
print(
'Failed to send notification. Status code: ${response.statusCode}');
print('Response body: ${response.body}');
if (retryCount > 0) {
print('Retrying... Attempts remaining: $retryCount');
await Future.delayed(
Duration(seconds: 2)); // Optional delay before retrying
return sendNotificationToDriverMAP(title, body, token, data, tone,
retryCount: retryCount - 1);
}
}
} catch (e) {
print('Error sending notification: $e');
if (retryCount > 0) {
print('Retrying... Attempts remaining: $retryCount');
await Future.delayed(
Duration(seconds: 2)); // Optional delay before retrying
return sendNotificationToDriverMAP(title, body, token, data, tone,
retryCount: retryCount - 1);
}
}
}
// if (response.statusCode == 200) {
// print(
// 'Notification sent successfully. Status code: ${response.statusCode}');
// // print('Response token: ${token}');
// } else {
// print(
// 'Failed to send notification. Status code: ${response.statusCode}');
// print('Response body: ${response.body}');
// if (retryCount > 0) {
// print('Retrying... Attempts remaining: $retryCount');
// await Future.delayed(
// Duration(seconds: 2)); // Optional delay before retrying
// return sendNotificationToDriverMAP(title, body, token, data, tone,
// retryCount: retryCount - 1);
// }
// }
// } catch (e) {
// print('Error sending notification: $e');
// if (retryCount > 0) {
// print('Retrying... Attempts remaining: $retryCount');
// await Future.delayed(
// Duration(seconds: 2)); // Optional delay before retrying
// return sendNotificationToDriverMAP(title, body, token, data, tone,
// retryCount: retryCount - 1);
// }
// }
// }
void sendNotificationToPassengerToken(
String title, body, token, List<String> map, String tone) async {
try {
if (serviceAccountKeyJson.isEmpty) {
print("🔴 Error: Service Account Key is empty");
return;
}
// Initialize AccessTokenManager
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// void sendNotificationToPassengerToken(
// String title, body, token, List<String> map, String tone) async {
// try {
// if (serviceAccountKeyJson.isEmpty) {
// print("🔴 Error: Service Account Key is empty");
// return;
// }
// // Initialize AccessTokenManager
// final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// Obtain an OAuth 2.0 access token
final accessToken = await accessTokenManager.getAccessToken();
// Log.print('accessToken: ${accessToken}');
// // Obtain an OAuth 2.0 access token
// final accessToken = await accessTokenManager.getAccessToken();
// // Log.print('accessToken: ${accessToken}');
// Send the notification
final response = await http.post(
Uri.parse(
'https://fcm.googleapis.com/v1/projects/intaleq-d48a7/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode({
'message': {
'token': token,
'notification': {
'title': title,
'body': body,
},
'android': {
'priority': 'HIGH ', // Set priority to high
'notification': {
'sound': tone,
},
},
'apns': {
'headers': {
'apns-priority': '10', // Set APNs priority to 10
},
'payload': {
'aps': {
'sound': tone,
},
},
},
},
}),
);
// // Send the notification
// final response = await http.post(
// Uri.parse(
// 'https://fcm.googleapis.com/v1/projects/intaleq-d48a7/messages:send'),
// headers: <String, String>{
// 'Content-Type': 'application/json',
// 'Authorization': 'Bearer $accessToken',
// },
// body: jsonEncode({
// 'message': {
// 'token': token,
// 'notification': {
// 'title': title,
// 'body': body,
// },
// 'android': {
// 'priority': 'HIGH ', // Set priority to high
// 'notification': {
// 'sound': tone,
// },
// },
// 'apns': {
// 'headers': {
// 'apns-priority': '10', // Set APNs priority to 10
// },
// 'payload': {
// 'aps': {
// 'sound': tone,
// },
// },
// },
// },
// }),
// );
if (response.statusCode == 200) {
print('✅ Notification sent successfully!');
} else {
print(
'🔴 Failed to send notification. Status code: ${response.statusCode}');
print('Response body: ${response.body}');
}
} catch (e) {
print('🔴 Error sending notification: $e');
}
}
// if (response.statusCode == 200) {
// print('✅ Notification sent successfully!');
// } else {
// print(
// '🔴 Failed to send notification. Status code: ${response.statusCode}');
// print('Response body: ${response.body}');
// }
// } catch (e) {
// print('🔴 Error sending notification: $e');
// }
// }
}
class DriverTipWidget extends StatelessWidget {