diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 95b2085c..563de659 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -17,6 +17,7 @@ class URLs { // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation static const String chatHubUrl = "https://apiderichat.hmg.com/chathub"; + static const String chatHubUrlApi = "$chatHubUrl/api"; // new V2 apis static const String chatHubUrlChat = "$chatHubUrl/hubs/chat"; // new V2 apis static const String chatApiKey = "f53a98286f82798d588f67a7f0db19f7aebc839e"; // new V2 apis diff --git a/lib/extensions/string_extensions.dart b/lib/extensions/string_extensions.dart index 16ae3fec..855560d1 100644 --- a/lib/extensions/string_extensions.dart +++ b/lib/extensions/string_extensions.dart @@ -7,17 +7,17 @@ extension StringExtensions on String { void get showToast => Fluttertoast.showToast(msg: this); String get chatMsgTime { - DateTime dateTime = DateTime.parse(this); + DateTime dateTime = DateTime.parse(this).toLocal(); return DateFormat('hh:mm a').format(dateTime); } String get chatMsgDate { - DateTime dateTime = DateTime.parse(this); + DateTime dateTime = DateTime.parse(this).toLocal(); return DateFormat('EEE dd MMM').format(dateTime); } String get chatMsgDateWithYear { - DateTime dateTime = DateTime.parse(this); + DateTime dateTime = DateTime.parse(this).toLocal(); return DateFormat('EEE dd MMM, yyyy').format(dateTime); } diff --git a/lib/extensions/widget_extensions.dart b/lib/extensions/widget_extensions.dart index 8caa8ccf..3fd48cd8 100644 --- a/lib/extensions/widget_extensions.dart +++ b/lib/extensions/widget_extensions.dart @@ -79,13 +79,15 @@ extension WidgetExtensions on Widget { : this; } - Widget toShimmer({bool isShow = true, double radius = 20, required BuildContext context}) => isShow + Widget toShimmer({bool isShow = true, double radius = 20, double? width, double? height, required BuildContext context}) => isShow ? Shimmer.fromColors( baseColor: context.isDark ? AppColor.backgroundDark : const Color(0xffe8eff0), highlightColor: AppColor.background(context), child: ClipRRect( borderRadius: BorderRadius.circular(radius), child: Container( + width: width, + height: height, color: AppColor.background(context), child: this, ), diff --git a/lib/modules/cm_module/views/service_request_detail_main_view.dart b/lib/modules/cm_module/views/service_request_detail_main_view.dart index 1f129652..e13d41eb 100644 --- a/lib/modules/cm_module/views/service_request_detail_main_view.dart +++ b/lib/modules/cm_module/views/service_request_detail_main_view.dart @@ -12,6 +12,7 @@ import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_mo import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart'; import 'package:test_sa/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart'; import 'package:test_sa/modules/cx_module/chat/chat_page.dart'; +import 'package:test_sa/modules/cx_module/chat/chat_provider.dart'; import 'package:test_sa/modules/cx_module/survey/survey_page.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; @@ -90,13 +91,35 @@ class _ServiceRequestDetailMainState extends State { Navigator.push(context, CupertinoPageRoute(builder: (context) => SurveyPage(moduleId: 1, requestId: widget.requestId, surveyId: 5))); }, ), - IconButton( - icon: const Icon(Icons.chat_bubble), - onPressed: () { - Navigator.push( - context, CupertinoPageRoute(builder: (context) => ChatPage(moduleId: 1, requestId: widget.requestId, title: _requestProvider.currentWorkOrder?.data?.workOrderNo ?? ""))); - }, - ), + Selector( + selector: (_, myModel) => myModel.isLoading, // Selects only the userName + builder: (_, isLoading, __) { + if (isLoading) { + return const SizedBox(); + } else { + ServiceRequestDetailProvider provider = Provider.of(context, listen: false); + if (provider.currentWorkOrder?.data?.status?.value == 2) { + getChatToken(1, provider.currentWorkOrder?.data?.workOrderNo ?? ""); + return Consumer(builder: (pContext, requestProvider, _) { + return IconButton( + icon: const Icon(Icons.chat_bubble), + onPressed: () { + Navigator.push( + context, + CupertinoPageRoute( + builder: (context) => ChatPage( + moduleId: 1, + requestId: widget.requestId, + title: _requestProvider.currentWorkOrder?.data?.workOrderNo ?? "", + readOnly: _requestProvider.isReadOnlyRequest, + ))); + }, + ).toShimmer(context: context, isShow: requestProvider.chatLoginTokenLoading, radius: 30, height: 30, width: 30); + }); + } + return const SizedBox(); + } + }), isNurse ? IconButton( icon: 'qr'.toSvgAsset( @@ -156,4 +179,21 @@ class _ServiceRequestDetailMainState extends State { )), ); } + + void getChatToken(int moduleId, String title) { + ChatProvider cProvider = Provider.of(context, listen: false); + if (cProvider.chatLoginResponse != null) return; + String assigneeEmployeeNumber = Provider.of(context, listen: false).currentWorkOrder?.data?.assignedEmployee?.employeeId ?? ""; + String myEmployeeId = context.userProvider.user!.username!; + + // String sender = context.settingProvider.username; + String receiver = context.userProvider.isNurse + ? assigneeEmployeeNumber + : (context.userProvider.isEngineer ? Provider.of(context, listen: false).currentWorkOrder!.data!.workOrderContactPerson.first.employeeId! : ""); + + // assigneeEmployeeNumber + // ChatProvider cProvider = Provider.of(context, listen: false); + // Provider.of(context, listen: false).getUserAutoLoginToken(widget.moduleId, widget.requestId, widget.title, myEmployeeId, assigneeEmployeeNumber); + cProvider.getUserAutoLoginTokenSilent(moduleId, widget.requestId, title, myEmployeeId, receiver); + } } diff --git a/lib/modules/cx_module/chat/chat_api_client.dart b/lib/modules/cx_module/chat/chat_api_client.dart index 9641b0ec..929f9946 100644 --- a/lib/modules/cx_module/chat/chat_api_client.dart +++ b/lib/modules/cx_module/chat/chat_api_client.dart @@ -13,6 +13,7 @@ import 'api_client.dart'; import 'model/chat_login_response_model.dart'; import 'model/chat_participant_model.dart'; import 'model/get_search_user_chat_model.dart'; +import 'model/get_single_user_chat_list_model.dart'; import 'model/get_user_login_token_model.dart' as userLoginTokenModel; import 'model/user_chat_history_model.dart'; @@ -74,14 +75,14 @@ class ChatApiClient { } } - Future> loadChatHistory(int moduleId, int referenceId, String myId, String otherId) async { + Future> loadChatHistory(int moduleId, int referenceId, String myId, String otherId) async { Response response = await ApiClient().postJsonForResponse( "${URLs.chatHubUrlApi}/UserChatHistory/GetUserChatHistory/$myId/$otherId/0", {"moduleCode": moduleId.toString(), "referenceId": referenceId.toString()}, token: chatLoginResponse!.token); // try { if (response.statusCode == 200) { List data = jsonDecode(response.body); - return data.map((elemet) => ChatHistoryResponse.fromJson(elemet)).toList(); + return data.map((elemet) => SingleUserChatModel.fromJson(elemet)).toList(); // return UserChatHistoryModel.fromJson(jsonDecode(response.body)); } else { @@ -92,7 +93,7 @@ class ChatApiClient { // } } - Future sendTextMessage(String message, int conversationId) async { +/* Future sendTextMessage(String message, int conversationId) async { try { Response response = await ApiClient().postJsonForResponse("${URLs.chatHubUrlApi}/chat/conversations/$conversationId/messages", {"content": message, "messageType": "Text"}, token: chatLoginResponse!.token); @@ -106,7 +107,7 @@ class ChatApiClient { print(ex); return null; } - } + }*/ // Future getChatMemberFromSearch(String searchParam, int cUserId, int pageNo) async { // ChatUserModel chatUserModel; diff --git a/lib/modules/cx_module/chat/chat_page.dart b/lib/modules/cx_module/chat/chat_page.dart index ef183c10..c1196027 100644 --- a/lib/modules/cx_module/chat/chat_page.dart +++ b/lib/modules/cx_module/chat/chat_page.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:audio_waveforms/audio_waveforms.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -15,6 +17,7 @@ import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; +import 'model/get_single_user_chat_list_model.dart'; import 'model/user_chat_history_model.dart'; enum ChatState { idle, voiceRecordingStarted, voiceRecordingCompleted } @@ -45,10 +48,12 @@ class _ChatPageState extends State { ChatState chatState = ChatState.idle; + late String receiver; + @override void initState() { super.initState(); - getChatToken(); + loadChatHistory(); playerController.addListener(() async { // if (playerController.playerState == PlayerState.playing && playerController.maxDuration == await playerController.getDuration()) { // await playerController.stopPlayer(); @@ -57,19 +62,14 @@ class _ChatPageState extends State { }); } - void getChatToken() { + void loadChatHistory() { String assigneeEmployeeNumber = Provider.of(context, listen: false).currentWorkOrder?.data?.assignedEmployee?.employeeId ?? ""; String myEmployeeId = context.userProvider.user!.username!; - // String sender = context.settingProvider.username; - String receiver = context.userProvider.isNurse + receiver = context.userProvider.isNurse ? assigneeEmployeeNumber : (context.userProvider.isEngineer ? Provider.of(context, listen: false).currentWorkOrder!.data!.workOrderContactPerson.first.employeeId! : ""); - - // assigneeEmployeeNumber - - // Provider.of(context, listen: false).getUserAutoLoginToken(widget.moduleId, widget.requestId, widget.title, myEmployeeId, assigneeEmployeeNumber); - Provider.of(context, listen: false).getUserAutoLoginToken(widget.moduleId, widget.requestId, widget.title, myEmployeeId, receiver); + Provider.of(context, listen: false).connectToHub(widget.moduleId, widget.requestId, myEmployeeId, receiver); } @override @@ -100,12 +100,10 @@ class _ChatPageState extends State { ), 24.height, AppFilledButton( - label: "Retry", + label: "Go Back", maxWidth: true, buttonColor: AppColor.primary10, - onPressed: () async { - getChatToken(); - }, + onPressed: () => Navigator.pop(context), ).paddingOnly(start: 48, end: 48) ], ).center; @@ -169,14 +167,14 @@ class _ChatPageState extends State { showDateHeader = true; } else { final nextMessage = chatProvider.chatResponseList[index + 1]; - final currentDate = DateUtils.dateOnly(DateTime.parse(currentMessage.createdDate!)); - final nextDate = DateUtils.dateOnly(DateTime.parse(nextMessage.createdDate!)); + final currentDate = DateUtils.dateOnly(currentMessage.createdDate!); + final nextDate = DateUtils.dateOnly(nextMessage.createdDate!); if (!currentDate.isAtSameMomentAs(nextDate)) { showDateHeader = true; } } return Column(mainAxisSize: MainAxisSize.min, children: [ - if (showDateHeader) dateCard(currentMessage.createdDate?.chatMsgDateWithYear ?? ""), + if (showDateHeader) dateCard(currentMessage.createdDate?.toString().chatMsgDateWithYear ?? ""), isSender ? senderMsgCard(showSenderName, chatProvider.chatResponseList[index]) : recipientMsgCard(showSenderName, chatProvider.chatResponseList[index]) ]); }, @@ -198,6 +196,9 @@ class _ChatPageState extends State { maxLines: 3, textInputAction: TextInputAction.none, keyboardType: TextInputType.multiline, + onChanged: (text) { + chatHubConnection.invoke("SendTypingAsync", args: [context.userProvider.user!.username!]); + }, decoration: InputDecoration( enabledBorder: InputBorder.none, focusedBorder: InputBorder.none, @@ -458,7 +459,19 @@ class _ChatPageState extends State { highlightColor: Colors.transparent, hoverColor: Colors.transparent, onPressed: () { - chatProvider.sendTextMessage(textEditingController.text).then((success) { + chatProvider.invokeSendMessage({ + "Contant": textEditingController.text, + // "ContantNo": "0cc8b126-6180-4f91-a64d-2f62443b3f3f", + // "CreatedDate": "2025-11-09T18:58:12.502Z", + "CurrentEmployeeNumber": context.userProvider.user!.username!, + "ChatEventId": 1, + "ConversationId": chatProvider.chatParticipantModel!.id!.toString(), + "ModuleCode": widget.moduleId.toString(), + "ReferenceNumber": widget.requestId.toString(), + "UserChatHistoryLineRequestList": [ + {"TargetEmployeeNumber": receiver, "TargetUserStatus": 1, "IsSeen": false, "IsDelivered": true, "SeenOn": null, "DeliveredOn": null} + ] + }).then((success) { if (success) { textEditingController.clear(); } @@ -499,7 +512,7 @@ class _ChatPageState extends State { .center; } - Widget senderMsgCard(bool showHeader, ChatHistoryResponse? chatResponse, {bool loading = false, String msg = ""}) { + Widget senderMsgCard(bool showHeader, SingleUserChatModel? chatResponse, {bool loading = false, String msg = ""}) { Widget senderHeader = Row( mainAxisSize: MainAxisSize.min, children: [ @@ -548,7 +561,7 @@ class _ChatPageState extends State { ).toShimmer(context: context, isShow: loading), if (loading) 4.height, Text( - chatResponse?.createdDate?.chatMsgTime ?? "2:00 PM", + chatResponse?.createdDate?.toString().chatMsgTime ?? "2:00 PM", style: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.neutral50.withOpacity(0.5)), ).toShimmer(context: context, isShow: loading), ], @@ -569,7 +582,7 @@ class _ChatPageState extends State { ); } - Widget recipientMsgCard(bool showHeader, ChatHistoryResponse? chatResponse, {bool loading = false, String msg = ""}) { + Widget recipientMsgCard(bool showHeader, SingleUserChatModel? chatResponse, {bool loading = false, String msg = ""}) { String extraSpaces = ""; int length = 0; if ((chatResponse?.contant ?? "").isNotEmpty) { @@ -624,7 +637,7 @@ class _ChatPageState extends State { alignment: Alignment.centerRight, widthFactor: 1, child: Text( - chatResponse?.createdDate?.chatMsgTime ?? "2:00 PM", + chatResponse?.createdDate?.toString().chatMsgTime ?? "2:00 PM", style: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.white10), ), ).toShimmer(context: context, isShow: loading), diff --git a/lib/modules/cx_module/chat/chat_provider.dart b/lib/modules/cx_module/chat/chat_provider.dart index c86c5096..84384087 100644 --- a/lib/modules/cx_module/chat/chat_provider.dart +++ b/lib/modules/cx_module/chat/chat_provider.dart @@ -116,11 +116,11 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { // UserChatHistoryModel? userChatHistory; - List? userChatHistory; + List? userChatHistory; bool messageIsSending = false; - List chatResponseList = []; + List chatResponseList = []; Participants? sender; Participants? recipient; @@ -137,41 +137,59 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { ChatApiClient().chatLoginResponse = null; } - Future getUserAutoLoginToken(int moduleId, int requestId, String title, String myId, String assigneeEmployeeNumber) async { + // Future getUserAutoLoginToken(int moduleId, int requestId, String title, String myId, String assigneeEmployeeNumber) async { + // reset(); + // chatLoginTokenLoading = true; + // notifyListeners(); + // chatLoginResponse = await ChatApiClient().getChatLoginToken(moduleId, requestId, title, myId); + // chatLoginTokenLoading = false; + // chatParticipantLoading = true; + // notifyListeners(); + // // loadParticipants(moduleId, requestId); + // if (chatLoginResponse != null) { + // await loadChatHistory(moduleId, requestId, myId, assigneeEmployeeNumber); + // } + // } + + Future getUserAutoLoginTokenSilent(int moduleId, int requestId, String title, String myId, String assigneeEmployeeNumber) async { reset(); chatLoginTokenLoading = true; notifyListeners(); - chatLoginResponse = await ChatApiClient().getChatLoginToken(moduleId, requestId, title, myId); + try { + chatLoginResponse = await ChatApiClient().getChatLoginToken(moduleId, requestId, title, myId); + chatParticipantModel = await ChatApiClient().loadParticipants(moduleId, requestId, assigneeEmployeeNumber); + sender = chatParticipantModel?.participants?.singleWhere((participant) => participant.employeeNumber == myId); + recipient = chatParticipantModel?.participants?.singleWhere((participant) => participant.employeeNumber == assigneeEmployeeNumber); + } catch (ex) {} chatLoginTokenLoading = false; - chatParticipantLoading = true; notifyListeners(); - // loadParticipants(moduleId, requestId); - loadChatHistory(moduleId, requestId, myId, assigneeEmployeeNumber); } - // Future loadParticipants(int moduleId, int requestId) async { - // // loadChatHistoryLoading = true; - // // notifyListeners(); - // chatParticipantModel = await ChatApiClient().loadParticipants(moduleId, requestId); - // chatParticipantLoading = false; + // Future getUserLoadChatHistory(int moduleId, int requestId, String myId, String assigneeEmployeeNumber) async { + // await loadChatHistory(moduleId, requestId, myId, assigneeEmployeeNumber); + // } + + // Future loadParticipants(int moduleId, int requestId, String myId, String assigneeEmployeeNumber) async { + // userChatHistoryLoading = true; // notifyListeners(); + // try { + // chatParticipantModel = await ChatApiClient().loadParticipants(moduleId, requestId, assigneeEmployeeNumber); + // } catch (ex) { + // userChatHistoryLoading = false; + // notifyListeners(); + // return; + // } + // + // try { + // sender = chatParticipantModel?.participants?.singleWhere((participant) => participant.employeeNumber == myId); + // recipient = chatParticipantModel?.participants?.singleWhere((participant) => participant.employeeNumber == assigneeEmployeeNumber); + // } catch (e) {} // } - Future loadChatHistory(int moduleId, int requestId, String myId, String assigneeEmployeeNumber) async { + Future connectToHub(int moduleId, int requestId, String myId, String assigneeEmployeeNumber) async { userChatHistoryLoading = true; notifyListeners(); - try { - chatParticipantModel = await ChatApiClient().loadParticipants(moduleId, requestId, assigneeEmployeeNumber); - } catch (ex) { - userChatHistoryLoading = false; - notifyListeners(); - return; - } - - try { - sender = chatParticipantModel?.participants?.singleWhere((participant) => participant.employeeNumber == myId); - recipient = chatParticipantModel?.participants?.singleWhere((participant) => participant.employeeNumber == assigneeEmployeeNumber); - } catch (e) {} + await buildHubConnection(chatParticipantModel!.id!.toString()); userChatHistory = await ChatApiClient().loadChatHistory(moduleId, requestId, myId, assigneeEmployeeNumber); chatResponseList = userChatHistory ?? []; chatResponseList.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); @@ -179,23 +197,64 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { notifyListeners(); } - Future sendTextMessage(String message) async { + // Future loadChatHistory(int moduleId, int requestId, String myId, String assigneeEmployeeNumber) async { + // userChatHistoryLoading = true; + // notifyListeners(); + // userChatHistory = await ChatApiClient().loadChatHistory(moduleId, requestId, myId, assigneeEmployeeNumber); + // chatResponseList = userChatHistory ?? []; + // chatResponseList.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); + // userChatHistoryLoading = false; + // notifyListeners(); + // } + + Future invokeSendMessage(Object object) async { messageIsSending = true; notifyListeners(); bool returnStatus = false; - ChatResponse? chatResponse = await ChatApiClient().sendTextMessage(message, chatParticipantModel!.id!); - if (chatResponse != null) { + try { + await chatHubConnection.invoke("AddChatUserAsync", args: [object]); returnStatus = true; - // chatResponseList.add(chatResponse); - try { - chatResponseList.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); - } catch (ex) {} - } + } catch (ex) {} + messageIsSending = false; notifyListeners(); return returnStatus; } + // Future sendTextMessage(String message) async { + // messageIsSending = true; + // notifyListeners(); + // bool returnStatus = false; + // + // ChatResponse? chatResponse = await ChatApiClient().sendTextMessage(message, chatParticipantModel!.id!); + // if (chatResponse != null) { + // returnStatus = true; + // // chatResponseList.add(chatResponse); + // try { + // chatResponseList.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); + // } catch (ex) {} + // } + // messageIsSending = false; + // notifyListeners(); + // return returnStatus; + // } + + void sendMsgSignalR() { + var abc = { + "Contant": "Follow-up: Test results look good.", + "ContantNo": "0cc8b126-6180-4f91-a64d-2f62443b3f3f", + "CreatedDate": "2025-11-09T18:58:12.502Z", + "CurrentEmployeeNumber": "EMP123456", + "ChatEventId": 1, + "ConversationId": "15521", + "ModuleCode": "CRM", + "ReferenceNumber": "CASE-55231", + "UserChatHistoryLineRequestList": [ + {"TargetEmployeeNumber": "EMP654321", "TargetUserStatus": 1, "IsSeen": false, "IsDelivered": true, "SeenOn": null, "DeliveredOn": null} + ] + }; + } + // List? uGroups = [], searchGroups = []; // Future getUserAutoLoginToken() async { @@ -216,14 +275,18 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { // } // } - Future buildHubConnection() async { + Future buildHubConnection(String conversationID) async { chatHubConnection = await getHubConnection(); await chatHubConnection.start(); if (kDebugMode) { print("Hub Conn: Startedddddddd"); } - // chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); - // chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); + + await chatHubConnection.invoke("JoinConversation", args: [conversationID]); + chatHubConnection.on("ReceiveMessage", onMsgReceived1); + chatHubConnection.on("OnMessageReceivedAsync", onMsgReceived); + chatHubConnection.on("OnSubmitChatAsync", OnSubmitChatAsync); + chatHubConnection.on("OnTypingAsync", OnTypingAsync); //group On message @@ -234,7 +297,7 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { HubConnection hub; HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); hub = HubConnectionBuilder() - .withUrl("${URLs.chatHubUrl}?UserId=${chatLoginResponse!.userId}&source=Desktop&access_token=${chatLoginResponse!.token}", options: httpOp) + .withUrl("${URLs.chatHubUrlChat}?UserId=${chatLoginResponse!.userId}&source=Desktop&access_token=${chatLoginResponse!.token}", options: httpOp) .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); return hub; } @@ -492,1502 +555,1529 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { // 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 OnTypingAsync(List? parameters) async { + print("OnTypingAsync:$parameters"); + } - // 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; - // } - // } - // } - // } + // Future OnSubmitChatAsync(List? parameters) async { + // // List data = jsonDecode(parameters!.first!.toString()); // - // // 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) { + // print("OnSubmitChatAsync:$parameters"); // - // // } 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; + // var data = getSingleUserChatModel(jsonEncode(msg)); + // print(data); // } // - // notifyListeners(); - // } - - // void sort() { - // searchedChats!.sort( - // (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo(a.unreadMessageCount!), - // ); + // // List data = parameters!.first!; + // // chatResponseList = chatResponseList + data.map((elemet) => ChatHistoryResponse.fromJson(element)).toList(); + // // chatResponseList.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); + // // notifyListeners(); // } - // 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(); - // } + Future onMsgReceived1(List? parameters) async { + print("onMsgReceived1:$parameters"); + } - 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; + Future onMsgReceived(List? parameters) async { + List data = [], temp = []; + print("OnMessageReceivedAsync:$parameters"); + 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(); + // userChatHistory = userChatHistory! + data; + // chatResponseList.sort((a, b) => b.createdDate!.compareTo(a.createdDate!)); + userChatHistory?.insert(0, data.first); + notifyListeners(); + // 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.userChatHistoryId, + // "TargetUserId": temp.first.targetUserId, + // "isDelivered": true, + // "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false + // } + // ]; + // updateUserChatHistoryOnMsg(list); + // invokeChatCounter(userId: AppState().chatDetails!.response!. + // id + // + // ! + // + // ); + + // notifyListeners + // + // ( + // + // ); } - 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 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) { + List data = []; + for (dynamic msg in parameters!) { + data = getSingleUserChatModel(jsonEncode(msg)); } + chatResponseList.insert(0, data.first); + notifyListeners(); } - // 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)]); - // } +// void sort() { +// searchedChats!.sort( +// (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo(a.unreadMessageCount!), +// ); +// } - //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 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(); +} - // 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(); - // } - // } - // } +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; + } +} - // 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(); - // // } - // } +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 ""; + } +} - // 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(); - // }); - // } +// 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)]); +// } - // void removeAttachment() { - // isAttachmentMsg = false; - // sFileType = ""; - // message.text = ''; - // notifyListeners(); - // } +//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)]); +// } - String? getFileExtension(String fileName) { - try { - if (kDebugMode) { - // logger.i("ext: " + "." + fileName.split('.').last); - } - return "." + fileName.split('.').last; - } catch (e) { - return null; +// 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; - } +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"; - } +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 chatReply(SingleUserChatModel data) { +// repliedMsg = []; +// data.isReplied = true; +// isReplyMsg = true; +// repliedMsg.add(data); +// notifyListeners(); +// } - // void closeMe() { - // repliedMsg = []; - // isReplyMsg = false; - // notifyListeners(); - // } +// void groupChatReply(groupchathistory.GetGroupChatHistoryAsync data) { +// groupChatReplyData = []; +// data.isReplied = true; +// isReplyMsg = true; +// groupChatReplyData.add(data); +// notifyListeners(); +// } - String dateFormte(DateTime data) { - DateFormat f = DateFormat('hh:mm a dd MMM yyyy', "en_US"); - f.format(data); - return f.format(data); - } +// void closeMe() { +// repliedMsg = []; +// isReplyMsg = false; +// notifyListeners(); +// } - // 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(); - // } +String dateFormte(DateTime data) { + DateFormat f = DateFormat('hh:mm a dd MMM yyyy', "en_US"); + f.format(data); + return f.format(data); +} - // 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()); - // } - // } +// 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 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(); - // } +// 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()); +// } +// } - 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; - } - } +// 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 deleteFile(String userID) async { +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'; - late File imageFile = File('$dirPath/$userID.jpg'); - if (await imageFile.exists()) { - await imageFile.delete(); + 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 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; +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(); } +} - 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 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."); - // } - // } - // } +// 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(); - // } +// 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 ""; - } +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 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]); - // } +// 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(); - // } +// 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 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'; - // } +// 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; +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(""); +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(); } - return file; + 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, - // ); - // } - // } - // } +// 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(); - // } +// +// 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(); - // } +// 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; +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(); @@ -2066,4 +2156,3 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { // isLoading = false; // notifyListeners(); // } -} 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 index 3722c093..06e3da34 100644 --- 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 @@ -41,10 +41,10 @@ class SingleUserChatModel { int? userChatHistoryLineId; String? contant; String? contantNo; - int? currentUserId; + String? currentUserId; String? currentUserName; String? currentUserEmail; - int? targetUserId; + String? targetUserId; String? targetUserName; String? targetUserEmail; String? encryptedTargetUserId; @@ -69,9 +69,9 @@ class SingleUserChatModel { 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"], + currentUserId: json["currentUserId"] == null ? null : json["currentUserId"].toString(), currentUserName: json["currentUserName"] == null ? null : json["currentUserName"], - targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], + targetUserId: json["targetUserId"] == null ? null : json["targetUserId"].toString(), targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], targetUserEmail: json["targetUserEmail"] == null ? null : json["targetUserEmail"], currentUserEmail: json["currentUserEmail"] == null ? null : json["currentUserEmail"], diff --git a/lib/modules/cx_module/chat/model/user_chat_history_model.dart b/lib/modules/cx_module/chat/model/user_chat_history_model.dart index 84d8a257..7ec1e9c3 100644 --- a/lib/modules/cx_module/chat/model/user_chat_history_model.dart +++ b/lib/modules/cx_module/chat/model/user_chat_history_model.dart @@ -1,224 +1,224 @@ -class UserChatHistoryModel { - List? response; - bool? isSuccess; - List? onlineUserConnId; - - UserChatHistoryModel({this.response, this.isSuccess, this.onlineUserConnId}); - - UserChatHistoryModel.fromJson(Map json) { - if (json['response'] != null) { - response = []; - json['response'].forEach((v) { - response!.add(new ChatResponse.fromJson(v)); - }); - } - isSuccess = json['isSuccess']; - onlineUserConnId = json['onlineUserConnId'].cast(); - } - - Map toJson() { - final Map data = new Map(); - if (this.response != null) { - data['response'] = this.response!.map((v) => v.toJson()).toList(); - } - data['isSuccess'] = this.isSuccess; - data['onlineUserConnId'] = this.onlineUserConnId; - return data; - } -} - -class ChatResponse { - int? id; - int? conversationId; - String? userId; - int? userIdInt; - String? userName; - String? content; - String? messageType; - String? createdAt; - - ChatResponse({this.id, this.conversationId, this.userId, this.userIdInt, this.userName, this.content, this.messageType, this.createdAt}); - - ChatResponse.fromJson(Map json) { - id = json['id']; - conversationId = json['conversationId']; - userId = json['userId']; - userIdInt = json['userIdInt']; - userName = json['userName']; - content = json['content']; - messageType = json['messageType']; - createdAt = json['createdAt']; - } - - Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['conversationId'] = this.conversationId; - data['userId'] = this.userId; - data['userIdInt'] = this.userIdInt; - data['userName'] = this.userName; - data['content'] = this.content; - data['messageType'] = this.messageType; - data['createdAt'] = this.createdAt; - return data; - } -} - -class ChatHistoryResponse { - int? userChatHistoryId; - int? userChatHistoryLineId; - String? contant; - String? contantNo; - String? currentUserId; - String? currentEmployeeNumber; - String? currentUserName; - String? currentUserEmail; - String? currentFullName; - String? targetUserId; - String? targetEmployeeNumber; - String? targetUserName; - String? targetUserEmail; - String? targetFullName; - String? encryptedTargetUserId; - String? encryptedTargetUserName; - int? chatEventId; - String? fileTypeId; - bool? isSeen; - bool? isDelivered; - String? createdDate; - int? chatSource; - String? conversationId; - FileTypeResponse? fileTypeResponse; - String? userChatReplyResponse; - String? deviceToken; - bool? isHuaweiDevice; - String? platform; - String? voipToken; - - ChatHistoryResponse( - {this.userChatHistoryId, - this.userChatHistoryLineId, - this.contant, - this.contantNo, - this.currentUserId, - this.currentEmployeeNumber, - this.currentUserName, - this.currentUserEmail, - this.currentFullName, - this.targetUserId, - this.targetEmployeeNumber, - this.targetUserName, - this.targetUserEmail, - this.targetFullName, - this.encryptedTargetUserId, - this.encryptedTargetUserName, - this.chatEventId, - this.fileTypeId, - this.isSeen, - this.isDelivered, - this.createdDate, - this.chatSource, - this.conversationId, - this.fileTypeResponse, - this.userChatReplyResponse, - this.deviceToken, - this.isHuaweiDevice, - this.platform, - this.voipToken}); - - ChatHistoryResponse.fromJson(Map json) { - userChatHistoryId = json['userChatHistoryId']; - userChatHistoryLineId = json['userChatHistoryLineId']; - contant = json['contant']; - contantNo = json['contantNo']; - currentUserId = json['currentUserId']; - currentEmployeeNumber = json['currentEmployeeNumber']; - currentUserName = json['currentUserName']; - currentUserEmail = json['currentUserEmail']; - currentFullName = json['currentFullName']; - targetUserId = json['targetUserId']; - targetEmployeeNumber = json['targetEmployeeNumber']; - targetUserName = json['targetUserName']; - targetUserEmail = json['targetUserEmail']; - targetFullName = json['targetFullName']; - encryptedTargetUserId = json['encryptedTargetUserId']; - encryptedTargetUserName = json['encryptedTargetUserName']; - chatEventId = json['chatEventId']; - fileTypeId = json['fileTypeId']; - isSeen = json['isSeen']; - isDelivered = json['isDelivered']; - createdDate = json['createdDate']; - chatSource = json['chatSource']; - conversationId = json['conversationId']; - fileTypeResponse = json['fileTypeResponse'] != null ? new FileTypeResponse.fromJson(json['fileTypeResponse']) : null; - userChatReplyResponse = json['userChatReplyResponse']; - deviceToken = json['deviceToken']; - isHuaweiDevice = json['isHuaweiDevice']; - platform = json['platform']; - voipToken = json['voipToken']; - } - - Map toJson() { - final Map data = new Map(); - data['userChatHistoryId'] = this.userChatHistoryId; - data['userChatHistoryLineId'] = this.userChatHistoryLineId; - data['contant'] = this.contant; - data['contantNo'] = this.contantNo; - data['currentUserId'] = this.currentUserId; - data['currentEmployeeNumber'] = this.currentEmployeeNumber; - data['currentUserName'] = this.currentUserName; - data['currentUserEmail'] = this.currentUserEmail; - data['currentFullName'] = this.currentFullName; - data['targetUserId'] = this.targetUserId; - data['targetEmployeeNumber'] = this.targetEmployeeNumber; - data['targetUserName'] = this.targetUserName; - data['targetUserEmail'] = this.targetUserEmail; - data['targetFullName'] = this.targetFullName; - data['encryptedTargetUserId'] = this.encryptedTargetUserId; - data['encryptedTargetUserName'] = this.encryptedTargetUserName; - data['chatEventId'] = this.chatEventId; - data['fileTypeId'] = this.fileTypeId; - data['isSeen'] = this.isSeen; - data['isDelivered'] = this.isDelivered; - data['createdDate'] = this.createdDate; - data['chatSource'] = this.chatSource; - data['conversationId'] = this.conversationId; - if (this.fileTypeResponse != null) { - data['fileTypeResponse'] = this.fileTypeResponse!.toJson(); - } - data['userChatReplyResponse'] = this.userChatReplyResponse; - data['deviceToken'] = this.deviceToken; - data['isHuaweiDevice'] = this.isHuaweiDevice; - data['platform'] = this.platform; - data['voipToken'] = this.voipToken; - return data; - } -} - -class FileTypeResponse { - int? fileTypeId; - String? fileTypeName; - String? fileTypeDescription; - String? fileKind; - String? fileName; - - FileTypeResponse({this.fileTypeId, this.fileTypeName, this.fileTypeDescription, this.fileKind, this.fileName}); - - FileTypeResponse.fromJson(Map json) { - fileTypeId = json['fileTypeId']; - fileTypeName = json['fileTypeName']; - fileTypeDescription = json['fileTypeDescription']; - fileKind = json['fileKind']; - fileName = json['fileName']; - } - - Map toJson() { - final Map data = new Map(); - data['fileTypeId'] = this.fileTypeId; - data['fileTypeName'] = this.fileTypeName; - data['fileTypeDescription'] = this.fileTypeDescription; - data['fileKind'] = this.fileKind; - data['fileName'] = this.fileName; - return data; - } -} +// class UserChatHistoryModel { +// List? response; +// bool? isSuccess; +// List? onlineUserConnId; +// +// UserChatHistoryModel({this.response, this.isSuccess, this.onlineUserConnId}); +// +// UserChatHistoryModel.fromJson(Map json) { +// if (json['response'] != null) { +// response = []; +// json['response'].forEach((v) { +// response!.add(new ChatResponse.fromJson(v)); +// }); +// } +// isSuccess = json['isSuccess']; +// onlineUserConnId = json['onlineUserConnId'].cast(); +// } +// +// Map toJson() { +// final Map data = new Map(); +// if (this.response != null) { +// data['response'] = this.response!.map((v) => v.toJson()).toList(); +// } +// data['isSuccess'] = this.isSuccess; +// data['onlineUserConnId'] = this.onlineUserConnId; +// return data; +// } +// } +// +// class ChatResponse { +// int? id; +// int? conversationId; +// String? userId; +// int? userIdInt; +// String? userName; +// String? content; +// String? messageType; +// String? createdAt; +// +// ChatResponse({this.id, this.conversationId, this.userId, this.userIdInt, this.userName, this.content, this.messageType, this.createdAt}); +// +// ChatResponse.fromJson(Map json) { +// id = json['id']; +// conversationId = json['conversationId']; +// userId = json['userId']; +// userIdInt = json['userIdInt']; +// userName = json['userName']; +// content = json['content']; +// messageType = json['messageType']; +// createdAt = json['createdAt']; +// } +// +// Map toJson() { +// final Map data = new Map(); +// data['id'] = this.id; +// data['conversationId'] = this.conversationId; +// data['userId'] = this.userId; +// data['userIdInt'] = this.userIdInt; +// data['userName'] = this.userName; +// data['content'] = this.content; +// data['messageType'] = this.messageType; +// data['createdAt'] = this.createdAt; +// return data; +// } +// } +// +// class ChatHistoryResponse { +// int? userChatHistoryId; +// int? userChatHistoryLineId; +// String? contant; +// String? contantNo; +// String? currentUserId; +// String? currentEmployeeNumber; +// String? currentUserName; +// String? currentUserEmail; +// String? currentFullName; +// String? targetUserId; +// String? targetEmployeeNumber; +// String? targetUserName; +// String? targetUserEmail; +// String? targetFullName; +// String? encryptedTargetUserId; +// String? encryptedTargetUserName; +// int? chatEventId; +// String? fileTypeId; +// bool? isSeen; +// bool? isDelivered; +// String? createdDate; +// int? chatSource; +// String? conversationId; +// FileTypeResponse? fileTypeResponse; +// String? userChatReplyResponse; +// String? deviceToken; +// bool? isHuaweiDevice; +// String? platform; +// String? voipToken; +// +// ChatHistoryResponse( +// {this.userChatHistoryId, +// this.userChatHistoryLineId, +// this.contant, +// this.contantNo, +// this.currentUserId, +// this.currentEmployeeNumber, +// this.currentUserName, +// this.currentUserEmail, +// this.currentFullName, +// this.targetUserId, +// this.targetEmployeeNumber, +// this.targetUserName, +// this.targetUserEmail, +// this.targetFullName, +// this.encryptedTargetUserId, +// this.encryptedTargetUserName, +// this.chatEventId, +// this.fileTypeId, +// this.isSeen, +// this.isDelivered, +// this.createdDate, +// this.chatSource, +// this.conversationId, +// this.fileTypeResponse, +// this.userChatReplyResponse, +// this.deviceToken, +// this.isHuaweiDevice, +// this.platform, +// this.voipToken}); +// +// ChatHistoryResponse.fromJson(Map json) { +// userChatHistoryId = json['userChatHistoryId']; +// userChatHistoryLineId = json['userChatHistoryLineId']; +// contant = json['contant']; +// contantNo = json['contantNo']; +// currentUserId = json['currentUserId']; +// currentEmployeeNumber = json['currentEmployeeNumber']; +// currentUserName = json['currentUserName']; +// currentUserEmail = json['currentUserEmail']; +// currentFullName = json['currentFullName']; +// targetUserId = json['targetUserId']; +// targetEmployeeNumber = json['targetEmployeeNumber']; +// targetUserName = json['targetUserName']; +// targetUserEmail = json['targetUserEmail']; +// targetFullName = json['targetFullName']; +// encryptedTargetUserId = json['encryptedTargetUserId']; +// encryptedTargetUserName = json['encryptedTargetUserName']; +// chatEventId = json['chatEventId']; +// fileTypeId = json['fileTypeId']; +// isSeen = json['isSeen']; +// isDelivered = json['isDelivered']; +// createdDate = json['createdDate']; +// chatSource = json['chatSource']; +// conversationId = json['conversationId']; +// fileTypeResponse = json['fileTypeResponse'] != null ? new FileTypeResponse.fromJson(json['fileTypeResponse']) : null; +// userChatReplyResponse = json['userChatReplyResponse']; +// deviceToken = json['deviceToken']; +// isHuaweiDevice = json['isHuaweiDevice']; +// platform = json['platform']; +// voipToken = json['voipToken']; +// } +// +// Map toJson() { +// final Map data = new Map(); +// data['userChatHistoryId'] = this.userChatHistoryId; +// data['userChatHistoryLineId'] = this.userChatHistoryLineId; +// data['contant'] = this.contant; +// data['contantNo'] = this.contantNo; +// data['currentUserId'] = this.currentUserId; +// data['currentEmployeeNumber'] = this.currentEmployeeNumber; +// data['currentUserName'] = this.currentUserName; +// data['currentUserEmail'] = this.currentUserEmail; +// data['currentFullName'] = this.currentFullName; +// data['targetUserId'] = this.targetUserId; +// data['targetEmployeeNumber'] = this.targetEmployeeNumber; +// data['targetUserName'] = this.targetUserName; +// data['targetUserEmail'] = this.targetUserEmail; +// data['targetFullName'] = this.targetFullName; +// data['encryptedTargetUserId'] = this.encryptedTargetUserId; +// data['encryptedTargetUserName'] = this.encryptedTargetUserName; +// data['chatEventId'] = this.chatEventId; +// data['fileTypeId'] = this.fileTypeId; +// data['isSeen'] = this.isSeen; +// data['isDelivered'] = this.isDelivered; +// data['createdDate'] = this.createdDate; +// data['chatSource'] = this.chatSource; +// data['conversationId'] = this.conversationId; +// if (this.fileTypeResponse != null) { +// data['fileTypeResponse'] = this.fileTypeResponse!.toJson(); +// } +// data['userChatReplyResponse'] = this.userChatReplyResponse; +// data['deviceToken'] = this.deviceToken; +// data['isHuaweiDevice'] = this.isHuaweiDevice; +// data['platform'] = this.platform; +// data['voipToken'] = this.voipToken; +// return data; +// } +// } +// +// class FileTypeResponse { +// int? fileTypeId; +// String? fileTypeName; +// String? fileTypeDescription; +// String? fileKind; +// String? fileName; +// +// FileTypeResponse({this.fileTypeId, this.fileTypeName, this.fileTypeDescription, this.fileKind, this.fileName}); +// +// FileTypeResponse.fromJson(Map json) { +// fileTypeId = json['fileTypeId']; +// fileTypeName = json['fileTypeName']; +// fileTypeDescription = json['fileTypeDescription']; +// fileKind = json['fileKind']; +// fileName = json['fileName']; +// } +// +// Map toJson() { +// final Map data = new Map(); +// data['fileTypeId'] = this.fileTypeId; +// data['fileTypeName'] = this.fileTypeName; +// data['fileTypeDescription'] = this.fileTypeDescription; +// data['fileKind'] = this.fileKind; +// data['fileName'] = this.fileName; +// return data; +// } +// }