added unread messages and unread chats counters

This commit is contained in:
Username1548
2025-02-20 16:41:07 +07:00
parent 120af45dd5
commit 93899e316f
45 changed files with 1784 additions and 1884 deletions

View File

@@ -0,0 +1,144 @@
import 'dart:async';
import 'dart:convert';
import 'package:eatvio_app/core/utils/enums.dart';
import 'package:eatvio_app/core/websockets/ws_manager.dart';
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart';
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ChatsCubit extends Cubit<ChatsState> {
final ChatRepository chatRepository;
final ProfileRepository profileRepository;
final WsManager wsManager;
late StreamSubscription? newIncomingMessagesSubscription;
late StreamSubscription? newLastMessageSubscription;
ChatsCubit({
required this.chatRepository,
required this.wsManager,
required this.profileRepository,
}) : super(ChatsState()) {
newIncomingMessagesSubscription = wsManager.newMessagesStream?.listen((event) {
_handleNewMessageViaSocket(event.data);
});
newLastMessageSubscription = chatRepository.newUserMessagesStream.listen((message) {
_setNewLastMessage(message);
});
}
String? _query;
Future<void> getChatRoomsWithLoading({String? query}) async {
_query = query;
emit(state.copyWith(state: BaseState.loading));
try {
final chatRooms = await chatRepository.getChatRoomPreviews(query: query);
final unreadChats = chatRooms.where(
(element) => element.unreadMessagesCount > 0,
);
emit(
state.copyWith(
chatRooms: chatRooms,
chatsWithUnreadMessagesCount: unreadChats.length,
state: BaseState.success,
),
);
} catch (e) {
emit(
state.copyWith(errorMessage: e.toString(), state: BaseState.error),
);
}
}
Future<void> getChatRooms({String? query}) async {
_query = query;
try {
final chatRooms = await chatRepository.getChatRoomPreviews(query: query);
final unreadChats = chatRooms.where(
(element) => element.unreadMessagesCount > 0,
);
emit(
state.copyWith(
chatRooms: chatRooms,
chatsWithUnreadMessagesCount: unreadChats.length,
state: BaseState.success,
),
);
} catch (e) {
emit(
state.copyWith(errorMessage: e.toString(), state: BaseState.error),
);
}
}
void reduceUnreadMessagesCount({required String chatId, required int count}) {
bool isChatRead = false;
final updatedChatRooms = state.chatRooms.map((room) {
if (room.id == chatId) {
int unreadMessagesCount = room.unreadMessagesCount - count;
if (unreadMessagesCount <= 0) {
unreadMessagesCount = 0;
isChatRead = true;
}
return room.copyWith(unreadMessagesCount: unreadMessagesCount);
}
return room;
}).toList();
emit(
state.copyWith(
chatRooms: updatedChatRooms,
chatsWithUnreadMessagesCount: isChatRead ? state.chatsWithUnreadMessagesCount - 1 : state.chatsWithUnreadMessagesCount,
),
);
}
Future<void> _handleNewMessageViaSocket(dynamic data) async {
final json = jsonDecode(data);
final message = ChatMessageModel.fromJson(json['message']);
final currentChatRooms = [...state.chatRooms];
bool wasChanged = false;
bool willIncrementUnreadChats = false;
final updatedChatRooms = currentChatRooms.map((chatRoom) {
if (chatRoom.id == message.roomId) {
wasChanged = true;
if (chatRoom.unreadMessagesCount == 0) {
willIncrementUnreadChats = true;
}
return chatRoom.copyWith(lastMessage: message, unreadMessagesCount: chatRoom.unreadMessagesCount + 1);
}
return chatRoom;
}).toList();
if (!wasChanged && _query == null) {
getChatRooms();
} else {
emit(
state.copyWith(
chatRooms: updatedChatRooms,
chatsWithUnreadMessagesCount: willIncrementUnreadChats ? state.chatsWithUnreadMessagesCount + 1 : state.chatsWithUnreadMessagesCount,
),
);
}
}
void _setNewLastMessage(ChatMessageModel message) {
final chats = state.chatRooms.map((chat) {
if (chat.id == message.roomId) {
return chat.copyWith(lastMessage: message);
}
return chat;
}).toList();
emit(state.copyWith(chatRooms: chats));
}
@override
Future<void> close() {
newIncomingMessagesSubscription?.cancel();
return super.close();
}
}

View File

@@ -0,0 +1,17 @@
import 'package:eatvio_app/core/utils/enums.dart';
import 'package:eatvio_app/features/chat/models/chat_room_preview_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'chats_state.freezed.dart';
@freezed
class ChatsState with _$ChatsState {
factory ChatsState({
@Default(BaseState.initial) BaseState state,
@Default(0) int chatsWithUnreadMessagesCount,
@Default([]) List<ChatRoom> chatRooms,
@Default(null) String? errorMessage,
}) = _ChatsState;
}

View File

@@ -0,0 +1,228 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'chats_state.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
/// @nodoc
mixin _$ChatsState {
BaseState get state => throw _privateConstructorUsedError;
int get chatsWithUnreadMessagesCount => throw _privateConstructorUsedError;
List<ChatRoom> get chatRooms => throw _privateConstructorUsedError;
String? get errorMessage => throw _privateConstructorUsedError;
/// Create a copy of ChatsState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$ChatsStateCopyWith<ChatsState> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $ChatsStateCopyWith<$Res> {
factory $ChatsStateCopyWith(
ChatsState value, $Res Function(ChatsState) then) =
_$ChatsStateCopyWithImpl<$Res, ChatsState>;
@useResult
$Res call(
{BaseState state,
int chatsWithUnreadMessagesCount,
List<ChatRoom> chatRooms,
String? errorMessage});
}
/// @nodoc
class _$ChatsStateCopyWithImpl<$Res, $Val extends ChatsState>
implements $ChatsStateCopyWith<$Res> {
_$ChatsStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of ChatsState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? state = null,
Object? chatsWithUnreadMessagesCount = null,
Object? chatRooms = null,
Object? errorMessage = freezed,
}) {
return _then(_value.copyWith(
state: null == state
? _value.state
: state // ignore: cast_nullable_to_non_nullable
as BaseState,
chatsWithUnreadMessagesCount: null == chatsWithUnreadMessagesCount
? _value.chatsWithUnreadMessagesCount
: chatsWithUnreadMessagesCount // ignore: cast_nullable_to_non_nullable
as int,
chatRooms: null == chatRooms
? _value.chatRooms
: chatRooms // ignore: cast_nullable_to_non_nullable
as List<ChatRoom>,
errorMessage: freezed == errorMessage
? _value.errorMessage
: errorMessage // ignore: cast_nullable_to_non_nullable
as String?,
) as $Val);
}
}
/// @nodoc
abstract class _$$ChatsStateImplCopyWith<$Res>
implements $ChatsStateCopyWith<$Res> {
factory _$$ChatsStateImplCopyWith(
_$ChatsStateImpl value, $Res Function(_$ChatsStateImpl) then) =
__$$ChatsStateImplCopyWithImpl<$Res>;
@override
@useResult
$Res call(
{BaseState state,
int chatsWithUnreadMessagesCount,
List<ChatRoom> chatRooms,
String? errorMessage});
}
/// @nodoc
class __$$ChatsStateImplCopyWithImpl<$Res>
extends _$ChatsStateCopyWithImpl<$Res, _$ChatsStateImpl>
implements _$$ChatsStateImplCopyWith<$Res> {
__$$ChatsStateImplCopyWithImpl(
_$ChatsStateImpl _value, $Res Function(_$ChatsStateImpl) _then)
: super(_value, _then);
/// Create a copy of ChatsState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? state = null,
Object? chatsWithUnreadMessagesCount = null,
Object? chatRooms = null,
Object? errorMessage = freezed,
}) {
return _then(_$ChatsStateImpl(
state: null == state
? _value.state
: state // ignore: cast_nullable_to_non_nullable
as BaseState,
chatsWithUnreadMessagesCount: null == chatsWithUnreadMessagesCount
? _value.chatsWithUnreadMessagesCount
: chatsWithUnreadMessagesCount // ignore: cast_nullable_to_non_nullable
as int,
chatRooms: null == chatRooms
? _value._chatRooms
: chatRooms // ignore: cast_nullable_to_non_nullable
as List<ChatRoom>,
errorMessage: freezed == errorMessage
? _value.errorMessage
: errorMessage // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// @nodoc
class _$ChatsStateImpl implements _ChatsState {
_$ChatsStateImpl(
{this.state = BaseState.initial,
this.chatsWithUnreadMessagesCount = 0,
final List<ChatRoom> chatRooms = const [],
this.errorMessage = null})
: _chatRooms = chatRooms;
@override
@JsonKey()
final BaseState state;
@override
@JsonKey()
final int chatsWithUnreadMessagesCount;
final List<ChatRoom> _chatRooms;
@override
@JsonKey()
List<ChatRoom> get chatRooms {
if (_chatRooms is EqualUnmodifiableListView) return _chatRooms;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_chatRooms);
}
@override
@JsonKey()
final String? errorMessage;
@override
String toString() {
return 'ChatsState(state: $state, chatsWithUnreadMessagesCount: $chatsWithUnreadMessagesCount, chatRooms: $chatRooms, errorMessage: $errorMessage)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$ChatsStateImpl &&
(identical(other.state, state) || other.state == state) &&
(identical(other.chatsWithUnreadMessagesCount,
chatsWithUnreadMessagesCount) ||
other.chatsWithUnreadMessagesCount ==
chatsWithUnreadMessagesCount) &&
const DeepCollectionEquality()
.equals(other._chatRooms, _chatRooms) &&
(identical(other.errorMessage, errorMessage) ||
other.errorMessage == errorMessage));
}
@override
int get hashCode => Object.hash(
runtimeType,
state,
chatsWithUnreadMessagesCount,
const DeepCollectionEquality().hash(_chatRooms),
errorMessage);
/// Create a copy of ChatsState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$ChatsStateImplCopyWith<_$ChatsStateImpl> get copyWith =>
__$$ChatsStateImplCopyWithImpl<_$ChatsStateImpl>(this, _$identity);
}
abstract class _ChatsState implements ChatsState {
factory _ChatsState(
{final BaseState state,
final int chatsWithUnreadMessagesCount,
final List<ChatRoom> chatRooms,
final String? errorMessage}) = _$ChatsStateImpl;
@override
BaseState get state;
@override
int get chatsWithUnreadMessagesCount;
@override
List<ChatRoom> get chatRooms;
@override
String? get errorMessage;
/// Create a copy of ChatsState
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$ChatsStateImplCopyWith<_$ChatsStateImpl> get copyWith =>
throw _privateConstructorUsedError;
}