25-10-5/1

This commit is contained in:
Hamza-Ayed
2025-10-08 13:14:07 +03:00
parent 1cc66029a3
commit 482c1296bc
22 changed files with 770 additions and 559 deletions

View File

@@ -356,8 +356,8 @@ Download the Intaleq app now and enjoy your ride!
'${'before'.tr} *${d['message']['expirationTime'].toString()}*\n\n'
'_*${d['message']['inviteCode'].toString()}*_\n\n'
'${"Install our app:".tr}\n'
'*Android:* https://play.google.com/store/apps/details?id=com.sefer_driver\n\n\n'
'*iOS:* https://apps.apple.com/ae/app/sefer-driver/id6502189302';
'*Android:* https://play.google.com/store/apps/details?id=com.intaleq_driver\n\n\n'
'*iOS:* https://apps.apple.com/st/app/intaleq-driver/id6482995159';
launchCommunication('whatsapp', formattedPhoneNumber, message);
invitePhoneController.clear();
@@ -395,8 +395,8 @@ Download the Intaleq app now and enjoy your ride!
'${'before'.tr} *${d['message']['expirationTime'].toString()}*\n\n'
'_*${d['message']['inviteCode'].toString()}*_\n\n'
'${"Install our app:".tr}\n'
'*Android:* https://play.google.com/store/apps/details?id=com.mobileapp.store.ride\n\n\n'
'*iOS:* https://apps.apple.com/us/app/sefer/id6458734951';
'*Android:* https://play.google.com/store/apps/details?id=com.Intaleq.intaleq\n\n\n'
'*iOS:* https://apps.apple.com/st/app/intaleq-rider/id6748075179';
launchCommunication('whatsapp', formattedPhoneNumber, message);
invitePhoneController.clear();

View File

@@ -26,6 +26,7 @@ import '../../../views/auth/captin/otp_page.dart';
import '../../../views/auth/captin/otp_token_page.dart';
import '../../../views/auth/syria/pending_driver_page.dart';
import '../../firebase/firbase_messge.dart';
import '../../firebase/notification_service.dart';
import '../../functions/encrypt_decrypt.dart';
import '../../functions/package_info.dart';
import '../../functions/secure_storage.dart';
@@ -258,7 +259,7 @@ class LoginDriverController extends GetxController {
update();
await SecurityHelper.performSecurityChecks();
// Log.print('(BoxName.emailDriver): ${box.read(BoxName.emailDriver)}');
// await getJWT();
var res = await CRUD().get(link: AppLink.loginFromGoogleCaptin, payload: {
'email': email ?? 'yet',
'id': driverID,
@@ -328,8 +329,11 @@ class LoginDriverController extends GetxController {
// if (box.read(BoxName.emailDriver).toString() !=
// '963992952235@intaleqapp.com') {
if (token != 'failure') {
if ((jsonDecode(token)['data'][0]['token'].toString()) !=
box.read(BoxName.tokenDriver).toString()) {
var serverData = jsonDecode(token);
if ((serverData['data'][0]['token'].toString()) !=
box.read(BoxName.tokenDriver).toString() ||
serverData['data'][0]['fingerPrint'].toString() !=
fingerPrint.toString()) {
await Get.defaultDialog(
barrierDismissible: false,
title: 'Device Change Detected'.tr,
@@ -534,12 +538,20 @@ class LoginDriverController extends GetxController {
if (token != 'failure') {
if ((jsonDecode(token)['data'][0]['token']) !=
(box.read(BoxName.tokenDriver))) {
Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
'token change'.tr,
'change device'.tr,
(jsonDecode(token)['data'][0]['token']).toString(),
[],
'ding.wav');
// Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
// 'token change'.tr,
// 'change device'.tr,
// (jsonDecode(token)['data'][0]['token']).toString(),
// [],
// 'ding.wav');
NotificationService.sendNotification(
target: (jsonDecode(token)['data'][0]['token']).toString(),
title: 'token change',
body: 'token change'.tr,
isTopic: false, // Important: this is a token
tone: 'cancel',
driverList: [],
);
Get.defaultDialog(
title: 'you will use this device?'.tr,
middleText: '',

View File

@@ -8,6 +8,7 @@ import '../../../constant/box_name.dart';
import '../../../constant/links.dart';
import '../../../main.dart';
import '../../firebase/firbase_messge.dart';
import '../../firebase/notification_service.dart';
import '../../functions/crud.dart';
class OtpVerificationController extends GetxController {
@@ -101,12 +102,20 @@ class OtpVerificationController extends GetxController {
? Get.find<FirebaseMessagesController>()
: Get.put(FirebaseMessagesController());
await fcm.sendNotificationToDriverMAP(
'token change',
'change device'.tr,
ptoken.toString(),
[],
'cancel.wav',
// await fcm.sendNotificationToDriverMAP(
// 'token change',
// 'change device'.tr,
// ptoken.toString(),
// [],
// 'cancel.wav',
// );
await NotificationService.sendNotification(
target: ptoken.toString(),
title: 'token change',
body: 'token change'.tr,
isTopic: false, // Important: this is a token
tone: 'cancel',
driverList: [],
);
Get.offAll(() => HomeCaptain());

View File

@@ -26,6 +26,7 @@ import '../functions/encrypt_decrypt.dart';
import '../functions/face_detect.dart';
import 'access_token.dart';
import 'local_notification.dart';
import 'notification_service.dart';
class FirebaseMessagesController extends GetxController {
final fcmToken = FirebaseMessaging.instance;
@@ -154,12 +155,20 @@ class FirebaseMessagesController extends GetxController {
'VIP Order'.tr, '', 'order', '');
}
MyDialog().getDialog('VIP Order'.tr, 'midTitle', () {
sendNotificationToPassengerToken(
'VIP Order Accepted'.tr,
'The driver accepted your trip'.tr,
driverList[0],
[driverList[1]],
'order');
// sendNotificationToPassengerToken(
// 'VIP Order Accepted'.tr,
// 'The driver accepted your trip'.tr,
// driverList[0],
// [driverList[1]],
// 'order');
NotificationService.sendNotification(
target: driverList[0].toString(),
title: 'VIP Order Accepted'.tr,
body: 'The driver accepted your trip'.tr,
isTopic: false, // Important: this is a token
tone: 'order',
driverList: [],
);
});
// Get.to(const VipOrderPage());
@@ -387,360 +396,360 @@ class FirebaseMessagesController extends GetxController {
// }));
// }
late String serviceAccountKeyJson;
@override
Future<void> onInit() async {
super.onInit();
try {
// getToken();
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');
}
}
// late String serviceAccountKeyJson;
// @override
// Future<void> onInit() async {
// super.onInit();
// try {
// // getToken();
// 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');
// }
// }
void sendNotificationAll(String title, body, tone) async {
// توكني الحالي (لا أرسل لنفسي)
final String myToken = box.read(BoxName.tokenFCM) ?? '';
// اقرأ قائمة كل التوكنات
final List<String> all =
List<String>.from(box.read(BoxName.tokens) ?? const []);
// void sendNotificationAll(String title, body, tone) async {
// // توكني الحالي (لا أرسل لنفسي)
// final String myToken = box.read(BoxName.tokenFCM) ?? '';
// // اقرأ قائمة كل التوكنات
// final List<String> all =
// List<String>.from(box.read(BoxName.tokens) ?? const []);
// استبعد توكنك واحذف الفارغ
final targets = all.where((t) => t.isNotEmpty && t != myToken).toList();
// // استبعد توكنك واحذف الفارغ
// final targets = all.where((t) => t.isNotEmpty && t != myToken).toList();
if (serviceAccountKeyJson.isEmpty) {
print("🔴 Error: Service Account Key is empty");
return;
}
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
final accessToken = await accessTokenManager.getAccessToken();
// if (serviceAccountKeyJson.isEmpty) {
// print("🔴 Error: Service Account Key is empty");
// return;
// }
// final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// final accessToken = await accessTokenManager.getAccessToken();
for (final t in targets) {
// ⚠️ المهم: استخدم t (توكن الهدف)، وليس المتغير myToken
final response = await http.post(
Uri.parse(
'https://fcm.googleapis.com/v1/projects/ride-b1bd8/messages:send'),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode({
'message': {
'token': t,
'notification': {'title': title, 'body': body},
'android': {
'priority': 'HIGH', // القيم الصحيحة: HIGH/NORMAL
'notification': {'sound': tone},
// (اختياري) TTL لتجنّب رسائل قديمة
'ttl': '30s',
},
'apns': {
'headers': {
'apns-priority': '10',
// لو iOS: حدد نوع الدفع
'apns-push-type': 'alert',
},
'payload': {
'aps': {'sound': tone}
},
},
},
}),
);
// for (final t in targets) {
// // ⚠️ المهم: استخدم t (توكن الهدف)، وليس المتغير myToken
// final response = await http.post(
// Uri.parse(
// 'https://fcm.googleapis.com/v1/projects/ride-b1bd8/messages:send'),
// headers: {
// 'Content-Type': 'application/json',
// 'Authorization': 'Bearer $accessToken',
// },
// body: jsonEncode({
// 'message': {
// 'token': t,
// 'notification': {'title': title, 'body': body},
// 'android': {
// 'priority': 'HIGH', // القيم الصحيحة: HIGH/NORMAL
// 'notification': {'sound': tone},
// // (اختياري) TTL لتجنّب رسائل قديمة
// 'ttl': '30s',
// },
// 'apns': {
// 'headers': {
// 'apns-priority': '10',
// // لو iOS: حدد نوع الدفع
// 'apns-push-type': 'alert',
// },
// 'payload': {
// 'aps': {'sound': tone}
// },
// },
// },
// }),
// );
if (response.statusCode != 200) {
// حاول تقرأ الخطأ وتشيل التوكنات التالفة
_handleV1Error(response, badToken: t);
await Future.delayed(const Duration(milliseconds: 50)); // تخفيف ضغط
}
}
}
// if (response.statusCode != 200) {
// // حاول تقرأ الخطأ وتشيل التوكنات التالفة
// _handleV1Error(response, badToken: t);
// await Future.delayed(const Duration(milliseconds: 50)); // تخفيف ضغط
// }
// }
// }
void _handleV1Error(http.Response res, {required String badToken}) {
try {
final body = jsonDecode(res.body);
final err = body['error']?['status']?.toString() ?? '';
// أمثلة شائعة:
if (err.contains('UNREGISTERED') || err.contains('NOT_FOUND')) {
removeInvalidToken(badToken);
} else if (err.contains('INVALID_ARGUMENT')) {
// payload غير صحيح
print(
'⚠️ INVALID_ARGUMENT for $badToken: ${body['error']?['message']}');
} else if (err.contains('RESOURCE_EXHAUSTED') ||
err.contains('QUOTA_EXCEEDED')) {
// تجاوزت الحصة—خفّف السرعة/قسّم الإرسال (FCM v1 له حصة/دقيقة)
// https docs: 600k req/min per project (token bucket)
print('⏳ Throttled by FCM: slow down sending rate.');
} else {
print('FCM v1 error: ${res.statusCode} ${res.body}');
}
} catch (_) {
print('FCM v1 error: ${res.statusCode} ${res.body}');
}
}
// void _handleV1Error(http.Response res, {required String badToken}) {
// try {
// final body = jsonDecode(res.body);
// final err = body['error']?['status']?.toString() ?? '';
// // أمثلة شائعة:
// if (err.contains('UNREGISTERED') || err.contains('NOT_FOUND')) {
// removeInvalidToken(badToken);
// } else if (err.contains('INVALID_ARGUMENT')) {
// // payload غير صحيح
// print(
// '⚠️ INVALID_ARGUMENT for $badToken: ${body['error']?['message']}');
// } else if (err.contains('RESOURCE_EXHAUSTED') ||
// err.contains('QUOTA_EXCEEDED')) {
// // تجاوزت الحصة—خفّف السرعة/قسّم الإرسال (FCM v1 له حصة/دقيقة)
// // https docs: 600k req/min per project (token bucket)
// print('⏳ Throttled by FCM: slow down sending rate.');
// } else {
// print('FCM v1 error: ${res.statusCode} ${res.body}');
// }
// } catch (_) {
// print('FCM v1 error: ${res.statusCode} ${res.body}');
// }
// }
void sendNotificationToPassengerToken(
String title, body, token, List<String> map, String tone,
{int retryCount = 2}) 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,
// {int retryCount = 2}) 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/ride-b1bd8/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode({
'message': {
'token': token,
'notification': {
'title': title,
'body': body,
},
'data': {
'passengerList': jsonEncode(map),
},
'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/ride-b1bd8/messages:send'),
// headers: <String, String>{
// 'Content-Type': 'application/json',
// 'Authorization': 'Bearer $accessToken',
// },
// body: jsonEncode({
// 'message': {
// 'token': token,
// 'notification': {
// 'title': title,
// 'body': body,
// },
// 'data': {
// 'passengerList': jsonEncode(map),
// },
// '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 body: ${response.body}');
} else {
print(
'Failed to send notification. Status code: ${response.statusCode}');
// if (response.statusCode == 200) {
// print(
// 'Notification sent successfully. Status code: ${response.statusCode}');
// print('Response body: ${response.body}');
// } 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(
const Duration(seconds: 2)); // Optional delay before retrying
return sendNotificationToPassengerToken(title, body, token, map, tone,
retryCount: retryCount - 1);
}
}
} catch (e) {
print('Error sending notification: $e');
if (retryCount > 0) {
print('Retrying... Attempts remaining: $retryCount');
await Future.delayed(
const Duration(seconds: 2)); // Optional delay before retrying
return sendNotificationToPassengerToken(title, body, token, map, tone,
retryCount: retryCount - 1);
}
}
}
// print('Response body: ${response.body}');
// if (retryCount > 0) {
// print('Retrying... Attempts remaining: $retryCount');
// await Future.delayed(
// const Duration(seconds: 2)); // Optional delay before retrying
// return sendNotificationToPassengerToken(title, body, token, map, tone,
// retryCount: retryCount - 1);
// }
// }
// } catch (e) {
// print('Error sending notification: $e');
// if (retryCount > 0) {
// print('Retrying... Attempts remaining: $retryCount');
// await Future.delayed(
// const Duration(seconds: 2)); // Optional delay before retrying
// return sendNotificationToPassengerToken(title, body, token, map, tone,
// retryCount: retryCount - 1);
// }
// }
// }
void sendNotificationToPassengerTokenCALL(
String title, body, token, List<String> map, String tone,
{int retryCount = 2}) async {
try {
if (serviceAccountKeyJson.isEmpty) {
print("🔴 Error: Service Account Key is empty");
return;
}
// Initialize AccessTokenManager
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// void sendNotificationToPassengerTokenCALL(
// String title, body, token, List<String> map, String tone,
// {int retryCount = 2}) 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/ride-b1bd8/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode({
'message': {
'token': token,
'notification': {
'title': title,
'body': body,
},
'data': {
'passengerList': jsonEncode(map),
},
'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/ride-b1bd8/messages:send'),
// headers: <String, String>{
// 'Content-Type': 'application/json',
// 'Authorization': 'Bearer $accessToken',
// },
// body: jsonEncode({
// 'message': {
// 'token': token,
// 'notification': {
// 'title': title,
// 'body': body,
// },
// 'data': {
// 'passengerList': jsonEncode(map),
// },
// '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 body: ${response.body}');
} else {
print(
'Failed to send notification. Status code: ${response.statusCode}');
// if (response.statusCode == 200) {
// print(
// 'Notification sent successfully. Status code: ${response.statusCode}');
// print('Response body: ${response.body}');
// } 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(
const Duration(seconds: 2)); // Optional delay before retrying
return sendNotificationToPassengerTokenCALL(
title, body, token, map, tone,
retryCount: retryCount - 1);
}
}
} catch (e) {
print('Error sending notification: $e');
if (retryCount > 0) {
print('Retrying... Attempts remaining: $retryCount');
await Future.delayed(
const Duration(seconds: 2)); // Optional delay before retrying
return sendNotificationToPassengerTokenCALL(
title, body, token, map, tone,
retryCount: retryCount - 1);
}
}
}
// print('Response body: ${response.body}');
// if (retryCount > 0) {
// print('Retrying... Attempts remaining: $retryCount');
// await Future.delayed(
// const Duration(seconds: 2)); // Optional delay before retrying
// return sendNotificationToPassengerTokenCALL(
// title, body, token, map, tone,
// retryCount: retryCount - 1);
// }
// }
// } catch (e) {
// print('Error sending notification: $e');
// if (retryCount > 0) {
// print('Retrying... Attempts remaining: $retryCount');
// await Future.delayed(
// const Duration(seconds: 2)); // Optional delay before retrying
// return sendNotificationToPassengerTokenCALL(
// title, body, token, map, tone,
// retryCount: retryCount - 1);
// }
// }
// }
Future<void> sendNotificationToDriverMAP(
String title, String body, String token, List<String> data, String tone,
{int retryCount = 2}) 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 = 2}) 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);
// }
// }
// }
Future<void> removeInvalidToken(String token) async {
// Remove token from your database/storage
// This prevents future attempts to send to invalid tokens
print('Removing invalid token from database: $token');
// Your database cleanup logic here
}
// Future<void> removeInvalidToken(String token) async {
// // Remove token from your database/storage
// // This prevents future attempts to send to invalid tokens
// print('Removing invalid token from database: $token');
// // Your database cleanup logic here
// }
}
class OverlayContent extends StatelessWidget {

View File

@@ -6,66 +6,50 @@ class NotificationService {
static const String _serverUrl =
'https://syria.intaleq.xyz/intaleq/fcm/send_fcm.php';
/// Sends a notification via your backend server.
///
/// [target]: The device token or the topic name.
/// [title]: The notification title.
/// [body]: The notification body.
/// [isTopic]: Set to true if the target is a topic, false if it's a device token.
static Future<void> sendNotification({
required String target,
required String title,
required String body,
String? tone,
List<String>? driverList, // <-- [تعديل 1] : إضافة المتغير الجديد
bool isTopic = false,
}) async {
try {
final Map<String, dynamic> payload = {
'target': target,
'title': title,
'body': body,
'isTopic': isTopic,
};
// نضيف النغمة فقط إذا لم تكن فارغة
if (tone != null) {
payload['tone'] = tone;
}
// <-- [تعديل 2] : نضيف قائمة البيانات بعد تشفيرها إلى JSON
if (driverList != null) {
payload['driverList'] = jsonEncode(driverList);
}
final response = await http.post(
Uri.parse(_serverUrl),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({
'target': target,
'title': title,
'body': body,
'isTopic': isTopic,
}),
body: jsonEncode(payload),
);
if (response.statusCode == 200) {
print('Notification sent successfully.');
print('Notification sent successfully.');
print('Server Response: ${response.body}');
} else {
print(
'Failed to send notification. Status code: ${response.statusCode}');
'Failed to send notification. Status code: ${response.statusCode}');
print('Server Error: ${response.body}');
}
} catch (e) {
print('An error occurred while sending notification: $e');
print('An error occurred while sending notification: $e');
}
}
}
// --- Example of how to use it ---
// To send to a specific driver (using their token)
void sendToSpecificDriver() {
String driverToken =
'bk3RNwTe3H0:CI2k_HHwgIpoDKCI5oT...'; // The driver's FCM token
NotificationService.sendNotification(
target: driverToken,
title: 'New Trip Request!',
body: 'A passenger is waiting for you.',
isTopic: false, // Important: this is a token
);
}
// To send to all drivers (using a topic)
void sendToAllDrivers() {
NotificationService.sendNotification(
target: 'drivers', // The name of the topic
title: 'Important Announcement',
body: 'Please update your app to the latest version.',
isTopic: true, // Important: this is a topic
);
}

View File

@@ -29,6 +29,7 @@ import '../../constant/api_key.dart';
import '../../constant/char_map.dart';
import '../../constant/colors.dart';
import '../../print.dart';
import '../firebase/notification_service.dart';
import 'encrypt_decrypt.dart';
import 'tts.dart';
import 'upload_image.dart';
@@ -105,12 +106,20 @@ class AI extends GetxController {
NotificationController().showNotification(
"Code approved".tr, "Code approved".tr, 'tone2', '');
// Notification text with dynamic token
Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
'You have received a gift token!'.tr,
'for '.tr + box.read(BoxName.phoneDriver).toString(),
jsonDecode(res)['message'][0]['token'].toString(),
[],
'tone2', // Type of notification
// Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
// 'You have received a gift token!'.tr,
// 'for '.tr + box.read(BoxName.phoneDriver).toString(),
// jsonDecode(res)['message'][0]['token'].toString(),
// [],
// 'tone2', // Type of notification
// );
NotificationService.sendNotification(
target: jsonDecode(res)['message'][0]['token'].toString(),
title: 'You have received a gift token!'.tr,
body: 'for '.tr + box.read(BoxName.phoneDriver).toString(),
isTopic: false, // Important: this is a token
tone: 'tone2',
driverList: [],
);
} else {
// mySnackeBarError(

View File

@@ -91,14 +91,16 @@ class DriverBehaviorController extends GetxController {
final summary = await analyzeData();
if (summary.isEmpty) return;
final body = {
final Map<String, dynamic> body = {
'driver_id': driverId,
'trip_id': tripId,
...summary,
...summary, // فيه doubles
};
CRUD().post(link: AppLink.saveBehavior, payload: (body));
// اجبر كل القيم على String
final payload = body.map((k, v) => MapEntry(k, v?.toString() ?? ''));
await CRUD().post(link: AppLink.saveBehavior, payload: payload);
await clearData();
}

View File

@@ -24,6 +24,7 @@ import '../../../print.dart';
import '../../../views/Rate/rate_passenger.dart';
import '../../../views/home/Captin/home_captain/home_captin.dart';
import '../../firebase/firbase_messge.dart';
import '../../firebase/notification_service.dart';
import '../../functions/crud.dart';
import '../../functions/encrypt_decrypt.dart';
import '../../functions/location_controller.dart';
@@ -195,13 +196,23 @@ class MapDriverController extends GetxController {
cancelTripFromDriverAfterApplied() async {
if (formKeyCancel.currentState!.validate()) {
box.write(BoxName.statusDriverLocation, 'off');
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
"Cancel Trip from driver",
"Trip Cancelled from driver. We are looking for a new driver. Please wait."
.tr,
tokenPassenger,
[],
'cancel.wav',
// Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
// "Cancel Trip from driver",
// "Trip Cancelled from driver. We are looking for a new driver. Please wait."
// .tr,
// tokenPassenger,
// [],
// 'cancel.wav',
// );
NotificationService.sendNotification(
target: tokenPassenger.toString(),
title: "Cancel Trip from driver".tr,
body:
"Trip Cancelled from driver. We are looking for a new driver. Please wait."
.tr,
isTopic: false, // Important: this is a token
tone: 'cancel',
driverList: [],
);
await CRUD().post(
link: "${AppLink.seferCairoServer}/ride/rides/update.php",
@@ -334,12 +345,20 @@ class MapDriverController extends GetxController {
// Get.find<HomeCaptainController>().changeToAppliedRide('Applied');
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
'Driver Is Going To Passenger',
box.read(BoxName.nameDriver).toString(), //todo name driver
tokenPassenger,
[],
'start.wav');
// Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
// 'Driver Is Going To Passenger',
// box.read(BoxName.nameDriver).toString(), //todo name driver
// tokenPassenger,
// [],
// 'start.wav');
NotificationService.sendNotification(
target: tokenPassenger.toString(),
title: 'Driver Is Going To Passenger'.tr,
body: box.read(BoxName.nameDriver).toString(),
isTopic: false, // Important: this is a token
tone: 'start',
driverList: [],
);
}
bool isSocialPressed = false;
@@ -427,15 +446,15 @@ class MapDriverController extends GetxController {
'order_id': (rideId).toString(),
'status': 'Begin'
});
final fcm = Get.isRegistered<FirebaseMessagesController>()
? Get.find<FirebaseMessagesController>()
: Get.put(FirebaseMessagesController());
fcm.sendNotificationToDriverMAP(
'Trip is Begin',
box.read(BoxName.nameDriver).toString(),
tokenPassenger,
[],
'start.wav');
NotificationService.sendNotification(
target: tokenPassenger.toString(),
title: 'Trip is Begin',
body: box.read(BoxName.nameDriver).toString(),
isTopic: false, // Important: this is a token
tone: 'start',
driverList: [],
);
rideIsBeginPassengerTimer();
update();
@@ -752,17 +771,30 @@ class MapDriverController extends GetxController {
Get.put(DriverBehaviorController())
.sendSummaryToServer(driverId, rideId);
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
"Driver Finish Trip",
'${'you will pay to Driver'.tr} $paymentAmount \$',
tokenPassenger,
[
box.read(BoxName.driverID),
rideId,
box.read(BoxName.tokenDriver),
paymentAmount.toString()
],
'ding.wav');
// Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
// "Driver Finish Trip",
// '${'you will pay to Driver'.tr} $paymentAmount \$',
// tokenPassenger,
// [
// box.read(BoxName.driverID),
// rideId,
// box.read(BoxName.tokenDriver),
// paymentAmount.toString()
// ],
// 'ding.wav');
NotificationService.sendNotification(
target: tokenPassenger.toString(),
title: "Driver Finish Trip",
body: '${'you will pay to Driver'.tr} $paymentAmount \$'.tr,
isTopic: false, // Important: this is a token
tone: 'ding',
driverList: [
box.read(BoxName.driverID),
rideId,
box.read(BoxName.tokenDriver),
paymentAmount.toString()
],
);
Get.to(() => RatePassenger(), arguments: {
'passengerId': passengerId,
@@ -1617,17 +1649,30 @@ class MapDriverController extends GetxController {
if (distance < 300) {
// 300 متر قبل الوجهة
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
"You are near the destination",
"You are near the destination".tr,
tokenPassenger,
[
// Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
// "You are near the destination",
// "You are near the destination".tr,
// tokenPassenger,
// [
// box.read(BoxName.driverID),
// rideId,
// box.read(BoxName.tokenDriver),
// paymentAmount.toString()
// ],
// 'ding.wav',
// );
NotificationService.sendNotification(
target: tokenPassenger.toString(),
title: "You are near the destination",
body: "You are near the destination".tr,
isTopic: false, // Important: this is a token
tone: 'ding',
driverList: [
box.read(BoxName.driverID),
rideId,
box.read(BoxName.tokenDriver),
paymentAmount.toString()
],
'ding.wav',
);
// يمكن إضافة أي إجراء آخر هنا عند الاقتراب من الوجهة
}

View File

@@ -14,6 +14,7 @@ import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import '../../../views/widgets/mydialoug.dart';
import '../../firebase/notification_service.dart';
class CaptainWalletController extends GetxController {
bool isLoading = false;
@@ -291,13 +292,23 @@ class CaptainWalletController extends GetxController {
'paymentMethod': paymentMethod2.toString(),
});
if (res1 != 'failure') {
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
'Transfer',
'${'You have transfer to your wallet from'.tr}'
'${box.read(BoxName.nameDriver)}',
amountToNewDriverMap[0]['token'].toString(),
[],
'order1.wav');
// Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
// 'Transfer',
// '${'You have transfer to your wallet from'.tr}'
// '${box.read(BoxName.nameDriver)}',
// amountToNewDriverMap[0]['token'].toString(),
// [],
// 'order1.wav');
NotificationService.sendNotification(
target: amountToNewDriverMap[0]['token'].toString(),
title: 'Transfer'.tr,
body: '${'You have transfer to your wallet from'.tr}'
'${box.read(BoxName.nameDriver)}',
isTopic: false, // Important: this is a token
tone: 'ding',
driverList: [],
);
await addSeferWallet('payout fee', '5');
Get.defaultDialog(

View File

@@ -140,6 +140,9 @@ class MyTranslation extends Translations {
"What is the feature of our wallet?": "ما هي مميزات محفظتنا؟",
"What is Types of Trips in Intaleq?":
"ما هي أنواع الرحلات في Intaleq؟",
"No rides available for your vehicle type.": "لا توجد رحلات متاحة .",
"Failed to fetch rides. Please try again.":
"فشل في جلب الرحلات. يرجى المحاولة مرة أخرى.",
'''Types of Trips in Intaleq:
Comfort: For cars newer than 2017 with air conditioning.

View File

@@ -8,6 +8,7 @@ import '../../constant/links.dart';
import '../../constant/style.dart';
import '../../main.dart';
import '../../views/widgets/elevated_btn.dart';
import '../firebase/notification_service.dart';
import '../functions/crud.dart';
class PassengerNotificationController extends GetxController {
@@ -53,8 +54,16 @@ class PassengerNotificationController extends GetxController {
'title': title,
'body': body,
});
FirebaseMessagesController()
.sendNotificationToPassengerToken(title, body, 'token', [], 'ding.wav');
// FirebaseMessagesController()
// .sendNotificationToPassengerToken(title, body, 'token', [], 'ding.wav');
NotificationService.sendNotification(
target: 'token'.toString(),
title: title,
body: body,
isTopic: false, // Important: this is a token
tone: 'ding',
driverList: [],
);
}
@override

View File

@@ -1,10 +1,8 @@
import 'dart:convert';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/colors.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/controller/functions/encrypt_decrypt.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:sefer_driver/views/widgets/mydialoug.dart';
@@ -24,9 +22,10 @@ class RatingController extends GetxController {
void _redirectToAppStore() async {
// URLs for App Store and Google Play Store
const appStoreUrl = 'https://apps.apple.com/app/6502189302';
const appStoreUrl =
'https://apps.apple.com/st/app/intaleq-driver/id6482995159';
const playStoreUrl =
'https://play.google.com/store/apps/details?id=com.sefer_driver';
'https://play.google.com/store/apps/details?id=com.intaleq_driver';
final url = GetPlatform.isIOS ? appStoreUrl : playStoreUrl;
if (await launchUrl(Uri.parse(url))) {
@@ -59,13 +58,14 @@ class RatingController extends GetxController {
if (res != 'failure') {
try {
// Attempt to parse the response as JSON
final parsedResponse = jsonDecode(res);
final parsedResponse = (res);
if (parsedResponse['status'] == 'success') {
// Display a success message
CRUD().post(link: AppLink.sendEmailRateingApp, payload: {
"name": payload["name"],
"email": payload["email"],
"phone": payload["phone"],
"rating": rating.toString(),
"comment": payload["comment"],
});

View File

@@ -11,6 +11,8 @@ import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/home/Captin/home_captain/home_captin.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import '../firebase/notification_service.dart';
// import '../home/captin/home_captain_controller.dart';
class RateController extends GetxController {
@@ -67,12 +69,20 @@ class RateController extends GetxController {
'driverID': box.read(BoxName.driverID).toString(),
});
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
'Wallet Added'.tr,
'Wallet Added${(remainingFee).toStringAsFixed(0)}'.tr,
Get.find<MapDriverController>().tokenPassenger,
[],
'tone2.wav');
// Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
// 'Wallet Added'.tr,
// 'Wallet Added${(remainingFee).toStringAsFixed(0)}'.tr,
// Get.find<MapDriverController>().tokenPassenger,
// [],
// 'tone2.wav');
NotificationService.sendNotification(
target: Get.find<MapDriverController>().tokenPassenger.toString(),
title: 'Wallet Added'.tr,
body: 'Wallet Added${(remainingFee).toStringAsFixed(0)}'.tr,
isTopic: false, // Important: this is a token
tone: 'tone2',
driverList: [],
);
walletChecked = 'true';
// }