25-7-28-2

This commit is contained in:
Hamza-Ayed
2025-07-28 12:21:28 +03:00
parent 660d60e1f5
commit 83a97baed1
549 changed files with 109870 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import 'crud.dart';
addError(String error, where) async {
CRUD().post(link: AppLink.addError, payload: {
'error': error.toString(), // Example error description
'userId': box.read(BoxName.driverID) ??
box.read(BoxName.passengerID), // Example user ID
'userType': box.read(BoxName.driverID) != null
? 'Driver'
: 'passenger', // Example user type
'phone': box.read(BoxName.phone) ??
box.read(BoxName.phoneDriver), // Example phone number
'device': where
});
}

View File

@@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:get/get.dart';
class AudioController extends GetxController {
final AudioPlayer _audioPlayer = AudioPlayer();
Future<void> playAudio() async {
// Check if the platform is Android
if (Theme.of(Get.context!).platform == TargetPlatform.android) {
try {
// Load the audio file from the raw resources
await _audioPlayer.setAsset(
'assets/order1.wav'); // Adjust the path based on your project structure
_audioPlayer.play();
} catch (e) {
// Handle errors, such as file not found
print('Error playing audio: $e');
}
}
}
Future<void> playAudio1(String path) async {
// Check if the platform is Android
// if (Theme.of(Get.context!).platform == TargetPlatform.android) {
try {
// Load the audio file from the raw resources
await _audioPlayer
.setAsset(path); // Adjust the path based on your project structure
_audioPlayer.play();
} catch (e) {
// Handle errors, such as file not found
print('Error playing audio: $e');
}
// }
}
@override
void onClose() {
// Release resources when done
_audioPlayer.dispose();
super.onClose();
}
}

View File

@@ -0,0 +1,129 @@
// import 'package:SEFER/constant/api_key.dart';
// import 'package:SEFER/controller/functions/crud.dart';
// // import 'package:agora_rtc_engine/agora_rtc_engine.dart';
// import 'package:get/get.dart';
// import 'package:permission_handler/permission_handler.dart';
// import '../../constant/box_name.dart';
// import '../firebase/firbase_messge.dart';
// import '../home/captin/map_driver_controller.dart';
// import '../../main.dart';
// class CallController extends GetxController {
// String channelName = ''; // Get.find<MapDriverController>().rideId;
// String token = '';
// // int uid = int.parse(box.read(BoxName.phoneDriver)); // uid of the local user
// int uid = 0;
// int? remoteUid; // uid of the remote user
// bool _isJoined = false; // Indicates if the local user has joined the channel
// String status = '';
// // late RtcEngine agoraEngine; // Agora engine instance
// @override
// void onInit() {
// super.onInit();
// channelName = Get.find<MapDriverController>().rideId; // 'sefer300'; //
// remoteUid = int.parse(Get.find<MapDriverController>().passengerPhone);
// uid = int.parse(box.read(BoxName.phoneDriver));
// initAgoraFull();
// }
// initAgoraFull() async {
// await fetchToken();
// // Set up an instance of Agora engine
// setupVoiceSDKEngine();
// // join();
// FirebaseMessagesController().sendNotificationToPassengerTokenCALL(
// 'Call Income',
// '${'You have call from driver'.tr} ${box.read(BoxName.nameDriver)}',
// Get.find<MapDriverController>().tokenPassenger,
// [
// token,
// channelName,
// uid.toString(),
// remoteUid.toString(),
// ],
// );
// join();
// }
// @override
// void onClose() {
// // agoraEngine.leaveChannel();
// super.onClose();
// }
// // Future<void> setupVoiceSDKEngine() async {
// // // retrieve or request microphone permission
// // await [Permission.microphone].request();
// // //create an instance of the Agora engine
// // agoraEngine = createAgoraRtcEngine();
// // await agoraEngine.initialize(RtcEngineContext(appId: AK.agoraAppId));
// // // Register the event handler
// // agoraEngine.registerEventHandler(
// // RtcEngineEventHandler(
// // onJoinChannelSuccess: (RtcConnection connection, int elapsed) {
// // // Get.snackbar(
// // // "Local user uid:${connection.localUid} joined the channel", '');
// // status = 'joined'.tr;
// // _isJoined = true;
// // update();
// // },
// // onUserJoined: (RtcConnection connection, int remoteUid, int elapsed) {
// // // Get.snackbar("Remote user uid:$remoteUid joined the channel", '');
// // status = '${Get.find<MapDriverController>().passengerName} '
// // 'joined'
// // .tr;
// // remoteUid = remoteUid;
// // update();
// // },
// // onUserOffline: (RtcConnection connection, int? remoteUid,
// // UserOfflineReasonType reason) {
// // // Get.snackbar("Remote user uid:$remoteUid left the channel", '');
// // status = 'Call Left'.tr;
// // remoteUid = null;
// // update();
// // },
// // ),
// // );
// // }
// // void join() async {
// // // Set channel options including the client role and channel profile
// // ChannelMediaOptions options = const ChannelMediaOptions(
// // clientRoleType: ClientRoleType.clientRoleBroadcaster,
// // channelProfile: ChannelProfileType.channelProfileCommunication,
// // );
// // await agoraEngine.joinChannel(
// // token: token,
// // channelId: channelName,
// // options: options,
// // uid: uid,
// // );
// // }
// // void leave() {
// // _isJoined = false;
// // remoteUid = null;
// // update();
// // agoraEngine.leaveChannel();
// // }
// // // Clean up the resources when you leave
// // @override
// // void dispose() async {
// // await agoraEngine.leaveChannel();
// // super.dispose();
// // }
// fetchToken() async {
// var res = await CRUD()
// .getAgoraToken(channelName: channelName, uid: uid.toString());
// token = res;
// update();
// }
// }

View File

@@ -0,0 +1,236 @@
import 'dart:convert';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:get/get.dart';
// import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:path/path.dart' as path;
import 'package:http/http.dart' as http;
import '../../main.dart';
class CameraClassController extends GetxController {
late CameraController cameraController;
late List<CameraDescription> cameras;
bool isCameraInitialized = false;
// final TextRecognizer _textRecognizer = TextRecognizer();
String? scannedText;
bool isloading = false;
@override
void onInit() {
super.onInit();
initializeCamera();
}
Future<void> initializeCamera() async {
try {
cameras = await availableCameras();
//update();
cameraController = CameraController(
cameras[0],
ResolutionPreset.medium,
enableAudio: false,
);
await cameraController.initialize();
isCameraInitialized = true;
update();
} catch (e) {
if (e is CameraException) {
switch (e.code) {
case 'CameraAccessDenied':
Get.defaultDialog(
title: 'Camera Access Denied.'.tr,
middleText: '',
confirm:
MyElevatedButton(title: 'Open Settings'.tr, onPressed: () {}),
);
break;
default:
// Handle other errors here.
break;
}
}
}
}
var imgUrl = '';
Future extractCardId() async {
// Construct the path for the image file
final directory = await path_provider.getTemporaryDirectory();
final imagePath =
path.join(directory.path, '${box.read(BoxName.driverID)}.png');
// Capture the image and save it to the specified path
final XFile capturedImage = await cameraController.takePicture();
// Move the captured image to the desired path
await capturedImage.saveTo(imagePath);
await uploadImage(File(capturedImage.path));
extractByAPI('${AppLink.server}/card_image/' + box.read(BoxName.driverID));
}
Future extractByAPI(String imgUrl) async {
var headers = {'apikey': 'K89368168788957'};
var request = http.MultipartRequest(
'POST', Uri.parse('https://api.ocr.space/parse/image'));
request.fields.addAll({
'language': 'ara',
'isOverlayRequired': 'false',
'url': imgUrl,
'iscreatesearchablepdf': 'false',
'issearchablepdfhidetextlayer': 'false'
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
} else {}
}
Future<String> uploadImage(File imageFile) async {
String? basicAuthCredentials =
await storage.read(key: BoxName.basicAuthCredentials);
var request = http.MultipartRequest(
'POST',
Uri.parse(AppLink.uploadImage),
);
// Attach the image file to the request
request.files.add(
await http.MultipartFile.fromPath('image', imageFile.path),
); // Add the headers to the request
request.headers.addAll({
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Basic ${base64Encode(utf8.encode(basicAuthCredentials.toString()))}',
});
// Add the driverID to the request
request.fields['driverID'] = box.read(BoxName.driverID);
// Send the request
var response = await request.send();
// Read the response
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
scannedText = responseString;
update();
// Return the link received from the server
return responseString;
}
// Future<void> takePictureAndMLGoogleScan() async {
// try {
// // Construct the path for the image file
// final directory = await path_provider.getTemporaryDirectory();
// final imagePath =
// path.join(directory.path, '${box.read(BoxName.driverID)}.png');
// // Capture the image and save it to the specified path
// final XFile capturedImage = await cameraController.takePicture();
// // Move the captured image to the desired path
// await capturedImage.saveTo(imagePath);
// // Recognize the text in the image
// final InputImage inputImage =
// InputImage.fromFile(File(capturedImage.path));
// final RecognizedText recognizedText =
// await _textRecognizer.processImage(inputImage);
// scannedText = recognizedText.text;
// // Extract the scanned text line by line
// final List<Map<String, dynamic>> lines = [];
// for (var i = 0; i < recognizedText.blocks.length; i++) {
// lines.add({
// 'line_number': i,
// 'text': recognizedText.blocks[i].text,
// });
// }
// // Convert the list of lines to a JSON string
// final String jsonOutput = jsonEncode(lines);
// update();
// // Print the JSON output
// // Get.back();
// } catch (e) {}
// }
String getTextAsJSON(String text) {
final lines = text.split('\n');
final jsonList = lines.map((line) {
return {
'line_text': line,
'num_words': line.trim().split(' ').length,
};
}).toList();
final json = {
'lines': jsonList,
'num_lines': lines.length,
};
return jsonEncode(json);
}
List<String> getTextBlocks(String text) {
return text.split('\n');
}
// Future<void> takePictureAndTesseractScan() async {
// try {
// // Construct the path for the image file
// final directory = await path_provider.getTemporaryDirectory();
// final imagePath =
// path.join(directory.path, '${box.read(BoxName.driverID)}.png');
// // Capture the image and save it to the specified path
// final XFile capturedImage = await cameraController.takePicture();
// // Move the captured image to the desired path
// await capturedImage.saveTo(imagePath);
// // Recognize the text in the image
// final languages = [
// 'eng',
// 'ara'
// ]; // Specify the languages you want to use for text extraction
// final text = await FlutterTesseractOcr.extractText(imagePath,
// language: languages.join('+'), // Combine multiple languages with '+'
// args: {
// "psm": "4",
// "preserve_interword_spaces": "1",
// // "rectangle": const Rect.fromLTWH(100, 100, 200, 200),
// } // Additional options if needed
// );
// isloading = false;
// final jsonText = getTextAsJSON(text);
// final textBlocks = getTextBlocks(text);
// update();
// scannedText =
// textBlocks.toString(); // Convert the extracted text to JSON.
// // Print the JSON to the console.
// update();
// } catch (e) {
// scannedText = '';
// }
// }
@override
void onClose() {
cameraController.dispose();
super.onClose();
}
}

View File

@@ -0,0 +1,624 @@
import 'dart:convert';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
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 '../../constant/api_key.dart';
import '../../constant/char_map.dart';
import '../../constant/info.dart';
import '../../print.dart';
import 'gemeni.dart';
import 'upload_image.dart';
class CRUD {
Future<dynamic> get({
required String link,
Map<String, dynamic>? payload,
}) async {
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
// Log.print('isTokenExpired: ${isTokenExpired}');
if (isTokenExpired) {
await LoginDriverController().getJWT();
}
// await Get.put(LoginDriverController()).getJWT();
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
},
);
print(response.request);
Log.print('response.body: ${response.body}');
print(payload);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return response.body;
}
return jsonData['status'];
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
await Get.put(LoginDriverController()).getJWT();
// mySnackbarSuccess('please order now'.tr);
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';
}
}
Future<dynamic> getWallet({
required String link,
Map<String, dynamic>? payload,
}) async {
var s = await LoginDriverController().getJwtWallet();
final hmac = box.read(BoxName.hmac);
// Log.print('hmac: ${hmac}');
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $s',
'X-HMAC-Auth': hmac.toString(),
},
);
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') {
return response.body;
}
return jsonData['status'];
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
// await Get.put(LoginDriverController()).getJwtWallet();
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';
}
}
Future<dynamic> postWallet(
{required String link, Map<String, dynamic>? payload}) async {
var s = await LoginDriverController().getJwtWallet();
// Log.print('jwt: ${s}');
final hmac = box.read(BoxName.hmac);
// Log.print('hmac: ${hmac}');
var url = Uri.parse(link);
// Log.print('url: ${url}');
try {
// await LoginDriverController().getJWT();
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $s',
'X-HMAC-Auth': hmac.toString(),
},
);
Log.print('response.request:${response.request}');
Log.print('response.body: ${response.body}');
Log.print('payload:$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);
try {
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
if (isTokenExpired) {
await LoginDriverController().getJWT();
}
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
// 'Authorization': 'Bearer ${box.read(BoxName.jwt)}'
},
);
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(), url);
return 'failure';
}
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
// await Get.put(LoginDriverController()).getJWT();
// MyDialog().getDialog(
// 'Session expired. Please log in again.'.tr,
// '',
// () {
// Get.put(LoginController()).loginUsingCredentials(
// box.read(BoxName.passengerID), box.read(BoxName.email));
// Get.back();
// },
// );
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> getAgoraToken({
required String channelName,
required String uid,
}) async {
var uid = box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver);
var res = await http.get(Uri.parse(
// 'https://repulsive-pig-rugby-shirt.cyclic.app/token?channelName=$channelName'),
'https://orca-app-b2i85.ondigitalocean.app/token?channelName=$channelName'),
headers: {'Authorization': 'Bearer ${AK.agoraAppCertificate}'});
if (res.statusCode == 200) {
var response = jsonDecode(res.body);
return response['token'];
} else {}
}
Future<dynamic> getLlama({
required String link,
required String payload,
required String prompt,
}) async {
var url = Uri.parse(
link,
);
var headers = {
'Content-Type': 'application/json',
'Authorization':
'Bearer LL-X5lJ0Px9CzKK0HTuVZ3u2u4v3tGWkImLTG7okGRk4t25zrsLqJ0qNoUzZ2x4ciPy'
// 'Authorization': 'Bearer ${Env.llamaKey}'
};
var data = json.encode({
"model": "Llama-3-70b-Inst-FW",
// "model": "llama-13b-chat",
"messages": [
{
"role": "user",
"content":
"Extract the desired information from the following passage as json decoded like $prompt just in this:\n\n$payload"
}
],
"temperature": 0.9
});
var response = await http.post(
url,
body: data,
headers: headers,
);
if (response.statusCode == 200) {
return response.body;
}
return response.statusCode;
}
Future allMethodForAI(String prompt, linkPHP, imagePath) async {
await ImageController().choosImage(linkPHP, imagePath);
Future.delayed(const Duration(seconds: 2));
var extractedString =
await arabicTextExtractByVisionAndAI(imagePath: imagePath);
var json = jsonDecode(extractedString);
var textValues = extractTextFromLines(json);
// await Get.put(AI()).geminiAiExtraction(prompt, textValues);
await Get.put(AI()).anthropicAI(textValues, prompt, imagePath);
}
String extractTextFromLines(Map<String, dynamic> jsonData) {
final readResult = jsonData['readResult'];
final blocks = readResult['blocks'];
final StringBuffer buffer = StringBuffer();
for (final block in blocks) {
final lines = block['lines'];
for (final line in lines) {
final text = line['text'];
buffer.write(text);
buffer.write('\n');
}
}
return buffer.toString().trim();
}
Future<dynamic> arabicTextExtractByVisionAndAI({
required String imagePath,
}) async {
var headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': AK.ocpApimSubscriptionKey
};
String imagePathFull =
'${AppLink.server}/card_image/$imagePath-${box.read(BoxName.driverID)}.jpg';
var request = http.Request('POST', Uri.parse(
// 'https://ocrhamza.cognitiveservices.azure.com/vision/v2.1/ocr?language=ar'));
// 'https://eastus.api.cognitive.microsoft.com/vision/v3.2/ocr'
'https://eastus.api.cognitive.microsoft.com/computervision/imageanalysis:analyze?features=caption,read&model-version=latest&language=en&api-version=2024-02-01'));
request.body = json.encode({"url": imagePathFull});
// request.body = json.encode({"url": imagePathFull});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// 'response.stream.bytesToString(): ${await response.stream.bytesToString()}');
return await response.stream.bytesToString();
} else {}
}
Future<dynamic> getChatGPT({
required String link,
required String payload,
}) async {
var url = Uri.parse(
link,
);
var headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ${Env.chatGPTkeySeferNew}'
};
var data = json.encode({
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content":
"Extract the desired information from the following passage as json decoded like vin,make,made,year,expiration_date,color,owner,registration_date just in this:\n\n$payload"
}
],
"temperature": 0.9
});
var response = await http.post(
url,
body: data,
headers: headers,
);
if (response.statusCode == 200) {
return response.body;
}
return response.statusCode;
}
Future<dynamic> postStripe({
required String link,
Map<String, dynamic>? payload,
}) async {
// String? secretKey = await storage.read(key: BoxName.secretKey);
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer ${AK.secretKeyStripe}',
},
);
if (response.statusCode == 200) {
return response.body;
} else {}
}
Future<dynamic> postPayMob({
required String link,
Map<String, dynamic>? payload,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse(
link,
);
var response = await http.post(url,
body: payload, headers: {'Content-Type': 'application/json'});
var jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
if (jsonData['status'] == 'success') {
return response.body;
} else {
return (jsonData['status']);
}
} else {
return response.statusCode;
}
}
Future<void> sendEmail(String link, Map<String, String>? payload) async {
// التحقق من صلاحية التوكن
String rawJwt = box.read(BoxName.jwt);
String token = X
.r(X.r(X.r(rawJwt, cn), cC), cs)
.toString()
.split(AppInformation.addd)[0];
bool isTokenExpired = JwtDecoder.isExpired(token);
if (isTokenExpired) {
await LoginDriverController().getJWT();
rawJwt = box.read(BoxName.jwt); // تحديث التوكن بعد التجديد
token = X
.r(X.r(X.r(rawJwt, cn), cC), cs)
.toString()
.split(AppInformation.addd)[0];
}
// إعداد الهيدر
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer $token",
};
// إعداد الطلب
final request = http.Request('POST', Uri.parse(link));
request.bodyFields = payload ?? {};
request.headers.addAll(headers);
// إرسال الطلب
final response = await request.send();
// التحقق من النتيجة
if (response.statusCode == 200) {
print("✅ Email sent successfully.");
} else {
print("❌ Failed to send email. Status: ${response.statusCode}");
final responseBody = await response.stream.bytesToString();
print("Response body: $responseBody");
}
}
Future<dynamic> postFromDialogue({
required String link,
Map<String, dynamic>? payload,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
);
if (response.body.isNotEmpty) {
var jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
if (jsonData['status'] == 'success') {
Get.back();
// Get.snackbar(
// jsonData['status'],
// jsonData['message'],
// );
return response.body;
}
}
return (jsonData['status']);
}
}
Future<void> sendVerificationRequest(String phoneNumber) async {
final accountSid = AK.accountSIDTwillo;
final authToken = AK.authTokenTwillo;
final verifySid = AK.twilloRecoveryCode;
final Uri verificationUri = Uri.parse(
'https://verify.twilio.com/v2/Services/$verifySid/Verifications');
// Send the verification request
final response = await http.post(
verificationUri,
headers: {
'Authorization':
'Basic ' + base64Encode(utf8.encode('$accountSid:$authToken')),
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
'To': phoneNumber,
'Channel': 'sms',
},
);
if (response.statusCode == 201) {
} else {}
// Prompt the user to enter the OTP
final otpCode = "123456"; // Replace with user input
// Check the verification code
final checkUri = Uri.parse(
'https://verify.twilio.com/v2/Services/$verifySid/VerificationCheck');
final checkResponse = await http.post(
checkUri,
headers: {
'Authorization':
'Basic ' + base64Encode(utf8.encode('$accountSid:$authToken')),
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
'To': phoneNumber,
'Code': otpCode,
},
);
if (checkResponse.statusCode == 201) {
} else {}
}
Future<dynamic> getGoogleApi({
required String link,
Map<String, dynamic>? payload,
}) async {
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
);
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'OK') {
return jsonData;
}
return (jsonData['status']);
}
Future<dynamic> update({
required String endpoint,
required Map<String, dynamic> data,
required String id,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse('$endpoint/$id');
var response = await http.put(
url,
body: json.encode(data),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
);
return json.decode(response.body);
}
Future<dynamic> delete({
required String endpoint,
required String id,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse('$endpoint/$id');
var response = await http.delete(
url,
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
);
return json.decode(response.body);
}
}

View File

@@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
class LineChartPainter extends CustomPainter {
final List<double> data;
LineChartPainter(this.data);
@override
void paint(Canvas canvas, Size size) {
// Calculate the scale factor.
final scaleFactor = size.height / 240;
// Draw the line chart.
for (var i = 0; i < data.length - 1; i++) {
final x1 = i * size.width / data.length;
final y1 = data[i] * scaleFactor;
final x2 = (i + 1) * size.width / data.length;
final y2 = data[i + 1] * scaleFactor;
canvas.drawLine(Offset(x1, y1), Offset(x2, y2), Paint());
}
}
@override
bool shouldRepaint(LineChartPainter oldDelegate) => false;
}

View File

@@ -0,0 +1,80 @@
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:get_storage/get_storage.dart';
import '../../constant/box_name.dart';
class DeviceInfo {
final String? manufacturer;
final String? model;
final String? deviceId;
final String? osVersion;
final String? platform;
final String? deviceName;
final bool? isPhysicalDevice;
DeviceInfo({
this.manufacturer,
this.model,
this.deviceId,
this.osVersion,
this.platform,
this.deviceName,
this.isPhysicalDevice,
});
Map<String, dynamic> toJson() => {
'manufacturer': manufacturer,
'model': model,
'deviceId': deviceId,
'osVersion': osVersion,
'platform': platform,
'deviceName': deviceName,
'isPhysicalDevice': isPhysicalDevice,
};
}
class DeviceController {
final box = GetStorage();
final _deviceInfo = DeviceInfoPlugin();
Future<DeviceInfo> getDeviceInfo() async {
if (Platform.isAndroid) {
return await _getAndroidDeviceInfo();
} else if (Platform.isIOS) {
return await _getIosDeviceInfo();
}
throw UnsupportedError('Unsupported platform');
}
Future<DeviceInfo> _getAndroidDeviceInfo() async {
final androidInfo = await _deviceInfo.androidInfo;
final deviceInfo = DeviceInfo(
manufacturer: androidInfo.manufacturer,
model: androidInfo.model,
deviceId: androidInfo.serialNumber,
osVersion: androidInfo.version.release,
platform: 'Android',
deviceName: androidInfo.device,
isPhysicalDevice: androidInfo.isPhysicalDevice,
);
box.write(BoxName.deviceInfo, deviceInfo.toJson());
return deviceInfo;
}
Future<DeviceInfo> _getIosDeviceInfo() async {
final iosInfo = await _deviceInfo.iosInfo;
final deviceInfo = DeviceInfo(
manufacturer: 'Apple',
model: iosInfo.model,
deviceId: iosInfo.identifierForVendor,
osVersion: iosInfo.systemVersion,
platform: 'iOS',
deviceName: iosInfo.name,
isPhysicalDevice: iosInfo.isPhysicalDevice,
);
box.write(BoxName.deviceInfo, deviceInfo.toJson());
return deviceInfo;
}
}

View File

@@ -0,0 +1,42 @@
import 'package:flutter/services.dart';
class DigitObscuringFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
final maskedText = maskDigits(newValue.text);
return newValue.copyWith(
text: maskedText,
selection: updateCursorPosition(maskedText, newValue.selection));
}
String maskDigits(String text) {
final totalDigits = text.length;
final visibleDigits = 4;
final hiddenDigits = totalDigits - visibleDigits * 2;
final firstVisibleDigits = text.substring(0, visibleDigits);
final lastVisibleDigits = text.substring(totalDigits - visibleDigits);
final maskedDigits = List.filled(hiddenDigits, '*').join();
return '$firstVisibleDigits$maskedDigits$lastVisibleDigits';
}
TextSelection updateCursorPosition(
String maskedText, TextSelection currentSelection) {
final cursorPosition = currentSelection.baseOffset;
final cursorOffset =
currentSelection.extentOffset - currentSelection.baseOffset;
final totalDigits = maskedText.length;
const visibleDigits = 4;
final hiddenDigits = totalDigits - visibleDigits * 2;
final updatedPosition = cursorPosition <= visibleDigits
? cursorPosition
: hiddenDigits + visibleDigits + (cursorPosition - visibleDigits);
return TextSelection.collapsed(
offset: updatedPosition, affinity: currentSelection.affinity);
}
}

View File

@@ -0,0 +1,41 @@
// import 'dart:io';
//
// import 'package:get/get.dart';
// import 'package:image_picker/image_picker.dart';
// import 'package:google_ml_kit/google_ml_kit.dart';
//
// class ImagePickerController extends GetxController {
// RxBool textScanning = false.obs;
// RxString scannedText = ''.obs;
//
// Future<void> getImage(ImageSource source) async {
// try {
// final pickedImage = await ImagePicker().pickImage(source: source);
// if (pickedImage != null) {
// textScanning.value = true;
// final imageFile = File(pickedImage.path);
// getRecognisedText(imageFile);
// }
// } catch (e) {
// textScanning.value = false;
// scannedText.value = "Error occurred while scanning";
// }
// }
//
// Future<void> getRecognisedText(File image) async {
// final inputImage = InputImage.fromFilePath(image.path);
// final textDetector = GoogleMlKit.vision.textRecognizer();
// final RecognizedText recognisedText =
// await textDetector.processImage(inputImage);
// await textDetector.close();
//
// scannedText.value = '';
// for (TextBlock block in recognisedText.blocks) {
// for (TextLine line in block.lines) {
// scannedText.value += line.text + '\n';
// }
// }
//
// textScanning.value = false;
// }
// }

View File

@@ -0,0 +1,32 @@
import 'dart:convert';
import 'package:encrypt/encrypt.dart' as encrypt;
import '../../constant/api_key.dart';
class KeyEncryption {
// استخدم مفتاح بطول 32 حرفًا
static final _key = encrypt.Key.fromUtf8(AK.keyOfApp);
static final _iv =
encrypt.IV.fromLength(16); // توليد تهيئة عشوائية بطول 16 بايت
static String encryptKey(String key) {
final encrypter =
encrypt.Encrypter(encrypt.AES(_key, mode: encrypt.AESMode.cbc));
final encrypted = encrypter.encrypt(key, iv: _iv);
final result = _iv.bytes + encrypted.bytes; // تضمين التهيئة مع النص المشفر
return base64Encode(result);
}
static String decryptKey(String encryptedKey) {
print('encryptedKey: ${AK.keyOfApp}');
final decoded = base64Decode(encryptedKey);
print('encryptedKey: $encryptedKey');
final iv = encrypt.IV(decoded.sublist(0, 16)); // استخراج التهيئة
final encrypted =
encrypt.Encrypted(decoded.sublist(16)); // استخراج النص المشفر
final encrypter =
encrypt.Encrypter(encrypt.AES(_key, mode: encrypt.AESMode.cbc));
return encrypter.decrypt(encrypted, iv: iv);
}
}

View File

@@ -0,0 +1,79 @@
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import '../../constant/box_name.dart';
import '../../constant/char_map.dart';
import '../../env/env.dart';
import '../../main.dart';
class EncryptionHelper {
static EncryptionHelper? _instance;
late final encrypt.Key key;
late final encrypt.IV iv;
EncryptionHelper._(this.key, this.iv);
static EncryptionHelper get instance {
if (_instance == null) {
throw Exception(
"EncryptionHelper is not initialized. Call `await EncryptionHelper.initialize()` in main.");
}
return _instance!;
}
/// Initializes and stores the instance globally
static Future<void> initialize() async {
if (_instance != null) {
debugPrint("EncryptionHelper is already initialized.");
return; // Prevent re-initialization
}
debugPrint("Initializing EncryptionHelper...");
// Read stored keys
var keyOfApp = r(Env.keyOfApp).toString().split(Env.addd)[0];
var initializationVector =
r(Env.initializationVector).toString().split(Env.addd)[0];
// Log.print('initializationVector: ${initializationVector}');
// Set the global instance
_instance = EncryptionHelper._(
encrypt.Key.fromUtf8(keyOfApp),
encrypt.IV.fromUtf8(initializationVector),
);
debugPrint("EncryptionHelper initialized successfully.");
}
/// Encrypts a string
String encryptData(String plainText) {
try {
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc)); // AES-GCM
final encrypted = encrypter.encrypt(plainText, iv: iv);
return encrypted.base64;
} catch (e) {
debugPrint('Encryption Error: $e');
return '';
}
}
/// Decrypts a string
String decryptData(String encryptedText) {
try {
final encrypter =
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
final encrypted = encrypt.Encrypted.fromBase64(encryptedText);
return encrypter.decrypt(encrypted, iv: iv);
} catch (e) {
debugPrint('Decryption Error: $e');
return '';
}
}
}
r(String string) {
return X.r(X.r(X.r(string, cn), cC), cs).toString();
}
c(String string) {
return X.c(X.c(X.c(string, cn), cC), cs).toString();
}

View File

@@ -0,0 +1,95 @@
import 'dart:convert';
import 'dart:io';
import 'package:sefer_driver/constant/api_key.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/main.dart';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import '../../constant/links.dart';
import 'encrypt_decrypt.dart';
import 'upload_image.dart';
Future<String> faceDetector() async {
await ImageController().choosFace(AppLink.uploadEgypt, 'face_detect');
await Future.delayed(const Duration(seconds: 2));
var headers = {
// 'Authorization': 'Basic ${AK.basicCompareFaces}',
'Authorization': 'Basic hamza:12345678',
'Content-Type': 'application/json'
};
// var request = http.Request('POST', Uri.parse(//Todo
// 'https://face-detect-f6924392c4c7.herokuapp.com/compare_faces'));
var request = http.Request(
'POST', Uri.parse('https://mohkh.online:5000/compare_faces'));
request.body = json.encode({
"url1":
"${AppLink.seferCairoServer}/card_image/id_front-${(box.read(BoxName.driverID))}.jpg",
"url2":
"https://api.sefer.live/sefer/card_image/face_detect-${(box.read(BoxName.driverID))}.jpg"
});
print('request.body: ${request.body}');
request.headers.addAll(headers);
try {
http.Client client = await createHttpClient();
http.StreamedResponse response = await client.send(request);
// http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
String result = await response.stream.bytesToString();
print('result: ${result}');
return result;
} else {
print('Error: ${response.reasonPhrase}');
return 'Error: ${response.reasonPhrase}';
}
} catch (e) {
print('Exception occurred: $e');
return 'Error: $e';
}
}
Future<http.Client> createHttpClient() async {
final SecurityContext securityContext = SecurityContext();
HttpClient httpClient = HttpClient(context: securityContext);
httpClient.badCertificateCallback =
(X509Certificate cert, String host, int port) => true; // Bypass SSL
return IOClient(httpClient);
}
Future<String> faceDetector2(String url1, String url2) async {
var headers = {
'Authorization': 'Basic hamza:12345678',
'Content-Type': 'application/json'
};
var request = http.Request(
'POST', Uri.parse('https://mohkh.online:5000/compare_faces'));
request.body = json.encode({"url1": url1, "url2": url2});
request.headers.addAll(headers);
try {
http.Client client = await createHttpClient(); // Use custom client
DateTime startTime = DateTime.now();
http.StreamedResponse response = await client.send(request);
DateTime endTime = DateTime.now();
Duration duration = endTime.difference(startTime);
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
print(duration.inSeconds);
return await response.stream.bytesToString();
} else {
print(await response.stream.bytesToString());
return 'Error: ${response.reasonPhrase}';
}
} catch (e) {
return 'Exception: $e';
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,34 @@
import 'package:geolocator/geolocator.dart';
class GeoLocation {
Future<Position> getCurrentLocation() async {
bool serviceEnabled;
LocationPermission permission;
// Check if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled, so we request the user to enable it.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, we cannot fetch the location.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, we cannot request permissions.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can fetch the location.
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
}
}

View File

@@ -0,0 +1,76 @@
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
void showInBrowser(String url) async {
if (await canLaunchUrl(Uri.parse(url))) {
launchUrl(Uri.parse(url));
} else {}
}
Future<void> makePhoneCall(String phoneNumber) async {
final Uri launchUri = Uri(
scheme: 'tel',
path: phoneNumber,
);
await launchUrl(launchUri);
}
void launchCommunication(
String method, String contactInfo, String message) async {
String url;
if (Platform.isIOS) {
switch (method) {
case 'phone':
url = 'tel:$contactInfo';
break;
case 'sms':
url = 'sms:$contactInfo?body=${Uri.encodeComponent(message)}';
break;
case 'whatsapp':
url =
'https://api.whatsapp.com/send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
break;
case 'email':
url =
'mailto:$contactInfo?subject=Subject&body=${Uri.encodeComponent(message)}';
break;
default:
return;
}
} else if (Platform.isAndroid) {
switch (method) {
case 'phone':
url = 'tel:$contactInfo';
break;
case 'sms':
url = 'sms:$contactInfo?body=${Uri.encodeComponent(message)}';
break;
case 'whatsapp':
// Check if WhatsApp is installed
final bool whatsappInstalled =
await canLaunchUrl(Uri.parse('whatsapp://'));
if (whatsappInstalled) {
url =
'whatsapp://send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
} else {
// Provide an alternative action, such as opening the WhatsApp Web API
url =
'https://api.whatsapp.com/send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
}
break;
case 'email':
url =
'mailto:$contactInfo?subject=Subject&body=${Uri.encodeComponent(message)}';
break;
default:
return;
}
} else {
return;
}
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url));
} else {}
}

View File

@@ -0,0 +1,37 @@
import 'dart:convert';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/controller/functions/gemeni.dart';
class LlamaAi {
Future<Map> getCarRegistrationData(String input, prompt) async {
Map exrtatDataFinal = {};
String oneLine = input.replaceAll('\n', ' ');
// var res = await CRUD().getLlama(link: AppLink.gemini, payload: oneLine);
var res = await CRUD()
.getLlama(link: AppLink.llama, payload: oneLine, prompt: prompt);
var decod = jsonDecode(res.toString());
// exrtatDataFinal = jsonDecode(extractDataFromJsonString(decod['choices']));
extractDataFromJsonString(decod['choices'][0]['message']['content']);
return exrtatDataFinal;
}
String extractDataFromJsonString(String jsonString) {
// Remove any leading or trailing whitespace from the string
jsonString = jsonString.trim();
// Extract the JSON substring from the given string
final startIndex = jsonString.indexOf('{');
final endIndex = jsonString.lastIndexOf('}');
final jsonSubstring = jsonString.substring(startIndex, endIndex + 1);
// Parse the JSON substring into a Map
final jsonData = jsonDecode(jsonSubstring);
// Return the extracted data
return jsonEncode(jsonData);
}
}

View File

@@ -0,0 +1,54 @@
// import 'dart:async';
// import 'package:background_location/background_location.dart';
// import 'package:get/get.dart';
// import 'package:permission_handler/permission_handler.dart';
// class LocationBackgroundController extends GetxController {
// @override
// void onInit() {
// super.onInit();
// requestLocationPermission();
// configureBackgroundLocation();
// }
// Future<void> requestLocationPermission() async {
// var status = await Permission.locationAlways.status;
// if (!status.isGranted) {
// await Permission.locationAlways.request();
// }
// }
// Future<void> configureBackgroundLocation() async {
// await BackgroundLocation.setAndroidNotification(
// title: 'Location Tracking Active'.tr,
// message: 'Your location is being tracked in the background.'.tr,
// icon: '@mipmap/launcher_icon',
// );
// BackgroundLocation.setAndroidConfiguration(3000);
// BackgroundLocation.startLocationService();
// BackgroundLocation.getLocationUpdates((location) {
// // Handle location updates here
// });
// }
// startBackLocation() async {
// Timer.periodic(const Duration(seconds: 3), (timer) {
// getBackgroundLocation();
// });
// }
// getBackgroundLocation() async {
// var status = await Permission.locationAlways.status;
// if (status.isGranted) {
// await BackgroundLocation.startLocationService(
// distanceFilter: 20, forceAndroidLocationManager: true);
// BackgroundLocation.setAndroidConfiguration(
// Duration.microsecondsPerSecond); // Set interval to 5 seconds
// BackgroundLocation.getLocationUpdates((location1) {});
// } else {
// await Permission.locationAlways.request();
// }
// }
// }

View File

@@ -0,0 +1,230 @@
import 'dart:async';
import 'dart:math';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:sefer_driver/constant/table_names.dart';
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import '../home/captin/home_captain_controller.dart';
import '../home/payment/captain_wallet_controller.dart';
import 'crud.dart';
import 'encrypt_decrypt.dart';
class LocationController extends GetxController {
LocationData? _currentLocation;
late Location location = Location();
bool isLoading = false;
late double heading = 0;
late double previousTime = 0;
late double latitude;
late double totalDistance = 0;
late double longitude;
late DateTime time;
late double speed = 0;
bool isActive = false;
late LatLng myLocation = LatLng(0, 0);
String totalPoints = '0';
LocationData? get currentLocation => _currentLocation;
Timer? _locationTimer;
LatLng? _lastSavedPosition;
@override
void onInit() async {
super.onInit();
location = Location();
await location.changeSettings(
accuracy: LocationAccuracy.high, interval: 5000, distanceFilter: 0);
location.enableBackgroundMode(enable: true);
await getLocation();
await startLocationUpdates();
totalPoints = Get.put(CaptainWalletController()).totalPoints.toString();
isActive = Get.put(HomeCaptainController()).isActive;
}
String getLocationArea(double latitude, double longitude) {
final locations = box.read(BoxName.locationName) ?? [];
for (final location in locations) {
final locationData = location as Map<String, dynamic>;
final minLatitude =
double.tryParse(locationData['min_latitude'].toString()) ?? 0.0;
final maxLatitude =
double.tryParse(locationData['max_latitude'].toString()) ?? 0.0;
final minLongitude =
double.tryParse(locationData['min_longitude'].toString()) ?? 0.0;
final maxLongitude =
double.tryParse(locationData['max_longitude'].toString()) ?? 0.0;
if (latitude >= minLatitude &&
latitude <= maxLatitude &&
longitude >= minLongitude &&
longitude <= maxLongitude) {
box.write(BoxName.serverChosen, (locationData['server_link']));
return locationData['name'];
}
}
box.write(BoxName.serverChosen, AppLink.seferCairoServer);
return 'Cairo';
}
int _insertCounter = 0;
double? _lastSpeed;
DateTime? _lastSpeedTime;
Future<void> startLocationUpdates() async {
if (box.read(BoxName.driverID) != null) {
_locationTimer =
Timer.periodic(const Duration(seconds: 5), (timer) async {
try {
totalPoints =
Get.find<CaptainWalletController>().totalPoints.toString();
isActive = Get.find<HomeCaptainController>().isActive;
if (isActive && double.parse(totalPoints) > -300) {
await getLocation();
if (myLocation.latitude == 0 && myLocation.longitude == 0) return;
String area =
getLocationArea(myLocation.latitude, myLocation.longitude);
final payload = {
'driver_id': box.read(BoxName.driverID).toString(),
'latitude': myLocation.latitude.toString(),
'longitude': myLocation.longitude.toString(),
'heading': heading.toString(),
'speed': (speed * 3.6).toStringAsFixed(1),
'distance': totalDistance.toStringAsFixed(2),
'status': box.read(BoxName.statusDriverLocation) ?? 'off',
};
// ✅ تحديث للسيرفر
await CRUD().post(
link:
box.read(BoxName.serverChosen) + '/ride/location/update.php',
payload: payload,
);
// ✅ تخزين في SQLite فقط إذا الرحلة On + تحرك أكثر من 10 متر
if ((box.read(BoxName.statusDriverLocation) ?? 'off') == 'on') {
if (_lastSavedPosition == null ||
_calculateDistanceInMeters(_lastSavedPosition!, myLocation) >=
10) {
double currentSpeed = speed; // m/s
double? acceleration = _calculateAcceleration(currentSpeed);
await sql.insertData({
'driver_id': box.read(BoxName.driverID).toString(),
'latitude': myLocation.latitude,
'longitude': myLocation.longitude,
'acceleration': acceleration ?? 0.0,
'created_at': DateTime.now().toIso8601String(),
'updated_at': DateTime.now().toIso8601String(),
}, TableName.behavior);
_lastSavedPosition = myLocation;
}
}
// ✅ إدخال للسيرفر كل دقيقة
_insertCounter++;
// Log.print('_insertCounter: ${_insertCounter}');
if (_insertCounter == 12) {
_insertCounter = 0;
await CRUD().post(
link: box.read(BoxName.serverChosen) + '/ride/location/add.php',
payload: payload,
);
}
// ✅ تحديث الكاميرا
Get.find<HomeCaptainController>()
.mapHomeCaptainController
?.animateCamera(
CameraUpdate.newLatLng(
LatLng(
myLocation.latitude,
myLocation.longitude,
),
),
);
}
} catch (e) {
print('Location update error: $e');
}
});
}
}
void stopLocationUpdates() {
_locationTimer?.cancel();
}
Future<void> getLocation() async {
bool serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) return;
}
PermissionStatus permissionGranted = await location.hasPermission();
if (permissionGranted == PermissionStatus.denied) {
permissionGranted = await location.requestPermission();
if (permissionGranted != PermissionStatus.granted) return;
}
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);
}
speed = _locationData.speed ?? 0;
heading = _locationData.heading ?? 0;
update();
} catch (e) {
print("Error getting location: $e");
}
});
}
double _calculateDistanceInMeters(LatLng start, LatLng end) {
const p = 0.017453292519943295;
final a = 0.5 -
cos((end.latitude - start.latitude) * p) / 2 +
cos(start.latitude * p) *
cos(end.latitude * p) *
(1 - cos((end.longitude - start.longitude) * p)) /
2;
return 12742 * 1000 * asin(sqrt(a)); // meters
}
double? _calculateAcceleration(double currentSpeed) {
final now = DateTime.now();
if (_lastSpeed != null && _lastSpeedTime != null) {
final deltaTime =
now.difference(_lastSpeedTime!).inMilliseconds / 1000.0; // seconds
if (deltaTime > 0) {
final acceleration = (currentSpeed - _lastSpeed!) / deltaTime;
_lastSpeed = currentSpeed;
_lastSpeedTime = now;
return double.parse(acceleration.toStringAsFixed(2));
}
}
_lastSpeed = currentSpeed;
_lastSpeedTime = now;
return null;
}
}

View File

@@ -0,0 +1,60 @@
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
import '../../print.dart';
import '../../views/widgets/mydialoug.dart';
import '../auth/captin/login_captin_controller.dart';
class LocationPermissions {
// late Location location;
// Future locationPermissions() async {
// location = Location();
// var permissionStatus = await location.requestPermission();
// if (permissionStatus == PermissionStatus.denied) {
// // The user denied the location permission.
// Get.defaultDialog(title: 'GPS Required Allow !.'.tr, middleText: '');
// return null;
// }
// }
}
Future<void> getPermissionLocation() async {
final PermissionStatus status = await Permission.locationAlways.status;
if (!await Permission.locationAlways.serviceStatus.isEnabled) {
Log.print('status.isGranted: ${status.isGranted}');
// box.write(BoxName.locationPermission, 'true');
await Permission.locationAlways.request();
Get.put(LoginDriverController()).update();
MyDialog().getDialog(
'Enable Location Permission'.tr, // {en:ar}
'Allowing location access will help us display orders near you. Please enable it now.'
.tr, // {en:ar}
() async {
Get.back();
box.write(BoxName.locationPermission, 'true');
await Permission.locationAlways.request();
},
);
}
}
Future<void> getPermissionLocation1() async {
PermissionStatus status = await Permission.locationWhenInUse.request();
if (status.isGranted) {
// After granting when in use, request "always" location permission
status = await Permission.locationAlways.request();
if (status.isGranted) {
print("Background location permission granted");
} else {
print("Background location permission denied");
}
} else {
print("Location permission denied");
await openAppSettings();
}
}

View File

@@ -0,0 +1,161 @@
import 'dart:io';
import 'package:sefer_driver/views/home/on_boarding_page.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
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/main.dart';
import 'package:sefer_driver/onbording_page.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:sefer_driver/views/widgets/my_textField.dart';
import '../../constant/style.dart';
import 'encrypt_decrypt.dart';
class LogOutController extends GetxController {
TextEditingController checkTxtController = TextEditingController();
final formKey = GlobalKey<FormState>();
final formKey1 = GlobalKey<FormState>();
final emailTextController = TextEditingController();
Future deleteMyAccountDriver(String id) async {
await CRUD().post(link: AppLink.removeUser, payload: {'id': id}).then(
(value) => Get.snackbar('Deleted'.tr, 'Your Account is Deleted',
backgroundColor: AppColor.redColor));
}
checkBeforeDelete() async {
var res = await CRUD().post(
link: AppLink.deletecaptainAccounr,
payload: {'id': box.read(BoxName.driverID)});
return res['message'][0]['id'];
}
deletecaptainAccount() {
Get.defaultDialog(
backgroundColor: AppColor.yellowColor,
title: 'Are you sure to delete your account?'.tr,
middleText:
'Your data will be erased after 2 weeks\nAnd you will can\'t return to use app after 1 month ',
titleStyle: AppStyle.title,
content: Column(
children: [
Container(
width: Get.width,
decoration: AppStyle.boxDecoration,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Your data will be erased after 2 weeks\nAnd you will can\'t return to use app after 1 month'
.tr,
style: AppStyle.title.copyWith(color: AppColor.redColor),
),
),
),
const SizedBox(
height: 20,
),
Form(
key: formKey,
child: SizedBox(
width: Get.width,
child: MyTextForm(
controller: checkTxtController,
label: 'Enter Your First Name'.tr,
hint: 'Enter Your First Name'.tr,
type: TextInputType.name,
),
))
],
),
confirm: MyElevatedButton(
title: 'Delete'.tr,
onPressed: () async {
if (checkTxtController.text == (box.read(BoxName.nameDriver))) {
// deletecaptainAccount();
var id = await checkBeforeDelete();
deleteMyAccountDriver(id);
} else {
mySnackeBarError('Your Name is Wrong'.tr);
}
}));
}
Future logOutPassenger() async {
Get.defaultDialog(
title: 'Are you Sure to LogOut?'.tr,
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MyElevatedButton(
title: 'Cancel'.tr,
onPressed: () => Get.back(),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(AppColor.redColor),
),
onPressed: () async {
// box.remove(BoxName.agreeTerms);
await box.erase();
await storage.deleteAll();
Get.offAll(OnBoardingPage());
},
child: Text(
'Sign Out'.tr,
style:
AppStyle.title.copyWith(color: AppColor.secondaryColor),
))
],
));
}
Future logOutCaptain() async {
Get.defaultDialog(
title: 'Are you Sure to LogOut?'.tr,
titleStyle: AppStyle.title,
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MyElevatedButton(
title: 'Cancel'.tr,
onPressed: () => Get.back(),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(AppColor.redColor),
),
onPressed: () async {
// box.remove(BoxName.agreeTerms);
await box.erase();
await storage.deleteAll();
Get.offAll(OnBoardingPage());
},
child: Text(
'Sign Out'.tr,
style:
AppStyle.title.copyWith(color: AppColor.secondaryColor),
))
],
));
}
deletePassengerAccount() async {
if (formKey1.currentState!.validate()) {
if (box.read(BoxName.email).toString() == emailTextController.text) {
await CRUD().post(link: AppLink.passengerRemovedAccountEmail, payload: {
'email': box.read(BoxName.email),
});
} else {
mySnackeBarError(
'Email you inserted is Wrong.'.tr,
);
}
}
}
}

View File

@@ -0,0 +1,651 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import 'package:sefer_driver/constant/api_key.dart';
import 'package:sefer_driver/constant/colors.dart';
import 'package:sefer_driver/constant/info.dart';
import 'package:sefer_driver/constant/style.dart';
import 'package:sefer_driver/constant/table_names.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../auth/captin/register_captin_controller.dart';
import 'launch.dart';
//
// class TextExtractionController extends GetxController {
// String extractedText = '';
// bool isloading = false;
// File? _scannedImage;
// // Convert the extracted text to JSON
// // Convert the extracted text to JSON
// String getTextAsJSON(String text) {
// final lines = text.split('\n');
// final jsonList = lines.map((line) {
// return {
// 'line_text': line,
// 'num_words': line.trim().split(' ').length,
// };
// }).toList();
//
// final json = {
// 'lines': jsonList,
// 'num_lines': lines.length,
// };
//
// return jsonEncode(json);
// }
//
// // Convert the extracted text to blocks by line
// List<String> getTextBlocks(String text) {
// return text.split('\n');
// }
//
// // Future<void> pickAndExtractText() async {
// // final pickedImage = await ImagePicker().pickImage(
// // source: ImageSource.camera,
// // preferredCameraDevice: CameraDevice.rear,
// // maxHeight: Get.height * .3,
// // maxWidth: Get.width * .8,
// // imageQuality: 99,
// // );
// // if (pickedImage != null) {
// // isloading = true;
// // update();
// // final imagePath = pickedImage.path;
// // final languages = [
// // 'eng',
// // 'ara'
// // ]; // Specify the languages you want to use for text extraction
//
// // try {
// // final text = await FlutterTesseractOcr.extractText(imagePath,
// // language:
// // languages.join('+'), // Combine multiple languages with '+'
// // args: {
// // "psm": "4",
// // "preserve_interword_spaces": "1",
// // // "rectangle": const Rect.fromLTWH(100, 100, 200, 200),
// // } // Additional options if needed
// // );
// // isloading = false;
// // final jsonText = getTextAsJSON(text);
// // final textBlocks = getTextBlocks(text);
// // update();
// // extractedText =
// // textBlocks.toString(); // Convert the extracted text to JSON.
//
// // // Print the JSON to the console.
// // update();
// // } catch (e) {
// // extractedText = '';
// // }
// // }
// // }
// }
// class TextMLGoogleRecognizerController extends GetxController {
// @override
// void onInit() {
// scanText();
// super.onInit();
// }
//
// // The ImagePicker instance
// final ImagePicker _imagePicker = ImagePicker();
//
// // The GoogleMlKit TextRecognizer instance
// final TextRecognizer _textRecognizer = TextRecognizer();
//
// // The scanned text
// String? scannedText;
// String? jsonOutput;
// final List<Map<String, dynamic>> lines = [];
//
// Map decode = {};
//
// Future<void> scanText() async {
// // Pick an image from the camera or gallery
// final XFile? image =
// await _imagePicker.pickImage(source: ImageSource.gallery);
//
// // If no image was picked, return
// if (image == null) {
// return;
// }
//
// // Convert the XFile object to an InputImage object
// final InputImage inputImage = InputImage.fromFile(File(image.path));
//
// // Recognize the text in the image
// final RecognizedText recognizedText =
// await _textRecognizer.processImage(inputImage);
// scannedText = recognizedText.text;
// Map extractedData = {};
// // Extract the scanned text line by line
// for (var i = 0; i < recognizedText.blocks.length; i++) {
// final block = recognizedText.blocks[i];
// for (final line in block.lines) {
// final lineText = line.text;
//
// if (lineText.contains('DL')) {
// final dlNumber = lineText.split('DL')[1].trim();
// extractedData['dl_number'] = dlNumber;
// }
// if (lineText.contains('USA')) {
// final usa = lineText.split('USA')[1].trim();
// extractedData['USA'] = usa;
// }
// if (lineText.contains('DRIVER LICENSE')) {
// final driverl = lineText;
// extractedData['DRIVER_LICENSE'] = driverl;
// }
//
// if (lineText.contains('EXP')) {
// final expiryDate = lineText.split('EXP')[1].trim();
// extractedData['expiry_date'] = expiryDate;
// }
//
// if (lineText.contains('DOB')) {
// final dob = lineText.split('DOB')[1].trim();
// extractedData['dob'] = dob;
// }
//
// if (lineText.contains("LN")) {
// if ((lineText.indexOf("LN") == 0)) {
// final lastName = lineText.split('LN')[1].trim();
// extractedData['lastName'] = lastName;
// }
// }
// if (lineText.contains("FN")) {
// final firstName = lineText.split('FN')[1].trim();
// extractedData['firstName'] = firstName;
// }
// if (lineText.contains("RSTR")) {
// final rstr = lineText.split('RSTR')[1].trim();
// extractedData['rstr'] = rstr;
// }
// if (lineText.contains("CLASS")) {
// final class1 = lineText.split('CLASS')[1].trim();
// extractedData['class'] = class1;
// }
// if (lineText.contains("END")) {
// final end = lineText.split('END')[1].trim();
// extractedData['end'] = end;
// }
// if (lineText.contains("DD")) {
// final dd = lineText.split('DD')[1].trim();
// extractedData['dd'] = dd;
// }
// if (lineText.contains("EYES")) {
// final eyes = lineText.split('EYES')[1].trim();
// extractedData['eyes'] = eyes;
// }
// if (lineText.contains("SEX")) {
// final parts = lineText.split("SEX ")[1];
// extractedData['sex'] = parts[0];
// }
// if (lineText.contains("HAIR")) {
// final hair = lineText.split('HAIR')[1].trim();
// extractedData['hair'] = hair;
// }
//
// if (lineText.contains('STREET') || lineText.contains(',')) {
// final address = lineText;
// extractedData['address'] = address;
// }
//
// // Repeat this process for other relevant data fields
// }
// }
//
// // Convert the list of lines to a JSON string
// jsonOutput = jsonEncode(extractedData);
// decode = jsonDecode(jsonOutput!);
//
// update();
// }
// }
class ScanDocumentsByApi extends GetxController {
bool isLoading = false;
Map<String, dynamic> responseMap = {};
final ImagePicker imagePicker = ImagePicker();
late Uint8List imagePortrait;
late Uint8List imageSignature;
late Uint8List imageDocumentFrontSide;
XFile? image;
XFile? imagePortraitFile;
XFile? imageFace;
late File tempFile;
late String imagePath;
DateTime now = DateTime.now();
late String name;
late String licenseClass;
late String documentNo;
late String address;
late String stateCode;
late String height;
late String sex;
late String postalCode;
late String dob;
late String expireDate;
// ///////////////////////
// late CameraController cameraController;
// late List<CameraDescription> cameras;
// bool isCameraInitialized = false;
// // final TextRecognizer _textRecognizer = TextRecognizer();
// String? scannedText;
// Future<void> initializeCamera(int cameraID) async {
// try {
// cameras = await availableCameras();
// //update();
// cameraController = CameraController(
// cameras[cameraID],
// ResolutionPreset.medium,
// enableAudio: false,
// );
// await cameraController.initialize();
// isCameraInitialized = true;
// update();
// } catch (e) {
// if (e is CameraException) {
// switch (e.code) {
// case 'CameraAccessDenied':
// Get.defaultDialog(
// title: 'Camera Access Denied.'.tr,
// middleText: '',
// confirm:
// MyElevatedButton(title: 'Open Settings', onPressed: () {}),
// );
// break;
// default:
// // Handle other errors here.
// break;
// }
// }
// }
// }
///
Future<void> scanDocumentsByApi() async {
// String? visionApi = await storage.read(key: BoxName.visionApi);
// String? visionApi = AK.visionApi;
// Pick an image from the camera or gallery
image = await imagePicker.pickImage(source: ImageSource.camera); //
// If no image was picked, return
if (image == null) {
return;
}
isLoading = true;
update();
var headers = {'X-BLOBR-KEY': AK.visionApi};
var request = http.MultipartRequest('POST',
Uri.parse('https://api.faceonlive.com/j2y3q25y1b6maif1/api/iddoc'));
request.files.add(await http.MultipartFile.fromPath('image', image!.path));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
String responseString = await response.stream.bytesToString();
responseMap = jsonDecode(responseString);
var ocrData = responseMap['data']['ocr'];
name = ocrData['name'].toString();
licenseClass = ocrData['dlClass'].toString();
documentNo = ocrData['documentNumber'].toString();
address = ocrData['address'].toString();
height = ocrData['height'].toString();
postalCode = ocrData['addressPostalCode'].toString();
sex = ocrData['sex'].toString();
stateCode = ocrData['addressJurisdictionCode'].toString();
expireDate = ocrData['dateOfExpiry'].toString();
dob = ocrData['dateOfBirth'].toString();
if (responseMap['data'] != null &&
responseMap['data']['image'] != null &&
responseMap['data']['image']['portrait'] != null) {
imagePortrait = base64Decode(responseMap['data']['image']['portrait']);
String tempPath = Directory.systemTemp.path;
tempFile = File('$tempPath/image.jpg');
await tempFile.writeAsBytes(imagePortrait);
imagePath = tempFile.path;
// imagePortraitFile=File(imagePath) ;
update();
} else {
// Handle error or provide a default value
}
if (responseMap['data']['image']['signature'] != null) {
imageSignature =
base64Decode(responseMap['data']['image']['signature']);
} else {
imageSignature = imagePortrait;
// Handle error or provide a default value
}
if (responseMap['data'] != null &&
responseMap['data']['image'] != null &&
responseMap['data']['image']['documentFrontSide'] != null) {
imageDocumentFrontSide =
base64Decode(responseMap['data']['image']['documentFrontSide']);
} else {
// Handle error or provide a default value
}
isLoading = false;
update();
} else {}
}
late int times;
Future checkMatchFaceApi() async {
sql.getAllData(TableName.faceDetectTimes).then((value) {
if (value.isEmpty || value == null) {
sql.insertData({'faceDetectTimes': 1}, TableName.faceDetectTimes);
sql.getAllData(TableName.faceDetectTimes).then((value) {
times = value[0]['faceDetectTimes'];
update();
});
} else {
if (times < 4) {
times++;
matchFaceApi();
sql.updateData(
{'faceDetectTimes': times}, TableName.faceDetectTimes, 1);
} else {
Get.defaultDialog(
barrierDismissible: false,
title: 'You have finished all times '.tr,
titleStyle: AppStyle.title,
middleText: 'if you want help you can email us here'.tr,
middleTextStyle: AppStyle.title,
cancel: MyElevatedButton(
title: 'Thanks'.tr,
kolor: AppColor.greenColor,
onPressed: () => Get.back(),
),
confirm: MyElevatedButton(
title: 'Email Us'.tr,
kolor: AppColor.yellowColor, //
onPressed: () {
launchCommunication('email', 'support@mobile-app.store',
'${'Hi'.tr} ${AppInformation.appName}\n${'I cant register in your app in face detection '.tr}');
Get.back();
},
));
}
}
});
}
Map res = {};
Future matchFaceApi() async {
// String? visionApi = await storage.read(key: BoxName.visionApi);
imageFace = await imagePicker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
// If no image was picked, return
if (image == null) {
return;
}
final imageFile = File(imageFace!.path);
// Uint8List imageBytes = await imageFile.readAsBytes();
var headers = {'X-BLOBR-KEY': AK.visionApi};
var request = http.MultipartRequest(
'POST',
Uri.parse(
'https://api.faceonlive.com/sntzbspfsdupgid1/api/face_compare'));
request.files
.add(await http.MultipartFile.fromPath('image1', imageFile.path));
request.files.add(await http.MultipartFile.fromPath('image2', imagePath));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
res = jsonDecode(await response.stream.bytesToString());
update();
res['data']['result'].toString().contains('No face detected in image')
? Get.defaultDialog(
barrierDismissible: false,
title: 'No face detected'.tr,
middleText: ''.tr,
titleStyle: AppStyle.title,
confirm: MyElevatedButton(
kolor: AppColor.yellowColor,
title: 'Back'.tr,
onPressed: () {
Get.back();
},
)) //
: Get.defaultDialog(
// barrierDismissible: false,
title: 'Image detecting result is '.tr,
titleStyle: AppStyle.title,
content: Column(
children: [
Text(
res['data']['result'].toString(),
style: res['data']['result'].toString() == 'Different'
? AppStyle.title.copyWith(color: AppColor.redColor)
: AppStyle.title.copyWith(color: AppColor.greenColor),
),
res['data']['result'].toString() == 'Different'
? Text(
'${'Be sure for take accurate images please\nYou have'.tr} $times ${'from 3 times Take Attention'.tr}',
style: AppStyle.title,
)
: Text(
'image verified'.tr,
style: AppStyle.title,
)
],
),
confirm: res['data']['result'].toString() == 'Different'
? MyElevatedButton(
title: 'Back'.tr,
onPressed: () => Get.back(),
kolor: AppColor.redColor,
)
: MyElevatedButton(
title: 'Next'.tr,
onPressed: () async {
RegisterCaptainController registerCaptainController =
Get.put(RegisterCaptainController());
await registerCaptainController.register();
await registerCaptainController.addLisence();
await uploadImagePortrate();
// Get.to(() => CarLicensePage());
},
// {
// await uploadImage(
// tempFile, AppLink.uploadImagePortrate);
// Get.to(() => CarLicensePage());
// },
kolor: AppColor.greenColor,
));
} else {}
}
// Todo upload images and fields
Future<String> uploadImagePortrate() async {
isLoading = true;
update();
var request = http.MultipartRequest(
'POST',
Uri.parse(AppLink.uploadImagePortrate),
);
request.files.add(
http.MultipartFile.fromBytes('image', imagePortrait),
);
request.headers.addAll({
"Content-Type": "multipart/form-data",
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
});
request.fields['driverID'] = box.read(BoxName.driverID).toString();
var response = await request.send();
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
isLoading = false;
update();
// Print the response string
return responseString;
}
@override
void onInit() {
// scanDocumentsByApi();
// initializeCamera(0);
sql.getAllData(TableName.faceDetectTimes).then((value) {
if (value.isEmpty) {
times = 0;
update();
// sql.insertData({'faceDetectTimes': 1}, TableName.faceDetectTimes);
} else {
times = value[0]['faceDetectTimes'];
}
});
super.onInit();
}
}
// class PassportDataExtractor extends GetxController {
// @override
// void onInit() {
// extractPassportData();
// super.onInit();
// }
//
// final ImagePicker _imagePicker = ImagePicker();
// late final XFile? image;
// final TextRecognizer _textRecognizer = TextRecognizer();
//
// Future<Map<String, dynamic>> extractPassportData() async {
// image = await _imagePicker.pickImage(source: ImageSource.gallery);
// update();
// if (image == null) {
// throw Exception('No image picked');
// }
//
// final InputImage inputImage = InputImage.fromFile(File(image!.path));
// final RecognizedText recognisedText =
// await _textRecognizer.processImage(inputImage);
//
// final Map<String, dynamic> extractedData = {};
// final List<Map<String, dynamic>> extractedTextWithCoordinates = [];
//
// for (TextBlock block in recognisedText.blocks) {
// for (TextLine line in block.lines) {
// final String lineText = line.text;
// final Rect lineBoundingBox = line.boundingBox!;
//
// extractedTextWithCoordinates.add({
// 'text': lineText,
// 'boundingBox': {
// 'left': lineBoundingBox.left,
// 'top': lineBoundingBox.top,
// 'width': lineBoundingBox.width,
// 'height': lineBoundingBox.height,
// },
// });
//
// // if (lineText.contains('Passport Number')) {
// // final String passportNumber =
// // lineText.split('Passport Number')[1].trim();
// // extractedData['passportNumber'] = passportNumber;
// // }
// // if (lineText.contains('Given Names')) {
// // final String givenNames = lineText.split('Given Names')[1].trim();
// // extractedData['givenNames'] = givenNames;
// // }
// // if (lineText.contains('Surname')) {
// // final String surname = lineText.split('Surname')[1].trim();
// // extractedData['surname'] = surname;
// // }
// // if (lineText.contains('Nationality')) {
// // final String nationality = lineText.split('Nationality')[1].trim();
// // extractedData['nationality'] = nationality;
// // }
// // if (lineText.contains('Date of Birth')) {
// // final String dob = lineText.split('Date of Birth')[1].trim();
// // extractedData['dateOfBirth'] = dob;
// // }
// // Add more field extraction conditions as needed
// }
// }
//
// extractedData['extractedTextWithCoordinates'] =
// extractedTextWithCoordinates;
// return extractedData;
// }
// }
//
// class PassportDataController extends GetxController {
// PassportDataExtractor passportDataExtractor = PassportDataExtractor();
// List<Map<String, dynamic>> extractedTextWithCoordinates = [];
//
// Future<void> extractDataAndDrawBoundingBoxes() async {
// try {
// Map<String, dynamic> extractedData =
// await passportDataExtractor.extractPassportData();
// extractedTextWithCoordinates =
// extractedData['extractedTextWithCoordinates'];
// update(); // Notify GetX that the state has changed
// } catch (e) {
// }
// }
// }
//
// class BoundingBoxPainter extends CustomPainter {
// final List<Map<String, dynamic>> boundingBoxes;
//
// BoundingBoxPainter(this.boundingBoxes);
//
// @override
// void paint(Canvas canvas, Size size) {
// final Paint paint = Paint()
// ..color = Colors.red
// ..style = PaintingStyle.stroke
// ..strokeWidth = 2.0;
//
// for (Map<String, dynamic> boundingBox in boundingBoxes) {
// double left = boundingBox['left'];
// double top = boundingBox['top'];
// double width = boundingBox['width'];
// double height = boundingBox['height'];
//
// Rect rect = Rect.fromLTWH(left, top, width, height);
// canvas.drawRect(rect, paint);
// }
// }
//
// @override
// bool shouldRepaint(covariant CustomPainter oldDelegate) {
// return false;
// }
// }

View File

@@ -0,0 +1,114 @@
import 'dart:io';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/views/widgets/mydialoug.dart';
import 'package:flutter/material.dart';
import 'package:flutter_confetti/flutter_confetti.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:get/get.dart';
import 'package:location/location.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
import '../auth/captin/login_captin_controller.dart';
import '../home/payment/captain_wallet_controller.dart';
Future<void> getPermissionOverlay() async {
if (Platform.isAndroid) {
final bool status = await FlutterOverlayWindow.isPermissionGranted();
if (status == false) {
MyDialog().getDialog(
'Allow overlay permission'.tr,
'To display orders instantly, please grant permission to draw over other apps.'
.tr,
() async {
Get.back();
await FlutterOverlayWindow.requestPermission();
},
);
}
}
}
Future<void> showDriverGiftClaim(BuildContext context) async {
if (box.read(BoxName.is_claimed).toString() == '0' ||
box.read(BoxName.is_claimed) == null) {
MyDialog().getDialog(
'You have gift 300 L.E'.tr, 'This for new registration'.tr, () async {
var res = await CRUD().post(link: AppLink.updateDriverClaim, payload: {
'driverId': box.read(BoxName.driverID),
});
if (res != 'failure') {
Get.find<CaptainWalletController>()
.addDriverWallet('new driver', '300', '300');
Confetti.launch(
context,
options:
const ConfettiOptions(particleCount: 100, spread: 70, y: 0.6),
);
box.write(BoxName.is_claimed, '1');
}
Get.back();
});
}
}
Future<void> closeOverlayIfFound() async {
if (Platform.isAndroid) {
bool isOverlayActive = await FlutterOverlayWindow.isActive();
if (isOverlayActive) {
await FlutterOverlayWindow.closeOverlay();
}
}
}
final location = Location();
Future<void> getLocationPermission() async {
bool serviceEnabled;
PermissionStatus permissionGranted;
// Check if location services are enabled
serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
// Location services are still not enabled, handle the error
return;
}
}
// Check if the app has permission to access location
permissionGranted = await location.hasPermission();
if (permissionGranted == PermissionStatus.denied) {
permissionGranted = await location.requestPermission();
if (permissionGranted != PermissionStatus.granted) {
// Location permission is still not granted, handle the error
permissionGranted = await location.requestPermission();
return;
}
}
if (permissionGranted.toString() == 'PermissionStatus.granted') {
box.write(BoxName.locationPermission, 'true');
Get.find<LoginDriverController>().update();
}
// update();
}
Future<void> getOverLay(String myListString) async {
bool isOverlayActive = await FlutterOverlayWindow.isActive();
if (isOverlayActive) {
await FlutterOverlayWindow.closeOverlay();
}
await FlutterOverlayWindow.showOverlay(
enableDrag: true,
flag: OverlayFlag.focusPointer,
visibility: NotificationVisibility.visibilityPublic,
positionGravity: PositionGravity.auto,
height: 700,
width: WindowSize.matchParent,
startPosition: const OverlayPosition(0, -150),
);
await FlutterOverlayWindow.shareData(myListString);
}

View File

@@ -0,0 +1,360 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:jailbreak_root_detection/jailbreak_root_detection.dart';
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:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../constant/info.dart';
import '../../main.dart';
import 'encrypt_decrypt.dart';
Future<void> checkForUpdate(BuildContext context) async {
final packageInfo = await PackageInfo.fromPlatform();
final currentVersion = packageInfo.buildNumber;
final version = packageInfo.version;
// print('currentVersion is : $currentVersion');
// Fetch the latest version from your server
String latestVersion = await getPackageInfo();
box.write(BoxName.packagInfo, version);
if (latestVersion.isNotEmpty && latestVersion != currentVersion) {
showUpdateDialog(context);
}
}
Future<String> getPackageInfo() async {
final response = await CRUD().get(link: AppLink.packageInfo, payload: {
"platform": Platform.isAndroid ? 'android' : 'ios',
"appName": AppInformation.appVersion,
});
if (response != 'failure') {
return jsonDecode(response)['message'][0]['version'];
}
return '';
}
void showUpdateDialog(BuildContext context) {
final String storeUrl = Platform.isAndroid
? 'https://play.google.com/store/apps/details?id=com.sefer_driver'
: 'https://apps.apple.com/ae/app/sefer-driver/id6502189302';
showGeneralDialog(
context: context,
barrierDismissible: false,
barrierColor: Colors.black.withOpacity(0.5),
pageBuilder: (_, __, ___) {
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: Center(
child: AlertDialog(
// Using AlertDialog for a more Material Design look
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(16)), // More rounded corners
elevation: 4, // Add a bit more elevation
contentPadding: EdgeInsets.zero, // Remove default content padding
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Image.asset(
'assets/images/logo.png',
height: 72, // Slightly larger logo
width: 72,
),
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Text(
'Update Available'.tr,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
// Use theme's title style
fontWeight: FontWeight.bold,
),
),
),
Padding(
padding: const EdgeInsets.all(24.0),
child: Text(
'A new version of the app is available. Please update to the latest version.'
.tr, // More encouraging message
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
// Use theme's body style
color: Colors.black87,
),
),
),
const Divider(height: 0),
Row(
children: [
Expanded(
child: TextButton(
// Using TextButton for "Cancel"
onPressed: () => Navigator.pop(context),
style: TextButton.styleFrom(
foregroundColor: Colors.grey,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(16),
),
),
),
child: Text('Cancel'.tr),
),
),
const SizedBox(
height: 48,
child: VerticalDivider(width: 0), // Using VerticalDivider
),
Expanded(
child: ElevatedButton(
// Using ElevatedButton for "Update"
onPressed: () async {
if (await canLaunchUrl(Uri.parse(storeUrl))) {
await launchUrl(Uri.parse(storeUrl));
}
if (context.mounted) Navigator.pop(context);
},
style: ElevatedButton.styleFrom(
backgroundColor: AppColor
.primaryColor, // Use theme's primary color
foregroundColor: Theme.of(context)
.colorScheme
.onPrimary, // Use theme's onPrimary color
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(16),
),
),
),
child: Text('Update'.tr),
),
),
],
),
],
),
),
),
);
},
transitionBuilder: (_, animation, __, child) {
return ScaleTransition(
scale: CurvedAnimation(
parent: animation,
curve: Curves.easeOutCubic, // More natural curve
),
child: child,
);
},
);
}
class DeviceHelper {
static Future<String> getDeviceFingerprint() async {
final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
var deviceData;
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 (fingerprint);
} catch (e) {
throw Exception('Failed to generate device fingerprint');
}
}
}
class SecurityHelper {
/// Performs security checks and handles potential risks
static Future<void> performSecurityChecks() async {
bool isNotTrust = false;
bool isJailBroken = false;
bool isRealDevice = true;
bool isOnExternalStorage = false;
bool checkForIssues = false;
bool isDevMode = false;
bool isTampered = false;
String bundleId = "";
try {
isNotTrust = await JailbreakRootDetection.instance.isNotTrust;
isJailBroken = await JailbreakRootDetection.instance.isJailBroken;
isRealDevice = await JailbreakRootDetection.instance.isRealDevice;
isOnExternalStorage =
await JailbreakRootDetection.instance.isOnExternalStorage;
List<JailbreakIssue> issues =
await JailbreakRootDetection.instance.checkForIssues;
checkForIssues = issues.isNotEmpty;
isDevMode = await JailbreakRootDetection.instance.isDevMode;
// Get Bundle ID
PackageInfo packageInfo = await PackageInfo.fromPlatform();
bundleId = packageInfo.packageName;
if (bundleId.isNotEmpty) {
// Pass the CORRECT bundle ID to isTampered
isTampered = await JailbreakRootDetection.instance.isTampered(bundleId);
}
} catch (e) {
debugPrint("Error during security checks: $e");
// Consider handling specific exceptions, not just general errors.
}
// Save values to storage (using GetStorage)
await box.write('isNotTrust', isNotTrust); // Use await for write operations
await box.write('isTampered', isTampered); // Use await
await box.write('isJailBroken', isJailBroken); // Use await
// debugPrint("Security Check Results:");
// debugPrint("isNotTrust: $isNotTrust");
// debugPrint("isJailBroken: $isJailBroken");
// debugPrint("isRealDevice: $isRealDevice");
// debugPrint("isOnExternalStorage: $isOnExternalStorage");
// debugPrint("checkForIssues: $checkForIssues");
// debugPrint("isDevMode: $isDevMode");
// debugPrint("isTampered: $isTampered");
// debugPrint("Bundle ID: $bundleId"); // Print the bundle ID
// Check for security risks and potentially show a warning
if (isJailBroken || isRealDevice == false || isTampered) {
// print("security_warning".tr); //using easy_localization
// Use a more robust approach to show a warning, like a dialog:
_showSecurityWarning();
}
}
/// Deletes all app data
static Future<void> clearAllData() async {
//await storage.deleteAll(); // What's 'storage'? Be specific. Likely GetStorage as well.
await box.erase(); // Clear GetStorage data
exit(0); // This will terminate the app. Be VERY careful with this.
}
// static void _showSecurityWarning() {
// // Show a dialog, navigate to an error screen, etc.
// // Example using Get.dialog (if you use GetX):
//
// Get.dialog(
// AlertDialog(
// title: Text("Security Warning".tr), // Or use localized string
// content: Text(
// "Potential security risks detected. The application may not function correctly."
// .tr), //Or use localized string
// actions: [
// TextButton(
// onPressed: () async {
// await storage.deleteAll();
// await box.erase();
// Get.back(); // Close the dialog
// // Or, if you really must, exit the app (but give the user a chance!)
// exit(0);
// },
// child: Text("OK"), // Or use a localized string
// ),
// ],
// ),
// barrierDismissible: false, // Prevent closing by tapping outside
// );
// }
static void _showSecurityWarning() {
// Use an RxInt to track the remaining seconds. This is the KEY!
RxInt secondsRemaining = 10.obs;
Get.dialog(
CupertinoAlertDialog(
title: Text("Security Warning".tr),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Obx(() => Text(
"Potential security risks detected. The application will close in @seconds seconds."
.trParams({
// Use trParams for placeholders
'seconds': secondsRemaining.value.toString(),
}),
// Wrap the Text widget in Obx
)),
SizedBox(height: 24), // More spacing before the progress bar
Obx(() => SizedBox(
width: double.infinity, // Make progress bar full width
child: CupertinoActivityIndicator(
// in case of loading
radius: 15,
animating: true,
))),
SizedBox(height: 8),
Obx(() => ClipRRect(
borderRadius: BorderRadius.circular(8), // Rounded corners
child: LinearProgressIndicator(
value: secondsRemaining.value / 10,
backgroundColor: Colors.grey.shade300, // Lighter background
valueColor: AlwaysStoppedAnimation<Color>(
CupertinoColors.systemRed), // iOS-style red
minHeight: 8, // Slightly thicker progress bar
),
)),
],
),
),
barrierDismissible: false,
);
Timer.periodic(Duration(seconds: 1), (timer) {
secondsRemaining.value--;
if (secondsRemaining.value <= 0) {
timer.cancel();
// Get.back();
_clearDataAndExit();
}
});
}
static Future<void> _clearDataAndExit() async {
await storage.deleteAll();
await box.erase();
exit(0); // Exit the app
print('exit');
}
}

View File

@@ -0,0 +1,8 @@
// import 'package:ride/controller/functions/crud.dart';
// class RemoveAccount {
// void removeAccount()async{
// var res=await CRUD().post(link: link)
// }
// }

View File

@@ -0,0 +1,25 @@
// import 'package:credit_card_scanner/credit_card_scanner.dart';
// import 'package:get/get.dart';
//
// class ScanIdCard extends GetxController {
// CardDetails? _cardDetails;
// CardScanOptions scanOptions = const CardScanOptions(
// scanCardHolderName: true,
// enableDebugLogs: true,
// validCardsToScanBeforeFinishingScan: 5,
// possibleCardHolderNamePositions: [
// CardHolderNameScanPosition.aboveCardNumber,
// ],
// );
//
// Future<void> scanCard() async {
// final CardDetails? cardDetails =
// await CardScanner.scanCard(scanOptions: scanOptions);
// if (cardDetails == null) {
// return;
// }
//
// _cardDetails = cardDetails;
// update();
// }
// }

View File

@@ -0,0 +1,88 @@
import 'dart:convert';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
import 'package:sefer_driver/controller/functions/encrypt_decrypt.dart';
import '../../constant/box_name.dart';
import '../../constant/char_map.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import 'crud.dart';
class SecureStorage {
final FlutterSecureStorage _storage = const FlutterSecureStorage();
void saveData(String key, value) async {
await _storage.write(key: key, value: value);
}
Future<String?> readData(String boxName) async {
final String? value = await _storage.read(key: boxName);
return value;
}
}
const List<String> keysToFetch = [
'serverPHP',
'seferAlexandriaServer',
'seferPaymentServer',
'seferCairoServer',
'seferGizaServer',
];
class AppInitializer {
List<Map<String, dynamic>> links = [];
Future<void> initializeApp() async {
if (box.read(BoxName.jwt) == null) {
await LoginDriverController().getJWT();
} else {
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
if (isTokenExpired) {
await LoginDriverController().getJWT();
}
}
// await getKey();
}
Future<void> getAIKey(String key1) async {
var res =
await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key1});
if (res != 'failure') {
var d = jsonDecode(res)['message'];
final rawValue = d[key1].toString();
// ✅ اكتبها في storage
await storage.write(key: key1, value: rawValue);
await Future.delayed(Duration.zero);
}
}
Future<void> getKey() async {
try {
var res =
await CRUD().get(link: AppLink.getLocationAreaLinks, payload: {});
if (res != 'failure') {
links = List<Map<String, dynamic>>.from(jsonDecode(res)['message']);
await box.write(BoxName.locationName, links);
await box.write(BoxName.basicLink, (links[0]['server_link']));
await box.write(links[2]['name'], (links[2]['server_link']));
await box.write(links[1]['name'], (links[3]['server_link']));
await box.write(links[3]['name'], (links[1]['server_link']));
await box.write(BoxName.paymentLink, (links[4]['server_link']));
}
} catch (e) {}
}
}

View File

@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
class SecurityChecks {
static const platform = MethodChannel(
'com.intaleq_driver/security'); // Choose a unique channel name
static Future<bool> isDeviceCompromised() async {
try {
final bool result = await platform
.invokeMethod('isNativeRooted'); // Invoke the native method
return result;
} on PlatformException catch (e) {
print("Failed to check security status: ${e.message}");
return true; // Treat platform errors as a compromised device (for safety)
}
}
static isDeviceRootedFromNative(BuildContext context) async {
bool compromised = await isDeviceCompromised();
if (compromised) {
showDialog(
barrierDismissible: false,
context: context,
builder: (context) => AlertDialog(
title: Text("Security Warning".tr),
content: Text(
"Your device appears to be compromised. The app will now close."
.tr),
actions: [
TextButton(
onPressed: () {
SystemNavigator.pop(); // Close the app
},
child: Text("OK"),
),
],
),
);
} else {
// Continue with normal app flow
print("Device is secure.");
}
}
}

View File

@@ -0,0 +1,104 @@
import 'dart:convert';
import 'package:sefer_driver/constant/api_key.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/info.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/auth/captin/register_captin_controller.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../auth/captin/login_captin_controller.dart';
import 'encrypt_decrypt.dart';
class SmsEgyptController extends GetxController {
var headers = {'Content-Type': 'application/json'};
Future<String> getSender() async {
var res = await CRUD().get(link: AppLink.getSender, payload: {});
if (res != 'failure') {
var d = jsonDecode(res)['message'][0]['senderId'].toString();
return d;
} else {
return "Sefer Egy";
}
}
Future<dynamic> sendSmsEgypt(String phone) async {
String sender = await getSender();
var body = jsonEncode({"receiver": "2$phone"});
var res = await http.post(
Uri.parse(AppLink.sendSms),
body: body,
headers: headers,
);
if (jsonDecode(res.body)['message'].toString() != "Success") {
await CRUD().post(link: AppLink.updatePhoneInvalidSMS, payload: {
"phone_number":
('+2${Get.find<RegisterCaptainController>().phoneController.text}')
});
box.write(BoxName.phoneDriver,
('+2${Get.find<RegisterCaptainController>().phoneController.text}'));
box.write(BoxName.phoneVerified, '1');
await Get.put(LoginDriverController()).loginWithGoogleCredential(
box.read(BoxName.driverID).toString(),
(box.read(BoxName.emailDriver).toString()),
);
} else {
Get.defaultDialog(
title: 'You will receive code in sms message'.tr,
middleText: '',
confirm: MyElevatedButton(
title: 'OK'.tr,
onPressed: () {
Get.back();
}));
}
}
Future checkCredit(String phone, otp) async {
var res = await http.post(
Uri.parse(AppLink.checkCredit),
body: {
"username": AppInformation.appName,
"password": AK.smsPasswordEgypt,
},
headers: headers,
);
}
Future sendSmsWithValidaty(String phone, otp) async {
var res = await http.post(
Uri.parse(AppLink.checkCredit),
body: {
"username": AppInformation.appName,
"password": AK.smsPasswordEgypt,
"message": "This is an example SMS message.",
"language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
"sender": "Sefer", //"Kazumi", // todo add sefer sender name
"receiver": "2$phone",
"validity": "10",
"StartTime": DateTime.now().toString() // "1/1/2024 10:00:00"
},
headers: headers,
);
}
Future sendSmsStatus(String smsid) async {
var res = await http.post(
Uri.parse(AppLink.checkCredit),
body: {
"username": AppInformation.appName,
"password": AK.smsPasswordEgypt,
"smsid": smsid //"00b77dfc-5b8f-474d-9def-9f0158b70f98"
},
headers: headers,
);
}
}

View File

@@ -0,0 +1,35 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/colors.dart';
import 'package:sefer_driver/constant/style.dart';
class Toast {
static void show(BuildContext context, String message, Color color) {
final snackBar = SnackBar(
clipBehavior: Clip.antiAliasWithSaveLayer,
backgroundColor: color,
elevation: 3,
content: Text(
message,
style: AppStyle.title.copyWith(color: AppColor.secondaryColor),
),
behavior: SnackBarBehavior.floating,
animation: const AlwaysStoppedAnimation(1.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0), // Custom border radius
),
width: Get.width * .8,
// shape: const StadiumBorder(
// side: BorderSide(
// color: AppColor.secondaryColor,
// width: 1.0,
// style: BorderStyle.solid,
// )),
duration: const Duration(seconds: 2),
);
ScaffoldMessenger.of(context).showSnackBar(
snackBar,
);
}
}

View File

@@ -0,0 +1,52 @@
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:get/get.dart';
class TextToSpeechController extends GetxController {
final flutterTts = FlutterTts();
bool isComplete = false;
// Initialize TTS in initState
@override
void onInit() {
super.onInit();
initTts();
}
// Dispose of TTS when controller is closed
@override
void onClose() {
super.onClose();
flutterTts.completionHandler;
}
// Function to initialize TTS engine
Future<void> initTts() async {
String? lang =
WidgetsBinding.instance.platformDispatcher.locale.countryCode;
await flutterTts
.setLanguage(box.read(BoxName.lang).toString()); //'en-US' Set language
// await flutterTts.setLanguage('ar-SA'); //'en-US' Set language
// await flutterTts.setLanguage(lang!); //'en-US' Set language
await flutterTts.setSpeechRate(0.5); // Adjust speech rate
await flutterTts.setVolume(1.0); // Set volume
}
// Function to speak the given text
Future<void> speakText(String text) async {
try {
await flutterTts.awaitSpeakCompletion(true);
var result = await flutterTts.speak(text);
if (result == 1) {
// TTS operation has started
// You can perform additional operations here, if needed
isComplete = true;
update();
}
} catch (error) {
mySnackeBarError('Failed to speak text: $error');
}
}
}

View File

@@ -0,0 +1,22 @@
// import 'package:ride/constant/credential.dart';
// import 'package:twilio_flutter/twilio_flutter.dart';
//
// class TwilioSMS {
// TwilioFlutter twilioFlutter = TwilioFlutter(
// accountSid: AppCredintials.accountSIDTwillo,
// authToken: AppCredintials.authTokenTwillo,
// twilioNumber: '+962 7 9858 3052');
//
// Future<void> sendSMS({
// required String recipientPhoneNumber,
// required String message,
// }) async {
// try {
// await twilioFlutter.sendSMS(
// toNumber: recipientPhoneNumber,
// messageBody: message,
// );
// } catch (e) {
// }
// }
// }

View File

@@ -0,0 +1,552 @@
import 'dart:convert';
import 'dart:io';
import 'package:sefer_driver/constant/api_key.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:image/image.dart' as img;
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../main.dart';
import '../../print.dart';
import 'encrypt_decrypt.dart';
class ImageController extends GetxController {
File? myImage;
bool isloading = false;
CroppedFile? croppedFile;
final picker = ImagePicker();
var image;
Future<img.Image> detectAndCropDocument(File imageFile) async {
img.Image? image = img.decodeImage(await imageFile.readAsBytes());
if (image == null) throw Exception('Unable to decode image');
int left = image.width, top = image.height, right = 0, bottom = 0;
// Threshold for considering a pixel as part of the document (adjust as needed)
const int threshold = 240;
for (int y = 0; y < image.height; y++) {
for (int x = 0; x < image.width; x++) {
final pixel = image.getPixel(x, y);
final luminance = img.getLuminance(pixel);
if (luminance < threshold) {
left = x < left ? x : left;
top = y < top ? y : top;
right = x > right ? x : right;
bottom = y > bottom ? y : bottom;
}
}
}
// Add a small padding
left = (left - 5).clamp(0, image.width);
top = (top - 5).clamp(0, image.height);
right = (right + 5).clamp(0, image.width);
bottom = (bottom + 5).clamp(0, image.height);
return img.copyCrop(image,
x: left, y: top, width: right - left, height: bottom - top);
}
Future<File> rotateImageIfNeeded(File imageFile) async {
img.Image croppedDoc = await detectAndCropDocument(imageFile);
// Check if the document is in portrait orientation
bool isPortrait = croppedDoc.height > croppedDoc.width;
img.Image processedImage;
if (isPortrait) {
// Rotate the image by 90 degrees clockwise
processedImage = img.copyRotate(croppedDoc, angle: 90);
} else {
processedImage = croppedDoc;
}
// Get temporary directory
final tempDir = await path_provider.getTemporaryDirectory();
final tempPath = tempDir.path;
// Create the processed image file
File processedFile = File('$tempPath/processed_image.jpg');
await processedFile.writeAsBytes(img.encodeJpg(processedImage));
return processedFile;
}
Future<File> rotateImage(File imageFile) async {
// Read the image file
img.Image? image = img.decodeImage(await imageFile.readAsBytes());
if (image == null) return imageFile;
// Rotate the image by 90 degrees clockwise
img.Image rotatedImage = img.copyRotate(image, angle: 90);
// Get temporary directory
final tempDir = await path_provider.getTemporaryDirectory();
final tempPath = tempDir.path;
// Create the rotated image file
File rotatedFile = File('$tempPath/rotated_image.jpg');
await rotatedFile.writeAsBytes(img.encodeJpg(rotatedImage));
return rotatedFile;
}
choosImage(String link, String imageType) async {
try {
final pickedImage = await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.rear,
);
if (pickedImage == null) return;
image = File(pickedImage.path);
croppedFile = await ImageCropper().cropImage(
sourcePath: image!.path,
uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper'.tr,
toolbarColor: AppColor.blueColor,
toolbarWidgetColor: AppColor.yellowColor,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false,
),
IOSUiSettings(
title: 'Cropper'.tr,
),
],
);
if (croppedFile == null) return;
myImage = File(croppedFile!.path);
isloading = true;
update();
// Rotate the compressed image
File processedImage = await rotateImageIfNeeded(File(croppedFile!.path));
File compressedImage = await compressImage(processedImage);
print('link =$link');
// Log.print('link: ${link}');
//n8u22456
await uploadImage(
compressedImage,
{
'driverID':
box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
'imageType': imageType,
},
link,
);
} catch (e) {
print('Error in choosImage: $e');
mySnackeBarError('Image Upload Failed'.tr);
// Get.snackbar('Image Upload Failed'.tr, e.toString(),
// backgroundColor: AppColor.primaryColor);
} finally {
isloading = false;
update();
}
}
choosImageNewCAr(String link, String imageType) async {
try {
final pickedImage = await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.rear,
);
if (pickedImage == null) return;
image = File(pickedImage.path);
croppedFile = await ImageCropper().cropImage(
sourcePath: image!.path,
uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper'.tr,
toolbarColor: AppColor.blueColor,
toolbarWidgetColor: AppColor.yellowColor,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false,
),
IOSUiSettings(
title: 'Cropper'.tr,
),
],
);
if (croppedFile == null) return;
myImage = File(croppedFile!.path);
isloading = true;
update();
// Rotate the compressed image
File processedImage = await rotateImageIfNeeded(File(croppedFile!.path));
File compressedImage = await compressImage(processedImage);
print('link =$link');
// Log.print('link: ${link}');
//n8u22456
await uploadNewCar(
compressedImage,
{
'driverID': box.read(BoxName.driverID) +
'_' +
DateTime.now().toIso8601String(),
'imageType': imageType,
},
link,
);
} catch (e) {
print('Error in choosImage: $e');
// Get.snackbar('Image Upload Failed'.tr, e.toString(),
// backgroundColor: AppColor.primaryColor);
mySnackeBarError('Image Upload Failed'.tr);
} finally {
isloading = false;
update();
}
}
// choosFaceFromDriverLicense(String link, String imageType) async {
// final pickedImage = await picker.pickImage(
// source: ImageSource.camera,
// preferredCameraDevice: CameraDevice.rear,
// );
// if (pickedImage == null) return;
// image = File(pickedImage.path);
// File? processedImage;
// // For face images, use face detection and cropping
// processedImage = await detectAndCropFace(image!);
// if (processedImage == null) {
// Get.snackbar('Face Detection Failed', 'No face detected in the image.');
// return;
// }
// isloading = true;
// update();
// File compressedImage = await compressImage(processedImage);
// try {
// await uploadImage(
// compressedImage,
// {
// 'driverID': box.read(BoxName.driverID).toString(),
// 'imageType': imageType
// },
// link,
// );
// } catch (e) {
// Get.snackbar('Image Upload Failed'.tr, e.toString(),
// backgroundColor: AppColor.redColor);
// } finally {
// isloading = false;
// update();
// }
// }
choosFace(String link, String imageType) async {
final pickedImage = await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
if (pickedImage != null) {
image = File(pickedImage.path);
isloading = true;
update();
// Compress the image
File compressedImage = await compressImage(File(pickedImage.path));
// Save the picked image directly
// File savedImage = File(pickedImage.path);
print('link =$link');
try {
await uploadImage(
compressedImage,
{
'driverID':
box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
'imageType': imageType
},
link,
);
} catch (e) {
mySnackeBarError('Image Upload Failed'.tr);
// Get.snackbar('Image Upload Failed'.tr, e.toString(),
// backgroundColor: AppColor.redColor);
} finally {
isloading = false;
update();
}
}
}
uploadImage(File file, Map data, String link) async {
var request = http.MultipartRequest(
'POST',
Uri.parse(link),
);
Log.print('request: ${request}');
var length = await file.length();
var stream = http.ByteStream(file.openRead());
var multipartFile = http.MultipartFile(
'image',
stream,
length,
filename: basename(file.path),
);
request.headers.addAll({
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
});
// Set the file name to the driverID
request.files.add(
http.MultipartFile(
'image',
stream,
length,
filename: '${box.read(BoxName.driverID)}.jpg',
),
);
data.forEach((key, value) {
request.fields[key] = value;
});
var myrequest = await request.send();
var res = await http.Response.fromStream(myrequest);
if (res.statusCode == 200) {
Log.print('jsonDecode(res.body): ${jsonDecode(res.body)}');
return jsonDecode(res.body);
} else {
throw Exception(
'Failed to upload image: ${res.statusCode} - ${res.body}');
}
}
uploadNewCar(File file, Map data, String link) async {
var request = http.MultipartRequest(
'POST',
Uri.parse(link),
);
var length = await file.length();
var stream = http.ByteStream(file.openRead());
var multipartFile = http.MultipartFile(
'image',
stream,
length,
filename: basename(file.path),
);
request.headers.addAll({
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
});
// Set the file name to the driverID
request.files.add(
http.MultipartFile(
'image',
stream,
length,
filename: '${box.read(BoxName.driverID)}.jpg',
),
);
data.forEach((key, value) {
request.fields[key] = value;
});
var myrequest = await request.send();
var res = await http.Response.fromStream(myrequest);
if (res.statusCode == 200) {
Log.print('jsonDecode(res.body): ${jsonDecode(res.body)}');
return jsonDecode(res.body);
} else {
throw Exception(
'Failed to upload image: ${res.statusCode} - ${res.body}');
}
}
choosImagePicture(String link, String imageType) async {
final pickedImage = await picker.pickImage(
source: ImageSource.gallery,
// preferredCameraDevice: CameraDevice.rear,
// maxHeight: Get.height * .3,
// maxWidth: Get.width * .9,
// imageQuality: 100,
);
image = File(pickedImage!.path);
croppedFile = await ImageCropper().cropImage(
sourcePath: image!.path,
uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper'.tr,
toolbarColor: AppColor.blueColor,
toolbarWidgetColor: AppColor.yellowColor,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
IOSUiSettings(
title: 'Cropper'.tr,
),
],
);
myImage = File(pickedImage.path);
isloading = true;
update();
// Save the cropped image
// File savedCroppedImage = File(croppedFile!.path);
File compressedImage = await compressImage(File(croppedFile!.path));
print('link =$link');
try {
await uploadImage(
compressedImage,
{
'driverID':
(box.read(BoxName.driverID)) ?? (box.read(BoxName.passengerID)),
'imageType': imageType
},
link,
);
} catch (e) {
mySnackeBarError('Image Upload Failed'.tr);
// Get.snackbar('Image Upload Failed'.tr, e.toString(),
// backgroundColor: AppColor.redColor);
} finally {
isloading = false;
update();
}
}
uploadImagePicture(File file, Map data, String link) async {
var request = http.MultipartRequest(
'POST',
Uri.parse(link), //'https://ride.mobile-app.store/uploadImage1.php'
);
var length = await file.length();
var stream = http.ByteStream(file.openRead());
var multipartFile = http.MultipartFile(
'image',
stream,
length,
filename: basename(file.path),
);
request.headers.addAll({
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
});
// Set the file name to the driverID
request.files.add(
http.MultipartFile(
'image',
stream,
length,
filename: '${(box.read(BoxName.driverID))}.jpg',
),
);
data.forEach((key, value) {
request.fields[key] = value;
});
var myrequest = await request.send();
var res = await http.Response.fromStream(myrequest);
if (res.statusCode == 200) {
return jsonDecode(res.body);
} else {
throw Exception(
'Failed to upload image: ${res.statusCode} - ${res.body}');
}
}
}
Future<File> compressImage(File file) async {
final dir = await path_provider.getTemporaryDirectory();
final targetPath = "${dir.absolute.path}/temp.jpg";
var result = await FlutterImageCompress.compressAndGetFile(
file.absolute.path,
targetPath,
quality: 70,
minWidth: 1024,
minHeight: 1024,
);
return File(result!.path);
}
// Future<File> detectAndCropFace(File imageFile) async {
// final inputImage = InputImage.fromFilePath(imageFile.path);
// final options = FaceDetectorOptions(
// enableClassification: false,
// enableLandmarks: false,
// enableTracking: false,
// minFaceSize: 0.15,
// performanceMode: FaceDetectorMode.accurate,
// );
// final faceDetector = FaceDetector(options: options);
// try {
// final List<Face> faces = await faceDetector.processImage(inputImage);
// final image = img.decodeImage(await imageFile.readAsBytes());
// if (image == null) throw Exception('Unable to decode image');
// int left, top, width, height;
// if (faces.isNotEmpty) {
// // Face detected, crop around the face
// final face = faces[0];
// double padding = 0.2; // 20% padding
// int paddingX = (face.boundingBox.width * padding).round();
// int paddingY = (face.boundingBox.height * padding).round();
// left = (face.boundingBox.left - paddingX).round();
// top = (face.boundingBox.top - paddingY).round();
// width = (face.boundingBox.width + 2 * paddingX).round();
// height = (face.boundingBox.height + 2 * paddingY).round();
// } else {
// // No face detected, crop the center of the image
// int size = min(image.width, image.height);
// left = (image.width - size) ~/ 2;
// top = (image.height - size) ~/ 2;
// width = size;
// height = size;
// }
// // Ensure dimensions are within image bounds
// left = left.clamp(0, image.width - 1);
// top = top.clamp(0, image.height - 1);
// width = width.clamp(1, image.width - left);
// height = height.clamp(1, image.height - top);
// final croppedImage =
// img.copyCrop(image, x: left, y: top, width: width, height: height);
// // Save the cropped image
// final tempDir = await path_provider.getTemporaryDirectory();
// final tempPath = tempDir.path;
// final croppedFile = File('$tempPath/cropped_image.jpg');
// await croppedFile.writeAsBytes(img.encodeJpg(croppedImage, quality: 100));
// return croppedFile;
// } finally {
// faceDetector.close();
// }
// }

View File

@@ -0,0 +1,15 @@
import 'package:get/get.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
class HomePageController extends GetxController {
late bool isVibrate = box.read(BoxName.isvibrate) ?? true;
void changeVibrateOption(bool value) {
isVibrate = box.read(BoxName.isvibrate) ?? true;
isVibrate = value;
box.write(BoxName.isvibrate, value);
update();
}
}