Initial commit for Intaleq Driver

This commit is contained in:
Hamza-Ayed
2025-09-01 19:04:50 +03:00
parent 889c67a691
commit 8c7f3e3a75
46 changed files with 4300 additions and 6192 deletions

View File

@@ -17,6 +17,201 @@ import 'gemeni.dart';
import 'upload_image.dart';
class CRUD {
/// Stores the signature of the last logged error to prevent duplicates.
static String _lastErrorSignature = '';
/// Stores the timestamp of the last logged error.
static DateTime _lastErrorTimestamp =
DateTime(2000); // Initialize with an old date
/// The minimum time that must pass before logging the same error again.
static const Duration _errorLogDebounceDuration = Duration(minutes: 1);
/// Asynchronously logs an error to the server with debouncing to prevent log flooding.
///
/// [error]: A concise description of the error.
/// [details]: Detailed information, such as a stack trace or the server response body.
/// [where]: The location in the code where the error occurred (e.g., 'ClassName.methodName').
static Future<void> addError(
String error, String details, String where) async {
try {
// Create a unique signature for the current error
final currentErrorSignature = '$where-$error';
final now = DateTime.now();
// Check if the same error occurred recently
if (currentErrorSignature == _lastErrorSignature &&
now.difference(_lastErrorTimestamp) < _errorLogDebounceDuration) {
// If it's the same error within the debounce duration, ignore it.
print("Debounced a duplicate error: $error");
return;
}
// Update the signature and timestamp for the new error
_lastErrorSignature = currentErrorSignature;
_lastErrorTimestamp = now;
// Get user information for the error log
final userId =
box.read(BoxName.driverID) ?? box.read(BoxName.passengerID);
final userType =
box.read(BoxName.driverID) != null ? 'Driver' : 'passenger';
final phone = box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver);
// Send the error data to the server
// Note: This is a fire-and-forget call. We don't await it or handle its response
// to prevent an infinite loop if the addError endpoint itself is failing.
CRUD().post(
link: AppLink.addError,
payload: {
'error': error.toString(),
'userId': userId.toString(),
'userType': userType,
'phone': phone.toString(),
'device': where, // The location of the error
'details': details, // The detailed stack trace or context
},
);
} catch (e) {
// If logging the error itself fails, print to the console to avoid infinite loops.
print("Failed to log error to server: $e");
}
}
Future<dynamic> _makeRequest({
required String link,
Map<String, dynamic>? payload,
required Map<String, String> headers,
}) async {
var url = Uri.parse(link);
try {
var response = await http.post(
url,
body: payload,
headers: headers,
);
// Handle successful response (200 OK)
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return jsonData; // Return the full JSON object on success
} else {
// The API reported a logical failure (e.g., validation error)
addError(
'API Logic Error: ${jsonData['status']}',
'Response: ${response.body}',
'CRUD._makeRequest - $link',
);
return jsonData['status']; // Return the specific status string
}
} catch (e, stackTrace) {
// Error decoding the JSON response from the server
addError(
'JSON Decode Error: $e',
'Response Body: ${response.body}\nStack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
return 'failure';
}
}
// Handle Unauthorized (401) - typically means token expired
else if (response.statusCode == 401) {
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// The token refresh logic is handled before the call,
// but we log this case if it still happens.
// addError(
// 'Token Expired',
// 'A new token should have been fetched before this call.',
// 'CRUD._makeRequest - $link',
// );
return 'token_expired';
} else {
// Other 401 errors (e.g., invalid token)
addError(
'Unauthorized Error: ${jsonData['error']}',
'Status Code: 401',
'CRUD._makeRequest - $link',
);
return 'failure';
}
}
// Handle all other non-successful status codes
else {
addError(
'HTTP Error',
'Status Code: ${response.statusCode}\nResponse Body: ${response.body}',
'CRUD._makeRequest - $link',
);
return 'failure';
}
} catch (e, stackTrace) {
// Handle network exceptions (e.g., no internet, DNS error)
addError(
'HTTP Request Exception: $e',
'Stack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
return 'failure';
}
}
Future<dynamic> post({
required String link,
Map<String, dynamic>? payload,
}) async {
// 1. Check if the token is expired
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
// 2. If expired, get a new one
if (isTokenExpired) {
await LoginDriverController().getJWT();
}
// 3. Prepare the headers with the valid token
final 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]}'
};
// 4. Make the request using the centralized helper
return await _makeRequest(
link: link,
payload: payload,
headers: headers,
);
}
/// Performs an authenticated POST request to the wallet endpoints.
/// Uses a separate JWT and HMAC for authentication.
Future<dynamic> postWallet({
required String link,
Map<String, dynamic>? payload,
}) async {
// 1. Get the specific JWT and HMAC for the wallet
var jwt = await LoginDriverController().getJwtWallet();
final hmac = box.read(BoxName.hmac);
// 2. Prepare the headers
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $jwt',
'X-HMAC-Auth': hmac.toString(),
};
// 3. Make the request using the centralized helper
return await _makeRequest(
link: link,
payload: payload,
headers: headers,
);
}
Future<dynamic> get({
required String link,
Map<String, dynamic>? payload,
@@ -125,132 +320,132 @@ class CRUD {
}
}
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();
// 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);
// 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';
}
}
// 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);
// 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();
// },
// );
// 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';
}
}
// 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,
@@ -579,7 +774,10 @@ class CRUD {
url,
body: payload,
);
Log.print('esponse.body: ${response.body}');
Log.print('esponse.body: ${response.request}');
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'OK') {
return jsonData;
}