25-3/18/1

This commit is contained in:
Hamza-Ayed
2025-03-18 13:54:27 +03:00
parent 6e77dec65f
commit 153d2f64c0
1307 changed files with 9505 additions and 528 deletions
Regular → Executable
+1
View File
@@ -6,6 +6,7 @@ import 'char_map.dart';
class AK {
static final String sss_pass = X.r(X.r(X.r(Env.sss_pass, cn), cC), cs);
static final String allowed = Env.allowed;
static final String allowedWallet = Env.allowedWallet;
static final String passnpassenger = X
.r(X.r(X.r(Env.passnpassenger, cn), cC), cs)
.toString()
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
+11 -10
View File
@@ -15,7 +15,7 @@ class AppLink {
// static final String seferAlexandriaServer = Env.seferAlexandriaServer;
// static final String seferCairoServer = Env.seferCairoServer;
// static final String seferCairoServer =
// 'https://server.sefer.live/sefer.click/sefer';
// 'https://server.sefer.click/sefer.click/sefer';
// static final String seferGizaServer = Env.seferCairoServer;
// static final String seferAlexandriaServer = Env.seferCairoServer;
// static final String seferPaymentServer = '${Env.seferCairoServer}/ride';
@@ -24,18 +24,19 @@ class AppLink {
// static final String seferGizaServer = Env.seferGizaServer;
static final String endPoint =
box.read(BoxName.serverChosen) ?? box.read(BoxName.basicLink);
// 'https://server.sefer.live/sefer.click/sefer';
// 'https://server.sefer.click/sefer.click/sefer';
static final String server = endPoint;
static String seferCairoServer = endPoint;
static String seferGizaServer = box.read('Giza');
static String seferAlexandriaServer = box.read('Alexandria');
// static final String server = Env.serverPHP;
static String loginJwtDriver = "$server/loginJwtDriver.php";
static String loginJwtDriver =
"https://server.sefer.click/sefer.click/sefer/loginJwtDriver.php";
static String loginJwtWalletDriver =
"$seferPaymentServer/loginJwtWalletDriver.php";
static String loginFirstTimeDriver =
"https://server.sefer.live/sefer.click/sefer/loginFirstTimeDriver.php";
"https://server.sefer.click/sefer.click/sefer/loginFirstTimeDriver.php";
static String googleMapsLink = 'https://maps.googleapis.com/maps/api/';
static String llama = 'https://api.llama-api.com/chat/completions';
@@ -104,7 +105,7 @@ class AppLink {
static String getapiKey = Env.getapiKey;
static String getapiKeySefer =
"https://api.sefer.live/sefer/ride/apiKey/get.php";
"https://api.sefer.click/sefer/ride/apiKey/get.php";
static String getRideStatusBegin = "$ride/rides/getRideStatusBegin.php";
static String getRideStatusFromStartApp =
"$ride/rides/getRideStatusFromStartApp.php";
@@ -225,16 +226,16 @@ class AppLink {
static String addRateToDriver = "$ride/rate/addRateToDriver.php";
static String addRateApp = "$ride/rate/add_rate_app.php";
static String sendEmailRateingApp =
"https://api.sefer.live/sefer/ride/rate/sendEmailRateingApp.php";
"https://api.sefer.click/sefer/ride/rate/sendEmailRateingApp.php";
static String getDriverRate = "$ride/rate/getDriverRate.php";
static String getPassengerRate = "$ride/rate/getPassengerRate.php";
////////////////emails ============//
static String sendEmailToPassengerForTripDetails =
"https://api.sefer.live/sefer/ride/rides/emailToPassengerTripDetail.php";
"https://api.sefer.click/sefer/ride/rides/emailToPassengerTripDetail.php";
static String sendEmailToDrivertransaction =
"https://api.sefer.live/sefer/Admin/sendEmailToDrivertransaction.php";
// "https://api.sefer.live/sefer/Admin/sendEmailToDrivertransaction.php";
"https://api.sefer.click/sefer/Admin/sendEmailToDrivertransaction.php";
// "https://api.sefer.click/sefer/Admin/sendEmailToDrivertransaction.php";
// ===========================================
static String pathImage = "$server/upload/types/";
static String uploadImage = "$server/uploadImage.php";
@@ -252,7 +253,7 @@ class AppLink {
static String getCarsLocationByPassenger = "$location/get.php";
static String addpassengerLocation = "$location/addpassengerLocation.php";
static String getLocationAreaLinks =
"https://server.sefer.live/sefer.click/sefer/ride/location/get_location_area_links.php";
"https://server.sefer.click/sefer.click/sefer/ride/location/get_location_area_links.php";
static String getLatestLocationPassenger =
"$location/getLatestLocationPassenger.php";
static String getFemalDriverLocationByPassenger =
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
View File
View File
+114 -71
View File
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:local_auth/local_auth.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/firebase/local_notification.dart';
@@ -153,55 +154,79 @@ Download the Tripz app now and enjoy your ride!
: 'You deserve the gift'.tr,
'${EncryptionHelper.instance.decryptData(driverInvitationData[index]['invitorName'])} ${(driverInvitationData[index]['countOfInvitDriver'])} / 100 ${'Trip'.tr}',
() async {
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (int.parse((driverInvitationData[index]['countOfInvitDriver'])) <
100) {
Get.back();
} else {
//claim your gift
if ((driverInvitationData[index]['isGiftToken']).toString() == '0') {
Get.back();
await CRUD().post(link: AppLink.updateInviteDriver, payload: {
'id': EncryptionHelper.instance
.encryptData(driverInvitationData[index]['id'])
});
await Get.find<CaptainWalletController>().addDriverPayment(
'paymentMethod',
EncryptionHelper.instance.encryptData('500'),
'',
);
// add for invitor too
await Get.find<CaptainWalletController>().addDriverWalletToInvitor(
'paymentMethod',
EncryptionHelper.instance
.encryptData(driverInvitationData[index]['driverInviterId']),
EncryptionHelper.instance.encryptData('500'),
);
await Get.find<CaptainWalletController>().addSeferWallet(
'giftInvitation',
EncryptionHelper.instance.encryptData('-1000'));
NotificationCaptainController().addNotificationCaptain(
driverInvitationData[index]['driverInviterId'].toString(),
"You have got a gift for invitation".tr,
'${"You have 500".tr} ${'LE'}',
false);
NotificationController().showNotification(
"You have got a gift for invitation".tr,
'${"You have 500".tr} ${'LE'}',
'tone1',
'');
} else
//claim your gift
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
if ((driverInvitationData[index]['isGiftToken']).toString() ==
'0') {
Get.back();
await CRUD().post(link: AppLink.updateInviteDriver, payload: {
'id': EncryptionHelper.instance
.encryptData(driverInvitationData[index]['id'])
});
await Get.find<CaptainWalletController>().addDriverPayment(
'paymentMethod',
('500'),
'',
);
// add for invitor too
await Get.find<CaptainWalletController>()
.addDriverWalletToInvitor(
'paymentMethod',
EncryptionHelper.instance.encryptData(
driverInvitationData[index]['driverInviterId']),
('500'),
);
await Get.find<CaptainWalletController>()
.addSeferWallet('giftInvitation', ('-1000'));
NotificationCaptainController().addNotificationCaptain(
driverInvitationData[index]['driverInviterId'].toString(),
"You have got a gift for invitation".tr,
'${"You have 500".tr} ${'LE'}',
false);
NotificationController().showNotification(
"You have got a gift for invitation".tr,
'${"You have 500".tr} ${'LE'}',
'tone1',
'');
} else {
Get.back();
MyDialog().getDialog("You have got a gift".tr,
"Share the app with another new driver".tr, () {
Get.back();
});
}
} else {
Get.back();
MyDialog().getDialog("You have got a gift".tr,
"Share the app with another new driver".tr, () {
// Authentication failed, handle accordingly
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
}
},
);
}
void onSelectPassengerInvitation(int index) async {
bool isAvailable = await LocalAuthentication().isDeviceSupported();
MyDialog().getDialog(
int.parse(driverInvitationDataToPassengers[index]['countOfInvitDriver']
.toString()) <
@@ -215,43 +240,61 @@ Download the Tripz app now and enjoy your ride!
.toString()) <
3) {
Get.back();
} else {
// Claim the gift if 100 trips are completed
if (driverInvitationDataToPassengers[index]['isGiftToken']
.toString() ==
'0') {
Get.back();
// Add wallet to the inviter
await Get.find<CaptainWalletController>()
.addDriverWallet('paymentMethod', '50', '50');
// add for invitor too
await Get.find<CaptainWalletController>().addDriverWalletToInvitor(
'paymentMethod',
driverInvitationData[index]['driverInviterId'],
'50');
// Update invitation as claimed
await CRUD().post(
link: AppLink.updatePassengerGift,
payload: {'id': driverInvitationDataToPassengers[index]['id']},
);
// Notify the inviter
NotificationCaptainController().addNotificationCaptain(
driverInvitationDataToPassengers[index]['passengerInviterId']
.toString(),
"You have got a gift for invitation".tr,
'${"You have 50".tr} ${'LE'}',
false,
);
} else if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
// Claim the gift if 100 trips are completed
if (driverInvitationDataToPassengers[index]['isGiftToken']
.toString() ==
'0') {
Get.back();
// Add wallet to the inviter
await Get.find<CaptainWalletController>()
.addDriverWallet('paymentMethod', '50', '50');
// add for invitor too
await Get.find<CaptainWalletController>()
.addDriverWalletToInvitor('paymentMethod',
driverInvitationData[index]['driverInviterId'], '50');
// Update invitation as claimed
await CRUD().post(
link: AppLink.updatePassengerGift,
payload: {'id': driverInvitationDataToPassengers[index]['id']},
);
// Notify the inviter
NotificationCaptainController().addNotificationCaptain(
driverInvitationDataToPassengers[index]['passengerInviterId']
.toString(),
"You have got a gift for invitation".tr,
'${"You have 50".tr} ${'LE'}',
false,
);
} else {
Get.back();
MyDialog().getDialog(
"You have got a gift".tr,
"Share the app with another new passenger".tr,
() {
Get.back();
},
);
}
} else {
Get.back();
MyDialog().getDialog(
"You have got a gift".tr,
"Share the app with another new passenger".tr,
() {
Get.back();
},
);
// Authentication failed, handle accordingly
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
}
},
);
+35 -20
View File
@@ -102,18 +102,23 @@ class LoginDriverController extends GetxController {
} else {
await SecurityChecks.isDeviceRootedFromNative(Get.context!);
}
String fingerPrint = await getDeviceFingerprint();
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
dev = Platform.isAndroid ? 'android' : 'ios';
var payload = {
'id': box.read(BoxName.passengerID),
'id': box.read(BoxName.driverID),
'password': AK.passnpassenger,
'aud': '${AK.allowed}$dev',
'aud': '${AK.allowedWallet}$dev',
'fingerPrint': fingerPrint
};
var response1 = await http.post(
Uri.parse(AppLink.loginJwtWalletDriver),
body: payload,
);
Log.print('response.request: ${response1.request}');
Log.print('response.body: ${response1.body}');
print(payload);
Log.print(
'jsonDecode(response1.body)["jwt"]: ${jsonDecode(response1.body)['jwt']}');
return jsonDecode(response1.body)['jwt'].toString();
}
@@ -155,6 +160,7 @@ class LoginDriverController extends GetxController {
} else {}
} else {
await EncryptionHelper.initialize();
var emailDecrypted = (box.read(BoxName.emailDriver));
var pass = passwordController.text.isEmpty
? '$emailDecrypted${box.read(BoxName.driverID)}'
@@ -246,7 +252,10 @@ class LoginDriverController extends GetxController {
if (jsonDecoeded.isNotEmpty) {
if (jsonDecoeded['status'] == 'success' &&
jsonDecoeded['data'][0]['is_verified'].toString() == '1') {
box.write(BoxName.emailDriver, (jsonDecoeded['data'][0]['email']));
box.write(
BoxName.emailDriver,
EncryptionHelper.instance
.decryptData(jsonDecoeded['data'][0]['email']));
box.write(BoxName.firstTimeLoadKey, 'false');
box.write(BoxName.driverID, (jsonDecoeded['data'][0]['id']));
box.write(BoxName.isTest, '1');
@@ -302,11 +311,12 @@ class LoginDriverController extends GetxController {
link: AppLink.getDriverToken,
payload: {'captain_id': (box.read(BoxName.driverID)).toString()});
String? fingerPrint = await DeviceHelper.getDeviceFingerprint();
await storage.write(key: BoxName.fingerPrint, value: fingerPrint);
if (token != 'failure') {
if (EncryptionHelper.instance
.decryptData(jsonDecode(token)['data'][0]['token']) !=
EncryptionHelper.instance
.decryptData(box.read(BoxName.tokenDriver))) {
if ((jsonDecode(token)['data'][0]['token']) !=
(box.read(BoxName.tokenDriver))) {
Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
'token change'.tr,
'change device'.tr,
@@ -315,7 +325,7 @@ class LoginDriverController extends GetxController {
.toString(),
[],
'promo.wav');
Get.defaultDialog(
await Get.defaultDialog(
title: 'you will use this device?'.tr,
middleText: '',
confirm: MyElevatedButton(
@@ -324,7 +334,8 @@ class LoginDriverController extends GetxController {
await CRUD()
.post(link: AppLink.addTokensDriver, payload: {
'token': (box.read(BoxName.tokenDriver)),
'captain_id': (box.read(BoxName.driverID)).toString()
'captain_id': (box.read(BoxName.driverID)).toString(),
'fingerPrint': (fingerPrint).toString()
});
await CRUD().post(
link:
@@ -332,7 +343,8 @@ class LoginDriverController extends GetxController {
payload: {
'token': (box.read(BoxName.tokenDriver)),
'captain_id':
(box.read(BoxName.driverID)).toString()
(box.read(BoxName.driverID)).toString(),
'fingerPrint': (fingerPrint).toString()
});
// await CRUD().post(
// link:
@@ -372,8 +384,7 @@ class LoginDriverController extends GetxController {
'email': EncryptionHelper.instance.encryptData(email),
'password': password,
});
box.write(BoxName.emailDriver,
EncryptionHelper.instance.decryptData(email).toString());
box.write(BoxName.emailDriver, (email).toString());
print(res);
if (res == 'failure') {
//Failure
@@ -439,15 +450,16 @@ class LoginDriverController extends GetxController {
}
updateAppTester(AppInformation.appName);
var fingerPrint = DeviceHelper.getDeviceFingerprint().toString();
await storage.write(key: BoxName.fingerPrint, value: fingerPrint);
var token = await CRUD().get(
link: AppLink.getDriverToken,
payload: {'captain_id': box.read(BoxName.driverID).toString()});
if (token != 'failure') {
if (EncryptionHelper.instance
.decryptData(jsonDecode(token)['data'][0]['token']) !=
EncryptionHelper.instance
.decryptData(box.read(BoxName.tokenDriver))) {
if ((jsonDecode(token)['data'][0]['token']) !=
(box.read(BoxName.tokenDriver))) {
Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
'token change'.tr,
'change device'.tr,
@@ -465,7 +477,8 @@ class LoginDriverController extends GetxController {
await CRUD()
.post(link: AppLink.addTokensDriver, payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id': box.read(BoxName.driverID).toString()
'captain_id': box.read(BoxName.driverID).toString(),
'fingerPrint': (fingerPrint).toString()
});
await CRUD().post(
link:
@@ -473,7 +486,8 @@ class LoginDriverController extends GetxController {
payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id':
box.read(BoxName.driverID).toString()
box.read(BoxName.driverID).toString(),
'fingerPrint': (fingerPrint).toString()
});
await CRUD().post(
link:
@@ -481,7 +495,8 @@ class LoginDriverController extends GetxController {
payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id':
box.read(BoxName.driverID).toString()
box.read(BoxName.driverID).toString(),
'fingerPrint': (fingerPrint).toString()
});
Get.back();
}));
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
+64 -9
View File
@@ -9,7 +9,6 @@ import 'package:sefer_driver/main.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:sefer_driver/env/env.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import '../../constant/api_key.dart';
import '../../constant/char_map.dart';
@@ -27,7 +26,7 @@ class CRUD {
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
Log.print('isTokenExpired: ${isTokenExpired}');
// Log.print('isTokenExpired: ${isTokenExpired}');
if (isTokenExpired) {
await LoginDriverController().getJWT();
@@ -45,9 +44,9 @@ class CRUD {
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
},
);
print(response.request);
print(response.body);
print(payload);
// print(response.request);
// Log.print('response.body: ${response.body}');
// print(payload);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
@@ -93,6 +92,10 @@ class CRUD {
'Authorization': 'Bearer $s'
},
);
// print(response.request);
// Log.print('response.request: ${response.request}');
// Log.print('response.body: ${response.body}');
// print(payload);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
@@ -121,6 +124,58 @@ class CRUD {
}
}
Future<dynamic> postWallet(
{required String link, Map<String, dynamic>? payload}) async {
var s = await LoginDriverController().getJwtWallet();
var url = Uri.parse(link);
try {
await LoginDriverController().getJWT();
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $s'
},
);
// print(response.request);
// Log.print('response.body: ${response.body}');
// print(payload);
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return jsonData;
} else {
return jsonData['status'];
}
} catch (e) {
addError(e.toString(), 'crud().post - JSON decoding');
return 'failure';
}
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
return 'failure';
}
} else {
addError('Non-200 response code: ${response.statusCode}',
'crud().post - Other');
return 'failure';
}
} catch (e) {
addError('HTTP request error: $e', 'crud().post - HTTP');
return 'failure';
}
}
Future<dynamic> post(
{required String link, Map<String, dynamic>? payload}) async {
var url = Uri.parse(link);
@@ -142,9 +197,9 @@ class CRUD {
// 'Authorization': 'Bearer ${box.read(BoxName.jwt)}'
},
);
print(response.request);
print(response.body);
print(payload);
// print(response.request);
// Log.print('response.body: ${response.body}');
// print(payload);
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
@@ -154,7 +209,7 @@ class CRUD {
return jsonData['status'];
}
} catch (e) {
addError(e.toString(), 'crud().post - JSON decoding');
addError(e.toString(), url);
return 'failure';
}
} else if (response.statusCode == 401) {
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
+71 -18
View File
@@ -170,7 +170,7 @@ class LocationController extends GetxController {
Future<void> getLocation() async {
if (location == null) {
location = Location(); // Ensure location is initialized
location = Location(); // تأكد من أن `Location` مهيأ
}
bool serviceEnabled;
@@ -192,27 +192,80 @@ class LocationController extends GetxController {
}
}
LocationData _locationData = await location.getLocation();
if (_locationData.latitude != null && _locationData.longitude != null) {
myLocation = LatLng(_locationData.latitude!, _locationData.longitude!);
} else {
myLocation = LatLng(0, 0); // Default value
}
/// **تجنب استدعاء `getLocation()` مباشرة على الـ Main Thread**
Future.delayed(Duration(milliseconds: 500), () async {
try {
LocationData _locationData = await location.getLocation();
if (_locationData.latitude != null && _locationData.longitude != null) {
myLocation =
LatLng(_locationData.latitude!, _locationData.longitude!);
} else {
myLocation = LatLng(0, 0); // Default value
}
speed = _locationData.speed ?? 0;
heading = _locationData.heading ?? 0;
speed = _locationData.speed ?? 0;
heading = _locationData.heading ?? 0;
if (Get.find<HomeCaptainController>().rideId == 'rideId') {
if (previousTime > 0) {
double distance = calculateDistanceInKmPerHour(
previousTime, _locationData.time, speed);
totalDistance += distance;
if (Get.find<HomeCaptainController>().rideId == 'rideId') {
if (previousTime > 0) {
double distance = calculateDistanceInKmPerHour(
previousTime, _locationData.time, speed);
totalDistance += distance;
}
previousTime = _locationData.time ?? 0;
}
update();
} catch (e) {
print("Error getting location: $e");
}
previousTime = _locationData.time ?? 0;
}
update();
});
}
// Future<void> getLocation() async {
// if (location == null) {
// location = Location(); // Ensure location is initialized
// }
// bool serviceEnabled;
// PermissionStatus permissionGranted;
// serviceEnabled = await location.serviceEnabled();
// if (!serviceEnabled) {
// serviceEnabled = await location.requestService();
// if (!serviceEnabled) {
// return;
// }
// }
// permissionGranted = await location.hasPermission();
// if (permissionGranted == PermissionStatus.denied) {
// permissionGranted = await location.requestPermission();
// if (permissionGranted != PermissionStatus.granted) {
// return;
// }
// }
// LocationData _locationData = await location.getLocation();
// if (_locationData.latitude != null && _locationData.longitude != null) {
// myLocation = LatLng(_locationData.latitude!, _locationData.longitude!);
// } else {
// myLocation = LatLng(0, 0); // Default value
// }
// speed = _locationData.speed ?? 0;
// heading = _locationData.heading ?? 0;
// if (Get.find<HomeCaptainController>().rideId == 'rideId') {
// if (previousTime > 0) {
// double distance = calculateDistanceInKmPerHour(
// previousTime, _locationData.time, speed);
// totalDistance += distance;
// }
// previousTime = _locationData.time ?? 0;
// }
// update();
// }
double calculateDistanceInKmPerHour(
double? startTime, double? endTime, double speedInMetersPerSecond) {
View File
View File
View File
View File
+37 -15
View File
@@ -164,23 +164,45 @@ void showUpdateDialog(BuildContext context) {
);
}
getDeviceFingerprint() async {
final deviceInfo = await DeviceInfoPlugin().deviceInfo;
var deviceData;
class DeviceHelper {
static Future<String> getDeviceFingerprint() async {
final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
var deviceData;
if (Platform.isAndroid) {
deviceData = deviceInfo.data;
} else if (Platform.isIOS) {
deviceData = deviceInfo.data;
try {
if (Platform.isAndroid) {
// Fetch Android-specific device information
AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
deviceData = androidInfo.toMap(); // Convert to a map for easier access
// Log.print('deviceData: ${jsonEncode(deviceData)}');
} else if (Platform.isIOS) {
// Fetch iOS-specific device information
IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
deviceData = iosInfo.toMap(); // Convert to a map for easier access
} else {
throw UnsupportedError('Unsupported platform');
}
// Extract relevant device information
final String deviceId = Platform.isAndroid
? deviceData['androidId'] ?? deviceData['serialNumber'] ?? 'unknown'
: deviceData['identifierForVendor'] ?? 'unknown';
final String deviceModel = deviceData['model'] ?? 'unknown';
final String osVersion = Platform.isAndroid
? deviceData['version']['release'] ?? 'unknown'
: deviceData['systemVersion'] ?? 'unknown';
// Log the extracted information
// Generate and return the encrypted fingerprint
final String fingerprint = '${deviceId}_${deviceModel}_$osVersion';
print(EncryptionHelper.instance.encryptData(fingerprint));
return EncryptionHelper.instance.encryptData(fingerprint);
} catch (e) {
throw Exception('Failed to generate device fingerprint');
}
}
final String deviceId =
deviceData['androidId'] ?? deviceData['identifierForVendor'];
final String deviceModel = deviceData['model'];
final String osVersion = deviceData['systemVersion'];
return EncryptionHelper.instance
.encryptData('${deviceId}_${deviceModel}_$osVersion');
}
class SecurityHelper {
View File
View File
+1 -5
View File
@@ -72,11 +72,7 @@ class AppInitializer {
await CRUD().get(link: AppLink.getLocationAreaLinks, payload: {});
if (res != 'failure') {
links = List<Map<String, dynamic>>.from(jsonDecode(res)['message']);
await box.remove(BoxName.locationName);
await box.remove(BoxName.basicLink);
await box.remove(links[4]['name']);
await box.remove(links[1]['name']);
await box.remove(links[2]['name']);
await box.write(BoxName.locationName, links);
await box.write(BoxName.basicLink,
EncryptionHelper.instance.decryptData(links[0]['server_link']));
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
+16 -4
View File
@@ -323,21 +323,33 @@ class HomeCaptainController extends GetxController {
// }
addToken() async {
String? fingerPrint = await storage.read(key: BoxName.fingerPrint);
await CRUD().post(link: AppLink.addTokensDriver, payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id': box.read(BoxName.driverID).toString()
'token': (box.read(BoxName.tokenDriver)),
'captain_id': (box.read(BoxName.driverID)).toString(),
'fingerPrint': (fingerPrint).toString()
});
await CRUD().post(
link: "${AppLink.seferAlexandriaServer}/ride/firebase/addDriver.php",
payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id': box.read(BoxName.driverID).toString()
'captain_id': box.read(BoxName.driverID).toString(),
'fingerPrint': (fingerPrint).toString()
});
await CRUD().post(
link: "${AppLink.seferGizaServer}/ride/firebase/addDriver.php",
payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id': box.read(BoxName.driverID).toString()
'captain_id': box.read(BoxName.driverID).toString(),
'fingerPrint': (fingerPrint).toString()
});
await CRUD().post(
link: "${AppLink.seferPaymentServer}/ride/firebase/addDriver.php",
payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id': box.read(BoxName.driverID).toString(),
'fingerPrint': (fingerPrint).toString()
});
MapDriverController().driverCallPassenger();
// box.write(BoxName.statusDriverLocation, 'off');
View File
View File
View File
+21 -15
View File
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:local_auth/local_auth.dart';
import 'package:sefer_driver/constant/style.dart';
import 'package:sefer_driver/controller/firebase/firbase_messge.dart';
import 'package:sefer_driver/controller/firebase/local_notification.dart';
@@ -12,6 +13,8 @@ import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import '../../../views/widgets/mydialoug.dart';
class CaptainWalletController extends GetxController {
bool isLoading = false;
final formKeyTransfer = GlobalKey<FormState>();
@@ -40,7 +43,7 @@ class CaptainWalletController extends GetxController {
await generateToken((pointFromBudget * -1).toString());
var paymentID = await getPaymentId(
'fromBudgetToPoints', (pointFromBudget * -1).toString());
await CRUD().post(link: AppLink.addDrivePayment, payload: {
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
'amount': (pointFromBudget * -1).toString(),
'rideId': paymentID.toString(),
'payment_method': 'myBudget',
@@ -79,7 +82,7 @@ class CaptainWalletController extends GetxController {
//get new driver details
isNewTransfer = true;
update();
var res = await CRUD().get(
var res = await CRUD().getWallet(
link: AppLink.getDriverDetails,
payload: {'driver_phone': '+2${newDriverPhoneController.text}'});
isNewTransfer = false;
@@ -100,7 +103,7 @@ class CaptainWalletController extends GetxController {
Future getCaptainWalletFromRide() async {
isLoading = true;
update();
var res = await CRUD().get(
var res = await CRUD().getWallet(
link: AppLink.getAllPaymentFromRide,
payload: {'driverID': box.read(BoxName.driverID).toString()},
);
@@ -109,7 +112,7 @@ class CaptainWalletController extends GetxController {
walletDate = jsonDecode(res);
totalAmount = walletDate['message'][0]['total_amount'] ?? '0';
update();
var res1 = await CRUD().get(
var res1 = await CRUD().getWallet(
link: AppLink.getAllPaymentVisa,
payload: {'driverID': box.read(BoxName.driverID).toString()});
walletDateVisa = jsonDecode(res1);
@@ -126,7 +129,7 @@ class CaptainWalletController extends GetxController {
// isLoading = true;
update();
var res = await CRUD().get(
var res = await CRUD().getWallet(
link: AppLink.getDriverPaymentPoints,
payload: {'driverID': box.read(BoxName.driverID).toString()},
);
@@ -147,7 +150,8 @@ class CaptainWalletController extends GetxController {
String paymentToken = '';
Future<String> generateToken(String amount) async {
var res = await CRUD().post(link: AppLink.addPaymentTokenDriver, payload: {
var res =
await CRUD().postWallet(link: AppLink.addPaymentTokenDriver, payload: {
'driverID': box.read(BoxName.driverID).toString(),
'amount': amount.toString(),
});
@@ -158,7 +162,8 @@ class CaptainWalletController extends GetxController {
// late String paymentID;
Future<String> getPaymentId(String paymentMethod, amount) async {
// paymentToken = await generateToken(amount);
var res = await CRUD().post(link: AppLink.addDriverPaymentPoints, payload: {
var res =
await CRUD().postWallet(link: AppLink.addDriverPaymentPoints, payload: {
'driverID': box.read(BoxName.driverID).toString(),
'amount': amount.toString(),
'payment_method': paymentMethod.toString(),
@@ -171,7 +176,7 @@ class CaptainWalletController extends GetxController {
Future addDriverWallet(String paymentMethod, point, count) async {
paymentToken = await generateToken(count);
var paymentID = await getPaymentId(paymentMethod, point);
await CRUD().post(link: AppLink.addDriversWalletPoints, payload: {
await CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
'driverID': box.read(BoxName.driverID).toString(),
'paymentID': paymentID.toString(),
'amount': point,
@@ -183,7 +188,7 @@ class CaptainWalletController extends GetxController {
Future addDriverPayment(String paymentMethod, point, wayPay) async {
paymentToken = await generateToken(point);
var paymentID = await getPaymentId(paymentMethod, point.toString());
await CRUD().post(link: AppLink.addDrivePayment, payload: {
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
'amount': point.toString(),
'rideId': paymentID.toString(),
'payment_method': paymentMethod,
@@ -195,7 +200,7 @@ class CaptainWalletController extends GetxController {
Future addDriverWalletFromPromo(String paymentMethod, point) async {
var resPromotion =
await CRUD().post(link: AppLink.addpromotionDriver, payload: {
await CRUD().postWallet(link: AppLink.addpromotionDriver, payload: {
'driver_id': box.read(BoxName.driverID).toString(),
'payment_amount': point,
'timePromo': paymentMethod,
@@ -203,7 +208,8 @@ class CaptainWalletController extends GetxController {
if (resPromotion != 'failure') {
paymentToken = await generateToken(point);
var paymentID = await getPaymentId(paymentMethod, point.toString());
var res = await CRUD().post(link: AppLink.addDrivePayment, payload: {
var res =
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
'amount': point,
'rideId': paymentID.toString(),
'payment_method': paymentMethod.toString(),
@@ -231,7 +237,7 @@ class CaptainWalletController extends GetxController {
Future addDriverWalletToInvitor(String paymentMethod, driverID, point) async {
paymentToken = await generateToken(point);
var paymentID = await getPaymentId(paymentMethod, point.toString());
await CRUD().post(link: AppLink.addDrivePayment, payload: {
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
'driverID': driverID,
'amount': point,
'token': paymentToken,
@@ -244,7 +250,7 @@ class CaptainWalletController extends GetxController {
Future addSeferWallet(String paymentMethod, String point) async {
var seferToken = await generateToken(point.toString());
await CRUD().post(link: AppLink.addSeferWallet, payload: {
await CRUD().postWallet(link: AppLink.addSeferWallet, payload: {
'amount': point.toString(),
'paymentMethod': paymentMethod,
'passengerId': 'driver',
@@ -259,7 +265,7 @@ class CaptainWalletController extends GetxController {
paymentToken = await generateToken(
(int.parse(amountFromBudgetController.text) * -1).toString());
await CRUD().post(link: AppLink.addDrivePayment, payload: {
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
'amount': (int.parse(amountFromBudgetController.text) * -1).toString(),
'rideId': paymentID.toString(),
'payment_method': paymentMethod1,
@@ -272,7 +278,7 @@ class CaptainWalletController extends GetxController {
(int.parse(amountFromBudgetController.text) - 5).toString());
paymentToken = await generateToken(amountFromBudgetController.text);
var res1 =
await CRUD().post(link: AppLink.addDriversWalletPoints, payload: {
await CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
'driverID': amountToNewDriverMap[0]['id'].toString(),
'paymentID': paymentID.toString(),
'amount': ((int.parse(amountFromBudgetController.text) - 5))
View File
+184 -98
View File
@@ -1,10 +1,9 @@
import 'dart:convert';
import 'package:local_auth/local_auth.dart';
import 'package:sefer_driver/constant/api_key.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/colors.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/print.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
@@ -12,6 +11,7 @@ import 'package:secure_string_operations/secure_string_operations.dart';
import '../../../constant/char_map.dart';
import '../../../constant/links.dart';
import '../../../views/widgets/mydialoug.dart';
import '../../functions/crud.dart';
import 'captain_wallet_controller.dart';
@@ -52,56 +52,78 @@ class PaymobPayout extends GetxController {
int payOutFee = 5;
payToDriverWallet(
String token, String amount, String issuer, String msisdn) async {
var headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
var body = json.encode({
"amount": amount, //"10.00",
"issuer": issuer, //"vodafone",
"msisdn": msisdn, // "01023456789"
});
var res = await http.post(
Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
headers: headers,
body: body,
);
var dec = jsonDecode(res.body);
if (dec['disbursement_status'] == 'successful') {
var paymentToken = await Get.find<CaptainWalletController>()
.generateToken(
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0));
await CRUD().post(link: AppLink.addDrivePayment, payload: {
'rideId': DateTime.now().toIso8601String(),
'amount': ((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0),
'payment_method': 'payout',
'passengerID': 'myself',
'token': paymentToken,
'driverID': box.read(BoxName.driverID).toString(),
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
var headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
var body = json.encode({
"amount": amount, //"10.00",
"issuer": issuer, //"vodafone",
"msisdn": msisdn, // "01023456789"
});
var res = await http.post(
Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
headers: headers,
body: body,
);
var dec = jsonDecode(res.body);
if (dec['disbursement_status'] == 'successful') {
var paymentToken = await Get.find<CaptainWalletController>()
.generateToken(
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0));
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
'rideId': DateTime.now().toIso8601String(),
'amount':
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0),
'payment_method': 'payout',
'passengerID': 'myself',
'token': paymentToken,
'driverID': box.read(BoxName.driverID).toString(),
});
await Get.find<CaptainWalletController>()
.addSeferWallet('payout fee myself', payOutFee.toString());
await updatePaymentToPaid(box.read(BoxName.driverID).toString());
await sendEmail(
box.read(BoxName.driverID).toString(),
amount,
box.read(BoxName.phoneDriver).toString(),
box.read(BoxName.nameDriver).toString(),
'Wallet',
box.read(BoxName.emailDriver).toString());
mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');
Get.find<CaptainWalletController>().refreshCaptainWallet();
} else if (dec['disbursement_status'] == 'failed') {
mySnackeBarError('Transaction failed'.tr);
}
} else {
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
await Get.find<CaptainWalletController>()
.addSeferWallet('payout fee myself', payOutFee.toString());
await updatePaymentToPaid(box.read(BoxName.driverID).toString());
await sendEmail(
box.read(BoxName.driverID).toString(),
amount,
box.read(BoxName.phoneDriver).toString(),
box.read(BoxName.nameDriver).toString(),
'Wallet',
box.read(BoxName.emailDriver).toString());
mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');
Get.find<CaptainWalletController>().refreshCaptainWallet();
} else if (dec['disbursement_status'] == 'failed') {
mySnackeBarError('Transaction failed'.tr);
}
}
Future updatePaymentToPaid(String driverID) async {
await CRUD().post(link: AppLink.updatePaymetToPaid, payload: {
await CRUD().postWallet(link: AppLink.updatePaymetToPaid, payload: {
'driverID': driverID.toString(),
});
}
@@ -129,66 +151,130 @@ class PaymobPayout extends GetxController {
payToDriverBankAccount(String token, String amount, String bankCardNumber,
String bankCode) async {
var headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
var body = {
"issuer": "bank_card",
"amount": amount, //9.0,
"full_name":
'${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
"bank_card_number": bankCardNumber, //"1111-2222-3333-4444",
"bank_code": bankCode, //"CIB",
"bank_transaction_type": "cash_transfer"
};
var res = await http.post(
Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
headers: headers,
body: body,
);
var dec = jsonDecode(res.body);
if (dec['disbursement_status'] == 'successful') {
var paymentToken = await Get.find<CaptainWalletController>()
.generateToken(
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0));
await CRUD().post(link: AppLink.addDrivePayment, payload: {
'rideId': DateTime.now().toIso8601String(),
'amount': ((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0),
'payment_method': 'payout',
'passengerID': 'myself',
'token': paymentToken,
'driverID': box.read(BoxName.driverID).toString(),
});
await Get.find<CaptainWalletController>()
.addSeferWallet('payout fee myself', payOutFee.toString());
await updatePaymentToPaid(box.read(BoxName.driverID).toString());
await sendEmail(
box.read(BoxName.driverID).toString(),
amount,
box.read(BoxName.phoneDriver).toString(),
box.read(BoxName.nameDriver).toString(),
'Wallet',
box.read(BoxName.emailDriver).toString());
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
var headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
var body = {
"issuer": "bank_card",
"amount": amount, //9.0,
"full_name":
'${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
"bank_card_number": bankCardNumber, //"1111-2222-3333-4444",
"bank_code": bankCode, //"CIB",
"bank_transaction_type": "cash_transfer"
};
var res = await http.post(
Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
headers: headers,
body: body,
);
var dec = jsonDecode(res.body);
if (dec['disbursement_status'] == 'successful') {
var paymentToken = await Get.find<CaptainWalletController>()
.generateToken(
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0));
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
'rideId': DateTime.now().toIso8601String(),
'amount':
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
.toStringAsFixed(0),
'payment_method': 'payout',
'passengerID': 'myself',
'token': paymentToken,
'driverID': box.read(BoxName.driverID).toString(),
});
await Get.find<CaptainWalletController>()
.addSeferWallet('payout fee myself', payOutFee.toString());
await updatePaymentToPaid(box.read(BoxName.driverID).toString());
await sendEmail(
box.read(BoxName.driverID).toString(),
amount,
box.read(BoxName.phoneDriver).toString(),
box.read(BoxName.nameDriver).toString(),
'Wallet',
box.read(BoxName.emailDriver).toString());
mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');
Get.find<CaptainWalletController>().refreshCaptainWallet();
} else if (dec['disbursement_status'] == 'failed') {
mySnackeBarError('Transaction failed'.tr);
mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');
Get.find<CaptainWalletController>().refreshCaptainWallet();
} else if (dec['disbursement_status'] == 'failed') {
mySnackeBarError('Transaction failed'.tr);
}
} else {
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
}
}
Future payToWalletDriverAll(
String amount, String issuer, String msisdn) async {
String token = await getToken();
await payToDriverWallet(token, amount, issuer, msisdn);
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
String token = await getToken();
await payToDriverWallet(token, amount, issuer, msisdn);
} else {
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
}
}
Future payToBankDriverAll(
String amount, String bankCardNumber, String bankCode) async {
String token = await getToken();
await payToDriverBankAccount(token, amount, bankCardNumber, bankCode);
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
String token = await getToken();
await payToDriverBankAccount(token, amount, bankCardNumber, bankCode);
} else {
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
}
}
}
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
@@ -0,0 +1,218 @@
import 'dart:io';
import 'dart:convert';
abstract class LingoHunter {
/// Extracts translatable strings...
static Future<void> extractAndCreateTranslationFiles({
required String baseLang,
required List<String> langs,
String? projectDirectory,
String? outputDirectory,
bool translateBaseLang = true,
List<RegExp>? additionalRegExps,
bool overrideRegExps = false,
List<String> fileExtensions = const ['.dart'],
}) async {
// 1. Find project root (improved logic)
String projectRoot;
if (projectDirectory != null) {
// Use provided directory, but check if it's valid
if (!await Directory(projectDirectory).exists()) {
throw ArgumentError(
"The provided projectDirectory '$projectDirectory' does not exist.");
}
projectRoot = projectDirectory;
} else {
projectRoot = await _findProjectRoot(); // Use the corrected function
}
// 2. Use the project root as output directory if not specified
final String outputDir = outputDirectory ?? projectRoot;
// 3. Output Directory Verification (Create if necessary)
final Directory outputDirObj = Directory(outputDir);
if (!await outputDirObj.exists()) {
try {
await outputDirObj.create(recursive: true);
} catch (e) {
throw Exception(
"Failed to create output directory: $outputDir. Error: $e");
}
}
print("Project root directory: $projectRoot");
print("Output directory: $outputDir");
// 4. Extract translatable strings
final Set<String> strings = await extractStringsFromFlutterProject(
directory: projectRoot, // Use the validated projectRoot
additionalRegExps: additionalRegExps,
overrideRegExps: overrideRegExps,
fileExtensions: fileExtensions,
);
// 5. Generate translation files
await _createTranslationFiles(
strings: strings,
outputDirectory: outputDir,
baseLang: baseLang,
langs: langs,
translateBaseLang: translateBaseLang,
);
print("Successfully extracted strings and generated translation files.");
}
/// Finds the project's root directory (corrected)
static Future<String> _findProjectRoot() async {
Directory current = Directory.current;
int maxIterations = 10; // Prevent infinite loop
int count = 0;
while (count < maxIterations) {
if (await File('${current.path}/pubspec.yaml').exists()) {
return current.path; // Return the directory *containing* pubspec.yaml
}
if (current.path == current.parent.path) {
break; // Reached root, stop searching
}
current = current.parent;
count++;
}
// If `pubspec.yaml` was not found, throw an exception
throw Exception(
"`pubspec.yaml` not found in the current directory or its parents.");
}
/// Extracts translatable strings (no changes needed here)
static Future<Set<String>> extractStringsFromFlutterProject({
required String directory,
List<RegExp>? additionalRegExps,
bool overrideRegExps = false,
List<String> fileExtensions = const ['.dart'],
}) async {
// ... (rest of the function remains the same) ...
final List<RegExp> defaultPatterns = [
RegExp(r'"([^"]+)"\.tr\(\)'), // "string".tr()
RegExp(r"'([^']+)'\.tr\(\)"), // 'string'.tr()
RegExp(r'"([^"]+)"\.tr'), // "string".tr
RegExp(r"'([^']+)'\.tr"), // 'string'.tr
RegExp(r'"([^"]+)"\.tr\(\w+\)'), // "string".tr(context)
RegExp(r"'([^']+)'\.tr\(\w+\)"), // 'string'.tr(context)
RegExp(r'context\.tr\("([^"]+)"\)'), // context.tr("string")
RegExp(r"context\.tr\('([^']+)'\)"), // context.tr('string')
RegExp(r'tr\(\w+, "([^"]+)"\)'), // tr(context, "string")
RegExp(r"tr\(\w+, '([^']+)'\)"), // tr(context, 'string')
RegExp(r'tr\("([^"]+)"\)'), // tr("string")
RegExp(r"tr\('([^']+)'\)"), // tr('string')
RegExp(r'"([^"]+)"\.tr\(args: \[.*?\]\)'), // "string".tr(args: [])
RegExp(r'"([^"]+)"\.plural\(\d+\)'), // "string".plural(3)
//Intl Package Patterns
RegExp(r'AppLocalizations\.of\(context\)!\.translate\("([^"]+)"\)'),
];
// Determine the patterns to use
List<RegExp> patterns;
if (overrideRegExps && additionalRegExps != null) {
patterns = additionalRegExps;
} else {
patterns = [...defaultPatterns];
if (additionalRegExps != null) {
patterns.addAll(additionalRegExps);
}
}
final Set<String> strings = {};
final Directory projectDirObj = Directory(directory);
// Check if the directory exists *before* listing
if (!await projectDirObj.exists()) {
throw ArgumentError("The directory '$directory' does not exist.");
}
final List<FileSystemEntity> entities =
await projectDirObj.list(recursive: true).toList();
// Filter files by the specified extensions
final List<File> filteredFiles = entities
.whereType<File>()
.where((file) => fileExtensions.any((ext) => file.path.endsWith(ext)))
.toList();
// Extract strings from files
for (final File file in filteredFiles) {
final String content = await file.readAsString();
for (final RegExp pattern in patterns) {
final Iterable<RegExpMatch> matches = pattern.allMatches(content);
for (final RegExpMatch match in matches) {
if (match.groupCount >= 1 && match.group(1) != null) {
strings.add(match.group(1)!);
}
}
}
}
return strings;
}
/// Creates translation files (no changes needed)
static Future<void> _createTranslationFiles({
required Set<String> strings,
required String outputDirectory,
required String baseLang,
required List<String> langs,
bool translateBaseLang = true,
}) async {
// ... (rest of the function remains the same) ...
final Directory outputDir = Directory(outputDirectory);
if (!await outputDir.exists()) {
await outputDir.create(recursive: true);
}
// Always create the base language file, even if `translateBaseLang` is false
final String baseFilePath = '$outputDirectory/translations_$baseLang.json';
final Map<String, String> baseStrings = {
for (final string in strings) string: translateBaseLang ? string : ""
};
await _writeTranslationFile(baseFilePath, baseStrings);
for (final String lang in langs) {
final String langFilePath = '$outputDirectory/translations_$lang.json';
final Map<String, String> langStrings = {
for (final string in strings) string: ""
};
await _writeTranslationFile(langFilePath, langStrings);
}
}
/// Writes a translation file (no changes needed)
static Future<void> _writeTranslationFile(
String filePath, Map<String, String> strings) async {
// ... (rest of the function remains the same) ...
final File file = File(filePath);
final StringBuffer content = StringBuffer();
content.writeln('{');
int index = 0;
for (final MapEntry<String, String> entry in strings.entries) {
final String comma = (index < strings.length - 1) ? ',' : '';
final String key =
jsonEncode(entry.key).substring(1, jsonEncode(entry.key).length - 1);
final String value = entry.value.isEmpty
? ""
: jsonEncode(entry.value)
.substring(1, jsonEncode(entry.value).length - 1);
content.writeln(' "$key": "$value"$comma');
index++;
}
content.writeln('}');
await file.writeAsString(content.toString());
}
}
View File
+86 -72
View File
@@ -56,7 +56,7 @@ class PaymentController extends GetxController {
isLoading = true;
update();
await CRUD().get(
await CRUD().getWallet(
link: AppLink.getWalletByPassenger,
payload: {'passenger_id': box.read(BoxName.passengerID)}).then((value) {
box.write(BoxName.passengerWalletTotal,
@@ -71,7 +71,7 @@ class PaymentController extends GetxController {
update();
// double sallaryAccountNowBeforeAdding =
// double.parse(box.read(BoxName.passengerWalletTotal).toString());
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
await CRUD().postWallet(link: AppLink.addPassengersWallet, payload: {
'passenger_id': box.read(BoxName.passengerID).toString(),
'balance': selectedAmount.toString()
}).then((value) {
@@ -440,8 +440,11 @@ class PaymentController extends GetxController {
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
);
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
final PaymobResponse? response = await PaymobPayment.instance.pay(
context: context,
@@ -490,73 +493,84 @@ class PaymentController extends GetxController {
);
}
} else {
Get.snackbar("Authentication Failed",
"Please enable Face ID or Fingerprint in your settings.");
// Authentication failed, handle accordingly
}
} else {
final PaymobResponse? response = await PaymobPayment.instance.pay(
context: context,
currency: currency, //"EGP",
amountInCents: newAmount, // 19.00 EGP
billingData: PaymobBillingData(),
onPayment: (PaymobResponse response) {},
);
if (response!.responseCode == 'APPROVED') {
Get.defaultDialog(
barrierDismissible: false,
title: 'Payment Successful'.tr,
titleStyle: AppStyle.title,
// backgroundColor: AppColor.greenColor,
content: Text(
'The payment was approved.'.tr,
style: AppStyle.title,
),
confirm: MyElevatedButton(
kolor: AppColor.greenColor,
title: 'OK'.tr,
onPressed: () async {
Get.back();
method();
},
),
);
} else {
Get.defaultDialog(
barrierDismissible: false,
// backgroundColor: AppColor.redColor,
title: 'Payment Failed'.tr,
content: Column(
children: [
IconButton(
onPressed: () {
Get.find<TextToSpeechController>().speakText(
'The payment was not approved. Please try again.'.tr,
);
},
icon: const Icon(Icons.headphones),
),
Text(
'The payment was not approved. Please try again.'.tr,
textAlign: TextAlign.center,
style: AppStyle.title,
),
Text(
'${'The reason is'.tr} ${response.message!.tr}',
textAlign: TextAlign.center,
style: AppStyle.title.copyWith(color: AppColor.redColor),
),
],
),
confirm: MyElevatedButton(
title: 'OK'.tr,
kolor: AppColor.redColor,
onPressed: () async {
Get.back();
},
),
);
}
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
// Authentication failed, handle accordingly
}
// else {
// final PaymobResponse? response = await PaymobPayment.instance.pay(
// context: context,
// currency: currency, //"EGP",
// amountInCents: newAmount, // 19.00 EGP
// billingData: PaymobBillingData(),
// onPayment: (PaymobResponse response) {},
// );
// if (response!.responseCode == 'APPROVED') {
// Get.defaultDialog(
// barrierDismissible: false,
// title: 'Payment Successful'.tr,
// titleStyle: AppStyle.title,
// // backgroundColor: AppColor.greenColor,
// content: Text(
// 'The payment was approved.'.tr,
// style: AppStyle.title,
// ),
// confirm: MyElevatedButton(
// kolor: AppColor.greenColor,
// title: 'OK'.tr,
// onPressed: () async {
// Get.back();
// method();
// },
// ),
// );
// } else {
// Get.defaultDialog(
// barrierDismissible: false,
// // backgroundColor: AppColor.redColor,
// title: 'Payment Failed'.tr,
// content: Column(
// children: [
// IconButton(
// onPressed: () {
// Get.find<TextToSpeechController>().speakText(
// 'The payment was not approved. Please try again.'.tr,
// );
// },
// icon: const Icon(Icons.headphones),
// ),
// Text(
// 'The payment was not approved. Please try again.'.tr,
// textAlign: TextAlign.center,
// style: AppStyle.title,
// ),
// Text(
// '${'The reason is'.tr} ${response.message!.tr}',
// textAlign: TextAlign.center,
// style: AppStyle.title.copyWith(color: AppColor.redColor),
// ),
// ],
// ),
// confirm: MyElevatedButton(
// title: 'OK'.tr,
// kolor: AppColor.redColor,
// onPressed: () async {
// Get.back();
// },
// ),
// );
// }
// }
} catch (e) {
Get.defaultDialog(
title: 'Error'.tr,
@@ -577,11 +591,11 @@ class PaymentController extends GetxController {
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: const AuthenticationOptions(
biometricOnly: true, // Only biometrics (no fallback to PIN/pattern)
),
);
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
final PaymobResponseWallet? response =
await PaymobPaymentWallet.instance.pay(
View File
View File
View File
View File
View File
View File
View File
View File
View File
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File

Some files were not shown because too many files have changed in this diff Show More