25-10-2/1

This commit is contained in:
Hamza-Ayed
2025-10-02 01:20:16 +03:00
parent 7595be8067
commit c48627a175
342 changed files with 15825 additions and 14862 deletions

View File

@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:convert';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/links.dart';
@@ -9,6 +10,7 @@ import 'package:Intaleq/env/env.dart';
import '../../constant/api_key.dart';
import '../../print.dart';
import '../../views/widgets/elevated_btn.dart';
import '../../views/widgets/error_snakbar.dart';
import 'encrypt_decrypt.dart';
@@ -22,6 +24,7 @@ import 'network/net_guard.dart';
class CRUD {
final NetGuard _netGuard = NetGuard();
final _client = http.Client();
/// Stores the signature of the last logged error to prevent duplicates.
static String _lastErrorSignature = '';
@@ -41,7 +44,6 @@ class CRUD {
if (currentErrorSignature == _lastErrorSignature &&
now.difference(_lastErrorTimestamp) < _errorLogDebounceDuration) {
print("Debounced a duplicate error: $error");
return;
}
@@ -66,9 +68,7 @@ class CRUD {
'details': details,
},
);
} catch (e) {
print("CRITICAL: Failed to log error to server: $e");
}
} catch (e) {}
}
/// Centralized private method to handle all API requests.
@@ -78,80 +78,72 @@ class CRUD {
Map<String, dynamic>? payload,
required Map<String, String> headers,
}) async {
// timeouts أقصر
const connectTimeout = Duration(seconds: 6);
const receiveTimeout = Duration(seconds: 10);
Future<http.Response> doPost() {
final url = Uri.parse(link);
// استخدم _client بدل http.post
return _client
.post(url, body: payload, headers: headers)
.timeout(connectTimeout + receiveTimeout);
}
http.Response response;
try {
var response = await HttpRetry.sendWithRetry(
() {
var url = Uri.parse(link);
return http.post(
url,
body: payload,
headers: headers,
);
},
maxRetries: 3,
timeout: const Duration(seconds: 15),
);
// retry ذكي: محاولة واحدة إضافية فقط لأخطاء شبكة/5xx
try {
response = await doPost();
} on SocketException catch (_) {
// محاولة ثانية واحدة فقط
response = await doPost();
} on TimeoutException catch (_) {
response = await doPost();
}
if (response.statusCode == 200) {
final sc = response.statusCode;
Log.print('sc: ${sc}');
Log.print('request: ${response.request}');
final body = response.body;
Log.print('body: ${body}');
// 2xx
if (sc >= 200 && sc < 300) {
try {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return jsonData;
} else {
// Log API logical errors (e.g., "Customer not found")
if (jsonData['status'] == 'failure') {
// return 'failure';
} else {
addError(
'API Logic Error: ${jsonData['status']}',
'Response: ${response.body}',
'CRUD._makeRequest - $link',
);
}
final jsonData = jsonDecode(body);
return jsonData; // لا تعيد 'success' فقط؛ أعِد الجسم كله
} catch (e, st) {
// لا تسجّل كخطأ شبكي لكل حالة؛ فقط معلومات
addError('JSON Decode Error', 'Body: $body\n$st',
'CRUD._makeRequest $link');
return 'failure';
}
}
return jsonData['status'];
}
} catch (e, stackTrace) {
addError(
'JSON Decode Error: $e',
'Response Body: ${response.body}\nStack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
return 'failure';
}
} else if (response.statusCode == 401) {
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
await Get.put(LoginController()).getJWT();
// mySnackbarSuccess('please order now'.tr);
return 'token_expired';
} else {
addError(
'Unauthorized Error: ${jsonData['error']}',
'Status Code: 401',
'CRUD._makeRequest - $link',
);
return 'failure';
}
} else {
// 401 → دع الطبقة العليا تتعامل مع التجديد
if (sc == 401) {
// لا تستدع getJWT هنا كي لا نضاعف الرحلات
return 'token_expired';
}
// 5xx: لا تعِد المحاولة هنا (حاولنا مرة ثانية فوق)
if (sc >= 500) {
addError(
'HTTP Error',
'Status Code: ${response.statusCode}\nResponse Body: ${response.body}',
'CRUD._makeRequest - $link',
);
'Server 5xx', 'SC: $sc\nBody: $body', 'CRUD._makeRequest $link');
return 'failure';
}
// 4xx أخرى: أعد الخطأ بدون تسجيل مكرر
return 'failure';
} on SocketException {
_netGuard.notifyOnce((title, msg) {
mySnackeBarError(msg);
});
_netGuard.notifyOnce((title, msg) => mySnackeBarError(msg));
return 'no_internet';
} catch (e, stackTrace) {
addError(
'HTTP Request Exception: $e',
'Stack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
} on TimeoutException {
return 'failure';
} catch (e, st) {
addError('HTTP Request Exception: $e', 'Stack: $st',
'CRUD._makeRequest $link');
return 'failure';
}
}
@@ -186,28 +178,45 @@ class CRUD {
required String link,
Map<String, dynamic>? payload,
}) async {
String token = r(box.read(BoxName.jwt)).toString().split(Env.addd)[0];
// if (JwtDecoder.isExpired(token)) {
// await Get.put(LoginController()).getJWT();
// token = r(box.read(BoxName.jwt)).toString().split(Env.addd)[0];
// }
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $token'
};
var result = await _makeRequest(
link: link,
payload: payload,
headers: headers,
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${r(box.read(BoxName.jwt)).toString().split(Env.addd)[0]}'
},
);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return response.body;
}
// The original 'get' method returned the raw body on success, maintaining that behavior.
if (result is Map && result['status'] == 'success') {
return jsonEncode(result);
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(LoginController()).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',
// url.toString());
return 'failure';
}
} else {
addError('Non-200 response code: ${response.statusCode}',
'crud().post - Other', url.toString());
return 'failure';
}
return result;
}
/// Performs an authenticated POST request to wallet endpoints.
@@ -236,27 +245,48 @@ class CRUD {
required String link,
Map<String, dynamic>? payload,
}) async {
var jwt = await LoginController().getJwtWallet();
var s = await LoginController().getJwtWallet();
final hmac = box.read(BoxName.hmac);
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $jwt',
'X-HMAC-Auth': hmac.toString(),
};
var result = await _makeRequest(
link: link,
payload: payload,
headers: headers,
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(),
},
);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return response.body;
}
if (result is Map && result['status'] == 'success') {
return jsonEncode(result);
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(LoginController()).getJwtWallet();
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401',
url.toString());
return 'failure';
}
} else {
addError('Non-200 response code: ${response.statusCode}',
'crud().post - Other', url.toString());
return 'failure';
}
return result;
}
// =======================================================================
// All other specialized methods remain below.
// They are kept separate because they interact with external third-party APIs
@@ -282,11 +312,6 @@ class CRUD {
},
);
print('req: ${response.request}');
print('status: ${response.statusCode}');
print('body: ${response.body}');
print('payload: $payload');
Map<String, dynamic> wrap(String status, {Object? message, int? code}) {
return {
'status': status,
@@ -728,9 +753,6 @@ class CRUD {
url,
body: payload,
);
// Log.print('req: ${response.request}');
// Log.print('response: ${response.body}');
// Log.print('payload: ${payload}');
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'OK') {
return jsonData;

View File

@@ -22,7 +22,7 @@ class DeviceInfoPlus {
'sdkVersion': androidInfo.version.sdkInt,
'manufacturer': androidInfo.manufacturer,
'isPhysicalDevice': androidInfo.isPhysicalDevice,
'serialNumber': androidInfo.serialNumber,
'serialNumber': androidInfo.fingerprint,
'fingerprint': androidInfo.fingerprint,
'type': androidInfo.type,
'data': androidInfo.data,

View File

@@ -1,12 +1,9 @@
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/env/env.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import '../../constant/char_map.dart';
import '../../main.dart';
import '../../print.dart';
class EncryptionHelper {
static EncryptionHelper? _instance;

View File

@@ -330,7 +330,7 @@ class DeviceHelper {
// Extract relevant device information
final String deviceId = Platform.isAndroid
? deviceData['androidId'] ?? deviceData['serialNumber'] ?? 'unknown'
? deviceData['androidId'] ?? deviceData['fingerprint'] ?? 'unknown'
: deviceData['identifierForVendor'] ?? 'unknown';
final String deviceModel = deviceData['model'] ?? 'unknown';

View File

@@ -26,10 +26,10 @@ class SecureStorage {
const List<String> keysToFetch = [
'serverPHP',
'seferAlexandriaServer',
'seferPaymentServer',
'seferCairoServer',
'seferGizaServer',
// 'seferAlexandriaServer',
// 'seferPaymentServer',
// 'seferCairoServer',
// 'seferGizaServer',
];
class AppInitializer {
@@ -39,10 +39,9 @@ class AppInitializer {
if (box.read(BoxName.jwt) == null) {
await LoginController().getJWT();
} else {
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
bool isTokenExpired = JwtDecoder.isExpired(
r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0]);
if (isTokenExpired) {
await LoginController().getJWT();
}