From 86ac29946fb2fea5ba17ea84d2e763f76064c170 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Sun, 20 Nov 2022 12:19:54 +0300 Subject: [PATCH] Chat Updates & Counter Event Modifications --- lib/api/chat/chat_provider_model.dart | 144 ++++++++++++++++++++------ lib/ui/chat/chat_home.dart | 2 +- lib/ui/chat/chat_home_screen.dart | 42 ++++---- 3 files changed, 134 insertions(+), 54 deletions(-) diff --git a/lib/api/chat/chat_provider_model.dart b/lib/api/chat/chat_provider_model.dart index 7439b98..2e8bcb8 100644 --- a/lib/api/chat/chat_provider_model.dart +++ b/lib/api/chat/chat_provider_model.dart @@ -44,7 +44,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { bool _firstAutoscrollExecuted = false; bool _shouldAutoscroll = false; - Future getUserAutoLoginToken() async { + Future getUserAutoLoginToken(BuildContext cxt) async { Response response = await ApiClient().postJsonForResponse( "${ApiConsts.chatServerBaseApiUrl}user/externaluserlogin", { @@ -76,7 +76,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { return searchUserJsonModel(response.body); } - List searchUserJsonModel(String str) => List.from(json.decode(str).map((x) => ChatUser.fromJson(x))); + List searchUserJsonModel(String str) => List.from( + json.decode(str).map( + (x) => ChatUser.fromJson(x), + ), + ); void getUserRecentChats() async { Response response = await ApiClient().getJsonForResponse( @@ -90,9 +94,18 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { token: AppState().chatDetails!.response!.token, ); ChatUserModel favUList = userToList(favRes.body); + GetUserChatHistoryNotDeliveredAsync( + userId: int.parse( + AppState().chatDetails!.response!.id.toString(), + ), + ); if (favUList.response != null) { favUsersList = favUList.response!; - favUsersList.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); + favUsersList.sort( + (ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo( + b.userName!.toLowerCase(), + ), + ); for (dynamic user in recentChat.response!) { for (dynamic favUser in favUList.response!) { if (user.id == favUser.id) { @@ -101,16 +114,23 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } } - pChatHistory = recentChat.response == null ? [] : recentChat.response; - if (pChatHistory != null) pChatHistory!.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); + pChatHistory = recentChat.response ?? []; + pChatHistory!.sort( + (ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo( + b.userName!.toLowerCase(), + ), + ); searchedChats = pChatHistory; isLoading = false; notifyListeners(); } - Future GetUserChatHistoryNotDeliveredAsync(int userId) async { - await hubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); + Future GetUserChatHistoryNotDeliveredAsync({required int userId}) async { + await hubConnection.invoke( + "GetUserChatHistoryNotDeliveredAsync", + args: [userId], + ); return ""; } @@ -132,35 +152,89 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } else { if (loadMore) { - List temp = getSingleUserChatModel(response.body).reversed.toList(); - userChatHistory.addAll(temp); + List temp = getSingleUserChatModel( + response.body, + ).reversed.toList(); + userChatHistory.addAll( + temp, + ); } else { - userChatHistory = getSingleUserChatModel(response.body).reversed.toList(); + userChatHistory = getSingleUserChatModel( + response.body, + ).reversed.toList(); } } + await GetUserChatHistoryNotDeliveredAsync( + userId: senderUID, + ); isLoading = false; - await GetUserChatHistoryNotDeliveredAsync(senderUID); notifyListeners(); + markRead( + userChatHistory, + receiverUID, + ); + } + + void markRead(List data, reciverID) { + for (SingleUserChatModel element in data!) { + if (!element.isSeen!) { + dynamic data = [ + { + "userChatHistoryId": element.userChatHistoryId, + "TargetUserId": element.targetUserId, + "isDelivered": true, + "isSeen": true, + } + ]; + updateUserChatHistoryStatusAsync(data); + } + } + for (ChatUser element in searchedChats!) { + if (element.id == reciverID) { + element.unreadMessageCount = 0; + notifyListeners(); + } + } } void updateUserChatHistoryStatusAsync(List data) { - hubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); + hubConnection.invoke( + "UpdateUserChatHistoryStatusAsync", + args: [data], + ); } - List getSingleUserChatModel(String str) => List.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); + List getSingleUserChatModel(String str) => List.from( + json.decode(str).map( + (x) => SingleUserChatModel.fromJson(x), + ), + ); - ChatUserModel userToList(String str) => ChatUserModel.fromJson(json.decode(str)); + ChatUserModel userToList(String str) => ChatUserModel.fromJson( + json.decode(str), + ); Future uploadAttachments(String userId, File file) async { dynamic result; - dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatServerBaseApiUrl}${ApiConsts.chatMediaImageUploadUrl}')); + dynamic request = MultipartRequest( + 'POST', + Uri.parse( + '${ApiConsts.chatServerBaseApiUrl}${ApiConsts.chatMediaImageUploadUrl}', + ), + ); request.fields.addAll({'userId': userId, 'fileSource': '1'}); request.files.add(await MultipartFile.fromPath('files', file.path)); - request.headers.addAll({'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}'}); + request.headers.addAll( + { + 'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}', + }, + ); try { StreamedResponse response = await request.send(); if (response.statusCode == 200) { - result = jsonDecode(await response.stream.bytesToString()); + result = jsonDecode( + await response.stream.bytesToString(), + ); } else { result = []; } @@ -176,7 +250,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { Future buildHubConnection() async { HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); hubConnection = HubConnectionBuilder() - .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Web&access_token=${AppState().chatDetails!.response!.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], ) @@ -194,6 +271,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { ({String? connectionId}) {}, ); if (hubConnection.state != HubConnectionState.Connected) { + print("Started"); await hubConnection.start(); hubConnection.on("OnUpdateUserStatusAsync", changeStatus); hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); @@ -260,23 +338,23 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void chatNotDelivered(List? args) { dynamic items = args!.toList(); for (dynamic item in items[0]) { - dynamic data = [ - { - "userChatHistoryId": item["userChatHistoryId"], - "TargetUserId": item["targetUserId"], - "isDelivered": true, - "isSeen": true, + searchedChats!.forEach((element) { + if (element.id == item["currentUserId"]) { + var val = element.unreadMessageCount == null ? 0 : element.unreadMessageCount; + element.unreadMessageCount = val! + 1; } - ]; - updateUserChatHistoryStatusAsync(data); + }); + // dynamic data = [ + // { + // "userChatHistoryId": item["userChatHistoryId"], + // "TargetUserId": item["targetUserId"], + // "isDelivered": true, + // "isSeen": true, + // } + // ]; + // updateUserChatHistoryStatusAsync(data); } - logger.d(items); - // for (var user in searchedChats!) { - // if (user.id == items.first["id"]) { - // user.userStatus = items.first["userStatus"]; - // } - // } - // notifyListeners();2 + notifyListeners(); } void changeStatus(List? args) { diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 9884d59..06a2c32 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -34,7 +34,7 @@ class _ChatHomeState extends State { // TODO: implement initState super.initState(); data = Provider.of(context, listen: false); - data.getUserAutoLoginToken().then((Object? value) { + data.getUserAutoLoginToken(context).then((Object? value) { data.getUserRecentChats(); }); } diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index 05623f7..816aaec 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -7,6 +7,7 @@ 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'; +import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/widgets/bottom_sheet.dart'; import 'package:mohem_flutter_app/widgets/bottom_sheets/search_employee_bottom_sheet.dart'; @@ -134,26 +135,26 @@ class _ChatHomeScreenState extends State { mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: [ - // if (m.searchedChats![index].unreadMessageCount != null) - // Flexible( - // child: Container( - // padding: EdgeInsets.zero, - // alignment: Alignment.centerRight, - // width: 18, - // height: 18, - // decoration: const BoxDecoration( - // color: MyColors.redColor, - // borderRadius: BorderRadius.all( - // Radius.circular(20), - // ), - // ), - // child: (m.searchedChats![index].unreadMessageCount!.toString()) - // .toText10( - // color: MyColors.white, - // ) - // .center, - // ), - // ), + if (m.searchedChats![index].unreadMessageCount! > 0) + Flexible( + child: Container( + padding: EdgeInsets.zero, + alignment: Alignment.centerRight, + width: 18, + height: 18, + decoration: const BoxDecoration( + color: MyColors.redColor, + borderRadius: BorderRadius.all( + Radius.circular(20), + ), + ), + child: (m.searchedChats![index].unreadMessageCount!.toString()) + .toText10( + color: MyColors.white, + ) + .center, + ), + ), Flexible( child: IconButton( alignment: Alignment.centerRight, @@ -192,6 +193,7 @@ class _ChatHomeScreenState extends State { AppRoutes.chatDetailed, arguments: {"targetUser": m.searchedChats![index], "isNewChat": false}, ).then((Object? value) { + // m.GetUserChatHistoryNotDeliveredAsync(userId: int.parse(AppState().chatDetails!.response!.id.toString())); m.clearSelections(); m.notifyListeners(); });