diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 7f8a61e9..6749e87f 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -15,6 +15,8 @@ class URLs { // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation + static const String chatHubUrl = "https://apiderichat.hmg.com/chathub/api"; // new V2 apis + static String _host = host1; set host(String value) => _host = value; diff --git a/lib/modules/cx_module/chat/chat_api_client.dart b/lib/modules/cx_module/chat/chat_api_client.dart index 5af7d273..fc473329 100644 --- a/lib/modules/cx_module/chat/chat_api_client.dart +++ b/lib/modules/cx_module/chat/chat_api_client.dart @@ -1,10 +1,16 @@ -// import 'dart:convert'; -// import 'dart:io'; -// import 'dart:typed_data'; -// -// import 'package:flutter/foundation.dart'; -// import 'package:flutter/material.dart'; -// import 'package:http/http.dart'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart'; +import 'package:test_sa/controllers/api_routes/api_manager.dart'; +import 'package:test_sa/extensions/string_extensions.dart'; + +import 'model/get_search_user_chat_model.dart'; +import 'model/get_user_login_token_model.dart'; + // import 'package:mohem_flutter_app/api/api_client.dart'; // import 'package:mohem_flutter_app/app_state/app_state.dart'; // import 'package:mohem_flutter_app/classes/consts.dart'; @@ -19,102 +25,108 @@ // import 'package:mohem_flutter_app/models/chat/get_user_groups_by_id.dart'; // import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as user; // import 'package:mohem_flutter_app/models/chat/make_user_favotire_unfavorite_chat_model.dart' as fav; -// -// class ChatApiClient { -// static final ChatApiClient _instance = ChatApiClient._internal(); -// -// ChatApiClient._internal(); -// -// factory ChatApiClient() => _instance; -// -// Future getUserLoginToken() async { -// user.UserAutoLoginModel userLoginResponse = user.UserAutoLoginModel(); -// String? deviceToken = AppState().getIsHuawei ? AppState().getHuaweiPushToken : AppState().getDeviceToken; -// Response response = await ApiClient().postJsonForResponse( -// "${ApiConsts.chatLoginTokenUrl}externaluserlogin", -// { -// "employeeNumber": AppState().memberInformationList!.eMPLOYEENUMBER.toString(), -// "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", -// "isMobile": true, -// "platform": Platform.isIOS ? "ios" : "android", -// "deviceToken": AppState().getIsHuawei ? AppState().getHuaweiPushToken : AppState().getDeviceToken, -// "isHuaweiDevice": AppState().getIsHuawei, -// "voipToken": Platform.isIOS ? "80a3b01fc1ef2453eb4f1daa4fc31d8142d9cb67baf848e91350b607971fe2ba" : "", -// }, -// ); -// -// if (!kReleaseMode) { -// logger.i("login-res: " + response.body); -// } -// if (response.statusCode == 200) { -// userLoginResponse = user.userAutoLoginModelFromJson(response.body); -// } else if (response.statusCode == 501 || response.statusCode == 502 || response.statusCode == 503 || response.statusCode == 504) { -// getUserLoginToken(); -// } else { -// userLoginResponse = user.userAutoLoginModelFromJson(response.body); -// Utils.showToast(userLoginResponse.errorResponses!.first.message!); -// } -// return userLoginResponse; -// } -// -// Future getChatMemberFromSearch(String searchParam, int cUserId, int pageNo) async { -// ChatUserModel chatUserModel; -// Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatLoginTokenUrl}getUserWithStatusAndFavAsync", {"employeeNumber": cUserId, "userName": searchParam, "pageNumber": pageNo}, -// token: AppState().chatDetails!.response!.token); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// chatUserModel = chatUserModelFromJson(response.body); -// return chatUserModel; -// } -// -// //Get User Recent Chats -// Future getRecentChats() async { -// try { -// Response response = await ApiClient().getJsonForResponse( -// "${ApiConsts.chatRecentUrl}getchathistorybyuserid", -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// return ChatUserModel.fromJson( -// json.decode(response.body), -// ); -// } catch (e) { -// throw e; -// } -// } -// -// // Get Favorite Users -// Future getFavUsers() async { -// Response favRes = await ApiClient().getJsonForResponse( -// "${ApiConsts.chatFavUser}getFavUserById/${AppState().chatDetails!.response!.id}", -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + favRes.body); -// } -// return ChatUserModel.fromJson(json.decode(favRes.body)); -// } -// -// //Get User Chat History -// Future getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false, required int paginationVal}) async { -// try { -// Response response = await ApiClient().getJsonForResponse( -// "${ApiConsts.chatSingleUserHistoryUrl}GetUserChatHistory/$senderUID/$receiverUID/$paginationVal", -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// return response; -// } catch (e) { -// getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); -// throw e; -// } -// } -// + +class ChatApiClient { + static final ChatApiClient _instance = ChatApiClient._internal(); + + ChatApiClient._internal(); + + factory ChatApiClient() => _instance; + + Future getUserLoginToken() async { + UserAutoLoginModel userLoginResponse = UserAutoLoginModel(); + String? deviceToken = AppState().getIsHuawei ? AppState().getHuaweiPushToken : AppState().getDeviceToken; + Response response = await ApiClient().postJsonForResponse( + "${ApiConsts.chatLoginTokenUrl}externaluserlogin", + { + "employeeNumber": AppState().memberInformationList!.eMPLOYEENUMBER.toString(), + "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", + "isMobile": true, + "platform": Platform.isIOS ? "ios" : "android", + "deviceToken": AppState().getIsHuawei ? AppState().getHuaweiPushToken : AppState().getDeviceToken, + "isHuaweiDevice": AppState().getIsHuawei, + "voipToken": Platform.isIOS ? "80a3b01fc1ef2453eb4f1daa4fc31d8142d9cb67baf848e91350b607971fe2ba" : "", + }, + ); + + if (!kReleaseMode) { + // logger.i("login-res: " + response.body); + } + if (response.statusCode == 200) { + userLoginResponse = user.userAutoLoginModelFromJson(response.body); + } else if (response.statusCode == 501 || response.statusCode == 502 || response.statusCode == 503 || response.statusCode == 504) { + getUserLoginToken(); + } else { + userLoginResponse = user.userAutoLoginModelFromJson(response.body); + userLoginResponse.errorResponses!.first.message!.showToast; + } + return userLoginResponse; + } + + Future getChatMemberFromSearch(String searchParam, int cUserId, int pageNo) async { + ChatUserModel chatUserModel; + Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatLoginTokenUrl}getUserWithStatusAndFavAsync", {"employeeNumber": cUserId, "userName": searchParam, "pageNumber": pageNo}, + token: AppState().chatDetails!.response!.token); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } + chatUserModel = chatUserModelFromJson(response.body); + return chatUserModel; + } + + //Get User Recent Chats + Future getRecentChats() async { + try { + Response response = + + + // await ApiManager.instance.get(URLs.getAllRequestsAndCount,h); + + + await ApiClient().getJsonForResponse( + "${ApiConsts.chatRecentUrl}getchathistorybyuserid", + token: AppState().chatDetails!.response!.token, + ); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } + return ChatUserModel.fromJson( + json.decode(response.body), + ); + } catch (e) { + throw e; + } + } + + // // Get Favorite Users + // Future getFavUsers() async { + // Response favRes = await ApiClient().getJsonForResponse( + // "${ApiConsts.chatFavUser}getFavUserById/${AppState().chatDetails!.response!.id}", + // token: AppState().chatDetails!.response!.token, + // ); + // if (!kReleaseMode) { + // logger.i("res: " + favRes.body); + // } + // return ChatUserModel.fromJson(json.decode(favRes.body)); + // } + + //Get User Chat History + Future getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false, required int paginationVal}) async { + try { + Response response = await ApiClient().getJsonForResponse( + "${ApiConsts.chatSingleUserHistoryUrl}GetUserChatHistory/$senderUID/$receiverUID/$paginationVal", + token: AppState().chatDetails!.response!.token, + ); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } + return response; + } catch (e) { + getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); + throw e; + } + } + // //Favorite Users // Future favUser({required int userID, required int targetUserID}) async { // Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatFavUser}addFavUser", {"targetUserId": targetUserID, "userId": userID}, token: AppState().chatDetails!.response!.token); @@ -124,193 +136,193 @@ // fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); // return favoriteChatUser; // } -// -// //UnFavorite Users -// Future unFavUser({required int userID, required int targetUserID}) async { -// try { -// Response response = await ApiClient().postJsonForResponse( -// "${ApiConsts.chatFavUser}deleteFavUser", -// {"targetUserId": targetUserID, "userId": userID}, -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); -// return favoriteChatUser; -// } catch (e) { -// e as APIException; -// throw e; -// } + + // //UnFavorite Users + // Future unFavUser({required int userID, required int targetUserID}) async { + // try { + // Response response = await ApiClient().postJsonForResponse( + // "${ApiConsts.chatFavUser}deleteFavUser", + // {"targetUserId": targetUserID, "userId": userID}, + // token: AppState().chatDetails!.response!.token, + // ); + // if (!kReleaseMode) { + // logger.i("res: " + response.body); + // } + // fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); + // return favoriteChatUser; + // } catch (e) { + // e as APIException; + // throw e; + // } + // } + +// Upload Chat Media + Future uploadMedia(String userId, File file, String fileSource) async { + if (kDebugMode) { + print("${ApiConsts.chatMediaImageUploadUrl}upload"); + print(AppState().chatDetails!.response!.token); + } + + dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatMediaImageUploadUrl}upload')); + request.fields.addAll({'userId': userId, 'fileSource': fileSource}); + request.files.add(await MultipartFile.fromPath('files', file.path)); + request.headers.addAll({'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}'}); + StreamedResponse response = await request.send(); + String data = await response.stream.bytesToString(); + if (!kReleaseMode) { + logger.i("res: " + data); + } + return jsonDecode(data); + } + + // Download File For Chat + Future downloadURL({required String fileName, required String fileTypeDescription, required int fileSource}) async { + Response response = await ApiClient().postJsonForResponse( + "${ApiConsts.chatMediaImageUploadUrl}download", + {"fileType": fileTypeDescription, "fileName": fileName, "fileSource": fileSource}, + token: AppState().chatDetails!.response!.token, + ); + Uint8List data = Uint8List.fromList(response.bodyBytes); + return data; + } + +// //Get Chat Users & Favorite Images +// Future> getUsersImages({required List encryptedEmails}) async { +// List imagesData = []; +// Response response = await ApiClient().postJsonForResponse( +// "${ApiConsts.chatUserImages}images", +// {"encryptedEmails": encryptedEmails, "fromClient": false}, +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); // } +// if (response.statusCode == 200) { +// imagesData = chatUserImageModelFromJson(response.body); +// } else if (response.statusCode == 500 || response.statusCode == 504) { +// getUsersImages(encryptedEmails: encryptedEmails); +// } else { +// Utils.showToast("Something went wrong while loading images"); +// imagesData = []; +// } +// return imagesData; +// } // -// // Upload Chat Media -// Future uploadMedia(String userId, File file, String fileSource) async { -// if (kDebugMode) { -// print("${ApiConsts.chatMediaImageUploadUrl}upload"); -// print(AppState().chatDetails!.response!.token); -// } -// -// dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatMediaImageUploadUrl}upload')); -// request.fields.addAll({'userId': userId, 'fileSource': fileSource}); -// request.files.add(await MultipartFile.fromPath('files', file.path)); -// request.headers.addAll({'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}'}); -// StreamedResponse response = await request.send(); -// String data = await response.stream.bytesToString(); +// //group chat apis start here. +// Future getGroupsByUserId() async { +// try { +// Response response = await ApiClient().getJsonForResponse( +// "${ApiConsts.getGroupByUserId}${AppState().chatDetails!.response!.id}", +// token: AppState().chatDetails!.response!.token, +// ); // if (!kReleaseMode) { -// logger.i("res: " + data); +// logger.i("res: " + response.body); // } -// return jsonDecode(data); +// return groups.GetUserGroups.fromRawJson(response.body); +// } catch (e) { +// //if fail api returning 500 hence just printing here +// print(e); +// throw e; // } -// -// // Download File For Chat -// Future downloadURL({required String fileName, required String fileTypeDescription, required int fileSource}) async { +// } + +// Future deleteGroup(int? groupId) async { +// try { // Response response = await ApiClient().postJsonForResponse( -// "${ApiConsts.chatMediaImageUploadUrl}download", -// {"fileType": fileTypeDescription, "fileName": fileName, "fileSource": fileSource}, +// ApiConsts.deleteGroup, +// {"groupId": groupId}, // token: AppState().chatDetails!.response!.token, // ); -// Uint8List data = Uint8List.fromList(response.bodyBytes); -// return data; +// if (!kReleaseMode) { +// logger.i("res: " + response.body); +// } +// return response; +// } catch (e) { +// //if fail api returning 500 hence just printing here +// print(e); +// throw e; // } -// -// //Get Chat Users & Favorite Images -// Future> getUsersImages({required List encryptedEmails}) async { -// List imagesData = []; +// } + +// Future updateGroupAdmin(int? groupId, List groupList) async { +// try { // Response response = await ApiClient().postJsonForResponse( -// "${ApiConsts.chatUserImages}images", -// {"encryptedEmails": encryptedEmails, "fromClient": false}, +// ApiConsts.updateGroupAdmin, +// {"groupId": groupId, "groupUserList": groupList}, // token: AppState().chatDetails!.response!.token, // ); // if (!kReleaseMode) { // logger.i("res: " + response.body); // } -// if (response.statusCode == 200) { -// imagesData = chatUserImageModelFromJson(response.body); -// } else if (response.statusCode == 500 || response.statusCode == 504) { -// getUsersImages(encryptedEmails: encryptedEmails); -// } else { -// Utils.showToast("Something went wrong while loading images"); -// imagesData = []; -// } -// return imagesData; +// return response; +// } catch (e) { +// //if fail api returning 500 hence just printing here +// print(e); +// throw e; // } -// -// //group chat apis start here. -// Future getGroupsByUserId() async { -// try { -// Response response = await ApiClient().getJsonForResponse( -// "${ApiConsts.getGroupByUserId}${AppState().chatDetails!.response!.id}", -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// return groups.GetUserGroups.fromRawJson(response.body); -// } catch (e) { -// //if fail api returning 500 hence just printing here -// print(e); -// throw e; -// } -// } -// -// Future deleteGroup(int? groupId) async { -// try { -// Response response = await ApiClient().postJsonForResponse( -// ApiConsts.deleteGroup, -// {"groupId": groupId}, -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// return response; -// } catch (e) { -// //if fail api returning 500 hence just printing here -// print(e); -// throw e; +// } + +// Future> getGroupChatHistory(int? groupId, List groupList) async { +// try { +// Response response = await ApiClient().postJsonForResponse( +// ApiConsts.getGroupChatHistoryAsync, +// {"groupId": groupId, "targetUserList": groupList, "CurrentId": AppState().chatDetails!.response!.id}, +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); // } -// } -// -// Future updateGroupAdmin(int? groupId, List groupList) async { -// try { -// Response response = await ApiClient().postJsonForResponse( -// ApiConsts.updateGroupAdmin, -// {"groupId": groupId, "groupUserList": groupList}, -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// return response; -// } catch (e) { -// //if fail api returning 500 hence just printing here -// print(e); -// throw e; +// List groupChat = []; +// List groupChatData = json.decode(response.body); +// for (var i in groupChatData) { +// groupChat.add(GetGroupChatHistoryAsync.fromJson(i)); // } -// } // -// Future> getGroupChatHistory(int? groupId, List groupList) async { -// try { -// Response response = await ApiClient().postJsonForResponse( -// ApiConsts.getGroupChatHistoryAsync, -// {"groupId": groupId, "targetUserList": groupList, "CurrentId": AppState().chatDetails!.response!.id}, -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// List groupChat = []; -// List groupChatData = json.decode(response.body); -// for (var i in groupChatData) { -// groupChat.add(GetGroupChatHistoryAsync.fromJson(i)); -// } -// -// groupChat.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); -// return groupChat; -// // for(GetGroupChatHistoryAsync i in groupChat) { -// // return GetGroupChatHistoryAsync.fromJson(jsonEncode(i)); -// // } -// } catch (e) { -// //if fail api returning 500 hence just printing here -// print(e); -// throw e; -// } +// groupChat.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); +// return groupChat; +// // for(GetGroupChatHistoryAsync i in groupChat) { +// // return GetGroupChatHistoryAsync.fromJson(jsonEncode(i)); +// // } +// } catch (e) { +// //if fail api returning 500 hence just printing here +// print(e); +// throw e; // } -// -// Future addGroupAndUsers(createGroup.CreateGroupRequest request) async { -// try { -// Response response = await ApiClient().postJsonForResponse( -// ApiConsts.addGroupsAndUsers, -// request, -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// return response.body; -// } catch (e) { -// //if fail api returning 500 hence just printing here -// print(e); -// throw e; +// } + +// Future addGroupAndUsers(createGroup.CreateGroupRequest request) async { +// try { +// Response response = await ApiClient().postJsonForResponse( +// ApiConsts.addGroupsAndUsers, +// request, +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); // } +// return response.body; +// } catch (e) { +// //if fail api returning 500 hence just printing here +// print(e); +// throw e; // } -// -// Future updateGroupAndUsers(createGroup.CreateGroupRequest request) async { -// try { -// Response response = await ApiClient().postJsonForResponse( -// ApiConsts.updateGroupsAndUsers, -// request, -// token: AppState().chatDetails!.response!.token, -// ); -// if (!kReleaseMode) { -// logger.i("res: " + response.body); -// } -// return response.body; -// } catch (e) { -// //if fail api returning 500 hence just printing here -// print(e); -// throw e; +// } + +// Future updateGroupAndUsers(createGroup.CreateGroupRequest request) async { +// try { +// Response response = await ApiClient().postJsonForResponse( +// ApiConsts.updateGroupsAndUsers, +// request, +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); // } +// return response.body; +// } catch (e) { +// //if fail api returning 500 hence just printing here +// print(e); +// throw e; // } // } +} diff --git a/lib/modules/cx_module/chat/chat_provider.dart b/lib/modules/cx_module/chat/chat_provider.dart index b8668078..a22545ae 100644 --- a/lib/modules/cx_module/chat/chat_provider.dart +++ b/lib/modules/cx_module/chat/chat_provider.dart @@ -1,15 +1,16 @@ -// import 'dart:async'; -// import 'dart:convert'; -// import 'dart:io'; -// import 'dart:typed_data'; -// import 'package:audio_waveforms/audio_waveforms.dart'; +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:audio_waveforms/audio_waveforms.dart'; // import 'package:easy_localization/easy_localization.dart'; -// import 'package:flutter/cupertino.dart'; -// import 'package:flutter/foundation.dart'; -// import 'package:flutter/services.dart'; -// import 'package:http/http.dart'; -// import 'package:just_audio/just_audio.dart' as JustAudio; -// import 'package:just_audio/just_audio.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:http/http.dart'; +import 'package:just_audio/just_audio.dart' as JustAudio; +import 'package:just_audio/just_audio.dart'; + // import 'package:mohem_flutter_app/api/chat/chat_api_client.dart'; // import 'package:mohem_flutter_app/api/my_team/my_team_api_client.dart'; // import 'package:mohem_flutter_app/app_state/app_state.dart'; @@ -33,1931 +34,1939 @@ // import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart'; // import 'package:mohem_flutter_app/widgets/image_picker.dart'; // import 'package:open_filex/open_filex.dart'; -// import 'package:path_provider/path_provider.dart'; -// import 'package:permission_handler/permission_handler.dart'; -// import 'package:signalr_netcore/hub_connection.dart'; -// import 'package:signalr_netcore/signalr_client.dart'; -// import 'package:uuid/uuid.dart'; -// import 'package:flutter/material.dart' as Material; -// -// class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { -// ScrollController scrollController = ScrollController(); -// -// TextEditingController message = TextEditingController(); -// TextEditingController search = TextEditingController(); -// TextEditingController searchGroup = TextEditingController(); -// -// List userChatHistory = [], repliedMsg = []; -// List? pChatHistory, searchedChats; -// String chatCID = ''; -// bool isLoading = true; -// bool isChatScreenActive = false; -// int receiverID = 0; -// late File selectedFile; -// String sFileType = ""; -// -// List favUsersList = []; -// int paginationVal = 0; -// int? cTypingUserId = 0; -// bool isTextMsg = false, isReplyMsg = false, isAttachmentMsg = false, isVoiceMsg = false; -// -// // Audio Recoding Work -// Timer? _timer; -// int _recodeDuration = 0; -// bool isRecoding = false; -// bool isPause = false; -// bool isPlaying = false; -// String? path; -// String? musicFile; -// late Directory appDirectory; -// late RecorderController recorderController; -// late PlayerController playerController; -// List getEmployeeSubordinatesList = []; -// List teamMembersList = []; -// groups.GetUserGroups userGroups = groups.GetUserGroups(); -// Material.TextDirection textDirection = Material.TextDirection.ltr; -// bool isRTL = false; -// String msgText = ""; -// -// //Chat Home Page Counter -// int chatUConvCounter = 0; -// -// late List groupChatHistory, groupChatReplyData; -// -// /// Search Provider -// List? chatUsersList = []; -// int pageNo = 1; -// -// bool disbaleChatForThisUser = false; -// List? uGroups = [], searchGroups = []; -// -// Future getUserAutoLoginToken() async { -// userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); -// -// if (userLoginResponse.StatusCode == 500) { -// disbaleChatForThisUser = true; -// notifyListeners(); -// } -// -// if (userLoginResponse.response != null) { -// AppState().setchatUserDetails = userLoginResponse; -// } else { -// AppState().setchatUserDetails = userLoginResponse; -// Utils.showToast( -// userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", -// ); -// disbaleChatForThisUser = true; -// notifyListeners(); -// } -// } -// -// Future buildHubConnection() async { -// chatHubConnection = await getHubConnection(); -// await chatHubConnection.start(); -// if (kDebugMode) { -// logger.i("Hub Conn: Startedddddddd"); -// } -// chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); -// chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); -// -// //group On message -// -// chatHubConnection.on("OnDeliveredGroupChatHistoryAsync", onGroupMsgReceived); -// } -// -// Future getHubConnection() async { -// HubConnection hub; -// HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); -// hub = HubConnectionBuilder() -// .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Desktop&access_token=${AppState().chatDetails!.response!.token}", options: httpOp) -// .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); -// return hub; -// } -// -// void registerEvents() { -// chatHubConnection.on("OnUpdateUserStatusAsync", changeStatus); -// // chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); -// -// chatHubConnection.on("OnSubmitChatAsync", OnSubmitChatAsync); -// chatHubConnection.on("OnUserTypingAsync", onUserTyping); -// chatHubConnection.on("OnUserCountAsync", userCountAsync); -// // chatHubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); -// chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); -// chatHubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); -// chatHubConnection.on("OnGetGroupUserStatusAsync", getGroupUserStatus); -// -// // -// // {"type":1,"target":"","arguments":[[{"id":217869,"userName":"Sultan.Khan","email":"Sultan.Khan@cloudsolutions.com.sa","phone":null,"title":"Sultan.Khan","userStatus":1,"image":null,"unreadMessageCount":0,"userAction":3,"isPin":false,"isFav":false,"isAdmin":false,"rKey":null,"totalCount":0,"isHuaweiDevice":false,"deviceToken":null},{"id":15153,"userName":"Tamer.Fanasheh","email":"Tamer.F@cloudsolutions.com.sa","phone":null,"title":"Tamer Fanasheh","userStatus":2,"image":null,"unreadMessageCount":0,"userAction":3,"isPin":false,"isFav":false,"isAdmin":true,"rKey":null,"totalCount":0,"isHuaweiDevice":false,"deviceToken":null}]]} -// -// if (kDebugMode) { -// logger.i("All listeners registered"); -// } -// } -// -// Future getUserRecentChats() async { -// ChatUserModel recentChat = await ChatApiClient().getRecentChats(); -// ChatUserModel favUList = await ChatApiClient().getFavUsers(); -// // userGroups = await ChatApiClient().getGroupsByUserId(); -// if (favUList.response != null && recentChat.response != null) { -// favUsersList = favUList.response!; -// favUsersList.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); -// for (dynamic user in recentChat.response!) { -// for (dynamic favUser in favUList.response!) { -// if (user.id == favUser.id) { -// user.isFav = favUser.isFav; -// } -// } -// } -// } -// pChatHistory = recentChat.response ?? []; -// uGroups = userGroups.groupresponse ?? []; -// pChatHistory!.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); -// searchedChats = pChatHistory; -// isLoading = false; -// await invokeUserChatHistoryNotDeliveredAsync(userId: int.parse(AppState().chatDetails!.response!.id.toString())); -// sort(); -// notifyListeners(); -// if (searchedChats!.isNotEmpty || favUsersList.isNotEmpty) { -// getUserImages(); -// } -// } -// -// Future invokeUserChatHistoryNotDeliveredAsync({required int userId}) async { -// await chatHubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); -// return ""; -// } -// -// void getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false}) async { -// isLoading = true; -// if (isNewChat) userChatHistory = []; -// if (!loadMore) paginationVal = 0; -// isChatScreenActive = true; -// receiverID = receiverUID; -// Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); -// if (response.statusCode == 204) { -// if (isNewChat) { -// userChatHistory = []; -// } else if (loadMore) {} -// } else { -// if (loadMore) { -// List temp = getSingleUserChatModel(response.body).reversed.toList(); -// userChatHistory.addAll(temp); -// } else { -// userChatHistory = getSingleUserChatModel(response.body).reversed.toList(); -// } -// } -// isLoading = false; -// notifyListeners(); -// -// if (isChatScreenActive && receiverUID == receiverID) { -// markRead(userChatHistory, receiverUID); -// } -// -// generateConvId(); -// } -// -// void generateConvId() async { -// Uuid uuid = const Uuid(); -// chatCID = uuid.v4(); -// } -// -// void markRead(List data, int receiverID) { -// for (SingleUserChatModel element in data!) { -// if (AppState().chatDetails!.response!.id! == element.targetUserId) { -// if (element.isSeen != null) { -// if (!element.isSeen!) { -// element.isSeen = true; -// dynamic data = [ -// { -// "userChatHistoryId": element.userChatHistoryId, -// "TargetUserId": element.currentUserId == receiverID ? element.currentUserId : element.targetUserId, -// "isDelivered": true, -// "isSeen": true, -// } -// ]; -// updateUserChatHistoryStatusAsync(data); -// notifyListeners(); -// } -// } -// for (ChatUser element in searchedChats!) { -// if (element.id == receiverID) { -// element.unreadMessageCount = 0; -// chatUConvCounter = 0; -// } -// } -// } -// } -// notifyListeners(); -// } -// -// void updateUserChatHistoryStatusAsync(List data) { -// try { -// chatHubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); -// } catch (e) { -// throw e; -// } -// } -// -// void updateUserChatHistoryOnMsg(List data) { -// try { -// chatHubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); -// } catch (e) { -// throw e; -// } -// } -// -// List getSingleUserChatModel(String str) => List.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); -// -// List getGroupChatHistoryAsync(String str) => -// List.from(json.decode(str).map((x) => groupchathistory.GetGroupChatHistoryAsync.fromJson(x))); -// -// Future uploadAttachments(String userId, File file, String fileSource) async { -// dynamic result; -// try { -// Object? response = await ChatApiClient().uploadMedia(userId, file, fileSource); -// if (response != null) { -// result = response; -// } else { -// result = []; -// } -// } catch (e) { -// throw e; -// } -// return result; -// } -// -// void updateUserChatStatus(List? args) { -// dynamic items = args!.toList(); -// for (var cItem in items[0]) { -// for (SingleUserChatModel chat in userChatHistory) { -// if (cItem["contantNo"].toString() == chat.contantNo.toString()) { -// chat.isSeen = cItem["isSeen"]; -// chat.isDelivered = cItem["isDelivered"]; -// } -// } -// } -// notifyListeners(); -// } -// -// void getGroupUserStatus(List? args) { -// //note: need to implement this function... -// print(args); -// } -// -// void onChatSeen(List? args) { -// dynamic items = args!.toList(); -// // for (var user in searchedChats!) { -// // if (user.id == items.first["id"]) { -// // user.userStatus = items.first["userStatus"]; -// // } -// // } -// // notifyListeners(); -// } -// -// void userCountAsync(List? args) { -// dynamic items = args!.toList(); -// // logger.d(items); -// //logger.d("---------------------------------User Count Async -------------------------------------"); -// //logger.d(items); -// // for (var user in searchedChats!) { -// // if (user.id == items.first["id"]) { -// // user.userStatus = items.first["userStatus"]; -// // } -// // } -// // notifyListeners(); -// } -// -// void updateChatHistoryWindow(List? args) { -// dynamic items = args!.toList(); -// if (kDebugMode) { -// logger.i("---------------------------------Update Chat History Windows Async -------------------------------------"); -// } -// logger.d(items); -// // for (var user in searchedChats!) { -// // if (user.id == items.first["id"]) { -// // user.userStatus = items.first["userStatus"]; -// // } -// // } -// // notifyListeners(); -// } -// -// void chatNotDelivered(List? args) { -// dynamic items = args!.toList(); -// for (dynamic item in items[0]) { -// for (ChatUser element in searchedChats!) { -// if (element.id == item["currentUserId"]) { -// int? val = element.unreadMessageCount ?? 0; -// element.unreadMessageCount = val! + 1; -// } -// } -// } -// notifyListeners(); -// } -// -// void changeStatus(List? args) { -// dynamic items = args!.toList(); -// for (ChatUser user in searchedChats!) { -// if (user.id == items.first["id"]) { -// user.userStatus = items.first["userStatus"]; -// } -// } -// if (teamMembersList.isNotEmpty) { -// for (ChatUser user in teamMembersList!) { -// if (user.id == items.first["id"]) { -// user.userStatus = items.first["userStatus"]; -// } -// } -// } -// -// notifyListeners(); -// } -// -// void filter(String value) async { -// List? tmp = []; -// if (value.isEmpty || value == "") { -// tmp = pChatHistory; -// } else { -// for (ChatUser element in pChatHistory!) { -// if (element.userName!.toLowerCase().contains(value.toLowerCase())) { -// tmp.add(element); -// } -// } -// } -// searchedChats = tmp; -// notifyListeners(); -// } -// -// Future onMsgReceived(List? parameters) async { -// List data = [], temp = []; -// for (dynamic msg in parameters!) { -// data = getSingleUserChatModel(jsonEncode(msg)); -// temp = getSingleUserChatModel(jsonEncode(msg)); -// data.first.targetUserId = temp.first.currentUserId; -// data.first.targetUserName = temp.first.currentUserName; -// data.first.targetUserEmail = temp.first.currentUserEmail; -// data.first.currentUserId = temp.first.targetUserId; -// data.first.currentUserName = temp.first.targetUserName; -// data.first.currentUserEmail = temp.first.targetUserEmail; -// -// if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { -// data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); -// } -// if (data.first.userChatReplyResponse != null) { -// if (data.first.fileTypeResponse != null) { -// if (data.first.userChatReplyResponse!.fileTypeId == 12 || data.first.userChatReplyResponse!.fileTypeId == 4 || data.first.userChatReplyResponse!.fileTypeId == 3) { -// data.first.userChatReplyResponse!.image = await ChatApiClient() -// .downloadURL(fileName: data.first.userChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); -// data.first.userChatReplyResponse!.isImageLoaded = true; -// } -// } -// } -// } -// -// if (searchedChats != null) { -// dynamic contain = searchedChats!.where((ChatUser element) => element.id == data.first.currentUserId); -// if (contain.isEmpty) { -// List emails = []; -// emails.add(await EmailImageEncryption().encrypt(val: data.first.currentUserEmail!)); -// List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); -// searchedChats!.add( -// ChatUser( -// id: data.first.currentUserId, -// userName: data.first.currentUserName, -// email: data.first.currentUserEmail, -// unreadMessageCount: 0, -// isImageLoading: false, -// image: chatImages!.first.profilePicture ?? "", -// isImageLoaded: true, -// userStatus: 1, -// isTyping: false, -// userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, data.first.currentUserId.toString()), -// ), -// ); -// } -// } -// setMsgTune(); -// if (isChatScreenActive && data.first.currentUserId == receiverID) { -// userChatHistory.insert(0, data.first); -// } else { -// if (searchedChats != null) { -// for (ChatUser user in searchedChats!) { -// if (user.id == data.first.currentUserId) { -// int tempCount = user.unreadMessageCount ?? 0; -// user.unreadMessageCount = tempCount + 1; -// } -// } -// sort(); -// } -// } -// -// List list = [ -// { -// "userChatHistoryId": data.first.userChatHistoryId, -// "TargetUserId": temp.first.targetUserId, -// "isDelivered": true, -// "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false -// } -// ]; -// updateUserChatHistoryOnMsg(list); -// invokeChatCounter(userId: AppState().chatDetails!.response!.id!); -// notifyListeners(); -// } -// -// Future onGroupMsgReceived(List? parameters) async { -// List data = [], temp = []; -// -// for (dynamic msg in parameters!) { -// // groupChatHistory.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); -// data.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); -// temp = data; -// // data.first.currentUserId = temp.first.currentUserId; -// // data.first.currentUserName = temp.first.currentUserName; -// // -// // data.first.currentUserId = temp.first.currentUserId; -// // data.first.currentUserName = temp.first.currentUserName; -// -// if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { -// data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); -// } -// if (data.first.groupChatReplyResponse != null) { -// if (data.first.fileTypeResponse != null) { -// if (data.first.groupChatReplyResponse!.fileTypeId == 12 || data.first.groupChatReplyResponse!.fileTypeId == 4 || data.first.groupChatReplyResponse!.fileTypeId == 3) { -// data.first.groupChatReplyResponse!.image = await ChatApiClient() -// .downloadURL(fileName: data.first.groupChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); -// data.first.groupChatReplyResponse!.isImageLoaded = true; -// } -// } -// } -// } -// -// // if (searchedChats != null) { -// // dynamic contain = searchedChats! -// // .where((ChatUser element) => element.id == data.first.currentUserId); -// // if (contain.isEmpty) { -// // List emails = []; -// // emails.add(await EmailImageEncryption() -// // .encrypt(val: data.first.currentUserEmail!)); -// // List chatImages = -// // await ChatApiClient().getUsersImages(encryptedEmails: emails); -// // searchedChats!.add( -// // ChatUser( -// // id: data.first.currentUserId, -// // userName: data.first.currentUserName, -// // email: data.first.currentUserEmail, -// // unreadMessageCount: 0, -// // isImageLoading: false, -// // image: chatImages!.first.profilePicture ?? "", -// // isImageLoaded: true, -// // userStatus: 1, -// // isTyping: false, -// // userLocalDownlaodedImage: await downloadImageLocal( -// // chatImages.first.profilePicture, -// // data.first.currentUserId.toString()), -// // ), -// // ); -// // } -// // } -// groupChatHistory.insert(0, data.first); -// setMsgTune(); -// // if (isChatScreenActive && data.first.currentUserId == receiverID) { -// -// // } else { -// // if (searchedChats != null) { -// // for (ChatUser user in searchedChats!) { -// // if (user.id == data.first.currentUserId) { -// // int tempCount = user.unreadMessageCount ?? 0; -// // user.unreadMessageCount = tempCount + 1; -// // } -// // } -// sort(); -// //} -// //} -// // -// // List list = [ -// // { -// // "userChatHistoryId": data.first.groupId, -// // "TargetUserId": temp.first.currentUserId, -// // "isDelivered": true, -// // "isSeen": isChatScreenActive && data.first.currentUserId == receiverID -// // ? true -// // : false -// // } -// // ]; -// // updateUserChatHistoryOnMsg(list); -// // invokeChatCounter(userId: AppState().chatDetails!.response!.id!); -// notifyListeners(); -// } -// -// void OnSubmitChatAsync(List? parameters) { -// print(isChatScreenActive); -// print(receiverID); -// print(isChatScreenActive); -// logger.i(parameters); -// List data = [], temp = []; -// for (dynamic msg in parameters!) { -// data = getSingleUserChatModel(jsonEncode(msg)); -// temp = getSingleUserChatModel(jsonEncode(msg)); -// data.first.targetUserId = temp.first.currentUserId; -// data.first.targetUserName = temp.first.currentUserName; -// data.first.targetUserEmail = temp.first.currentUserEmail; -// data.first.currentUserId = temp.first.targetUserId; -// data.first.currentUserName = temp.first.targetUserName; -// data.first.currentUserEmail = temp.first.targetUserEmail; -// } -// if (isChatScreenActive && data.first.currentUserId == receiverID) { -// int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == 0); -// logger.d(index); -// userChatHistory[index] = data.first; -// } -// -// notifyListeners(); -// } -// -// void sort() { -// searchedChats!.sort( -// (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo(a.unreadMessageCount!), -// ); -// } -// -// void onUserTyping(List? parameters) { -// for (ChatUser user in searchedChats!) { -// if (user.id == parameters![1] && parameters[0] == true) { -// user.isTyping = parameters[0] as bool?; -// Future.delayed( -// const Duration(seconds: 2), -// () { -// user.isTyping = false; -// notifyListeners(); -// }, -// ); -// } -// } -// notifyListeners(); -// } -// -// int getFileType(String value) { -// switch (value) { -// case ".pdf": -// return 1; -// case ".png": -// return 3; -// case ".txt": -// return 5; -// case ".jpg": -// return 12; -// case ".jpeg": -// return 4; -// case ".xls": -// return 7; -// case ".xlsx": -// return 7; -// case ".doc": -// return 6; -// case ".docx": -// return 6; -// case ".ppt": -// return 8; -// case ".pptx": -// return 8; -// case ".zip": -// return 2; -// case ".rar": -// return 2; -// case ".aac": -// return 13; -// case ".mp3": -// return 14; -// case ".mp4": -// return 16; -// case ".mov": -// return 16; -// case ".avi": -// return 16; -// case ".flv": -// return 16; -// -// default: -// return 0; -// } -// } -// -// String getFileTypeDescription(String value) { -// switch (value) { -// case ".pdf": -// return "application/pdf"; -// case ".png": -// return "image/png"; -// case ".txt": -// return "text/plain"; -// case ".jpg": -// return "image/jpg"; -// case ".jpeg": -// return "image/jpeg"; -// case ".ppt": -// return "application/vnd.openxmlformats-officedocument.presentationml.presentation"; -// case ".pptx": -// return "application/vnd.openxmlformats-officedocument.presentationml.presentation"; -// case ".doc": -// return "application/vnd.openxmlformats-officedocument.wordprocessingm"; -// case ".docx": -// return "application/vnd.openxmlformats-officedocument.wordprocessingm"; -// case ".xls": -// return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; -// case ".xlsx": -// return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; -// case ".zip": -// return "application/octet-stream"; -// case ".rar": -// return "application/octet-stream"; -// case ".aac": -// return "audio/aac"; -// case ".mp3": -// return "audio/mp3"; -// case ".mp4": -// return "video/mp4"; -// case ".avi": -// return "video/avi"; -// case ".flv": -// return "video/flv"; -// case ".mov": -// return "video/mov"; -// -// default: -// return ""; -// } -// } -// -// Future sendChatToServer( -// {required int chatEventId, -// required fileTypeId, -// required int targetUserId, -// required String targetUserName, -// required chatReplyId, -// required bool isAttachment, -// required bool isReply, -// Uint8List? image, -// required bool isImageLoaded, -// String? userEmail, -// int? userStatus, -// File? voiceFile, -// required bool isVoiceAttached}) async { -// Uuid uuid = const Uuid(); -// String contentNo = uuid.v4(); -// String msg; -// if (isVoiceAttached) { -// msg = voiceFile!.path.split("/").last; -// } else { -// msg = message.text; -// logger.w(msg); -// } -// SingleUserChatModel data = SingleUserChatModel( -// userChatHistoryId: 0, -// chatEventId: chatEventId, -// chatSource: 1, -// contant: msg, -// contantNo: contentNo, -// conversationId: chatCID, -// createdDate: DateTime.now(), -// currentUserId: AppState().chatDetails!.response!.id, -// currentUserName: AppState().chatDetails!.response!.userName, -// targetUserId: targetUserId, -// targetUserName: targetUserName, -// isReplied: false, -// fileTypeId: fileTypeId, -// userChatReplyResponse: isReply ? UserChatReplyResponse.fromJson(repliedMsg.first.toJson()) : null, -// fileTypeResponse: isAttachment -// ? FileTypeResponse( -// fileTypeId: fileTypeId, -// fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), -// fileKind: "file", -// fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, -// fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString()), -// ) -// : null, -// image: image, -// isImageLoaded: isImageLoaded, -// voice: isVoiceMsg ? voiceFile! : null, -// voiceController: isVoiceMsg ? AudioPlayer() : null); -// if (kDebugMode) { -// logger.i("model data: " + jsonEncode(data)); -// } -// userChatHistory.insert(0, data); -// isTextMsg = false; -// isReplyMsg = false; -// isAttachmentMsg = false; -// isVoiceMsg = false; -// sFileType = ""; -// message.clear(); -// notifyListeners(); -// -// String chatData = -// '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId": $fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"chatReplyId":$chatReplyId,"conversationId":"$chatCID"}'; -// -// await chatHubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); -// } -// -// //groupChatMessage -// -// Future sendGroupChatToServer( -// {required int chatEventId, -// required fileTypeId, -// required int targetGroupId, -// required String targetUserName, -// required chatReplyId, -// required bool isAttachment, -// required bool isReply, -// Uint8List? image, -// required bool isImageLoaded, -// String? userEmail, -// int? userStatus, -// File? voiceFile, -// required bool isVoiceAttached, -// required List userList}) async { -// Uuid uuid = const Uuid(); -// String contentNo = uuid.v4(); -// String msg; -// if (isVoiceAttached) { -// msg = voiceFile!.path.split("/").last; -// } else { -// msg = message.text; -// logger.w(msg); -// } -// groupchathistory.GetGroupChatHistoryAsync data = groupchathistory.GetGroupChatHistoryAsync( -// //userChatHistoryId: 0, -// chatEventId: chatEventId, -// chatSource: 1, -// contant: msg, -// contantNo: contentNo, -// conversationId: chatCID, -// createdDate: DateTime.now().toString(), -// currentUserId: AppState().chatDetails!.response!.id, -// currentUserName: AppState().chatDetails!.response!.userName, -// groupId: targetGroupId, -// groupName: targetUserName, -// isReplied: false, -// fileTypeId: fileTypeId, -// fileTypeResponse: isAttachment -// ? groupchathistory.FileTypeResponse( -// fileTypeId: fileTypeId, -// fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), -// fileKind: "file", -// fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, -// fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString())) -// : null, -// image: image, -// isImageLoaded: isImageLoaded, -// voice: isVoiceMsg ? voiceFile! : null, -// voiceController: isVoiceMsg ? AudioPlayer() : null); -// if (kDebugMode) { -// logger.i("model data: " + jsonEncode(data)); -// } -// groupChatHistory.insert(0, data); -// isTextMsg = false; -// isReplyMsg = false; -// isAttachmentMsg = false; -// isVoiceMsg = false; -// sFileType = ""; -// message.clear(); -// notifyListeners(); -// -// List targetUsers = []; -// -// for (GroupUserList element in userList) { -// targetUsers.add(TargetUsers(isDelivered: false, isSeen: false, targetUserId: element.id, userAction: element.userAction, userStatus: element.userStatus)); -// } -// -// String chatData = -// '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId":$fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"groupId":$targetGroupId,"groupChatHistoryLineRequestList":${json.encode(targetUsers)},"chatReplyId": $chatReplyId,"conversationId":"${uuid.v4()}"}'; -// -// await chatHubConnection.invoke("AddGroupChatHistoryAsync", args: [json.decode(chatData)]); -// } -// -// void sendGroupChatMessage( -// BuildContext context, { -// required int targetUserId, -// required int userStatus, -// required String userEmail, -// required String targetUserName, -// required List userList, -// }) async { -// if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { -// logger.d("// Normal Text Message"); -// if (message.text.isEmpty) { -// return; -// } -// sendGroupChatToServer( -// chatEventId: 1, -// fileTypeId: null, -// targetGroupId: targetUserId, -// targetUserName: targetUserName, -// isAttachment: false, -// chatReplyId: null, -// isReply: false, -// isImageLoaded: false, -// image: null, -// isVoiceAttached: false, -// userEmail: userEmail, -// userStatus: userStatus, -// userList: userList); -// } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { -// logger.d("// Text Message as Reply"); -// if (message.text.isEmpty) { -// return; -// } -// sendGroupChatToServer( -// chatEventId: 1, -// fileTypeId: null, -// targetGroupId: targetUserId, -// targetUserName: targetUserName, -// chatReplyId: groupChatReplyData.first.groupChatHistoryId, -// isAttachment: false, -// isReply: true, -// isImageLoaded: groupChatReplyData.first.isImageLoaded!, -// image: groupChatReplyData.first.image, -// isVoiceAttached: false, -// voiceFile: null, -// userEmail: userEmail, -// userStatus: userStatus, -// userList: userList); -// } -// // Attachment -// else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { -// logger.d("// Normal Image Message"); -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); -// String? ext = getFileExtension(selectedFile.path); -// Utils.hideLoading(context); -// sendGroupChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// targetGroupId: targetUserId, -// targetUserName: targetUserName, -// isAttachment: true, -// chatReplyId: null, -// isReply: false, -// isImageLoaded: true, -// image: selectedFile.readAsBytesSync(), -// isVoiceAttached: false, -// userEmail: userEmail, -// userStatus: userStatus, -// userList: userList); -// } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { -// logger.d("// Image as Reply Msg"); -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); -// String? ext = getFileExtension(selectedFile.path); -// Utils.hideLoading(context); -// sendGroupChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// targetGroupId: targetUserId, -// targetUserName: targetUserName, -// isAttachment: true, -// chatReplyId: repliedMsg.first.userChatHistoryId, -// isReply: true, -// isImageLoaded: true, -// image: selectedFile.readAsBytesSync(), -// isVoiceAttached: false, -// userEmail: userEmail, -// userStatus: userStatus, -// userList: userList); -// } -// //Voice -// -// else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { -// logger.d("// Normal Voice Message"); -// -// if (!isPause) { -// path = await recorderController.stop(false); -// } -// if (kDebugMode) { -// logger.i("path:" + path!); -// } -// File voiceFile = File(path!); -// voiceFile.readAsBytesSync(); -// _timer?.cancel(); -// isPause = false; -// isPlaying = false; -// isRecoding = false; -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); -// String? ext = getFileExtension(voiceFile.path); -// Utils.hideLoading(context); -// sendGroupChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// //, -// targetGroupId: targetUserId, -// targetUserName: targetUserName, -// chatReplyId: null, -// isAttachment: true, -// isReply: isReplyMsg, -// isImageLoaded: false, -// voiceFile: voiceFile, -// isVoiceAttached: true, -// userEmail: userEmail, -// userStatus: userStatus, -// userList: userList); -// notifyListeners(); -// } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { -// logger.d("// Voice as Reply Msg"); -// -// if (!isPause) { -// path = await recorderController.stop(false); -// } -// if (kDebugMode) { -// logger.i("path:" + path!); -// } -// File voiceFile = File(path!); -// voiceFile.readAsBytesSync(); -// _timer?.cancel(); -// isPause = false; -// isPlaying = false; -// isRecoding = false; -// -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); -// String? ext = getFileExtension(voiceFile.path); -// Utils.hideLoading(context); -// sendGroupChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// targetGroupId: targetUserId, -// targetUserName: targetUserName, -// chatReplyId: null, -// isAttachment: true, -// isReply: isReplyMsg, -// isImageLoaded: false, -// voiceFile: voiceFile, -// isVoiceAttached: true, -// userEmail: userEmail, -// userStatus: userStatus, -// userList: userList); -// notifyListeners(); -// } -// if (searchedChats != null) { -// dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); -// if (contain.isEmpty) { -// List emails = []; -// emails.add(await EmailImageEncryption().encrypt(val: userEmail)); -// List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); -// searchedChats!.add( -// ChatUser( -// id: targetUserId, -// userName: targetUserName, -// unreadMessageCount: 0, -// email: userEmail, -// isImageLoading: false, -// image: chatImages.first.profilePicture ?? "", -// isImageLoaded: true, -// isTyping: false, -// isFav: false, -// userStatus: userStatus, -// // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), -// ), -// ); -// notifyListeners(); -// } -// } -// } -// -// void sendChatMessage( -// BuildContext context, { -// required int targetUserId, -// required int userStatus, -// required String userEmail, -// required String targetUserName, -// }) async { -// if (kDebugMode) { -// print("====================== Values ============================"); -// print("Is Text " + isTextMsg.toString()); -// print("isReply " + isReplyMsg.toString()); -// print("isAttachment " + isAttachmentMsg.toString()); -// print("isVoice " + isVoiceMsg.toString()); -// } -// //Text -// if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { -// logger.d("// Normal Text Message"); -// if (message.text.isEmpty) { -// return; -// } -// sendChatToServer( -// chatEventId: 1, -// fileTypeId: null, -// targetUserId: targetUserId, -// targetUserName: targetUserName, -// isAttachment: false, -// chatReplyId: null, -// isReply: false, -// isImageLoaded: false, -// image: null, -// isVoiceAttached: false, -// userEmail: userEmail, -// userStatus: userStatus); -// } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { -// logger.d("// Text Message as Reply"); -// if (message.text.isEmpty) { -// return; -// } -// sendChatToServer( -// chatEventId: 1, -// fileTypeId: null, -// targetUserId: targetUserId, -// targetUserName: targetUserName, -// chatReplyId: repliedMsg.first.userChatHistoryId, -// isAttachment: false, -// isReply: true, -// isImageLoaded: repliedMsg.first.isImageLoaded!, -// image: repliedMsg.first.image, -// isVoiceAttached: false, -// voiceFile: null, -// userEmail: userEmail, -// userStatus: userStatus); -// } -// // Attachment -// else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { -// logger.d("// Normal Image Message"); -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); -// String? ext = getFileExtension(selectedFile.path); -// Utils.hideLoading(context); -// sendChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// targetUserId: targetUserId, -// targetUserName: targetUserName, -// isAttachment: true, -// chatReplyId: null, -// isReply: false, -// isImageLoaded: true, -// image: selectedFile.readAsBytesSync(), -// isVoiceAttached: false, -// userEmail: userEmail, -// userStatus: userStatus); -// } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { -// logger.d("// Image as Reply Msg"); -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); -// String? ext = getFileExtension(selectedFile.path); -// Utils.hideLoading(context); -// sendChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// targetUserId: targetUserId, -// targetUserName: targetUserName, -// isAttachment: true, -// chatReplyId: repliedMsg.first.userChatHistoryId, -// isReply: true, -// isImageLoaded: true, -// image: selectedFile.readAsBytesSync(), -// isVoiceAttached: false, -// userEmail: userEmail, -// userStatus: userStatus); -// } -// //Voice -// -// else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { -// logger.d("// Normal Voice Message"); -// -// if (!isPause) { -// path = await recorderController.stop(false); -// } -// if (kDebugMode) { -// logger.i("path:" + path!); -// } -// File voiceFile = File(path!); -// voiceFile.readAsBytesSync(); -// _timer?.cancel(); -// isPause = false; -// isPlaying = false; -// isRecoding = false; -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); -// String? ext = getFileExtension(voiceFile.path); -// Utils.hideLoading(context); -// sendChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// targetUserId: targetUserId, -// targetUserName: targetUserName, -// chatReplyId: null, -// isAttachment: true, -// isReply: isReplyMsg, -// isImageLoaded: false, -// voiceFile: voiceFile, -// isVoiceAttached: true, -// userEmail: userEmail, -// userStatus: userStatus); -// notifyListeners(); -// } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { -// logger.d("// Voice as Reply Msg"); -// -// if (!isPause) { -// path = await recorderController.stop(false); -// } -// if (kDebugMode) { -// logger.i("path:" + path!); -// } -// File voiceFile = File(path!); -// voiceFile.readAsBytesSync(); -// _timer?.cancel(); -// isPause = false; -// isPlaying = false; -// isRecoding = false; -// -// Utils.showLoading(context); -// dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); -// String? ext = getFileExtension(voiceFile.path); -// Utils.hideLoading(context); -// sendChatToServer( -// chatEventId: 2, -// fileTypeId: getFileType(ext.toString()), -// targetUserId: targetUserId, -// targetUserName: targetUserName, -// chatReplyId: null, -// isAttachment: true, -// isReply: isReplyMsg, -// isImageLoaded: false, -// voiceFile: voiceFile, -// isVoiceAttached: true, -// userEmail: userEmail, -// userStatus: userStatus); -// notifyListeners(); -// } -// if (searchedChats != null) { -// dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); -// if (contain.isEmpty) { -// List emails = []; -// emails.add(await EmailImageEncryption().encrypt(val: userEmail)); -// List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); -// searchedChats!.add( -// ChatUser( -// id: targetUserId, -// userName: targetUserName, -// unreadMessageCount: 0, -// email: userEmail, -// isImageLoading: false, -// image: chatImages.first.profilePicture ?? "", -// isImageLoaded: true, -// isTyping: false, -// isFav: false, -// userStatus: userStatus, -// userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), -// ), -// ); -// notifyListeners(); -// } -// } -// // else { -// // List emails = []; -// // emails.add(await EmailImageEncryption().encrypt(val: userEmail)); -// // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); -// // searchedChats!.add( -// // ChatUser( -// // id: targetUserId, -// // userName: targetUserName, -// // unreadMessageCount: 0, -// // email: userEmail, -// // isImageLoading: false, -// // image: chatImages.first.profilePicture ?? "", -// // isImageLoaded: true, -// // isTyping: false, -// // isFav: false, -// // userStatus: userStatus, -// // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), -// // ), -// // ); -// // notifyListeners(); -// // } -// } -// -// void selectImageToUpload(BuildContext context) { -// ImageOptions.showImageOptionsNew(context, true, (String image, File file) async { -// if (checkFileSize(file.path)) { -// selectedFile = file; -// isAttachmentMsg = true; -// isTextMsg = false; -// sFileType = getFileExtension(file.path)!; -// message.text = file.path.split("/").last; -// Navigator.of(context).pop(); -// } else { -// Utils.showToast("Max 1 mb size is allowed to upload"); -// } -// notifyListeners(); -// }); -// } -// -// void removeAttachment() { -// isAttachmentMsg = false; -// sFileType = ""; -// message.text = ''; -// notifyListeners(); -// } -// -// String? getFileExtension(String fileName) { -// try { -// if (kDebugMode) { -// logger.i("ext: " + "." + fileName.split('.').last); -// } -// return "." + fileName.split('.').last; -// } catch (e) { -// return null; -// } -// } -// -// bool checkFileSize(String path) { -// int fileSizeLimit = 5120; -// File f = File(path); -// double fileSizeInKB = f.lengthSync() / 5000; -// double fileSizeInMB = fileSizeInKB / 5000; -// if (fileSizeInKB > fileSizeLimit) { -// return false; -// } else { -// return true; -// } -// } -// -// String getType(String type) { -// switch (type) { -// case ".pdf": -// return "assets/images/pdf.svg"; -// case ".png": -// return "assets/images/png.svg"; -// case ".txt": -// return "assets/icons/chat/txt.svg"; -// case ".jpg": -// return "assets/images/jpg.svg"; -// case ".jpeg": -// return "assets/images/jpg.svg"; -// case ".xls": -// return "assets/icons/chat/xls.svg"; -// case ".xlsx": -// return "assets/icons/chat/xls.svg"; -// case ".doc": -// return "assets/icons/chat/doc.svg"; -// case ".docx": -// return "assets/icons/chat/doc.svg"; -// case ".ppt": -// return "assets/icons/chat/ppt.svg"; -// case ".pptx": -// return "assets/icons/chat/ppt.svg"; -// case ".zip": -// return "assets/icons/chat/zip.svg"; -// case ".rar": -// return "assets/icons/chat/zip.svg"; -// case ".aac": -// return "assets/icons/chat/aac.svg"; -// case ".mp3": -// return "assets/icons/chat/zip.mp3"; -// default: -// return "assets/images/thumb.svg"; -// } -// } -// -// void chatReply(SingleUserChatModel data) { -// repliedMsg = []; -// data.isReplied = true; -// isReplyMsg = true; -// repliedMsg.add(data); -// notifyListeners(); -// } -// -// void groupChatReply(groupchathistory.GetGroupChatHistoryAsync data) { -// groupChatReplyData = []; -// data.isReplied = true; -// isReplyMsg = true; -// groupChatReplyData.add(data); -// notifyListeners(); -// } -// -// void closeMe() { -// repliedMsg = []; -// isReplyMsg = false; -// notifyListeners(); -// } -// -// String dateFormte(DateTime data) { -// DateFormat f = DateFormat('hh:mm a dd MMM yyyy', "en_US"); -// f.format(data); -// return f.format(data); -// } -// -// Future favoriteUser({required int userID, required int targetUserID, required bool fromSearch}) async { -// fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().favUser(userID: userID, targetUserID: targetUserID); -// if (favoriteChatUser.response != null) { -// for (ChatUser user in searchedChats!) { -// if (user.id == favoriteChatUser.response!.targetUserId!) { -// user.isFav = favoriteChatUser.response!.isFav; -// dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); -// if (contain.isEmpty) { -// favUsersList.add(user); -// } -// } -// } -// -// for (ChatUser user in chatUsersList!) { -// if (user.id == favoriteChatUser.response!.targetUserId!) { -// user.isFav = favoriteChatUser.response!.isFav; -// dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); -// if (contain.isEmpty) { -// favUsersList.add(user); -// } -// } -// } -// } -// if (fromSearch) { -// for (ChatUser user in favUsersList) { -// if (user.id == targetUserID) { -// user.userLocalDownlaodedImage = null; -// user.isImageLoading = false; -// user.isImageLoaded = false; -// } -// } -// } -// notifyListeners(); -// } -// -// Future unFavoriteUser({required int userID, required int targetUserID}) async { -// fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().unFavUser(userID: userID, targetUserID: targetUserID); -// -// if (favoriteChatUser.response != null) { -// for (ChatUser user in searchedChats!) { -// if (user.id == favoriteChatUser.response!.targetUserId!) { -// user.isFav = favoriteChatUser.response!.isFav; -// } -// } -// favUsersList.removeWhere( -// (ChatUser element) => element.id == targetUserID, -// ); -// } -// -// for (ChatUser user in chatUsersList!) { -// if (user.id == favoriteChatUser.response!.targetUserId!) { -// user.isFav = favoriteChatUser.response!.isFav; -// } -// } -// -// notifyListeners(); -// } -// -// void clearSelections() { -// searchedChats = pChatHistory; -// search.clear(); -// isChatScreenActive = false; -// receiverID = 0; -// paginationVal = 0; -// message.text = ''; -// isAttachmentMsg = false; -// repliedMsg = []; -// sFileType = ""; -// isReplyMsg = false; -// isTextMsg = false; -// isVoiceMsg = false; -// notifyListeners(); -// } -// -// void clearAll() { -// searchedChats = pChatHistory; -// search.clear(); -// isChatScreenActive = false; -// receiverID = 0; -// paginationVal = 0; -// message.text = ''; -// isTextMsg = false; -// isAttachmentMsg = false; -// isVoiceMsg = false; -// isReplyMsg = false; -// repliedMsg = []; -// sFileType = ""; -// } -// -// void disposeData() { -// if (!disbaleChatForThisUser) { -// search.clear(); -// isChatScreenActive = false; -// receiverID = 0; -// paginationVal = 0; -// message.text = ''; -// isTextMsg = false; -// isAttachmentMsg = false; -// isVoiceMsg = false; -// isReplyMsg = false; -// repliedMsg = []; -// sFileType = ""; -// deleteData(); -// favUsersList.clear(); -// searchedChats?.clear(); -// pChatHistory?.clear(); -// uGroups?.clear(); -// searchGroup?.clear(); -// chatHubConnection.stop(); -// AppState().chatDetails = null; -// } -// } -// -// void deleteData() { -// List exists = [], unique = []; -// if (searchedChats != null) exists.addAll(searchedChats!); -// exists.addAll(favUsersList!); -// Map profileMap = {}; -// for (ChatUser item in exists) { -// profileMap[item.email!] = item; -// } -// unique = profileMap.values.toList(); -// for (ChatUser element in unique!) { -// deleteFile(element.id.toString()); -// } -// } -// -// void getUserImages() async { -// List emails = []; -// List exists = [], unique = []; -// exists.addAll(searchedChats!); -// exists.addAll(favUsersList!); -// Map profileMap = {}; -// for (ChatUser item in exists) { -// profileMap[item.email!] = item; -// } -// unique = profileMap.values.toList(); -// for (ChatUser element in unique!) { -// emails.add(await EmailImageEncryption().encrypt(val: element.email!)); -// } -// -// List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); -// for (ChatUser user in searchedChats!) { -// for (ChatUserImageModel uImage in chatImages) { -// if (user.email == uImage.email) { -// user.image = uImage.profilePicture ?? ""; -// user.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, user.id.toString()); -// user.isImageLoading = false; -// user.isImageLoaded = true; -// } -// } -// } -// for (ChatUser favUser in favUsersList) { -// for (ChatUserImageModel uImage in chatImages) { -// if (favUser.email == uImage.email) { -// favUser.image = uImage.profilePicture ?? ""; -// favUser.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, favUser.id.toString()); -// favUser.isImageLoading = false; -// favUser.isImageLoaded = true; -// } -// } -// } -// -// notifyListeners(); -// } -// -// Future downloadImageLocal(String? encodedBytes, String userID) async { -// File? myfile; -// if (encodedBytes == null) { -// return myfile; -// } else { -// await deleteFile(userID); -// Uint8List decodedBytes = base64Decode(encodedBytes); -// Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); -// String dirPath = '${appDocumentsDirectory.path}/chat_images'; -// if (!await Directory(dirPath).exists()) { -// await Directory(dirPath).create(); -// await File('$dirPath/.nomedia').create(); -// } -// late File imageFile = File("$dirPath/$userID.jpg"); -// imageFile.writeAsBytesSync(decodedBytes); -// return imageFile; -// } -// } -// -// Future deleteFile(String userID) async { -// Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); -// String dirPath = '${appDocumentsDirectory.path}/chat_images'; -// late File imageFile = File('$dirPath/$userID.jpg'); -// if (await imageFile.exists()) { -// await imageFile.delete(); -// } -// } -// -// Future downChatMedia(Uint8List bytes, String ext) async { -// String dir = (await getApplicationDocumentsDirectory()).path; -// File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + "." + ext); -// await file.writeAsBytes(bytes); -// return file.path; -// } -// -// void setMsgTune() async { -// JustAudio.AudioPlayer player = JustAudio.AudioPlayer(); -// await player.setVolume(1.0); -// String audioAsset = ""; -// if (Platform.isAndroid) { -// audioAsset = "assets/audio/pulse_tone_android.mp3"; -// } else { -// audioAsset = "assets/audio/pulse_tune_ios.caf"; -// } -// try { -// await player.setAsset(audioAsset); -// await player.load(); -// player.play(); -// } catch (e) { -// print("Error: $e"); -// } -// } -// -// Future getChatMedia(BuildContext context, {required String fileName, required String fileTypeName, required int fileTypeID, required int fileSource}) async { -// Utils.showLoading(context); -// if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2 || fileTypeID == 16) { -// Uint8List encodedString = await ChatApiClient().downloadURL(fileName: fileName, fileTypeDescription: getFileTypeDescription(fileTypeName), fileSource: fileSource); -// try { -// String path = await downChatMedia(encodedString, fileTypeName ?? ""); -// Utils.hideLoading(context); -// OpenFilex.open(path); -// } catch (e) { -// Utils.showToast("Cannot open file."); -// } -// } -// } -// -// void onNewChatConversion(List? params) { -// dynamic items = params!.toList(); -// chatUConvCounter = items[0]["singleChatCount"] ?? 0; -// notifyListeners(); -// } -// -// Future invokeChatCounter({required int userId}) async { -// await chatHubConnection.invoke("GetChatCounversationCount", args: [userId]); -// return ""; -// } -// -// void userTypingInvoke({required int currentUser, required int reciptUser}) async { -// await chatHubConnection.invoke("UserTypingAsync", args: [reciptUser, currentUser]); -// } -// -// void groupTypingInvoke({required GroupResponse groupDetails, required int groupId}) async { -// var data = json.decode(json.encode(groupDetails.groupUserList)); -// await chatHubConnection.invoke("GroupTypingAsync", args: ["${groupDetails.adminUser!.userName}", data, groupId]); -// } -// -// //////// Audio Recoding Work //////////////////// -// -// Future initAudio({required int receiverId}) async { -// // final dir = Directory((Platform.isAndroid -// // ? await getExternalStorageDirectory() //FOR ANDROID -// // : await getApplicationSupportDirectory() //FOR IOS -// // )! -// appDirectory = await getApplicationDocumentsDirectory(); -// String dirPath = '${appDirectory.path}/chat_audios'; -// if (!await Directory(dirPath).exists()) { -// await Directory(dirPath).create(); -// await File('$dirPath/.nomedia').create(); -// } -// path = "$dirPath/${AppState().chatDetails!.response!.id}-$receiverID-${DateTime.now().microsecondsSinceEpoch}.aac"; -// recorderController = RecorderController() -// ..androidEncoder = AndroidEncoder.aac -// ..androidOutputFormat = AndroidOutputFormat.mpeg4 -// ..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC -// ..sampleRate = 6000 -// ..updateFrequency = const Duration(milliseconds: 100) -// ..bitRate = 18000; -// playerController = PlayerController(); -// } -// -// void disposeAudio() { -// isRecoding = false; -// isPlaying = false; -// isPause = false; -// isVoiceMsg = false; -// recorderController.dispose(); -// playerController.dispose(); -// } -// -// void startRecoding(BuildContext context) async { -// await Permission.microphone.request().then((PermissionStatus status) { -// if (status.isPermanentlyDenied) { -// Utils.confirmDialog( -// context, -// "The app needs microphone access to be able to record audio.", -// onTap: () { -// Navigator.of(context).pop(); -// openAppSettings(); -// }, -// ); -// } else if (status.isDenied) { -// Utils.confirmDialog( -// context, -// "The app needs microphone access to be able to record audio.", -// onTap: () { -// Navigator.of(context).pop(); -// openAppSettings(); -// }, -// ); -// } else if (status.isGranted) { -// sRecoding(); -// } else { -// startRecoding(context); -// } -// }); -// } -// -// void sRecoding() async { -// isVoiceMsg = true; -// recorderController.reset(); -// await recorderController.record(path: path); -// _recodeDuration = 0; -// _startTimer(); -// isRecoding = !isRecoding; -// notifyListeners(); -// } -// -// Future _startTimer() async { -// _timer?.cancel(); -// _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) async { -// _recodeDuration++; -// if (_recodeDuration <= 59) { -// applyCounter(); -// } else { -// pauseRecoding(); -// } -// }); -// } -// -// void applyCounter() { -// buildTimer(); -// notifyListeners(); -// } -// -// Future pauseRecoding() async { -// isPause = true; -// isPlaying = true; -// recorderController.pause(); -// path = await recorderController.stop(false); -// File file = File(path!); -// file.readAsBytesSync(); -// path = file.path; -// await playerController.preparePlayer(path:file.path, volume: 1.0); -// _timer?.cancel(); -// notifyListeners(); -// } -// -// Future deleteRecoding() async { -// _recodeDuration = 0; -// _timer?.cancel(); -// if (path == null) { -// path = await recorderController.stop(true); -// } else { -// await recorderController.stop(true); -// } -// if (path != null && path!.isNotEmpty) { -// File delFile = File(path!); -// double fileSizeInKB = delFile.lengthSync() / 1024; -// double fileSizeInMB = fileSizeInKB / 1024; -// if (kDebugMode) { -// debugPrint("Deleted file size: ${delFile.lengthSync()}"); -// debugPrint("Deleted file size in KB: " + fileSizeInKB.toString()); -// debugPrint("Deleted file size in MB: " + fileSizeInMB.toString()); -// } -// if (await delFile.exists()) { -// delFile.delete(); -// } -// isPause = false; -// isRecoding = false; -// isPlaying = false; -// isVoiceMsg = false; -// notifyListeners(); -// } -// } -// -// String buildTimer() { -// String minutes = _formatNum(_recodeDuration ~/ 60); -// String seconds = _formatNum(_recodeDuration % 60); -// return '$minutes : $seconds'; -// } -// -// String _formatNum(int number) { -// String numberStr = number.toString(); -// if (number < 10) { -// numberStr = '0' + numberStr; -// } -// return numberStr; -// } -// -// Future downChatVoice(Uint8List bytes, String ext, SingleUserChatModel data) async { -// File file; -// try { -// String dirPath = '${(await getApplicationDocumentsDirectory()).path}/chat_audios'; -// if (!await Directory(dirPath).exists()) { -// await Directory(dirPath).create(); -// await File('$dirPath/.nomedia').create(); -// } -// file = File("$dirPath/${data.currentUserId}-${data.targetUserId}-${DateTime.now().microsecondsSinceEpoch}" + ext); -// await file.writeAsBytes(bytes); -// } catch (e) { -// if (kDebugMode) { -// print(e); -// } -// file = File(""); -// } -// return file; -// } -// -// void scrollToMsg(SingleUserChatModel data) { -// if (data.userChatReplyResponse != null && data.userChatReplyResponse!.userChatHistoryId != null) { -// int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == data.userChatReplyResponse!.userChatHistoryId); -// if (index >= 1) { -// double contentSize = scrollController.position.viewportDimension + scrollController.position.maxScrollExtent; -// double target = contentSize * index / userChatHistory.length; -// scrollController.position.animateTo( -// target, -// duration: const Duration(seconds: 1), -// curve: Curves.easeInOut, -// ); -// } -// } -// } -// -// Future getTeamMembers() async { -// teamMembersList = []; -// isLoading = true; -// if (AppState().getemployeeSubordinatesList.isNotEmpty) { -// getEmployeeSubordinatesList = AppState().getemployeeSubordinatesList; -// for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { -// if (element.eMPLOYEEEMAILADDRESS != null) { -// if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { -// teamMembersList.add( -// ChatUser( -// id: int.parse(element.eMPLOYEENUMBER!), -// email: element.eMPLOYEEEMAILADDRESS, -// userName: element.eMPLOYEENAME, -// phone: element.eMPLOYEEMOBILENUMBER, -// userStatus: 0, -// unreadMessageCount: 0, -// isFav: false, -// isTyping: false, -// isImageLoading: false, -// image: element.eMPLOYEEIMAGE ?? "", -// isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, -// userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), -// ), -// ); -// } -// } -// } -// } else { -// getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates("", "", ""); -// AppState().setemployeeSubordinatesList = getEmployeeSubordinatesList; -// for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { -// if (element.eMPLOYEEEMAILADDRESS != null) { -// if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { -// teamMembersList.add( -// ChatUser( -// id: int.parse(element.eMPLOYEENUMBER!), -// email: element.eMPLOYEEEMAILADDRESS, -// userName: element.eMPLOYEENAME, -// phone: element.eMPLOYEEMOBILENUMBER, -// userStatus: 0, -// unreadMessageCount: 0, -// isFav: false, -// isTyping: false, -// isImageLoading: false, -// image: element.eMPLOYEEIMAGE ?? "", -// isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, -// userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), -// ), -// ); -// } -// } -// } -// } -// -// for (ChatUser user in searchedChats!) { -// for (ChatUser teamUser in teamMembersList!) { -// if (user.id == teamUser.id) { -// teamUser.userStatus = user.userStatus; -// } -// } -// } -// -// isLoading = false; -// notifyListeners(); -// } -// -// void inputBoxDirection(String val) { -// if (val.isNotEmpty) { -// isTextMsg = true; -// } else { -// isTextMsg = false; -// } -// msgText = val; -// notifyListeners(); -// } -// -// void onDirectionChange(bool val) { -// isRTL = val; -// notifyListeners(); -// } -// -// Material.TextDirection getTextDirection(String v) { -// String str = v.trim(); -// if (str.isEmpty) return Material.TextDirection.ltr; -// int firstUnit = str.codeUnitAt(0); -// if (firstUnit > 0x0600 && firstUnit < 0x06FF || -// firstUnit > 0x0750 && firstUnit < 0x077F || -// firstUnit > 0x07C0 && firstUnit < 0x07EA || -// firstUnit > 0x0840 && firstUnit < 0x085B || -// firstUnit > 0x08A0 && firstUnit < 0x08B4 || -// firstUnit > 0x08E3 && firstUnit < 0x08FF || -// firstUnit > 0xFB50 && firstUnit < 0xFBB1 || -// firstUnit > 0xFBD3 && firstUnit < 0xFD3D || -// firstUnit > 0xFD50 && firstUnit < 0xFD8F || -// firstUnit > 0xFD92 && firstUnit < 0xFDC7 || -// firstUnit > 0xFDF0 && firstUnit < 0xFDFC || -// firstUnit > 0xFE70 && firstUnit < 0xFE74 || -// firstUnit > 0xFE76 && firstUnit < 0xFEFC || -// firstUnit > 0x10800 && firstUnit < 0x10805 || -// firstUnit > 0x1B000 && firstUnit < 0x1B0FF || -// firstUnit > 0x1D165 && firstUnit < 0x1D169 || -// firstUnit > 0x1D16D && firstUnit < 0x1D172 || -// firstUnit > 0x1D17B && firstUnit < 0x1D182 || -// firstUnit > 0x1D185 && firstUnit < 0x1D18B || -// firstUnit > 0x1D1AA && firstUnit < 0x1D1AD || -// firstUnit > 0x1D242 && firstUnit < 0x1D244) { -// return Material.TextDirection.rtl; -// } -// return Material.TextDirection.ltr; -// } -// -// void openChatByNoti(BuildContext context) async { -// SingleUserChatModel nUser = SingleUserChatModel(); -// Utils.saveStringFromPrefs("isAppOpendByChat", "false"); -// if (await Utils.getStringFromPrefs("notificationData") != "null") { -// nUser = SingleUserChatModel.fromJson(jsonDecode(await Utils.getStringFromPrefs("notificationData"))); -// Utils.saveStringFromPrefs("notificationData", "null"); -// Future.delayed(const Duration(seconds: 2)); -// for (ChatUser user in searchedChats!) { -// if (user.id == nUser.targetUserId) { -// Navigator.pushNamed(context, AppRoutes.chatDetailed, arguments: ChatDetailedScreenParams(user, false)); -// return; -// } -// } -// } -// Utils.saveStringFromPrefs("notificationData", "null"); -// } -// -// //group chat functions added here -// -// void filterGroups(String value) async { -// // filter function added here. -// List tmp = []; -// if (value.isEmpty || value == "") { -// tmp = userGroups.groupresponse!; -// } else { -// for (groups.GroupResponse element in uGroups!) { -// if (element.groupName!.toLowerCase().contains(value.toLowerCase())) { -// tmp.add(element); -// } -// } -// } -// uGroups = tmp; -// notifyListeners(); -// } -// -// Future deleteGroup(GroupResponse groupDetails) async { -// isLoading = true; -// await ChatApiClient().deleteGroup(groupDetails.groupId); -// userGroups = await ChatApiClient().getGroupsByUserId(); -// uGroups = userGroups.groupresponse; -// isLoading = false; -// notifyListeners(); -// } -// -// Future getGroupChatHistory(groups.GroupResponse groupDetails) async { -// isLoading = true; -// groupChatHistory = await ChatApiClient().getGroupChatHistory(groupDetails.groupId, groupDetails.groupUserList as List); -// -// isLoading = false; -// -// notifyListeners(); -// } -// -// void updateGroupAdmin(int? groupId, List groupUserList) async { -// isLoading = true; -// await ChatApiClient().updateGroupAdmin(groupId, groupUserList); -// isLoading = false; -// notifyListeners(); -// } -// -// Future addGroupAndUsers(createGroup.CreateGroupRequest request) async { -// isLoading = true; -// var groups = await ChatApiClient().addGroupAndUsers(request); -// userGroups.groupresponse!.add(GroupResponse.fromJson(json.decode(groups)['response'])); -// -// isLoading = false; -// notifyListeners(); -// } -// -// Future updateGroupAndUsers(createGroup.CreateGroupRequest request) async { -// isLoading = true; -// await ChatApiClient().updateGroupAndUsers(request); -// userGroups = await ChatApiClient().getGroupsByUserId(); -// uGroups = userGroups.groupresponse; -// isLoading = false; -// notifyListeners(); -// } -// } +import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:signalr_netcore/hub_connection.dart'; +import 'package:signalr_netcore/signalr_client.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/extensions/string_extensions.dart'; +import 'package:uuid/uuid.dart'; +import 'package:flutter/material.dart' as Material; + +import 'model/get_search_user_chat_model.dart'; +import 'get_single_user_chat_list_model.dart'; + +late HubConnection chatHubConnection; + +class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { + ScrollController scrollController = ScrollController(); + + TextEditingController message = TextEditingController(); + TextEditingController search = TextEditingController(); + TextEditingController searchGroup = TextEditingController(); + + List userChatHistory = [], repliedMsg = []; + List? pChatHistory, searchedChats; + String chatCID = ''; + bool isLoading = true; + bool isChatScreenActive = false; + int receiverID = 0; + late File selectedFile; + String sFileType = ""; + + List favUsersList = []; + int paginationVal = 0; + int? cTypingUserId = 0; + bool isTextMsg = false, isReplyMsg = false, isAttachmentMsg = false, isVoiceMsg = false; + + // Audio Recoding Work + Timer? _timer; + int _recodeDuration = 0; + bool isRecoding = false; + bool isPause = false; + bool isPlaying = false; + String? path; + String? musicFile; + late Directory appDirectory; + late RecorderController recorderController; + late PlayerController playerController; + + // List getEmployeeSubordinatesList = []; + List teamMembersList = []; + + // groups.GetUserGroups userGroups = groups.GetUserGroups(); + Material.TextDirection textDirection = Material.TextDirection.ltr; + bool isRTL = false; + String msgText = ""; + + //Chat Home Page Counter + int chatUConvCounter = 0; + + // late List groupChatHistory, groupChatReplyData; + + /// Search Provider + List? chatUsersList = []; + int pageNo = 1; + + bool disbaleChatForThisUser = false; + + // List? uGroups = [], searchGroups = []; + + Future getUserAutoLoginToken() async { + userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + + if (userLoginResponse.StatusCode == 500) { + disbaleChatForThisUser = true; + notifyListeners(); + } + + if (userLoginResponse.response != null) { + // AppState().setchatUserDetails = userLoginResponse; + } else { + // AppState().setchatUserDetails = userLoginResponse; + userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr".showToast; + disbaleChatForThisUser = true; + notifyListeners(); + } + } + + Future buildHubConnection() async { + chatHubConnection = await getHubConnection(); + await chatHubConnection.start(); + if (kDebugMode) { + // logger.i("Hub Conn: Startedddddddd"); + } + chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); + chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); + + //group On message + + chatHubConnection.on("OnDeliveredGroupChatHistoryAsync", onGroupMsgReceived); + } + + Future getHubConnection() async { + HubConnection hub; + HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); + hub = HubConnectionBuilder() + .withUrl(URLs.chatHubUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Desktop&access_token=${AppState().chatDetails!.response!.token}", options: httpOp) + .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); + return hub; + } + + void registerEvents() { + chatHubConnection.on("OnUpdateUserStatusAsync", changeStatus); + // chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); + + chatHubConnection.on("OnSubmitChatAsync", OnSubmitChatAsync); + chatHubConnection.on("OnUserTypingAsync", onUserTyping); + chatHubConnection.on("OnUserCountAsync", userCountAsync); + // chatHubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); + chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); + chatHubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); + chatHubConnection.on("OnGetGroupUserStatusAsync", getGroupUserStatus); + + // + // {"type":1,"target":"","arguments":[[{"id":217869,"userName":"Sultan.Khan","email":"Sultan.Khan@cloudsolutions.com.sa","phone":null,"title":"Sultan.Khan","userStatus":1,"image":null,"unreadMessageCount":0,"userAction":3,"isPin":false,"isFav":false,"isAdmin":false,"rKey":null,"totalCount":0,"isHuaweiDevice":false,"deviceToken":null},{"id":15153,"userName":"Tamer.Fanasheh","email":"Tamer.F@cloudsolutions.com.sa","phone":null,"title":"Tamer Fanasheh","userStatus":2,"image":null,"unreadMessageCount":0,"userAction":3,"isPin":false,"isFav":false,"isAdmin":true,"rKey":null,"totalCount":0,"isHuaweiDevice":false,"deviceToken":null}]]} + + if (kDebugMode) { + logger.i("All listeners registered"); + } + } + + Future getUserRecentChats() async { + ChatUserModel recentChat = await ChatApiClient().getRecentChats(); + ChatUserModel favUList = await ChatApiClient().getFavUsers(); + // userGroups = await ChatApiClient().getGroupsByUserId(); + if (favUList.response != null && recentChat.response != null) { + favUsersList = favUList.response!; + favUsersList.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); + for (dynamic user in recentChat.response!) { + for (dynamic favUser in favUList.response!) { + if (user.id == favUser.id) { + user.isFav = favUser.isFav; + } + } + } + } + pChatHistory = recentChat.response ?? []; + uGroups = userGroups.groupresponse ?? []; + pChatHistory!.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); + searchedChats = pChatHistory; + isLoading = false; + await invokeUserChatHistoryNotDeliveredAsync(userId: int.parse(AppState().chatDetails!.response!.id.toString())); + sort(); + notifyListeners(); + if (searchedChats!.isNotEmpty || favUsersList.isNotEmpty) { + getUserImages(); + } + } + + Future invokeUserChatHistoryNotDeliveredAsync({required int userId}) async { + await chatHubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); + return ""; + } + + void getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false}) async { + isLoading = true; + if (isNewChat) userChatHistory = []; + if (!loadMore) paginationVal = 0; + isChatScreenActive = true; + receiverID = receiverUID; + Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); + if (response.statusCode == 204) { + if (isNewChat) { + userChatHistory = []; + } else if (loadMore) {} + } else { + if (loadMore) { + List temp = getSingleUserChatModel(response.body).reversed.toList(); + userChatHistory.addAll(temp); + } else { + userChatHistory = getSingleUserChatModel(response.body).reversed.toList(); + } + } + isLoading = false; + notifyListeners(); + + if (isChatScreenActive && receiverUID == receiverID) { + markRead(userChatHistory, receiverUID); + } + + generateConvId(); + } + + void generateConvId() async { + Uuid uuid = const Uuid(); + chatCID = uuid.v4(); + } + + void markRead(List data, int receiverID) { + for (SingleUserChatModel element in data!) { + if (AppState().chatDetails!.response!.id! == element.targetUserId) { + if (element.isSeen != null) { + if (!element.isSeen!) { + element.isSeen = true; + dynamic data = [ + { + "userChatHistoryId": element.userChatHistoryId, + "TargetUserId": element.currentUserId == receiverID ? element.currentUserId : element.targetUserId, + "isDelivered": true, + "isSeen": true, + } + ]; + updateUserChatHistoryStatusAsync(data); + notifyListeners(); + } + } + for (ChatUser element in searchedChats!) { + if (element.id == receiverID) { + element.unreadMessageCount = 0; + chatUConvCounter = 0; + } + } + } + } + notifyListeners(); + } + + void updateUserChatHistoryStatusAsync(List data) { + try { + chatHubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); + } catch (e) { + throw e; + } + } + + void updateUserChatHistoryOnMsg(List data) { + try { + chatHubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); + } catch (e) { + throw e; + } + } + + List getSingleUserChatModel(String str) => List.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); + + List getGroupChatHistoryAsync(String str) => + List.from(json.decode(str).map((x) => groupchathistory.GetGroupChatHistoryAsync.fromJson(x))); + + Future uploadAttachments(String userId, File file, String fileSource) async { + dynamic result; + try { + Object? response = await ChatApiClient().uploadMedia(userId, file, fileSource); + if (response != null) { + result = response; + } else { + result = []; + } + } catch (e) { + throw e; + } + return result; + } + + void updateUserChatStatus(List? args) { + dynamic items = args!.toList(); + for (var cItem in items[0]) { + for (SingleUserChatModel chat in userChatHistory) { + if (cItem["contantNo"].toString() == chat.contantNo.toString()) { + chat.isSeen = cItem["isSeen"]; + chat.isDelivered = cItem["isDelivered"]; + } + } + } + notifyListeners(); + } + + void getGroupUserStatus(List? args) { + //note: need to implement this function... + print(args); + } + + void onChatSeen(List? args) { + dynamic items = args!.toList(); + // for (var user in searchedChats!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // notifyListeners(); + } + + void userCountAsync(List? args) { + dynamic items = args!.toList(); + // logger.d(items); + //logger.d("---------------------------------User Count Async -------------------------------------"); + //logger.d(items); + // for (var user in searchedChats!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // notifyListeners(); + } + + void updateChatHistoryWindow(List? args) { + dynamic items = args!.toList(); + if (kDebugMode) { + logger.i("---------------------------------Update Chat History Windows Async -------------------------------------"); + } + logger.d(items); + // for (var user in searchedChats!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // notifyListeners(); + } + + void chatNotDelivered(List? args) { + dynamic items = args!.toList(); + for (dynamic item in items[0]) { + for (ChatUser element in searchedChats!) { + if (element.id == item["currentUserId"]) { + int? val = element.unreadMessageCount ?? 0; + element.unreadMessageCount = val! + 1; + } + } + } + notifyListeners(); + } + + void changeStatus(List? args) { + dynamic items = args!.toList(); + for (ChatUser user in searchedChats!) { + if (user.id == items.first["id"]) { + user.userStatus = items.first["userStatus"]; + } + } + if (teamMembersList.isNotEmpty) { + for (ChatUser user in teamMembersList!) { + if (user.id == items.first["id"]) { + user.userStatus = items.first["userStatus"]; + } + } + } + + notifyListeners(); + } + + void filter(String value) async { + List? tmp = []; + if (value.isEmpty || value == "") { + tmp = pChatHistory; + } else { + for (ChatUser element in pChatHistory!) { + if (element.userName!.toLowerCase().contains(value.toLowerCase())) { + tmp.add(element); + } + } + } + searchedChats = tmp; + notifyListeners(); + } + + Future onMsgReceived(List? parameters) async { + List data = [], temp = []; + for (dynamic msg in parameters!) { + data = getSingleUserChatModel(jsonEncode(msg)); + temp = getSingleUserChatModel(jsonEncode(msg)); + data.first.targetUserId = temp.first.currentUserId; + data.first.targetUserName = temp.first.currentUserName; + data.first.targetUserEmail = temp.first.currentUserEmail; + data.first.currentUserId = temp.first.targetUserId; + data.first.currentUserName = temp.first.targetUserName; + data.first.currentUserEmail = temp.first.targetUserEmail; + + if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { + data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); + } + if (data.first.userChatReplyResponse != null) { + if (data.first.fileTypeResponse != null) { + if (data.first.userChatReplyResponse!.fileTypeId == 12 || data.first.userChatReplyResponse!.fileTypeId == 4 || data.first.userChatReplyResponse!.fileTypeId == 3) { + data.first.userChatReplyResponse!.image = await ChatApiClient() + .downloadURL(fileName: data.first.userChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); + data.first.userChatReplyResponse!.isImageLoaded = true; + } + } + } + } + + if (searchedChats != null) { + dynamic contain = searchedChats!.where((ChatUser element) => element.id == data.first.currentUserId); + if (contain.isEmpty) { + List emails = []; + emails.add(await EmailImageEncryption().encrypt(val: data.first.currentUserEmail!)); + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + searchedChats!.add( + ChatUser( + id: data.first.currentUserId, + userName: data.first.currentUserName, + email: data.first.currentUserEmail, + unreadMessageCount: 0, + isImageLoading: false, + image: chatImages!.first.profilePicture ?? "", + isImageLoaded: true, + userStatus: 1, + isTyping: false, + userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, data.first.currentUserId.toString()), + ), + ); + } + } + setMsgTune(); + if (isChatScreenActive && data.first.currentUserId == receiverID) { + userChatHistory.insert(0, data.first); + } else { + if (searchedChats != null) { + for (ChatUser user in searchedChats!) { + if (user.id == data.first.currentUserId) { + int tempCount = user.unreadMessageCount ?? 0; + user.unreadMessageCount = tempCount + 1; + } + } + sort(); + } + } + + List list = [ + { + "userChatHistoryId": data.first.userChatHistoryId, + "TargetUserId": temp.first.targetUserId, + "isDelivered": true, + "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false + } + ]; + updateUserChatHistoryOnMsg(list); + invokeChatCounter(userId: AppState().chatDetails!.response!.id!); + notifyListeners(); + } + + Future onGroupMsgReceived(List? parameters) async { + List data = [], temp = []; + + for (dynamic msg in parameters!) { + // groupChatHistory.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); + data.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); + temp = data; + // data.first.currentUserId = temp.first.currentUserId; + // data.first.currentUserName = temp.first.currentUserName; + // + // data.first.currentUserId = temp.first.currentUserId; + // data.first.currentUserName = temp.first.currentUserName; + + if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { + data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); + } + if (data.first.groupChatReplyResponse != null) { + if (data.first.fileTypeResponse != null) { + if (data.first.groupChatReplyResponse!.fileTypeId == 12 || data.first.groupChatReplyResponse!.fileTypeId == 4 || data.first.groupChatReplyResponse!.fileTypeId == 3) { + data.first.groupChatReplyResponse!.image = await ChatApiClient() + .downloadURL(fileName: data.first.groupChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); + data.first.groupChatReplyResponse!.isImageLoaded = true; + } + } + } + } + + // if (searchedChats != null) { + // dynamic contain = searchedChats! + // .where((ChatUser element) => element.id == data.first.currentUserId); + // if (contain.isEmpty) { + // List emails = []; + // emails.add(await EmailImageEncryption() + // .encrypt(val: data.first.currentUserEmail!)); + // List chatImages = + // await ChatApiClient().getUsersImages(encryptedEmails: emails); + // searchedChats!.add( + // ChatUser( + // id: data.first.currentUserId, + // userName: data.first.currentUserName, + // email: data.first.currentUserEmail, + // unreadMessageCount: 0, + // isImageLoading: false, + // image: chatImages!.first.profilePicture ?? "", + // isImageLoaded: true, + // userStatus: 1, + // isTyping: false, + // userLocalDownlaodedImage: await downloadImageLocal( + // chatImages.first.profilePicture, + // data.first.currentUserId.toString()), + // ), + // ); + // } + // } + groupChatHistory.insert(0, data.first); + setMsgTune(); + // if (isChatScreenActive && data.first.currentUserId == receiverID) { + + // } else { + // if (searchedChats != null) { + // for (ChatUser user in searchedChats!) { + // if (user.id == data.first.currentUserId) { + // int tempCount = user.unreadMessageCount ?? 0; + // user.unreadMessageCount = tempCount + 1; + // } + // } + sort(); + //} + //} + // + // List list = [ + // { + // "userChatHistoryId": data.first.groupId, + // "TargetUserId": temp.first.currentUserId, + // "isDelivered": true, + // "isSeen": isChatScreenActive && data.first.currentUserId == receiverID + // ? true + // : false + // } + // ]; + // updateUserChatHistoryOnMsg(list); + // invokeChatCounter(userId: AppState().chatDetails!.response!.id!); + notifyListeners(); + } + + void OnSubmitChatAsync(List? parameters) { + print(isChatScreenActive); + print(receiverID); + print(isChatScreenActive); + logger.i(parameters); + List data = [], temp = []; + for (dynamic msg in parameters!) { + data = getSingleUserChatModel(jsonEncode(msg)); + temp = getSingleUserChatModel(jsonEncode(msg)); + data.first.targetUserId = temp.first.currentUserId; + data.first.targetUserName = temp.first.currentUserName; + data.first.targetUserEmail = temp.first.currentUserEmail; + data.first.currentUserId = temp.first.targetUserId; + data.first.currentUserName = temp.first.targetUserName; + data.first.currentUserEmail = temp.first.targetUserEmail; + } + if (isChatScreenActive && data.first.currentUserId == receiverID) { + int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == 0); + logger.d(index); + userChatHistory[index] = data.first; + } + + notifyListeners(); + } + + void sort() { + searchedChats!.sort( + (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo(a.unreadMessageCount!), + ); + } + + void onUserTyping(List? parameters) { + for (ChatUser user in searchedChats!) { + if (user.id == parameters![1] && parameters[0] == true) { + user.isTyping = parameters[0] as bool?; + Future.delayed( + const Duration(seconds: 2), + () { + user.isTyping = false; + notifyListeners(); + }, + ); + } + } + notifyListeners(); + } + + int getFileType(String value) { + switch (value) { + case ".pdf": + return 1; + case ".png": + return 3; + case ".txt": + return 5; + case ".jpg": + return 12; + case ".jpeg": + return 4; + case ".xls": + return 7; + case ".xlsx": + return 7; + case ".doc": + return 6; + case ".docx": + return 6; + case ".ppt": + return 8; + case ".pptx": + return 8; + case ".zip": + return 2; + case ".rar": + return 2; + case ".aac": + return 13; + case ".mp3": + return 14; + case ".mp4": + return 16; + case ".mov": + return 16; + case ".avi": + return 16; + case ".flv": + return 16; + + default: + return 0; + } + } + + String getFileTypeDescription(String value) { + switch (value) { + case ".pdf": + return "application/pdf"; + case ".png": + return "image/png"; + case ".txt": + return "text/plain"; + case ".jpg": + return "image/jpg"; + case ".jpeg": + return "image/jpeg"; + case ".ppt": + return "application/vnd.openxmlformats-officedocument.presentationml.presentation"; + case ".pptx": + return "application/vnd.openxmlformats-officedocument.presentationml.presentation"; + case ".doc": + return "application/vnd.openxmlformats-officedocument.wordprocessingm"; + case ".docx": + return "application/vnd.openxmlformats-officedocument.wordprocessingm"; + case ".xls": + return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + case ".xlsx": + return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + case ".zip": + return "application/octet-stream"; + case ".rar": + return "application/octet-stream"; + case ".aac": + return "audio/aac"; + case ".mp3": + return "audio/mp3"; + case ".mp4": + return "video/mp4"; + case ".avi": + return "video/avi"; + case ".flv": + return "video/flv"; + case ".mov": + return "video/mov"; + + default: + return ""; + } + } + + Future sendChatToServer( + {required int chatEventId, + required fileTypeId, + required int targetUserId, + required String targetUserName, + required chatReplyId, + required bool isAttachment, + required bool isReply, + Uint8List? image, + required bool isImageLoaded, + String? userEmail, + int? userStatus, + File? voiceFile, + required bool isVoiceAttached}) async { + Uuid uuid = const Uuid(); + String contentNo = uuid.v4(); + String msg; + if (isVoiceAttached) { + msg = voiceFile!.path.split("/").last; + } else { + msg = message.text; + logger.w(msg); + } + SingleUserChatModel data = SingleUserChatModel( + userChatHistoryId: 0, + chatEventId: chatEventId, + chatSource: 1, + contant: msg, + contantNo: contentNo, + conversationId: chatCID, + createdDate: DateTime.now(), + currentUserId: AppState().chatDetails!.response!.id, + currentUserName: AppState().chatDetails!.response!.userName, + targetUserId: targetUserId, + targetUserName: targetUserName, + isReplied: false, + fileTypeId: fileTypeId, + userChatReplyResponse: isReply ? UserChatReplyResponse.fromJson(repliedMsg.first.toJson()) : null, + fileTypeResponse: isAttachment + ? FileTypeResponse( + fileTypeId: fileTypeId, + fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), + fileKind: "file", + fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, + fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString()), + ) + : null, + image: image, + isImageLoaded: isImageLoaded, + voice: isVoiceMsg ? voiceFile! : null, + voiceController: isVoiceMsg ? AudioPlayer() : null); + if (kDebugMode) { + logger.i("model data: " + jsonEncode(data)); + } + userChatHistory.insert(0, data); + isTextMsg = false; + isReplyMsg = false; + isAttachmentMsg = false; + isVoiceMsg = false; + sFileType = ""; + message.clear(); + notifyListeners(); + + String chatData = + '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId": $fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"chatReplyId":$chatReplyId,"conversationId":"$chatCID"}'; + + await chatHubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); + } + + //groupChatMessage + + Future sendGroupChatToServer( + {required int chatEventId, + required fileTypeId, + required int targetGroupId, + required String targetUserName, + required chatReplyId, + required bool isAttachment, + required bool isReply, + Uint8List? image, + required bool isImageLoaded, + String? userEmail, + int? userStatus, + File? voiceFile, + required bool isVoiceAttached, + required List userList}) async { + Uuid uuid = const Uuid(); + String contentNo = uuid.v4(); + String msg; + if (isVoiceAttached) { + msg = voiceFile!.path.split("/").last; + } else { + msg = message.text; + logger.w(msg); + } + groupchathistory.GetGroupChatHistoryAsync data = groupchathistory.GetGroupChatHistoryAsync( + //userChatHistoryId: 0, + chatEventId: chatEventId, + chatSource: 1, + contant: msg, + contantNo: contentNo, + conversationId: chatCID, + createdDate: DateTime.now().toString(), + currentUserId: AppState().chatDetails!.response!.id, + currentUserName: AppState().chatDetails!.response!.userName, + groupId: targetGroupId, + groupName: targetUserName, + isReplied: false, + fileTypeId: fileTypeId, + fileTypeResponse: isAttachment + ? groupchathistory.FileTypeResponse( + fileTypeId: fileTypeId, + fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), + fileKind: "file", + fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, + fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString())) + : null, + image: image, + isImageLoaded: isImageLoaded, + voice: isVoiceMsg ? voiceFile! : null, + voiceController: isVoiceMsg ? AudioPlayer() : null); + if (kDebugMode) { + logger.i("model data: " + jsonEncode(data)); + } + groupChatHistory.insert(0, data); + isTextMsg = false; + isReplyMsg = false; + isAttachmentMsg = false; + isVoiceMsg = false; + sFileType = ""; + message.clear(); + notifyListeners(); + + List targetUsers = []; + + for (GroupUserList element in userList) { + targetUsers.add(TargetUsers(isDelivered: false, isSeen: false, targetUserId: element.id, userAction: element.userAction, userStatus: element.userStatus)); + } + + String chatData = + '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId":$fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"groupId":$targetGroupId,"groupChatHistoryLineRequestList":${json.encode(targetUsers)},"chatReplyId": $chatReplyId,"conversationId":"${uuid.v4()}"}'; + + await chatHubConnection.invoke("AddGroupChatHistoryAsync", args: [json.decode(chatData)]); + } + + void sendGroupChatMessage( + BuildContext context, { + required int targetUserId, + required int userStatus, + required String userEmail, + required String targetUserName, + required List userList, + }) async { + if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + logger.d("// Normal Text Message"); + if (message.text.isEmpty) { + return; + } + sendGroupChatToServer( + chatEventId: 1, + fileTypeId: null, + targetGroupId: targetUserId, + targetUserName: targetUserName, + isAttachment: false, + chatReplyId: null, + isReply: false, + isImageLoaded: false, + image: null, + isVoiceAttached: false, + userEmail: userEmail, + userStatus: userStatus, + userList: userList); + } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + logger.d("// Text Message as Reply"); + if (message.text.isEmpty) { + return; + } + sendGroupChatToServer( + chatEventId: 1, + fileTypeId: null, + targetGroupId: targetUserId, + targetUserName: targetUserName, + chatReplyId: groupChatReplyData.first.groupChatHistoryId, + isAttachment: false, + isReply: true, + isImageLoaded: groupChatReplyData.first.isImageLoaded!, + image: groupChatReplyData.first.image, + isVoiceAttached: false, + voiceFile: null, + userEmail: userEmail, + userStatus: userStatus, + userList: userList); + } + // Attachment + else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + logger.d("// Normal Image Message"); + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); + String? ext = getFileExtension(selectedFile.path); + Utils.hideLoading(context); + sendGroupChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetGroupId: targetUserId, + targetUserName: targetUserName, + isAttachment: true, + chatReplyId: null, + isReply: false, + isImageLoaded: true, + image: selectedFile.readAsBytesSync(), + isVoiceAttached: false, + userEmail: userEmail, + userStatus: userStatus, + userList: userList); + } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + logger.d("// Image as Reply Msg"); + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); + String? ext = getFileExtension(selectedFile.path); + Utils.hideLoading(context); + sendGroupChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetGroupId: targetUserId, + targetUserName: targetUserName, + isAttachment: true, + chatReplyId: repliedMsg.first.userChatHistoryId, + isReply: true, + isImageLoaded: true, + image: selectedFile.readAsBytesSync(), + isVoiceAttached: false, + userEmail: userEmail, + userStatus: userStatus, + userList: userList); + } + //Voice + + else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { + logger.d("// Normal Voice Message"); + + if (!isPause) { + path = await recorderController.stop(false); + } + if (kDebugMode) { + logger.i("path:" + path!); + } + File voiceFile = File(path!); + voiceFile.readAsBytesSync(); + _timer?.cancel(); + isPause = false; + isPlaying = false; + isRecoding = false; + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); + String? ext = getFileExtension(voiceFile.path); + Utils.hideLoading(context); + sendGroupChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + //, + targetGroupId: targetUserId, + targetUserName: targetUserName, + chatReplyId: null, + isAttachment: true, + isReply: isReplyMsg, + isImageLoaded: false, + voiceFile: voiceFile, + isVoiceAttached: true, + userEmail: userEmail, + userStatus: userStatus, + userList: userList); + notifyListeners(); + } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { + logger.d("// Voice as Reply Msg"); + + if (!isPause) { + path = await recorderController.stop(false); + } + if (kDebugMode) { + logger.i("path:" + path!); + } + File voiceFile = File(path!); + voiceFile.readAsBytesSync(); + _timer?.cancel(); + isPause = false; + isPlaying = false; + isRecoding = false; + + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); + String? ext = getFileExtension(voiceFile.path); + Utils.hideLoading(context); + sendGroupChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetGroupId: targetUserId, + targetUserName: targetUserName, + chatReplyId: null, + isAttachment: true, + isReply: isReplyMsg, + isImageLoaded: false, + voiceFile: voiceFile, + isVoiceAttached: true, + userEmail: userEmail, + userStatus: userStatus, + userList: userList); + notifyListeners(); + } + if (searchedChats != null) { + dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); + if (contain.isEmpty) { + List emails = []; + emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + searchedChats!.add( + ChatUser( + id: targetUserId, + userName: targetUserName, + unreadMessageCount: 0, + email: userEmail, + isImageLoading: false, + image: chatImages.first.profilePicture ?? "", + isImageLoaded: true, + isTyping: false, + isFav: false, + userStatus: userStatus, + // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + ), + ); + notifyListeners(); + } + } + } + + void sendChatMessage( + BuildContext context, { + required int targetUserId, + required int userStatus, + required String userEmail, + required String targetUserName, + }) async { + if (kDebugMode) { + print("====================== Values ============================"); + print("Is Text " + isTextMsg.toString()); + print("isReply " + isReplyMsg.toString()); + print("isAttachment " + isAttachmentMsg.toString()); + print("isVoice " + isVoiceMsg.toString()); + } + //Text + if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + logger.d("// Normal Text Message"); + if (message.text.isEmpty) { + return; + } + sendChatToServer( + chatEventId: 1, + fileTypeId: null, + targetUserId: targetUserId, + targetUserName: targetUserName, + isAttachment: false, + chatReplyId: null, + isReply: false, + isImageLoaded: false, + image: null, + isVoiceAttached: false, + userEmail: userEmail, + userStatus: userStatus); + } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + logger.d("// Text Message as Reply"); + if (message.text.isEmpty) { + return; + } + sendChatToServer( + chatEventId: 1, + fileTypeId: null, + targetUserId: targetUserId, + targetUserName: targetUserName, + chatReplyId: repliedMsg.first.userChatHistoryId, + isAttachment: false, + isReply: true, + isImageLoaded: repliedMsg.first.isImageLoaded!, + image: repliedMsg.first.image, + isVoiceAttached: false, + voiceFile: null, + userEmail: userEmail, + userStatus: userStatus); + } + // Attachment + else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + logger.d("// Normal Image Message"); + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); + String? ext = getFileExtension(selectedFile.path); + Utils.hideLoading(context); + sendChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetUserId: targetUserId, + targetUserName: targetUserName, + isAttachment: true, + chatReplyId: null, + isReply: false, + isImageLoaded: true, + image: selectedFile.readAsBytesSync(), + isVoiceAttached: false, + userEmail: userEmail, + userStatus: userStatus); + } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + logger.d("// Image as Reply Msg"); + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); + String? ext = getFileExtension(selectedFile.path); + Utils.hideLoading(context); + sendChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetUserId: targetUserId, + targetUserName: targetUserName, + isAttachment: true, + chatReplyId: repliedMsg.first.userChatHistoryId, + isReply: true, + isImageLoaded: true, + image: selectedFile.readAsBytesSync(), + isVoiceAttached: false, + userEmail: userEmail, + userStatus: userStatus); + } + //Voice + + else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { + logger.d("// Normal Voice Message"); + + if (!isPause) { + path = await recorderController.stop(false); + } + if (kDebugMode) { + logger.i("path:" + path!); + } + File voiceFile = File(path!); + voiceFile.readAsBytesSync(); + _timer?.cancel(); + isPause = false; + isPlaying = false; + isRecoding = false; + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); + String? ext = getFileExtension(voiceFile.path); + Utils.hideLoading(context); + sendChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetUserId: targetUserId, + targetUserName: targetUserName, + chatReplyId: null, + isAttachment: true, + isReply: isReplyMsg, + isImageLoaded: false, + voiceFile: voiceFile, + isVoiceAttached: true, + userEmail: userEmail, + userStatus: userStatus); + notifyListeners(); + } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { + logger.d("// Voice as Reply Msg"); + + if (!isPause) { + path = await recorderController.stop(false); + } + if (kDebugMode) { + logger.i("path:" + path!); + } + File voiceFile = File(path!); + voiceFile.readAsBytesSync(); + _timer?.cancel(); + isPause = false; + isPlaying = false; + isRecoding = false; + + Utils.showLoading(context); + dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); + String? ext = getFileExtension(voiceFile.path); + Utils.hideLoading(context); + sendChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetUserId: targetUserId, + targetUserName: targetUserName, + chatReplyId: null, + isAttachment: true, + isReply: isReplyMsg, + isImageLoaded: false, + voiceFile: voiceFile, + isVoiceAttached: true, + userEmail: userEmail, + userStatus: userStatus); + notifyListeners(); + } + if (searchedChats != null) { + dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); + if (contain.isEmpty) { + List emails = []; + emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + searchedChats!.add( + ChatUser( + id: targetUserId, + userName: targetUserName, + unreadMessageCount: 0, + email: userEmail, + isImageLoading: false, + image: chatImages.first.profilePicture ?? "", + isImageLoaded: true, + isTyping: false, + isFav: false, + userStatus: userStatus, + userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + ), + ); + notifyListeners(); + } + } + // else { + // List emails = []; + // emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + // searchedChats!.add( + // ChatUser( + // id: targetUserId, + // userName: targetUserName, + // unreadMessageCount: 0, + // email: userEmail, + // isImageLoading: false, + // image: chatImages.first.profilePicture ?? "", + // isImageLoaded: true, + // isTyping: false, + // isFav: false, + // userStatus: userStatus, + // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + // ), + // ); + // notifyListeners(); + // } + } + + void selectImageToUpload(BuildContext context) { + ImageOptions.showImageOptionsNew(context, true, (String image, File file) async { + if (checkFileSize(file.path)) { + selectedFile = file; + isAttachmentMsg = true; + isTextMsg = false; + sFileType = getFileExtension(file.path)!; + message.text = file.path.split("/").last; + Navigator.of(context).pop(); + } else { + Utils.showToast("Max 1 mb size is allowed to upload"); + } + notifyListeners(); + }); + } + + void removeAttachment() { + isAttachmentMsg = false; + sFileType = ""; + message.text = ''; + notifyListeners(); + } + + String? getFileExtension(String fileName) { + try { + if (kDebugMode) { + logger.i("ext: " + "." + fileName.split('.').last); + } + return "." + fileName.split('.').last; + } catch (e) { + return null; + } + } + + bool checkFileSize(String path) { + int fileSizeLimit = 5120; + File f = File(path); + double fileSizeInKB = f.lengthSync() / 5000; + double fileSizeInMB = fileSizeInKB / 5000; + if (fileSizeInKB > fileSizeLimit) { + return false; + } else { + return true; + } + } + + String getType(String type) { + switch (type) { + case ".pdf": + return "assets/images/pdf.svg"; + case ".png": + return "assets/images/png.svg"; + case ".txt": + return "assets/icons/chat/txt.svg"; + case ".jpg": + return "assets/images/jpg.svg"; + case ".jpeg": + return "assets/images/jpg.svg"; + case ".xls": + return "assets/icons/chat/xls.svg"; + case ".xlsx": + return "assets/icons/chat/xls.svg"; + case ".doc": + return "assets/icons/chat/doc.svg"; + case ".docx": + return "assets/icons/chat/doc.svg"; + case ".ppt": + return "assets/icons/chat/ppt.svg"; + case ".pptx": + return "assets/icons/chat/ppt.svg"; + case ".zip": + return "assets/icons/chat/zip.svg"; + case ".rar": + return "assets/icons/chat/zip.svg"; + case ".aac": + return "assets/icons/chat/aac.svg"; + case ".mp3": + return "assets/icons/chat/zip.mp3"; + default: + return "assets/images/thumb.svg"; + } + } + + void chatReply(SingleUserChatModel data) { + repliedMsg = []; + data.isReplied = true; + isReplyMsg = true; + repliedMsg.add(data); + notifyListeners(); + } + + void groupChatReply(groupchathistory.GetGroupChatHistoryAsync data) { + groupChatReplyData = []; + data.isReplied = true; + isReplyMsg = true; + groupChatReplyData.add(data); + notifyListeners(); + } + + void closeMe() { + repliedMsg = []; + isReplyMsg = false; + notifyListeners(); + } + + String dateFormte(DateTime data) { + DateFormat f = DateFormat('hh:mm a dd MMM yyyy', "en_US"); + f.format(data); + return f.format(data); + } + + Future favoriteUser({required int userID, required int targetUserID, required bool fromSearch}) async { + fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().favUser(userID: userID, targetUserID: targetUserID); + if (favoriteChatUser.response != null) { + for (ChatUser user in searchedChats!) { + if (user.id == favoriteChatUser.response!.targetUserId!) { + user.isFav = favoriteChatUser.response!.isFav; + dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); + if (contain.isEmpty) { + favUsersList.add(user); + } + } + } + + for (ChatUser user in chatUsersList!) { + if (user.id == favoriteChatUser.response!.targetUserId!) { + user.isFav = favoriteChatUser.response!.isFav; + dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); + if (contain.isEmpty) { + favUsersList.add(user); + } + } + } + } + if (fromSearch) { + for (ChatUser user in favUsersList) { + if (user.id == targetUserID) { + user.userLocalDownlaodedImage = null; + user.isImageLoading = false; + user.isImageLoaded = false; + } + } + } + notifyListeners(); + } + + Future unFavoriteUser({required int userID, required int targetUserID}) async { + fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().unFavUser(userID: userID, targetUserID: targetUserID); + + if (favoriteChatUser.response != null) { + for (ChatUser user in searchedChats!) { + if (user.id == favoriteChatUser.response!.targetUserId!) { + user.isFav = favoriteChatUser.response!.isFav; + } + } + favUsersList.removeWhere( + (ChatUser element) => element.id == targetUserID, + ); + } + + for (ChatUser user in chatUsersList!) { + if (user.id == favoriteChatUser.response!.targetUserId!) { + user.isFav = favoriteChatUser.response!.isFav; + } + } + + notifyListeners(); + } + + void clearSelections() { + searchedChats = pChatHistory; + search.clear(); + isChatScreenActive = false; + receiverID = 0; + paginationVal = 0; + message.text = ''; + isAttachmentMsg = false; + repliedMsg = []; + sFileType = ""; + isReplyMsg = false; + isTextMsg = false; + isVoiceMsg = false; + notifyListeners(); + } + + void clearAll() { + searchedChats = pChatHistory; + search.clear(); + isChatScreenActive = false; + receiverID = 0; + paginationVal = 0; + message.text = ''; + isTextMsg = false; + isAttachmentMsg = false; + isVoiceMsg = false; + isReplyMsg = false; + repliedMsg = []; + sFileType = ""; + } + + void disposeData() { + if (!disbaleChatForThisUser) { + search.clear(); + isChatScreenActive = false; + receiverID = 0; + paginationVal = 0; + message.text = ''; + isTextMsg = false; + isAttachmentMsg = false; + isVoiceMsg = false; + isReplyMsg = false; + repliedMsg = []; + sFileType = ""; + deleteData(); + favUsersList.clear(); + searchedChats?.clear(); + pChatHistory?.clear(); + uGroups?.clear(); + searchGroup?.clear(); + chatHubConnection.stop(); + AppState().chatDetails = null; + } + } + + void deleteData() { + List exists = [], unique = []; + if (searchedChats != null) exists.addAll(searchedChats!); + exists.addAll(favUsersList!); + Map profileMap = {}; + for (ChatUser item in exists) { + profileMap[item.email!] = item; + } + unique = profileMap.values.toList(); + for (ChatUser element in unique!) { + deleteFile(element.id.toString()); + } + } + + void getUserImages() async { + List emails = []; + List exists = [], unique = []; + exists.addAll(searchedChats!); + exists.addAll(favUsersList!); + Map profileMap = {}; + for (ChatUser item in exists) { + profileMap[item.email!] = item; + } + unique = profileMap.values.toList(); + for (ChatUser element in unique!) { + emails.add(await EmailImageEncryption().encrypt(val: element.email!)); + } + + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + for (ChatUser user in searchedChats!) { + for (ChatUserImageModel uImage in chatImages) { + if (user.email == uImage.email) { + user.image = uImage.profilePicture ?? ""; + user.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, user.id.toString()); + user.isImageLoading = false; + user.isImageLoaded = true; + } + } + } + for (ChatUser favUser in favUsersList) { + for (ChatUserImageModel uImage in chatImages) { + if (favUser.email == uImage.email) { + favUser.image = uImage.profilePicture ?? ""; + favUser.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, favUser.id.toString()); + favUser.isImageLoading = false; + favUser.isImageLoaded = true; + } + } + } + + notifyListeners(); + } + + Future downloadImageLocal(String? encodedBytes, String userID) async { + File? myfile; + if (encodedBytes == null) { + return myfile; + } else { + await deleteFile(userID); + Uint8List decodedBytes = base64Decode(encodedBytes); + Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); + String dirPath = '${appDocumentsDirectory.path}/chat_images'; + if (!await Directory(dirPath).exists()) { + await Directory(dirPath).create(); + await File('$dirPath/.nomedia').create(); + } + late File imageFile = File("$dirPath/$userID.jpg"); + imageFile.writeAsBytesSync(decodedBytes); + return imageFile; + } + } + + Future deleteFile(String userID) async { + Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); + String dirPath = '${appDocumentsDirectory.path}/chat_images'; + late File imageFile = File('$dirPath/$userID.jpg'); + if (await imageFile.exists()) { + await imageFile.delete(); + } + } + + Future downChatMedia(Uint8List bytes, String ext) async { + String dir = (await getApplicationDocumentsDirectory()).path; + File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + "." + ext); + await file.writeAsBytes(bytes); + return file.path; + } + + void setMsgTune() async { + JustAudio.AudioPlayer player = JustAudio.AudioPlayer(); + await player.setVolume(1.0); + String audioAsset = ""; + if (Platform.isAndroid) { + audioAsset = "assets/audio/pulse_tone_android.mp3"; + } else { + audioAsset = "assets/audio/pulse_tune_ios.caf"; + } + try { + await player.setAsset(audioAsset); + await player.load(); + player.play(); + } catch (e) { + print("Error: $e"); + } + } + + Future getChatMedia(BuildContext context, {required String fileName, required String fileTypeName, required int fileTypeID, required int fileSource}) async { + Utils.showLoading(context); + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2 || fileTypeID == 16) { + Uint8List encodedString = await ChatApiClient().downloadURL(fileName: fileName, fileTypeDescription: getFileTypeDescription(fileTypeName), fileSource: fileSource); + try { + String path = await downChatMedia(encodedString, fileTypeName ?? ""); + Utils.hideLoading(context); + OpenFilex.open(path); + } catch (e) { + Utils.showToast("Cannot open file."); + } + } + } + + void onNewChatConversion(List? params) { + dynamic items = params!.toList(); + chatUConvCounter = items[0]["singleChatCount"] ?? 0; + notifyListeners(); + } + + Future invokeChatCounter({required int userId}) async { + await chatHubConnection.invoke("GetChatCounversationCount", args: [userId]); + return ""; + } + + void userTypingInvoke({required int currentUser, required int reciptUser}) async { + await chatHubConnection.invoke("UserTypingAsync", args: [reciptUser, currentUser]); + } + + void groupTypingInvoke({required GroupResponse groupDetails, required int groupId}) async { + var data = json.decode(json.encode(groupDetails.groupUserList)); + await chatHubConnection.invoke("GroupTypingAsync", args: ["${groupDetails.adminUser!.userName}", data, groupId]); + } + +//////// Audio Recoding Work //////////////////// + + Future initAudio({required int receiverId}) async { + // final dir = Directory((Platform.isAndroid + // ? await getExternalStorageDirectory() //FOR ANDROID + // : await getApplicationSupportDirectory() //FOR IOS + // )! + appDirectory = await getApplicationDocumentsDirectory(); + String dirPath = '${appDirectory.path}/chat_audios'; + if (!await Directory(dirPath).exists()) { + await Directory(dirPath).create(); + await File('$dirPath/.nomedia').create(); + } + path = "$dirPath/${AppState().chatDetails!.response!.id}-$receiverID-${DateTime.now().microsecondsSinceEpoch}.aac"; + recorderController = RecorderController() + ..androidEncoder = AndroidEncoder.aac + ..androidOutputFormat = AndroidOutputFormat.mpeg4 + ..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC + ..sampleRate = 6000 + ..updateFrequency = const Duration(milliseconds: 100) + ..bitRate = 18000; + playerController = PlayerController(); + } + + void disposeAudio() { + isRecoding = false; + isPlaying = false; + isPause = false; + isVoiceMsg = false; + recorderController.dispose(); + playerController.dispose(); + } + + void startRecoding(BuildContext context) async { + await Permission.microphone.request().then((PermissionStatus status) { + if (status.isPermanentlyDenied) { + Utils.confirmDialog( + context, + "The app needs microphone access to be able to record audio.", + onTap: () { + Navigator.of(context).pop(); + openAppSettings(); + }, + ); + } else if (status.isDenied) { + Utils.confirmDialog( + context, + "The app needs microphone access to be able to record audio.", + onTap: () { + Navigator.of(context).pop(); + openAppSettings(); + }, + ); + } else if (status.isGranted) { + sRecoding(); + } else { + startRecoding(context); + } + }); + } + + void sRecoding() async { + isVoiceMsg = true; + recorderController.reset(); + await recorderController.record(path: path); + _recodeDuration = 0; + _startTimer(); + isRecoding = !isRecoding; + notifyListeners(); + } + + Future _startTimer() async { + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) async { + _recodeDuration++; + if (_recodeDuration <= 59) { + applyCounter(); + } else { + pauseRecoding(); + } + }); + } + + void applyCounter() { + buildTimer(); + notifyListeners(); + } + + Future pauseRecoding() async { + isPause = true; + isPlaying = true; + recorderController.pause(); + path = await recorderController.stop(false); + File file = File(path!); + file.readAsBytesSync(); + path = file.path; + await playerController.preparePlayer(path: file.path, volume: 1.0); + _timer?.cancel(); + notifyListeners(); + } + + Future deleteRecoding() async { + _recodeDuration = 0; + _timer?.cancel(); + if (path == null) { + path = await recorderController.stop(true); + } else { + await recorderController.stop(true); + } + if (path != null && path!.isNotEmpty) { + File delFile = File(path!); + double fileSizeInKB = delFile.lengthSync() / 1024; + double fileSizeInMB = fileSizeInKB / 1024; + if (kDebugMode) { + debugPrint("Deleted file size: ${delFile.lengthSync()}"); + debugPrint("Deleted file size in KB: " + fileSizeInKB.toString()); + debugPrint("Deleted file size in MB: " + fileSizeInMB.toString()); + } + if (await delFile.exists()) { + delFile.delete(); + } + isPause = false; + isRecoding = false; + isPlaying = false; + isVoiceMsg = false; + notifyListeners(); + } + } + + String buildTimer() { + String minutes = _formatNum(_recodeDuration ~/ 60); + String seconds = _formatNum(_recodeDuration % 60); + return '$minutes : $seconds'; + } + + String _formatNum(int number) { + String numberStr = number.toString(); + if (number < 10) { + numberStr = '0' + numberStr; + } + return numberStr; + } + + Future downChatVoice(Uint8List bytes, String ext, SingleUserChatModel data) async { + File file; + try { + String dirPath = '${(await getApplicationDocumentsDirectory()).path}/chat_audios'; + if (!await Directory(dirPath).exists()) { + await Directory(dirPath).create(); + await File('$dirPath/.nomedia').create(); + } + file = File("$dirPath/${data.currentUserId}-${data.targetUserId}-${DateTime.now().microsecondsSinceEpoch}" + ext); + await file.writeAsBytes(bytes); + } catch (e) { + if (kDebugMode) { + print(e); + } + file = File(""); + } + return file; + } + + void scrollToMsg(SingleUserChatModel data) { + if (data.userChatReplyResponse != null && data.userChatReplyResponse!.userChatHistoryId != null) { + int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == data.userChatReplyResponse!.userChatHistoryId); + if (index >= 1) { + double contentSize = scrollController.position.viewportDimension + scrollController.position.maxScrollExtent; + double target = contentSize * index / userChatHistory.length; + scrollController.position.animateTo( + target, + duration: const Duration(seconds: 1), + curve: Curves.easeInOut, + ); + } + } + } + + Future getTeamMembers() async { + teamMembersList = []; + isLoading = true; + if (AppState().getemployeeSubordinatesList.isNotEmpty) { + getEmployeeSubordinatesList = AppState().getemployeeSubordinatesList; + for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { + if (element.eMPLOYEEEMAILADDRESS != null) { + if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { + teamMembersList.add( + ChatUser( + id: int.parse(element.eMPLOYEENUMBER!), + email: element.eMPLOYEEEMAILADDRESS, + userName: element.eMPLOYEENAME, + phone: element.eMPLOYEEMOBILENUMBER, + userStatus: 0, + unreadMessageCount: 0, + isFav: false, + isTyping: false, + isImageLoading: false, + image: element.eMPLOYEEIMAGE ?? "", + isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, + userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), + ), + ); + } + } + } + } else { + getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates("", "", ""); + AppState().setemployeeSubordinatesList = getEmployeeSubordinatesList; + for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { + if (element.eMPLOYEEEMAILADDRESS != null) { + if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { + teamMembersList.add( + ChatUser( + id: int.parse(element.eMPLOYEENUMBER!), + email: element.eMPLOYEEEMAILADDRESS, + userName: element.eMPLOYEENAME, + phone: element.eMPLOYEEMOBILENUMBER, + userStatus: 0, + unreadMessageCount: 0, + isFav: false, + isTyping: false, + isImageLoading: false, + image: element.eMPLOYEEIMAGE ?? "", + isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, + userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), + ), + ); + } + } + } + } + + for (ChatUser user in searchedChats!) { + for (ChatUser teamUser in teamMembersList!) { + if (user.id == teamUser.id) { + teamUser.userStatus = user.userStatus; + } + } + } + + isLoading = false; + notifyListeners(); + } + + void inputBoxDirection(String val) { + if (val.isNotEmpty) { + isTextMsg = true; + } else { + isTextMsg = false; + } + msgText = val; + notifyListeners(); + } + + void onDirectionChange(bool val) { + isRTL = val; + notifyListeners(); + } + + Material.TextDirection getTextDirection(String v) { + String str = v.trim(); + if (str.isEmpty) return Material.TextDirection.ltr; + int firstUnit = str.codeUnitAt(0); + if (firstUnit > 0x0600 && firstUnit < 0x06FF || + firstUnit > 0x0750 && firstUnit < 0x077F || + firstUnit > 0x07C0 && firstUnit < 0x07EA || + firstUnit > 0x0840 && firstUnit < 0x085B || + firstUnit > 0x08A0 && firstUnit < 0x08B4 || + firstUnit > 0x08E3 && firstUnit < 0x08FF || + firstUnit > 0xFB50 && firstUnit < 0xFBB1 || + firstUnit > 0xFBD3 && firstUnit < 0xFD3D || + firstUnit > 0xFD50 && firstUnit < 0xFD8F || + firstUnit > 0xFD92 && firstUnit < 0xFDC7 || + firstUnit > 0xFDF0 && firstUnit < 0xFDFC || + firstUnit > 0xFE70 && firstUnit < 0xFE74 || + firstUnit > 0xFE76 && firstUnit < 0xFEFC || + firstUnit > 0x10800 && firstUnit < 0x10805 || + firstUnit > 0x1B000 && firstUnit < 0x1B0FF || + firstUnit > 0x1D165 && firstUnit < 0x1D169 || + firstUnit > 0x1D16D && firstUnit < 0x1D172 || + firstUnit > 0x1D17B && firstUnit < 0x1D182 || + firstUnit > 0x1D185 && firstUnit < 0x1D18B || + firstUnit > 0x1D1AA && firstUnit < 0x1D1AD || + firstUnit > 0x1D242 && firstUnit < 0x1D244) { + return Material.TextDirection.rtl; + } + return Material.TextDirection.ltr; + } + + void openChatByNoti(BuildContext context) async { + SingleUserChatModel nUser = SingleUserChatModel(); + Utils.saveStringFromPrefs("isAppOpendByChat", "false"); + if (await Utils.getStringFromPrefs("notificationData") != "null") { + nUser = SingleUserChatModel.fromJson(jsonDecode(await Utils.getStringFromPrefs("notificationData"))); + Utils.saveStringFromPrefs("notificationData", "null"); + Future.delayed(const Duration(seconds: 2)); + for (ChatUser user in searchedChats!) { + if (user.id == nUser.targetUserId) { + Navigator.pushNamed(context, AppRoutes.chatDetailed, arguments: ChatDetailedScreenParams(user, false)); + return; + } + } + } + Utils.saveStringFromPrefs("notificationData", "null"); + } + + //group chat functions added here + + void filterGroups(String value) async { + // filter function added here. + List tmp = []; + if (value.isEmpty || value == "") { + tmp = userGroups.groupresponse!; + } else { + for (groups.GroupResponse element in uGroups!) { + if (element.groupName!.toLowerCase().contains(value.toLowerCase())) { + tmp.add(element); + } + } + } + uGroups = tmp; + notifyListeners(); + } + + Future deleteGroup(GroupResponse groupDetails) async { + isLoading = true; + await ChatApiClient().deleteGroup(groupDetails.groupId); + userGroups = await ChatApiClient().getGroupsByUserId(); + uGroups = userGroups.groupresponse; + isLoading = false; + notifyListeners(); + } + + Future getGroupChatHistory(groups.GroupResponse groupDetails) async { + isLoading = true; + groupChatHistory = await ChatApiClient().getGroupChatHistory(groupDetails.groupId, groupDetails.groupUserList as List); + + isLoading = false; + + notifyListeners(); + } + + void updateGroupAdmin(int? groupId, List groupUserList) async { + isLoading = true; + await ChatApiClient().updateGroupAdmin(groupId, groupUserList); + isLoading = false; + notifyListeners(); + } + + Future addGroupAndUsers(createGroup.CreateGroupRequest request) async { + isLoading = true; + var groups = await ChatApiClient().addGroupAndUsers(request); + userGroups.groupresponse!.add(GroupResponse.fromJson(json.decode(groups)['response'])); + + isLoading = false; + notifyListeners(); + } + + Future updateGroupAndUsers(createGroup.CreateGroupRequest request) async { + isLoading = true; + await ChatApiClient().updateGroupAndUsers(request); + userGroups = await ChatApiClient().getGroupsByUserId(); + uGroups = userGroups.groupresponse; + isLoading = false; + notifyListeners(); + } +} diff --git a/lib/modules/cx_module/chat/model/get_search_user_chat_model.dart b/lib/modules/cx_module/chat/model/get_search_user_chat_model.dart new file mode 100644 index 00000000..7c638e9e --- /dev/null +++ b/lib/modules/cx_module/chat/model/get_search_user_chat_model.dart @@ -0,0 +1,137 @@ +import 'dart:convert'; +import 'dart:io'; + +ChatUserModel chatUserModelFromJson(String str) => ChatUserModel.fromJson(json.decode(str)); + +String chatUserModelToJson(ChatUserModel data) => json.encode(data.toJson()); + +class ChatUserModel { + ChatUserModel({ + this.response, + this.errorResponses, + }); + + List? response; + List? errorResponses; + + factory ChatUserModel.fromJson(Map json) => ChatUserModel( + response: json["response"] == null ? null : List.from(json["response"].map((x) => ChatUser.fromJson(x))), + errorResponses: json["errorResponses"] == null ? null : List.from(json["errorResponses"].map((x) => ErrorResponse.fromJson(x))), + ); + + Map toJson() => { + "response": response == null ? null : List.from(response!.map((x) => x.toJson())), + "errorResponses": errorResponses == null ? null : List.from(errorResponses!.map((x) => x.toJson())), + }; +} + +class ErrorResponse { + ErrorResponse({ + this.fieldName, + this.message, + }); + + dynamic? fieldName; + String? message; + + factory ErrorResponse.fromRawJson(String str) => ErrorResponse.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory ErrorResponse.fromJson(Map json) => ErrorResponse( + fieldName: json["fieldName"], + message: json["message"] == null ? null : json["message"], + ); + + Map toJson() => { + "fieldName": fieldName, + "message": message == null ? null : message, + }; +} + +class ChatUser { + ChatUser({ + this.id, + this.userName, + this.email, + this.phone, + this.title, + this.userStatus, + this.image, + this.unreadMessageCount, + this.userAction, + this.isPin, + this.isFav, + this.isAdmin, + this.rKey, + this.totalCount, + this.isTyping, + this.isImageLoaded, + this.isImageLoading, + this.userLocalDownlaodedImage, + this.isChecked + }); + + int? id; + String? userName; + String? email; + dynamic? phone; + String? title; + int? userStatus; + dynamic? image; + int? unreadMessageCount; + dynamic? userAction; + bool? isPin; + bool? isFav; + bool? isAdmin; + dynamic? rKey; + int? totalCount; + bool? isTyping; + bool? isImageLoaded; + bool? isImageLoading; + File? userLocalDownlaodedImage; + bool? isChecked; + factory ChatUser.fromRawJson(String str) => ChatUser.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory ChatUser.fromJson(Map json) => ChatUser( + id: json["id"] == null ? null : json["id"], + userName: json["userName"] == null ? null : json["userName"], + email: json["email"] == null ? null : json["email"], + phone: json["phone"], + title: json["title"] == null ? null : json["title"], + userStatus: json["userStatus"] == null ? null : json["userStatus"], + image: json["image"], + unreadMessageCount: json["unreadMessageCount"] == null ? null : json["unreadMessageCount"], + userAction: json["userAction"], + isPin: json["isPin"] == null ? null : json["isPin"], + isFav: json["isFav"] == null ? null : json["isFav"], + isAdmin: json["isAdmin"] == null ? null : json["isAdmin"], + rKey: json["rKey"], + totalCount: json["totalCount"] == null ? null : json["totalCount"], + isTyping: false, + isImageLoaded: false, + isImageLoading: true, + userLocalDownlaodedImage: null, + isChecked: false + ); + + Map toJson() => { + "id": id == null ? null : id, + "userName": userName == null ? null : userName, + "email": email == null ? null : email, + "phone": phone, + "title": title == null ? null : title, + "userStatus": userStatus == null ? null : userStatus, + "image": image, + "unreadMessageCount": unreadMessageCount == null ? null : unreadMessageCount, + "userAction": userAction, + "isPin": isPin == null ? null : isPin, + "isFav": isFav == null ? null : isFav, + "isAdmin": isAdmin == null ? null : isAdmin, + "rKey": rKey, + "totalCount": totalCount == null ? null : totalCount, + "isChecked":isChecked + }; +} diff --git a/lib/modules/cx_module/chat/model/get_single_user_chat_list_model.dart b/lib/modules/cx_module/chat/model/get_single_user_chat_list_model.dart new file mode 100644 index 00000000..3722c093 --- /dev/null +++ b/lib/modules/cx_module/chat/model/get_single_user_chat_list_model.dart @@ -0,0 +1,206 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'package:just_audio/just_audio.dart'; + +List singleUserChatModelFromJson(String str) => List.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); + +String singleUserChatModelToJson(List data) => json.encode(List.from(data.map((x) => x.toJson()))); + +class SingleUserChatModel { + SingleUserChatModel( + {this.userChatHistoryId, + this.userChatHistoryLineId, + this.contant, + this.contantNo, + this.currentUserId, + this.currentUserName, + this.targetUserId, + this.targetUserName, + this.encryptedTargetUserId, + this.encryptedTargetUserName, + this.currentUserEmail, + this.targetUserEmail, + this.chatEventId, + this.fileTypeId, + this.isSeen, + this.isDelivered, + this.createdDate, + this.chatSource, + this.conversationId, + this.fileTypeResponse, + this.userChatReplyResponse, + this.isReplied, + this.isImageLoaded, + this.image, + this.voice, + this.voiceController}); + + int? userChatHistoryId; + int? userChatHistoryLineId; + String? contant; + String? contantNo; + int? currentUserId; + String? currentUserName; + String? currentUserEmail; + int? targetUserId; + String? targetUserName; + String? targetUserEmail; + String? encryptedTargetUserId; + String? encryptedTargetUserName; + int? chatEventId; + dynamic? fileTypeId; + bool? isSeen; + bool? isDelivered; + DateTime? createdDate; + int? chatSource; + String? conversationId; + FileTypeResponse? fileTypeResponse; + UserChatReplyResponse? userChatReplyResponse; + bool? isReplied; + bool? isImageLoaded; + Uint8List? image; + File? voice; + AudioPlayer? voiceController; + + factory SingleUserChatModel.fromJson(Map json) => SingleUserChatModel( + userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], + userChatHistoryLineId: json["userChatHistoryLineId"] == null ? null : json["userChatHistoryLineId"], + contant: json["contant"] == null ? null : json["contant"], + contantNo: json["contantNo"] == null ? null : json["contantNo"], + currentUserId: json["currentUserId"] == null ? null : json["currentUserId"], + currentUserName: json["currentUserName"] == null ? null : json["currentUserName"], + targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], + targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], + targetUserEmail: json["targetUserEmail"] == null ? null : json["targetUserEmail"], + currentUserEmail: json["currentUserEmail"] == null ? null : json["currentUserEmail"], + encryptedTargetUserId: json["encryptedTargetUserId"] == null ? null : json["encryptedTargetUserId"], + encryptedTargetUserName: json["encryptedTargetUserName"] == null ? null : json["encryptedTargetUserName"], + chatEventId: json["chatEventId"] == null ? null : json["chatEventId"], + fileTypeId: json["fileTypeId"], + isSeen: json["isSeen"] == null ? null : json["isSeen"], + isDelivered: json["isDelivered"] == null ? null : json["isDelivered"], + createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), + chatSource: json["chatSource"] == null ? null : json["chatSource"], + conversationId: json["conversationId"] == null ? null : json["conversationId"], + fileTypeResponse: json["fileTypeResponse"] == null ? null : FileTypeResponse.fromJson(json["fileTypeResponse"]), + userChatReplyResponse: json["userChatReplyResponse"] == null ? null : UserChatReplyResponse.fromJson(json["userChatReplyResponse"]), + isReplied: false, + isImageLoaded: false, + image: null, + voice: null, + voiceController: json["fileTypeId"] == 13 ? AudioPlayer() : null); + + Map toJson() => { + "userChatHistoryId": userChatHistoryId == null ? null : userChatHistoryId, + "userChatHistoryLineId": userChatHistoryLineId == null ? null : userChatHistoryLineId, + "contant": contant == null ? null : contant, + "contantNo": contantNo == null ? null : contantNo, + "currentUserId": currentUserId == null ? null : currentUserId, + "currentUserName": currentUserName == null ? null : currentUserName, + "targetUserId": targetUserId == null ? null : targetUserId, + "targetUserName": targetUserName == null ? null : targetUserName, + "encryptedTargetUserId": encryptedTargetUserId == null ? null : encryptedTargetUserId, + "encryptedTargetUserName": encryptedTargetUserName == null ? null : encryptedTargetUserName, + "currentUserEmail": currentUserEmail == null ? null : currentUserEmail, + "targetUserEmail": targetUserEmail == null ? null : targetUserEmail, + "chatEventId": chatEventId == null ? null : chatEventId, + "fileTypeId": fileTypeId, + "isSeen": isSeen == null ? null : isSeen, + "isDelivered": isDelivered == null ? null : isDelivered, + "createdDate": createdDate == null ? null : createdDate!.toIso8601String(), + "chatSource": chatSource == null ? null : chatSource, + "conversationId": conversationId == null ? null : conversationId, + "fileTypeResponse": fileTypeResponse == null ? null : fileTypeResponse!.toJson(), + "userChatReplyResponse": userChatReplyResponse == null ? null : userChatReplyResponse!.toJson(), + }; +} + +class FileTypeResponse { + FileTypeResponse({ + this.fileTypeId, + this.fileTypeName, + this.fileTypeDescription, + this.fileKind, + this.fileName, + }); + + int? fileTypeId; + dynamic fileTypeName; + dynamic fileTypeDescription; + dynamic fileKind; + dynamic fileName; + + factory FileTypeResponse.fromJson(Map json) => FileTypeResponse( + fileTypeId: json["fileTypeId"] == null ? null : json["fileTypeId"], + fileTypeName: json["fileTypeName"], + fileTypeDescription: json["fileTypeDescription"], + fileKind: json["fileKind"], + fileName: json["fileName"], + ); + + Map toJson() => { + "fileTypeId": fileTypeId == null ? null : fileTypeId, + "fileTypeName": fileTypeName, + "fileTypeDescription": fileTypeDescription, + "fileKind": fileKind, + "fileName": fileName, + }; +} + +class UserChatReplyResponse { + UserChatReplyResponse( + {this.userChatHistoryId, + this.chatEventId, + this.contant, + this.contantNo, + this.fileTypeId, + this.createdDate, + this.targetUserId, + this.targetUserName, + this.fileTypeResponse, + this.isImageLoaded, + this.image, + this.voice}); + + int? userChatHistoryId; + int? chatEventId; + String? contant; + String? contantNo; + dynamic? fileTypeId; + DateTime? createdDate; + int? targetUserId; + String? targetUserName; + FileTypeResponse? fileTypeResponse; + bool? isImageLoaded; + Uint8List? image; + Uint8List? voice; + + factory UserChatReplyResponse.fromJson(Map json) => UserChatReplyResponse( + userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], + chatEventId: json["chatEventId"] == null ? null : json["chatEventId"], + contant: json["contant"] == null ? null : json["contant"], + contantNo: json["contantNo"] == null ? null : json["contantNo"], + fileTypeId: json["fileTypeId"], + createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), + targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], + targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], + fileTypeResponse: json["fileTypeResponse"] == null ? null : FileTypeResponse.fromJson(json["fileTypeResponse"]), + isImageLoaded: false, + image: null, + voice: null, + ); + + Map toJson() => { + "userChatHistoryId": userChatHistoryId == null ? null : userChatHistoryId, + "chatEventId": chatEventId == null ? null : chatEventId, + "contant": contant == null ? null : contant, + "contantNo": contantNo == null ? null : contantNo, + "fileTypeId": fileTypeId, + "createdDate": createdDate == null ? null : createdDate!.toIso8601String(), + "targetUserId": targetUserId == null ? null : targetUserId, + "targetUserName": targetUserName == null ? null : targetUserName, + "fileTypeResponse": fileTypeResponse == null ? null : fileTypeResponse!.toJson(), + }; +} diff --git a/lib/modules/cx_module/chat/model/get_user_login_token_model.dart b/lib/modules/cx_module/chat/model/get_user_login_token_model.dart new file mode 100644 index 00000000..f0620c3b --- /dev/null +++ b/lib/modules/cx_module/chat/model/get_user_login_token_model.dart @@ -0,0 +1,97 @@ +import 'dart:convert'; + +UserAutoLoginModel userAutoLoginModelFromJson(String str) => UserAutoLoginModel.fromJson(json.decode(str)); + +String userAutoLoginModelToJson(UserAutoLoginModel data) => json.encode(data.toJson()); + +class UserAutoLoginModel { + UserAutoLoginModel({this.response, this.errorResponses, this.StatusCode}); + + Response? response; + List? errorResponses; + int? StatusCode; + + factory UserAutoLoginModel.fromJson(Map json) => UserAutoLoginModel( + response: json["response"] == null ? null : Response.fromJson(json["response"]), + StatusCode: json["StatusCode"], + errorResponses: json["errorResponses"] == null ? null : List.from(json["errorResponses"].map((x) => ErrorResponse.fromJson(x))), + ); + + Map toJson() => { + "response": response == null ? null : response!.toJson(), + "StatusCode": StatusCode, + "errorResponses": errorResponses == null ? null : List.from(errorResponses!.map((x) => x.toJson())), + }; +} + +class Response { + Response({ + this.id, + this.userName, + this.email, + this.phone, + this.title, + this.token, + this.isDomainUser, + this.isActiveCode, + this.encryptedUserId, + this.encryptedUserName, + }); + + int? id; + String? userName; + String? email; + String? phone; + String? title; + String? token; + bool? isDomainUser; + bool? isActiveCode; + String? encryptedUserId; + String? encryptedUserName; + + factory Response.fromJson(Map json) => Response( + id: json["id"] == null ? null : json["id"], + userName: json["userName"] == null ? null : json["userName"], + email: json["email"] == null ? null : json["email"], + phone: json["phone"] == null ? null : json["phone"], + title: json["title"] == null ? null : json["title"], + token: json["token"] == null ? null : json["token"], + isDomainUser: json["isDomainUser"] == null ? null : json["isDomainUser"], + isActiveCode: json["isActiveCode"] == null ? null : json["isActiveCode"], + encryptedUserId: json["encryptedUserId"] == null ? null : json["encryptedUserId"], + encryptedUserName: json["encryptedUserName"] == null ? null : json["encryptedUserName"], + ); + + Map toJson() => { + "id": id == null ? null : id, + "userName": userName == null ? null : userName, + "email": email == null ? null : email, + "phone": phone == null ? null : phone, + "title": title == null ? null : title, + "token": token == null ? null : token, + "isDomainUser": isDomainUser == null ? null : isDomainUser, + "isActiveCode": isActiveCode == null ? null : isActiveCode, + "encryptedUserId": encryptedUserId == null ? null : encryptedUserId, + "encryptedUserName": encryptedUserName == null ? null : encryptedUserName, + }; +} + +class ErrorResponse { + ErrorResponse({ + this.fieldName, + this.message, + }); + + String? fieldName; + String? message; + + factory ErrorResponse.fromJson(Map json) => ErrorResponse( + fieldName: json["fieldName"] == null ? null : json["fieldName"], + message: json["message"] == null ? null : json["message"], + ); + + Map toJson() => { + "fieldName": fieldName == null ? null : fieldName, + "message": message == null ? null : message, + }; +} diff --git a/pubspec.lock b/pubspec.lock index 7d69171a..1693c075 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -949,6 +949,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.4.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" lottie: dependency: "direct main" description: @@ -973,6 +981,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.11.1" + message_pack_dart: + dependency: transitive + description: + name: message_pack_dart + sha256: "71b9f0ff60e5896e60b337960bb535380d7dba3297b457ac763ccae807385b59" + url: "https://pub.dev" + source: hosted + version: "2.0.1" meta: dependency: transitive description: @@ -1293,6 +1309,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.10.2+1" + pool: + dependency: transitive + description: + name: pool + sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + url: "https://pub.dev" + source: hosted + version: "1.5.2" provider: dependency: "direct main" description: @@ -1429,6 +1453,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.4.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" shimmer: dependency: "direct main" description: @@ -1437,6 +1469,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" + signalr_netcore: + dependency: "direct main" + description: + name: signalr_netcore + sha256: "8d59dc61284c5ff8aa27c4e3e802fcf782367f06cf42b39d5ded81680b72f8b8" + url: "https://pub.dev" + source: hosted + version: "1.4.4" signature: dependency: "direct main" description: @@ -1506,6 +1546,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.5.4+4" + sse: + dependency: transitive + description: + name: sse + sha256: fcc97470240bb37377f298e2bd816f09fd7216c07928641c0560719f50603643 + url: "https://pub.dev" + source: hosted + version: "4.1.8" + sse_channel: + dependency: transitive + description: + name: sse_channel + sha256: "9aad5d4eef63faf6ecdefb636c0f857bd6f74146d2196087dcf4b17ab5b49b1b" + url: "https://pub.dev" + source: hosted + version: "0.1.1" stack_trace: dependency: transitive description: @@ -1578,6 +1634,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.0" + tuple: + dependency: transitive + description: + name: tuple + sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151 + url: "https://pub.dev" + source: hosted + version: "2.0.2" typed_data: dependency: transitive description: @@ -1714,6 +1778,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" wifi_iot: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index f766ebde..424aecc3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -97,6 +97,8 @@ dependencies: clipboard: ^2.0.2 audio_waveforms: ^1.3.0 + signalr_netcore: ^1.4.4 + local_auth_darwin: any dev_dependencies: flutter_test: