Chat Updates & Counter Event Modifications

merge-requests/61/head
Aamir Muhammad 3 years ago
parent 5708c93ae5
commit 86ac29946f

@ -44,7 +44,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
bool _firstAutoscrollExecuted = false; bool _firstAutoscrollExecuted = false;
bool _shouldAutoscroll = false; bool _shouldAutoscroll = false;
Future<void> getUserAutoLoginToken() async { Future<void> getUserAutoLoginToken(BuildContext cxt) async {
Response response = await ApiClient().postJsonForResponse( Response response = await ApiClient().postJsonForResponse(
"${ApiConsts.chatServerBaseApiUrl}user/externaluserlogin", "${ApiConsts.chatServerBaseApiUrl}user/externaluserlogin",
{ {
@ -76,7 +76,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
return searchUserJsonModel(response.body); return searchUserJsonModel(response.body);
} }
List<ChatUser> searchUserJsonModel(String str) => List<ChatUser>.from(json.decode(str).map((x) => ChatUser.fromJson(x))); List<ChatUser> searchUserJsonModel(String str) => List<ChatUser>.from(
json.decode(str).map(
(x) => ChatUser.fromJson(x),
),
);
void getUserRecentChats() async { void getUserRecentChats() async {
Response response = await ApiClient().getJsonForResponse( Response response = await ApiClient().getJsonForResponse(
@ -90,9 +94,18 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
token: AppState().chatDetails!.response!.token, token: AppState().chatDetails!.response!.token,
); );
ChatUserModel favUList = userToList(favRes.body); ChatUserModel favUList = userToList(favRes.body);
GetUserChatHistoryNotDeliveredAsync(
userId: int.parse(
AppState().chatDetails!.response!.id.toString(),
),
);
if (favUList.response != null) { if (favUList.response != null) {
favUsersList = favUList.response!; 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 user in recentChat.response!) {
for (dynamic favUser in favUList.response!) { for (dynamic favUser in favUList.response!) {
if (user.id == favUser.id) { if (user.id == favUser.id) {
@ -101,16 +114,23 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
} }
} }
} }
pChatHistory = recentChat.response == null ? [] : recentChat.response; pChatHistory = recentChat.response ?? [];
if (pChatHistory != null) pChatHistory!.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); pChatHistory!.sort(
(ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(
b.userName!.toLowerCase(),
),
);
searchedChats = pChatHistory; searchedChats = pChatHistory;
isLoading = false; isLoading = false;
notifyListeners(); notifyListeners();
} }
Future GetUserChatHistoryNotDeliveredAsync(int userId) async { Future GetUserChatHistoryNotDeliveredAsync({required int userId}) async {
await hubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); await hubConnection.invoke(
"GetUserChatHistoryNotDeliveredAsync",
args: [userId],
);
return ""; return "";
} }
@ -132,35 +152,89 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
} }
} else { } else {
if (loadMore) { if (loadMore) {
List<SingleUserChatModel> temp = getSingleUserChatModel(response.body).reversed.toList(); List<SingleUserChatModel> temp = getSingleUserChatModel(
userChatHistory.addAll(temp); response.body,
).reversed.toList();
userChatHistory.addAll(
temp,
);
} else { } else {
userChatHistory = getSingleUserChatModel(response.body).reversed.toList(); userChatHistory = getSingleUserChatModel(
response.body,
).reversed.toList();
} }
} }
await GetUserChatHistoryNotDeliveredAsync(
userId: senderUID,
);
isLoading = false; isLoading = false;
await GetUserChatHistoryNotDeliveredAsync(senderUID);
notifyListeners(); notifyListeners();
markRead(
userChatHistory,
receiverUID,
);
}
void markRead(List<SingleUserChatModel> 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) { void updateUserChatHistoryStatusAsync(List data) {
hubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); hubConnection.invoke(
"UpdateUserChatHistoryStatusAsync",
args: [data],
);
} }
List<SingleUserChatModel> getSingleUserChatModel(String str) => List<SingleUserChatModel>.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); List<SingleUserChatModel> getSingleUserChatModel(String str) => List<SingleUserChatModel>.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<dynamic> uploadAttachments(String userId, File file) async { Future<dynamic> uploadAttachments(String userId, File file) async {
dynamic result; 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.fields.addAll({'userId': userId, 'fileSource': '1'});
request.files.add(await MultipartFile.fromPath('files', file.path)); 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 { try {
StreamedResponse response = await request.send(); StreamedResponse response = await request.send();
if (response.statusCode == 200) { if (response.statusCode == 200) {
result = jsonDecode(await response.stream.bytesToString()); result = jsonDecode(
await response.stream.bytesToString(),
);
} else { } else {
result = []; result = [];
} }
@ -176,7 +250,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
Future<void> buildHubConnection() async { Future<void> buildHubConnection() async {
HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true);
hubConnection = HubConnectionBuilder() 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( .withAutomaticReconnect(
retryDelays: <int>[2000, 5000, 10000, 20000], retryDelays: <int>[2000, 5000, 10000, 20000],
) )
@ -194,6 +271,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
({String? connectionId}) {}, ({String? connectionId}) {},
); );
if (hubConnection.state != HubConnectionState.Connected) { if (hubConnection.state != HubConnectionState.Connected) {
print("Started");
await hubConnection.start(); await hubConnection.start();
hubConnection.on("OnUpdateUserStatusAsync", changeStatus); hubConnection.on("OnUpdateUserStatusAsync", changeStatus);
hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived);
@ -260,23 +338,23 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
void chatNotDelivered(List<Object?>? args) { void chatNotDelivered(List<Object?>? args) {
dynamic items = args!.toList(); dynamic items = args!.toList();
for (dynamic item in items[0]) { for (dynamic item in items[0]) {
dynamic data = [ searchedChats!.forEach((element) {
{ if (element.id == item["currentUserId"]) {
"userChatHistoryId": item["userChatHistoryId"], var val = element.unreadMessageCount == null ? 0 : element.unreadMessageCount;
"TargetUserId": item["targetUserId"], element.unreadMessageCount = val! + 1;
"isDelivered": true,
"isSeen": true,
} }
]; });
updateUserChatHistoryStatusAsync(data); // dynamic data = [
// {
// "userChatHistoryId": item["userChatHistoryId"],
// "TargetUserId": item["targetUserId"],
// "isDelivered": true,
// "isSeen": true,
// }
// ];
// updateUserChatHistoryStatusAsync(data);
} }
logger.d(items); notifyListeners();
// for (var user in searchedChats!) {
// if (user.id == items.first["id"]) {
// user.userStatus = items.first["userStatus"];
// }
// }
// notifyListeners();2
} }
void changeStatus(List<Object?>? args) { void changeStatus(List<Object?>? args) {

@ -34,7 +34,7 @@ class _ChatHomeState extends State<ChatHome> {
// TODO: implement initState // TODO: implement initState
super.initState(); super.initState();
data = Provider.of<ChatProviderModel>(context, listen: false); data = Provider.of<ChatProviderModel>(context, listen: false);
data.getUserAutoLoginToken().then((Object? value) { data.getUserAutoLoginToken(context).then((Object? value) {
data.getUserRecentChats(); data.getUserRecentChats();
}); });
} }

@ -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/classes/colors.dart';
import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.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/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheet.dart'; import 'package:mohem_flutter_app/widgets/bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheets/search_employee_bottom_sheet.dart'; import 'package:mohem_flutter_app/widgets/bottom_sheets/search_employee_bottom_sheet.dart';
@ -134,26 +135,26 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.max, mainAxisSize: MainAxisSize.max,
children: <Widget>[ children: <Widget>[
// if (m.searchedChats![index].unreadMessageCount != null) if (m.searchedChats![index].unreadMessageCount! > 0)
// Flexible( Flexible(
// child: Container( child: Container(
// padding: EdgeInsets.zero, padding: EdgeInsets.zero,
// alignment: Alignment.centerRight, alignment: Alignment.centerRight,
// width: 18, width: 18,
// height: 18, height: 18,
// decoration: const BoxDecoration( decoration: const BoxDecoration(
// color: MyColors.redColor, color: MyColors.redColor,
// borderRadius: BorderRadius.all( borderRadius: BorderRadius.all(
// Radius.circular(20), Radius.circular(20),
// ), ),
// ), ),
// child: (m.searchedChats![index].unreadMessageCount!.toString()) child: (m.searchedChats![index].unreadMessageCount!.toString())
// .toText10( .toText10(
// color: MyColors.white, color: MyColors.white,
// ) )
// .center, .center,
// ), ),
// ), ),
Flexible( Flexible(
child: IconButton( child: IconButton(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
@ -192,6 +193,7 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
AppRoutes.chatDetailed, AppRoutes.chatDetailed,
arguments: {"targetUser": m.searchedChats![index], "isNewChat": false}, arguments: {"targetUser": m.searchedChats![index], "isNewChat": false},
).then((Object? value) { ).then((Object? value) {
// m.GetUserChatHistoryNotDeliveredAsync(userId: int.parse(AppState().chatDetails!.response!.id.toString()));
m.clearSelections(); m.clearSelections();
m.notifyListeners(); m.notifyListeners();
}); });

Loading…
Cancel
Save