diff --git a/lib/api/chat/chat_provider_model.dart b/lib/api/chat/chat_provider_model.dart index d4b49f8..465c5af 100644 --- a/lib/api/chat/chat_provider_model.dart +++ b/lib/api/chat/chat_provider_model.dart @@ -6,10 +6,13 @@ import 'package:fluttertoast/fluttertoast.dart'; import 'package:http/http.dart'; import 'package:logging/logging.dart'; import 'package:mohem_flutter_app/api/api_client.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_Model.dart'; +import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as login; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:signalr_netcore/hub_connection.dart'; import 'package:signalr_netcore/signalr_client.dart'; import 'package:logger/logger.dart' as L; @@ -21,17 +24,23 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { L.Logger logger = L.Logger(); TextEditingController message = TextEditingController(); ScrollController scrollController = ScrollController(); - static String token = - "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiI0MjA2MiIsImVtYWlsIjoiYWFtaXIubXVoYW1tYWRAY2xvdWRzb2x1dGlvbnMuY29tLnNhIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy91c2VyZGF0YSI6ImFhbWlyLm11aGFtbWFkIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbW9iaWxlcGhvbmUiOiI5NjY1MzA4OTYwMTgiLCJuYmYiOjE2NjU5MjA2NDEsImV4cCI6MTY2NjAwNzA0MSwiaWF0IjoxNjY1OTIwNjQxfQ.70tXWdpXtQ20PNBO3WF9ScWNWSyECpFfrW7_iuOmNfWmA63PCZzlTO0E6I3q3K9Kg2CWvOT9-dSDLjlRuXuC2w"; - bool isLoading = true; + Future getUserAutoLoginToken() async { + String userName = AppState().memberInformationList!.eMPLOYEEEMAILADDRESS!.split("@").first.toString(); + Response response = + await ApiClient().postJsonForResponse("${ApiConsts.chatServerBaseApiUrl}user/desktopuserlogin", {"userName": userName, "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", "loginType": 2}); + login.UserAutoLoginModel userLoginResponse = login.userAutoLoginModelFromJson(response.body); + AppState().setchatUserDetails = userLoginResponse; + await buildHubConnection(); + } + void getChatMemberFromSearch(String sName, int cUserId) async { isLoading = true; notifyListeners(); Response response = await ApiClient().getJsonForResponse( "${ApiConsts.chatSearchMember}$sName/$cUserId", - token: token, + token: AppState().chatDetails!.response!.token, ); isLoading = false; notifyListeners(); @@ -40,7 +49,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void getUserRecentChats() async { Response response = await ApiClient().getJsonForResponse( "${ApiConsts.chatServerBaseApiUrl}${ApiConsts.chatRecentUrl}", - token: token, + token: AppState().chatDetails!.response!.token, ); ChatUserModel recentChat = userToList(response.body); pChatHistory = recentChat.response; @@ -53,11 +62,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { isLoading = true; Response response = await ApiClient().getJsonForResponse( "${ApiConsts.chatServerBaseApiUrl}${ApiConsts.chatSingleUserHistoryUrl}/$senderUID/$receiverUID/$pagination", - token: token, + token: AppState().chatDetails!.response!.token, ); + logger.d(response.body); userChatHistory = getSingleUserChatintoModel(response.body); isLoading = false; - logger.d(jsonEncode(userChatHistory)); notifyListeners(); } @@ -65,10 +74,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { ChatUserModel userToList(String str) => ChatUserModel.fromJson(json.decode(str)); - void buildHubConnection() async { + Future buildHubConnection() async { HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); hubConnection = await HubConnectionBuilder() - .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=42062&source=Web&access_token=$token", options: httpOp) + .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Web&access_token=${AppState().chatDetails!.response!.token}", options: httpOp) .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]) .configureLogging(Logger("Logs Enabled")) .build(); @@ -92,20 +101,64 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { await hubConnection.start(); hubConnection.on("OnUpdateUserStatusAsync", changeStatus); hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); - // hubConnection.on("OnUserTypingAsync", onUserTyping); - //hubConnection.on("OnUserTypingAsync", changeTypingStatus); + + // hubConnection.on("OnUserTypingAsync", onUserTyping); + // hubConnection.on("OnUserCountAsync", userCountAsync); + // hubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); + // hubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); } else { hubConnection.on("OnUpdateUserStatusAsync", changeStatus); hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); - // hubConnection.on("OnUserTypingAsync", onUserTyping); - //hubConnection.on("OnUserTypingAsync", changeTypingStatus); + + // hubConnection.on("OnUserTypingAsync", onUserTyping); + // hubConnection.on("OnUserCountAsync", userCountAsync); + // hubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); + // hubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); } isLoading = false; notifyListeners(); } + void userCountAsync(List? args) { + List items = args!.toList(); + print("---------------------------------User Count Async -------------------------------------"); + logger.d(items); + // for (var user in searchedChats!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // notifyListeners(); + } + + void updateChatHistoryWindow(List? args) { + List items = args!.toList(); + print("---------------------------------Update Chat History Windows Async -------------------------------------"); + logger.d(items); + // for (var user in searchedChats!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // notifyListeners(); + } + + void chatNotDelivered(List? args) { + List items = args!.toList(); + print("--------------------------------- Chat Not Delivered Windows Async -------------------------------------"); + logger.d(items); + // for (var user in searchedChats!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // notifyListeners(); + } + void changeStatus(List? args) { + // print("================= Status Online // Offline ===================="); List items = args!.toList(); + logger.d(items); for (var user in searchedChats!) { if (user.id == items.first["id"]) { user.userStatus = items.first["userStatus"]; @@ -163,7 +216,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { return; } String chatData = - '{"contant":"$chatMessage","contantNo":"8a129295-36d7-7185-5d34-cc4eec7bcba4","chatEventId":1,"fileTypeId":null,"currentUserId":42062,"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"conversationId":"715f8b13-96ee-cd36-cb07-5a982a219982"}'; + '{"contant":"$chatMessage","contantNo":"8a129295-36d7-7185-5d34-cc4eec7bcba4","chatEventId":1,"fileTypeId":null,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"conversationId":"715f8b13-96ee-cd36-cb07-5a982a219982"}'; await hubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); userChatHistory.add( SingleUserChatModel( @@ -173,8 +226,8 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { contantNo: "8a129295-36d7-7185-5d34-cc4eec7bcba4", conversationId: "715f8b13-96ee-cd36-cb07-5a982a219982", createdDate: DateTime.now(), - currentUserId: 42062, - currentUserName: "aamir.muhammad", + currentUserId: AppState().chatDetails!.response!.id, + currentUserName: AppState().chatDetails!.response!.userName, targetUserId: targetUserId, targetUserName: targetUserName, ), @@ -190,9 +243,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { curve: Curves.easeOut, duration: const Duration(milliseconds: 300), ); - - // scrollController.animateTo(double.parse(userChatHistory.length.toString()), duration: Duration(milliseconds: 500), curve: Curves.fastOutSlowIn); - notifyListeners(); } diff --git a/lib/app_state/app_state.dart b/lib/app_state/app_state.dart index d7f6a9d..ceb4881 100644 --- a/lib/app_state/app_state.dart +++ b/lib/app_state/app_state.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; +import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart'; import 'package:mohem_flutter_app/models/itg_forms_models/request_detail_model.dart'; import 'package:mohem_flutter_app/models/member_information_list_model.dart'; import 'package:mohem_flutter_app/models/member_login_list_model.dart'; @@ -116,4 +117,10 @@ class AppState { int? itgWorkListIndex; set setItgWorkListIndex(int? _itgWorkListIndex) => itgWorkListIndex = _itgWorkListIndex; + + UserAutoLoginModel? chatDetails; + + set setchatUserDetails(UserAutoLoginModel details) => chatDetails = details; + + UserAutoLoginModel? get getchatUserDetails => chatDetails; } diff --git a/lib/models/chat/get_user_login_token_model.dart b/lib/models/chat/get_user_login_token_model.dart new file mode 100644 index 0000000..8afd3a9 --- /dev/null +++ b/lib/models/chat/get_user_login_token_model.dart @@ -0,0 +1,78 @@ + +import 'dart:convert'; + +UserAutoLoginModel userAutoLoginModelFromJson(String str) => UserAutoLoginModel.fromJson(json.decode(str)); + +String userAutoLoginModelToJson(UserAutoLoginModel data) => json.encode(data.toJson()); + +class UserAutoLoginModel { + UserAutoLoginModel({ + this.response, + this.errorResponses, + }); + + Response? response; + dynamic? errorResponses; + + factory UserAutoLoginModel.fromJson(Map json) => UserAutoLoginModel( + response: json["response"] == null ? null : Response.fromJson(json["response"]), + errorResponses: json["errorResponses"], + ); + + Map toJson() => { + "response": response == null ? null : response!.toJson(), + "errorResponses": errorResponses, + }; +} + +class Response { + Response({ + this.id, + this.userName, + this.email, + this.phone, + this.title, + this.token, + this.isDomainUser, + this.isActiveCode, + this.encryptedUserId, + this.encryptedUserName, + }); + + int? id; + String? userName; + String? email; + String? phone; + String? title; + String? token; + bool? isDomainUser; + bool? isActiveCode; + String? encryptedUserId; + String? encryptedUserName; + + factory Response.fromJson(Map json) => Response( + id: json["id"] == null ? null : json["id"], + userName: json["userName"] == null ? null : json["userName"], + email: json["email"] == null ? null : json["email"], + phone: json["phone"] == null ? null : json["phone"], + title: json["title"] == null ? null : json["title"], + token: json["token"] == null ? null : json["token"], + isDomainUser: json["isDomainUser"] == null ? null : json["isDomainUser"], + isActiveCode: json["isActiveCode"] == null ? null : json["isActiveCode"], + encryptedUserId: json["encryptedUserId"] == null ? null : json["encryptedUserId"], + encryptedUserName: json["encryptedUserName"] == null ? null : json["encryptedUserName"], + ); + + Map toJson() => { + "id": id == null ? null : id, + "userName": userName == null ? null : userName, + "email": email == null ? null : email, + "phone": phone == null ? null : phone, + "title": title == null ? null : title, + "token": token == null ? null : token, + "isDomainUser": isDomainUser == null ? null : isDomainUser, + "isActiveCode": isActiveCode == null ? null : isActiveCode, + "encryptedUserId": encryptedUserId == null ? null : encryptedUserId, + "encryptedUserName": encryptedUserName == null ? null : encryptedUserName, + }; +} diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 17ba325..b647a38 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -4,6 +4,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/api/chat/chat_provider_model.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; import 'package:mohem_flutter_app/ui/chat/chat_bubble.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; @@ -20,7 +21,7 @@ class ChatDetailScreen extends StatelessWidget { Widget build(BuildContext context) { userDetails = ModalRoute.of(context)!.settings.arguments; data = Provider.of(context, listen: false); - data.getSingleUserChatHistory(senderUID: "42062", receiverUID: userDetails["targetUser"].id, pagination: "0"); + data.getSingleUserChatHistory(senderUID: AppState().chatDetails!.response!.id.toString(), receiverUID: userDetails["targetUser"].id, pagination: "0"); Timer(const Duration(seconds: 1), () => data.scrollDown()); return Scaffold( backgroundColor: const Color(0xFFF8F8F8), @@ -70,7 +71,8 @@ class ChatDetailScreen extends StatelessWidget { width: 35, ), onPressed: () { - m.sendChatMessage(m.message.text, userDetails["targetUser"].id, userDetails["targetUser"].userName); + // m.logger.d(userDetails); + m.sendChatMessage(m.message.text, userDetails["targetUser"].id, userDetails["targetUser"].userName); }, ), ), diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 236a73f..18c11bf 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -5,6 +5,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/api/chat/chat_provider_model.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; @@ -30,8 +31,9 @@ class _ChatHomeScreenState extends State { void initState() { super.initState(); data = Provider.of(context, listen: false); - data.buildHubConnection(); - data.getUserRecentChats(); + data.getUserAutoLoginToken().whenComplete(() { + data.getUserRecentChats(); + }); } @override @@ -115,7 +117,7 @@ class _ChatHomeScreenState extends State { Navigator.pushNamed( context, AppRoutes.chatDetailed, - arguments: {"currentUser": "42062", "targetUser": m.searchedChats![index]}, + arguments: {"targetUser": m.searchedChats![index]}, ); }, );