25-7-26-1
This commit is contained in:
19
lib/controller/functions/add_error.dart
Normal file
19
lib/controller/functions/add_error.dart
Normal 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
|
||||
});
|
||||
}
|
||||
166
lib/controller/functions/audio_record1.dart
Normal file
166
lib/controller/functions/audio_record1.dart
Normal file
@@ -0,0 +1,166 @@
|
||||
import 'dart:io';
|
||||
|
||||
// import 'package:flutter_sound/flutter_sound.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:record/record.dart';
|
||||
|
||||
class AudioRecorderController extends GetxController {
|
||||
AudioPlayer audioPlayer = AudioPlayer();
|
||||
AudioRecorder recorder = AudioRecorder();
|
||||
|
||||
bool isRecording = false;
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
String filePath = '';
|
||||
String? selectedFilePath;
|
||||
double currentPosition = 0;
|
||||
double totalDuration = 0;
|
||||
|
||||
Future<void> playSoundFromAssets(String sound) async {
|
||||
try {
|
||||
await audioPlayer.setAsset(sound);
|
||||
audioPlayer.play();
|
||||
} catch (e) {
|
||||
print("Error playing sound: $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Start recording
|
||||
Future<void> startRecording() async {
|
||||
final bool isPermissionGranted = await recorder.hasPermission();
|
||||
if (!isPermissionGranted) {
|
||||
// RecordingPermissionException('l');
|
||||
return;
|
||||
}
|
||||
|
||||
final directory = await getApplicationDocumentsDirectory();
|
||||
// Generate a unique file name using the current timestamp
|
||||
String fileName =
|
||||
// '${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}_${Get.find<MapPassengerController>().rideId}.m4a';
|
||||
'${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}.m4a';
|
||||
filePath = '${directory.path}/$fileName';
|
||||
|
||||
// Define the configuration for the recording
|
||||
const config = RecordConfig(
|
||||
// Specify the format, encoder, sample rate, etc., as needed
|
||||
encoder: AudioEncoder.aacLc, // For example, using AAC codec
|
||||
sampleRate: 44100, // Sample rate
|
||||
bitRate: 128000, // Bit rate
|
||||
);
|
||||
|
||||
// Start recording to file with the specified configuration
|
||||
await recorder.start(config, path: filePath);
|
||||
|
||||
isRecording = true;
|
||||
update();
|
||||
}
|
||||
|
||||
// Pause recording
|
||||
Future<void> pauseRecording() async {
|
||||
if (isRecording && !isPaused) {
|
||||
await recorder.pause();
|
||||
isPaused = true;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Resume recording
|
||||
Future<void> resumeRecording() async {
|
||||
if (isRecording && isPaused) {
|
||||
await recorder.resume();
|
||||
isPaused = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Stop recording
|
||||
Future<void> stopRecording() async {
|
||||
await recorder.stop();
|
||||
isRecording = false;
|
||||
isPaused = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// Play the selected recorded file
|
||||
Future<void> playRecordedFile(String filePath) async {
|
||||
await audioPlayer.setFilePath(filePath);
|
||||
totalDuration = audioPlayer.duration?.inSeconds.toDouble() ?? 0;
|
||||
audioPlayer.play();
|
||||
|
||||
isPlaying = true;
|
||||
isPaused = false;
|
||||
audioPlayer.positionStream.listen((position) {
|
||||
currentPosition = position.inSeconds.toDouble();
|
||||
update();
|
||||
});
|
||||
selectedFilePath = filePath;
|
||||
update();
|
||||
}
|
||||
|
||||
// Pause playback
|
||||
Future<void> pausePlayback() async {
|
||||
if (isPlaying && !isPaused) {
|
||||
await audioPlayer.pause();
|
||||
isPaused = true;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Resume playback
|
||||
Future<void> resumePlayback() async {
|
||||
if (isPlaying && isPaused) {
|
||||
await audioPlayer.play();
|
||||
isPaused = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Stop playback
|
||||
Future<void> stopPlayback() async {
|
||||
await audioPlayer.stop();
|
||||
isPlaying = false;
|
||||
isPaused = false;
|
||||
currentPosition = 0;
|
||||
update();
|
||||
}
|
||||
|
||||
// Get a list of recorded files
|
||||
Future<List<String>> getRecordedFiles() async {
|
||||
final directory = await getApplicationDocumentsDirectory();
|
||||
final files = await directory.list().toList();
|
||||
return files
|
||||
.map((file) => file.path)
|
||||
.where((path) => path.endsWith('.m4a'))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// Delete a specific recorded file
|
||||
Future<void> deleteRecordedFile(String filePath) async {
|
||||
final file = File(filePath);
|
||||
if (await file.exists()) {
|
||||
await file.delete();
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Delete all recorded files
|
||||
Future<void> deleteAllRecordedFiles() async {
|
||||
final directory = await getApplicationDocumentsDirectory();
|
||||
final files = await directory.list().toList();
|
||||
for (final file in files) {
|
||||
if (file.path.endsWith('.m4a')) {
|
||||
await deleteRecordedFile(file.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
audioPlayer.dispose();
|
||||
recorder.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
134
lib/controller/functions/call_controller.dart
Normal file
134
lib/controller/functions/call_controller.dart
Normal file
@@ -0,0 +1,134 @@
|
||||
// import 'package:SEFER/constant/api_key.dart';
|
||||
// import 'package:SEFER/controller/functions/crud.dart';
|
||||
// import 'package:SEFER/controller/home/map_passenger_controller.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 '../../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();
|
||||
// // if (box.read(BoxName.passengerID) != null) {
|
||||
// channelName = Get.find<MapPassengerController>().rideId; // 'sefer300'; //
|
||||
// remoteUid = int.parse(Get.find<MapPassengerController>().driverPhone);
|
||||
// uid = int.parse(box.read(BoxName.phone));
|
||||
// // } else {
|
||||
// // 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().sendNotificationToPassengerToken(
|
||||
// 'Call Income from Passenger',
|
||||
// '${'You have call from Passenger'.tr} ${box.read(BoxName.name)}',
|
||||
// Get.find<MapPassengerController>().driverToken,
|
||||
// [
|
||||
// token,
|
||||
// channelName,
|
||||
// uid.toString(),
|
||||
// remoteUid.toString(),
|
||||
// ],
|
||||
// 'iphone_ringtone.wav',
|
||||
// );
|
||||
// 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<MapPassengerController>().driverName.toString();
|
||||
// ' 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();
|
||||
// }
|
||||
// }
|
||||
709
lib/controller/functions/crud.dart
Normal file
709
lib/controller/functions/crud.dart
Normal file
@@ -0,0 +1,709 @@
|
||||
import 'dart:convert';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
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 'add_error.dart';
|
||||
import 'encrypt_decrypt.dart';
|
||||
import 'upload_image.dart';
|
||||
|
||||
class CRUD {
|
||||
Future<dynamic> get({
|
||||
required String link,
|
||||
Map<String, dynamic>? payload,
|
||||
}) async {
|
||||
// print(r(box.read(BoxName.jwt)).toString().split(Env.addd)[0]);
|
||||
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]}'
|
||||
},
|
||||
);
|
||||
// print('req: ${response.request}');
|
||||
// Log.print('response: ${response.body}');
|
||||
// Log.print('payload: ${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(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');
|
||||
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 LoginController().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(),
|
||||
},
|
||||
);
|
||||
// print('req: ${response.request}');
|
||||
// Log.print('response: ${response.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
if (response.statusCode == 200) {
|
||||
var jsonData = jsonDecode(response.body);
|
||||
Log.print('jsonData: $jsonData');
|
||||
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(LoginController()).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> post(
|
||||
{required String link, Map<String, dynamic>? payload}) async {
|
||||
var url = Uri.parse(link);
|
||||
try {
|
||||
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]}'
|
||||
},
|
||||
);
|
||||
// Log.print('req: ${response.request}');
|
||||
// Log.print('response: ${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') {
|
||||
// Show snackbar prompting to re-login
|
||||
await Get.put(LoginController()).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> postWallet(
|
||||
{required String link, Map<String, dynamic>? payload}) async {
|
||||
var s = await LoginController().getJwtWallet();
|
||||
|
||||
final hmac = box.read(BoxName.hmac);
|
||||
|
||||
var url = Uri.parse(link);
|
||||
try {
|
||||
var response = await http.post(
|
||||
url,
|
||||
body: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
'Authorization': 'Bearer $s',
|
||||
'X-HMAC-Auth': hmac.toString(),
|
||||
},
|
||||
);
|
||||
// print('req: ${response.request}');
|
||||
// Log.print('response: ${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') {
|
||||
// Show snackbar prompting to re-login
|
||||
await Get.put(LoginController()).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> getTokenParent({
|
||||
required String link,
|
||||
Map<String, dynamic>? payload,
|
||||
}) async {
|
||||
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.toString()))}',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
var jsonData = jsonDecode(response.body);
|
||||
// if (jsonData['status'] == 'success') {
|
||||
|
||||
return jsonData;
|
||||
// }
|
||||
|
||||
// return jsonData['status'];
|
||||
}
|
||||
}
|
||||
|
||||
Future sendWhatsAppAuth(String to, String token) async {
|
||||
var res = await CRUD()
|
||||
.get(link: AppLink.getApiKey, payload: {'keyName': 'whatsapp_key'});
|
||||
var accesstoken = jsonDecode(res)['message']['whatsapp_key'];
|
||||
var headers = {
|
||||
'Authorization': 'Bearer $accesstoken',
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
|
||||
var url = 'https://graph.facebook.com/v20.0/${Env.whatappID}/messages';
|
||||
var request = http.Request('POST', Uri.parse(url));
|
||||
|
||||
var body = json.encode({
|
||||
"messaging_product": "whatsapp",
|
||||
"to": to,
|
||||
"type": "template",
|
||||
"template": {
|
||||
"name": "sefer1",
|
||||
"language": {"code": "en"},
|
||||
"components": [
|
||||
{
|
||||
"type": "body",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": token,
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
request.body = body;
|
||||
request.headers.addAll(headers);
|
||||
|
||||
try {
|
||||
http.StreamedResponse response = await request.send();
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
String responseBody = await response.stream.bytesToString();
|
||||
|
||||
Get.defaultDialog(
|
||||
title: 'You will receive a code in WhatsApp Messenger'.tr,
|
||||
middleText: 'wait 1 minute to recive message'.tr,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'OK'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
},
|
||||
),
|
||||
);
|
||||
} else {
|
||||
String errorBody = await response.stream.bytesToString();
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
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));
|
||||
String extracted =
|
||||
await arabicTextExtractByVisionAndAI(imagePath: imagePath);
|
||||
// await AI().geminiAiExtraction(prompt, extracted);
|
||||
}
|
||||
|
||||
Future<dynamic> arabicTextExtractByVisionAndAI({
|
||||
required String imagePath,
|
||||
}) async {
|
||||
var headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Ocp-Apim-Subscription-Key': '21010e54b50f41a4904708c526e102df'
|
||||
};
|
||||
var url = Uri.parse(
|
||||
'https://ocrhamza.cognitiveservices.azure.com/vision/v2.1/ocr?language=ar',
|
||||
);
|
||||
String imagePathFull =
|
||||
'${AppLink.server}card_image/$imagePath-${box.read(BoxName.driverID) ?? box.read(BoxName.passengerID)}.jpg';
|
||||
|
||||
var requestBody = {"url": imagePathFull};
|
||||
var response = await http.post(
|
||||
url,
|
||||
body: jsonEncode(requestBody), // Encode the JSON object to a string
|
||||
headers: headers,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
var responseBody = jsonDecode(response.body);
|
||||
return responseBody.toString();
|
||||
}
|
||||
return response.statusCode;
|
||||
}
|
||||
|
||||
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.secretKey}',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
return response.body;
|
||||
} else {}
|
||||
}
|
||||
|
||||
// Future<dynamic> post({
|
||||
// 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))}',
|
||||
// },
|
||||
// );
|
||||
// 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<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;
|
||||
}
|
||||
}
|
||||
|
||||
sendEmail(
|
||||
String link,
|
||||
Map<String, String>? payload,
|
||||
) async {
|
||||
var headers = {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
'Authorization':
|
||||
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
|
||||
};
|
||||
var request = http.Request('POST', Uri.parse(link));
|
||||
request.bodyFields = payload!;
|
||||
request.headers.addAll(headers);
|
||||
|
||||
http.StreamedResponse response = await request.send();
|
||||
if (response.statusCode == 200) {
|
||||
} else {}
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
// 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;
|
||||
}
|
||||
return (jsonData['status']);
|
||||
}
|
||||
|
||||
Future<dynamic> getHereMap({
|
||||
required String link,
|
||||
}) async {
|
||||
var url = Uri.parse(link);
|
||||
try {
|
||||
var response = await http.get(url);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
// Ensure the response body is decoded as UTF-8
|
||||
var decodedBody = utf8.decode(response.bodyBytes);
|
||||
var data = jsonDecode(decodedBody);
|
||||
return data;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
26
lib/controller/functions/custom_pant.dart
Normal file
26
lib/controller/functions/custom_pant.dart
Normal 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;
|
||||
}
|
||||
92
lib/controller/functions/device_info.dart
Normal file
92
lib/controller/functions/device_info.dart
Normal file
@@ -0,0 +1,92 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
|
||||
import '../../print.dart';
|
||||
|
||||
class DeviceInfoPlus {
|
||||
static List<Map<String, dynamic>> deviceDataList = [];
|
||||
|
||||
static Future<List<Map<String, dynamic>>> getDeviceInfo() async {
|
||||
final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
|
||||
|
||||
try {
|
||||
if (Platform.isAndroid) {
|
||||
AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
|
||||
Map<String, dynamic> deviceData = {
|
||||
'platform': 'Android',
|
||||
'brand': androidInfo.brand,
|
||||
'model': androidInfo.model,
|
||||
'androidId': androidInfo.device,
|
||||
'versionRelease': androidInfo.version.release,
|
||||
'sdkVersion': androidInfo.version.sdkInt,
|
||||
'manufacturer': androidInfo.manufacturer,
|
||||
'isPhysicalDevice': androidInfo.isPhysicalDevice,
|
||||
'serialNumber': androidInfo.serialNumber,
|
||||
'fingerprint': androidInfo.fingerprint,
|
||||
'type': androidInfo.type,
|
||||
'data': androidInfo.data,
|
||||
'version': androidInfo.version,
|
||||
'tags': androidInfo.tags,
|
||||
'display': androidInfo.display,
|
||||
};
|
||||
// Log.print('deviceData: ${deviceData}');
|
||||
deviceDataList.add(deviceData);
|
||||
} else if (Platform.isIOS) {
|
||||
IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
|
||||
Map<String, dynamic> deviceData = {
|
||||
'brand': 'Apple',
|
||||
'model': iosInfo.model,
|
||||
'systemName': iosInfo.systemName,
|
||||
'systemVersion': iosInfo.systemVersion,
|
||||
'utsname': iosInfo.utsname,
|
||||
'isPhysicalDevice': iosInfo.isPhysicalDevice,
|
||||
'identifierForVendor': iosInfo.identifierForVendor,
|
||||
'name': iosInfo.name,
|
||||
'localizedModel': iosInfo.localizedModel,
|
||||
};
|
||||
deviceDataList.add(deviceData);
|
||||
} else if (Platform.isMacOS) {
|
||||
MacOsDeviceInfo macInfo = await deviceInfoPlugin.macOsInfo;
|
||||
Map<String, dynamic> deviceData = {
|
||||
'platform': 'macOS',
|
||||
'model': macInfo.model,
|
||||
'version': macInfo.systemGUID,
|
||||
};
|
||||
deviceDataList.add(deviceData);
|
||||
} else if (Platform.isWindows) {
|
||||
WindowsDeviceInfo windowsInfo = await deviceInfoPlugin.windowsInfo;
|
||||
Map<String, dynamic> deviceData = {
|
||||
'platform': 'Windows',
|
||||
'manufacturer': windowsInfo.computerName,
|
||||
'version': windowsInfo.majorVersion,
|
||||
'deviceId': windowsInfo.deviceId,
|
||||
'userName': windowsInfo.userName,
|
||||
'productName': windowsInfo.productName,
|
||||
'installDate': windowsInfo.installDate,
|
||||
'productId': windowsInfo.productId,
|
||||
'numberOfCores': windowsInfo.numberOfCores,
|
||||
'systemMemoryInMegabytes': windowsInfo.systemMemoryInMegabytes,
|
||||
};
|
||||
deviceDataList.add(deviceData);
|
||||
} else if (Platform.isLinux) {
|
||||
LinuxDeviceInfo linuxInfo = await deviceInfoPlugin.linuxInfo;
|
||||
Map<String, dynamic> deviceData = {
|
||||
'platform': 'Linux',
|
||||
'manufacturer': linuxInfo.name,
|
||||
'version': linuxInfo.version,
|
||||
};
|
||||
deviceDataList.add(deviceData);
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
return deviceDataList;
|
||||
}
|
||||
|
||||
// Method to print all device data
|
||||
static void printDeviceInfo() {
|
||||
for (Map<String, dynamic> deviceData in deviceDataList) {
|
||||
'Version: ${deviceData['version'] ?? deviceData['versionRelease'] ?? 'N/A'}';
|
||||
}
|
||||
}
|
||||
}
|
||||
42
lib/controller/functions/digit_obsecur_formate.dart
Normal file
42
lib/controller/functions/digit_obsecur_formate.dart
Normal 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);
|
||||
// }
|
||||
// }
|
||||
78
lib/controller/functions/encrypt_decrypt.dart
Normal file
78
lib/controller/functions/encrypt_decrypt.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
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;
|
||||
|
||||
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...");
|
||||
var keyOfApp = r(Env.keyOfApp).toString().split(Env.addd)[0];
|
||||
var initializationVector =
|
||||
r(Env.initializationVector).toString().split(Env.addd)[0];
|
||||
|
||||
// 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));
|
||||
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();
|
||||
}
|
||||
34
lib/controller/functions/geolocation.dart
Normal file
34
lib/controller/functions/geolocation.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
77
lib/controller/functions/launch.dart
Normal file
77
lib/controller/functions/launch.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
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 {}
|
||||
}
|
||||
148
lib/controller/functions/location_controller.dart
Normal file
148
lib/controller/functions/location_controller.dart
Normal file
@@ -0,0 +1,148 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:location/location.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/controller/home/payment/captain_wallet_controller.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
// LocationController.dart
|
||||
class LocationController extends GetxController {
|
||||
LocationData? _currentLocation;
|
||||
late Location location;
|
||||
bool isLoading = false;
|
||||
late double heading = 0;
|
||||
late double accuracy = 0;
|
||||
late double previousTime = 0;
|
||||
late double latitude;
|
||||
late double totalDistance = 0;
|
||||
late double longitude;
|
||||
late DateTime time;
|
||||
late double speed = 0;
|
||||
late double speedAccuracy = 0;
|
||||
late double headingAccuracy = 0;
|
||||
bool isActive = false;
|
||||
late LatLng myLocation;
|
||||
String totalPoints = '0';
|
||||
LocationData? get currentLocation => _currentLocation;
|
||||
Timer? _locationTimer;
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
super.onInit();
|
||||
location = Location();
|
||||
getLocation();
|
||||
// startLocationUpdates();
|
||||
|
||||
totalPoints = Get.put(CaptainWalletController()).totalPoints;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
// if (isActive) {
|
||||
if (double.parse(totalPoints) > -300) {
|
||||
await getLocation();
|
||||
|
||||
// if (box.read(BoxName.driverID) != null) {
|
||||
await CRUD()
|
||||
.post(link: AppLink.addCarsLocationByPassenger, 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 == 0
|
||||
? '0'
|
||||
: totalDistance < 1
|
||||
? totalDistance.toStringAsFixed(3)
|
||||
: totalDistance.toStringAsFixed(1),
|
||||
'status': box.read(BoxName.statusDriverLocation).toString()
|
||||
});
|
||||
}
|
||||
|
||||
// }
|
||||
} catch (e) {
|
||||
// Handle the error gracefully
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void stopLocationUpdates() {
|
||||
_locationTimer?.cancel();
|
||||
}
|
||||
|
||||
Future<void> getLocation() async {
|
||||
// isLoading = true;
|
||||
// update();
|
||||
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
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Configure location accuracy
|
||||
// LocationAccuracy desiredAccuracy = LocationAccuracy.high;
|
||||
|
||||
// Get the current location
|
||||
LocationData _locationData = await location.getLocation();
|
||||
myLocation =
|
||||
(_locationData.latitude != null && _locationData.longitude != null
|
||||
? LatLng(_locationData.latitude!, _locationData.longitude!)
|
||||
: null)!;
|
||||
speed = _locationData.speed!;
|
||||
heading = _locationData.heading!;
|
||||
// Calculate the distance between the current location and the previous location
|
||||
// if (Get.find<HomeCaptainController>().rideId == 'rideId') {
|
||||
// if (previousTime > 0) {
|
||||
// double distance = calculateDistanceInKmPerHour(
|
||||
// previousTime, _locationData.time, speed);
|
||||
// totalDistance += distance;
|
||||
// }
|
||||
|
||||
// previousTime = _locationData.time!;
|
||||
// }
|
||||
// Print location details
|
||||
// isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
double calculateDistanceInKmPerHour(
|
||||
double? startTime, double? endTime, double speedInMetersPerSecond) {
|
||||
// Calculate the time difference in hours
|
||||
double timeDifferenceInHours = (endTime! - startTime!) / 1000 / 3600;
|
||||
|
||||
// Convert speed to kilometers per hour
|
||||
double speedInKmPerHour = speedInMetersPerSecond * 3.6;
|
||||
|
||||
// Calculate the distance in kilometers
|
||||
double distanceInKilometers = speedInKmPerHour * timeDifferenceInHours;
|
||||
|
||||
return distanceInKilometers;
|
||||
}
|
||||
}
|
||||
16
lib/controller/functions/location_permission.dart
Normal file
16
lib/controller/functions/location_permission.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:location/location.dart';
|
||||
import 'package:get/get.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
184
lib/controller/functions/log_out.dart
Normal file
184
lib/controller/functions/log_out.dart
Normal file
@@ -0,0 +1,184 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/onbording_page.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:Intaleq/views/widgets/my_textField.dart';
|
||||
|
||||
import '../../constant/style.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)}).then((value) => exit(0));
|
||||
}
|
||||
|
||||
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: () {
|
||||
if (checkTxtController.text == box.read(BoxName.nameDriver)) {
|
||||
deletecaptainAccount();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
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: () {
|
||||
// box.remove(BoxName.agreeTerms);
|
||||
box.remove(BoxName.passengerPhotoUrl);
|
||||
box.remove(BoxName.driverID);
|
||||
box.remove(BoxName.email);
|
||||
box.remove(BoxName.lang);
|
||||
box.remove(BoxName.name);
|
||||
box.remove(BoxName.passengerID);
|
||||
box.remove(BoxName.phone);
|
||||
box.remove(BoxName.tokenFCM);
|
||||
box.remove(BoxName.tokens);
|
||||
box.remove(BoxName.addHome);
|
||||
box.remove(BoxName.addWork);
|
||||
box.remove(BoxName.agreeTerms);
|
||||
box.remove(BoxName.apiKeyRun);
|
||||
box.remove(BoxName.countryCode);
|
||||
box.remove(BoxName.accountIdStripeConnect);
|
||||
box.remove(BoxName.passengerWalletTotal);
|
||||
box.remove(BoxName.isVerified);
|
||||
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: () {
|
||||
// box.remove(BoxName.agreeTerms);
|
||||
box.remove(BoxName.driverID);
|
||||
box.remove(BoxName.sexDriver);
|
||||
box.remove(BoxName.dobDriver);
|
||||
box.remove(BoxName.nameDriver);
|
||||
box.remove(BoxName.emailDriver);
|
||||
box.remove(BoxName.phoneDriver);
|
||||
box.remove(BoxName.statusDriverLocation);
|
||||
box.remove(BoxName.cvvCodeDriver);
|
||||
box.remove(BoxName.lastNameDriver);
|
||||
box.remove(BoxName.passwordDriver);
|
||||
box.remove(BoxName.cardNumberDriver);
|
||||
box.remove(BoxName.expiryDateDriver);
|
||||
box.remove(BoxName.cardHolderNameDriver);
|
||||
box.remove(BoxName.vin);
|
||||
box.remove(BoxName.make);
|
||||
box.remove(BoxName.year);
|
||||
box.remove(BoxName.owner);
|
||||
box.remove(BoxName.onBoarding);
|
||||
box.remove(BoxName.agreeTerms);
|
||||
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 {
|
||||
Get.snackbar('Email Wrong'.tr, 'Email you inserted is Wrong.'.tr,
|
||||
snackPosition: SnackPosition.BOTTOM,
|
||||
backgroundColor: AppColor.redColor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
351
lib/controller/functions/package_info.dart
Normal file
351
lib/controller/functions/package_info.dart
Normal file
@@ -0,0 +1,351 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:jailbreak_root_detection/jailbreak_root_detection.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/colors.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.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 = box.read(BoxName.package);
|
||||
box.write(BoxName.packagInfo, version);
|
||||
|
||||
if (latestVersion.isNotEmpty && latestVersion != currentVersion) {
|
||||
showUpdateDialog(context);
|
||||
}
|
||||
}
|
||||
|
||||
checkForBounusInvitation() {
|
||||
if (box.read(BoxName.inviteCode) != null) {}
|
||||
}
|
||||
|
||||
// Future<String> getPackageInfo() async {
|
||||
// final response = await CRUD().get(link: AppLink.packageInfo, payload: {
|
||||
// "platform": Platform.isAndroid ? 'android' : 'ios',
|
||||
// "appName": AppInformation.appName,
|
||||
// });
|
||||
|
||||
// if (response != 'failure') {
|
||||
// return jsonDecode(response)['message'][0]['version'];
|
||||
// }
|
||||
// return '';
|
||||
// }
|
||||
// getDeviceFingerprint() async {
|
||||
// final deviceInfo = await DeviceInfoPlugin().deviceInfo;
|
||||
// var deviceData;
|
||||
|
||||
// if (Platform.isAndroid) {
|
||||
// deviceData = deviceInfo.data;
|
||||
// Log.print('deviceData: ${jsonEncode(deviceData)}');
|
||||
// } else if (Platform.isIOS) {
|
||||
// deviceData = deviceInfo.data;
|
||||
// }
|
||||
|
||||
// final String deviceId =
|
||||
// deviceData['device'] ?? deviceData['identifierForVendor'];
|
||||
// final String deviceModel = deviceData['model'];
|
||||
// final String osVersion = deviceData['systemVersion'];
|
||||
|
||||
// Log.print('fingr: ${'${deviceId}_${deviceModel}_$osVersion'}');
|
||||
// Log.print('deviceModel: ${deviceModel}');
|
||||
// Log.print('osVersion: ${osVersion}');
|
||||
// return EncryptionHelper.instance
|
||||
// .encryptData('${deviceId}_${deviceModel}_$osVersion');
|
||||
// }
|
||||
|
||||
void showUpdateDialog(BuildContext context) {
|
||||
final String storeUrl = Platform.isAndroid
|
||||
? 'https://play.google.com/store/apps/details?id=com.Intaleq.intaleq'
|
||||
: 'https://apps.apple.com/jo/app/intaleq-rider/id6748075179';
|
||||
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 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 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');
|
||||
}
|
||||
}
|
||||
|
||||
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 EncryptionHelper.instance.encryptData(fingerprint);
|
||||
} catch (e) {
|
||||
throw Exception('Failed to generate device fingerprint');
|
||||
}
|
||||
}
|
||||
}
|
||||
8
lib/controller/functions/remove_account.dart
Normal file
8
lib/controller/functions/remove_account.dart
Normal file
@@ -0,0 +1,8 @@
|
||||
// import 'package:ride/controller/functions/crud.dart';
|
||||
|
||||
// class RemoveAccount {
|
||||
|
||||
// void removeAccount()async{
|
||||
// var res=await CRUD().post(link: link)
|
||||
// }
|
||||
// }
|
||||
25
lib/controller/functions/scan_id_card.dart
Normal file
25
lib/controller/functions/scan_id_card.dart
Normal 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();
|
||||
// }
|
||||
// }
|
||||
85
lib/controller/functions/secure_storage.dart
Normal file
85
lib/controller/functions/secure_storage.dart
Normal file
@@ -0,0 +1,85 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/info.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:jwt_decoder/jwt_decoder.dart';
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import 'crud.dart';
|
||||
import 'encrypt_decrypt.dart';
|
||||
|
||||
class SecureStorage {
|
||||
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.toString();
|
||||
}
|
||||
}
|
||||
|
||||
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 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]);
|
||||
if (isTokenExpired) {
|
||||
await LoginController().getJWT();
|
||||
}
|
||||
}
|
||||
|
||||
// await getKey();
|
||||
}
|
||||
|
||||
getAIKey(String key1) async {
|
||||
if (box.read(BoxName.firstTimeLoadKey) == null) {
|
||||
var res =
|
||||
await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key1});
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res)['message'];
|
||||
storage.write(key: key1, value: d[key1].toString());
|
||||
} else {}
|
||||
}
|
||||
}
|
||||
|
||||
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.remove(BoxName.locationName);
|
||||
await box.remove(BoxName.basicLink);
|
||||
await box.remove(links[4]['name']);
|
||||
await box.remove(links[1]['name']);
|
||||
await box.remove(links[2]['name']);
|
||||
await box.write(BoxName.locationName, links);
|
||||
await box.write(BoxName.basicLink, (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) {}
|
||||
}
|
||||
}
|
||||
46
lib/controller/functions/securty_check.dart
Normal file
46
lib/controller/functions/securty_check.dart
Normal 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.intaleq/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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
168
lib/controller/functions/sms_controller.dart
Normal file
168
lib/controller/functions/sms_controller.dart
Normal file
@@ -0,0 +1,168 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/api_key.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/info.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:Intaleq/env/env.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../print.dart';
|
||||
import '../auth/register_controller.dart';
|
||||
import 'crud.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, otp) async {
|
||||
// String sender = await getSender();
|
||||
// var body = jsonEncode({
|
||||
// "username": 'Sefer',
|
||||
// "password": AK.smsPasswordEgypt,
|
||||
// "message": "${AppInformation.appName} app code is $otp\ncopy it to app",
|
||||
// "language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
|
||||
// "sender": sender, //"Sefer Egy",
|
||||
// "receiver": phone
|
||||
// });
|
||||
|
||||
var res = await CRUD().post(link: AppLink.sendSmsFromPHP, payload: {
|
||||
"language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
|
||||
"receiver": phone,
|
||||
});
|
||||
if (res != 'failure') {
|
||||
// var res = await http.post(
|
||||
// Uri.parse(AppLink.sendSms),
|
||||
// body: body,
|
||||
// headers: headers,
|
||||
// );
|
||||
|
||||
// else if (jsonDecode(res)['message'].toString() ==
|
||||
// "Invalid Sender with Connection") {
|
||||
//
|
||||
// }
|
||||
// else {
|
||||
Get.defaultDialog(
|
||||
title: 'You will receive a code in SMS message'.tr,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(
|
||||
title: 'OK'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
}));
|
||||
} else {
|
||||
await CRUD().post(link: AppLink.updatePhoneInvalidSMSPassenger, payload: {
|
||||
"phone_number":
|
||||
'+2${Get.find<RegisterController>().phoneController.text}'
|
||||
});
|
||||
box.write(BoxName.phoneDriver,
|
||||
'+2${Get.find<RegisterController>().phoneController.text}');
|
||||
box.write(BoxName.isVerified, '1');
|
||||
|
||||
await Get.put(LoginController()).loginUsingCredentials(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
box.read(BoxName.emailDriver).toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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": "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,
|
||||
);
|
||||
}
|
||||
|
||||
Future sendWhatsAppAuth(String to, String token) async {
|
||||
var headers = {
|
||||
'Authorization': 'Bearer ${Env.whatsapp}',
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
var request = http.Request(
|
||||
'POST',
|
||||
Uri.parse(
|
||||
'https://graph.facebook.com/v20.0/${Env.whatappID}/messages'));
|
||||
request.body = json.encode({
|
||||
"messaging_product": "whatsapp",
|
||||
"to": to, //"962798583052",
|
||||
"type": "template",
|
||||
"template": {
|
||||
"name": "sefer1",
|
||||
"language": {"code": "en"},
|
||||
"components": [
|
||||
{
|
||||
"type": "body",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": token,
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
request.headers.addAll(headers);
|
||||
|
||||
http.StreamedResponse response = await request.send();
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print(await response.stream.bytesToString());
|
||||
Get.defaultDialog(
|
||||
title: 'You will receive a code in WhatsApp Messenger'.tr,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(
|
||||
title: 'OK'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
}));
|
||||
} else {
|
||||
print(response.reasonPhrase);
|
||||
}
|
||||
}
|
||||
}
|
||||
18
lib/controller/functions/sss.dart
Normal file
18
lib/controller/functions/sss.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../main.dart';
|
||||
|
||||
class Sss {
|
||||
static read(String boxname) async {
|
||||
return box.read(X.r(X.r(X.r(boxname, cn), cC), cs));
|
||||
}
|
||||
|
||||
static write(String boxname, value) async {
|
||||
return box.write(boxname, X.c(X.c(X.c(value, cn), cC), cs));
|
||||
}
|
||||
|
||||
static delete(String boxname) async {
|
||||
return box.remove(boxname);
|
||||
}
|
||||
}
|
||||
35
lib/controller/functions/toast.dart
Normal file
35
lib/controller/functions/toast.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/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,
|
||||
);
|
||||
}
|
||||
}
|
||||
51
lib/controller/functions/tts.dart
Normal file
51
lib/controller/functions/tts.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_tts/flutter_tts.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../main.dart';
|
||||
|
||||
class TextToSpeechController extends GetxController {
|
||||
final flutterTts = FlutterTts();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
initTts();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
flutterTts.stop(); // Stop any ongoing TTS
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
// Initialize TTS engine with language check
|
||||
Future<void> initTts() async {
|
||||
try {
|
||||
String langCode = box.read(BoxName.lang) ?? 'en-US';
|
||||
bool isAvailable = await flutterTts.isLanguageAvailable(langCode);
|
||||
|
||||
// If language is unavailable, default to 'en-US'
|
||||
if (!isAvailable) {
|
||||
langCode = 'en-US';
|
||||
}
|
||||
|
||||
await flutterTts.setLanguage(langCode);
|
||||
await flutterTts.setSpeechRate(0.5); // Adjust speech rate
|
||||
await flutterTts.setVolume(1.0); // Set volume
|
||||
} catch (error) {
|
||||
Get.snackbar('Error', 'Failed to initialize TTS: $error');
|
||||
}
|
||||
}
|
||||
|
||||
// Function to speak the given text
|
||||
Future<void> speakText(String text) async {
|
||||
try {
|
||||
await flutterTts.awaitSpeakCompletion(true);
|
||||
await flutterTts.speak(text);
|
||||
} catch (error) {
|
||||
Get.snackbar('Error', 'Failed to speak text: $error');
|
||||
}
|
||||
}
|
||||
}
|
||||
22
lib/controller/functions/twilio_service.dart
Normal file
22
lib/controller/functions/twilio_service.dart
Normal 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) {
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
104
lib/controller/functions/upload_image.dart
Normal file
104
lib/controller/functions/upload_image.dart
Normal file
@@ -0,0 +1,104 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:Intaleq/constant/api_key.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:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../constant/colors.dart';
|
||||
import '../../constant/info.dart';
|
||||
import '../../main.dart';
|
||||
|
||||
class ImageController extends GetxController {
|
||||
File? myImage;
|
||||
bool isloading = false;
|
||||
CroppedFile? croppedFile;
|
||||
final picker = ImagePicker();
|
||||
var image;
|
||||
choosImage(String link, String imageType) async {
|
||||
final pickedImage = await picker.pickImage(source: ImageSource.gallery);
|
||||
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);
|
||||
try {
|
||||
await uploadImage(
|
||||
savedCroppedImage,
|
||||
{
|
||||
'driverID':
|
||||
box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
|
||||
'imageType': imageType
|
||||
},
|
||||
link,
|
||||
);
|
||||
} catch (e) {
|
||||
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), //'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':
|
||||
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
|
||||
});
|
||||
// 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}');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user