rewrite connection inspection of websocket, and notificate user when connection is done
parent
9a730d68e5
commit
5c2022d107
|
@ -17,8 +17,9 @@ import 'package:together_mobile/notification_api.dart';
|
||||||
|
|
||||||
enum SocketStatus {
|
enum SocketStatus {
|
||||||
connected,
|
connected,
|
||||||
closed,
|
reconnecting,
|
||||||
error,
|
error,
|
||||||
|
closed,
|
||||||
}
|
}
|
||||||
|
|
||||||
class WebSocketManager extends ChangeNotifier {
|
class WebSocketManager extends ChangeNotifier {
|
||||||
|
@ -29,21 +30,17 @@ class WebSocketManager extends ChangeNotifier {
|
||||||
Timer? heartBeatTimer;
|
Timer? heartBeatTimer;
|
||||||
Timer? serverTimer;
|
Timer? serverTimer;
|
||||||
Timer? reconnectTimer;
|
Timer? reconnectTimer;
|
||||||
int reconnectCount = 30;
|
int reconnectCount = 10;
|
||||||
int reconnectTimes = 0;
|
int reconnectTimes = 0;
|
||||||
Duration timeout = const Duration(seconds: 4);
|
Duration heartBeatTimeout = const Duration(seconds: 4);
|
||||||
|
Duration reconnectTimeout = const Duration(seconds: 3);
|
||||||
|
|
||||||
void connect(String userId, bool isReconnect) {
|
void connect(String userId, bool isReconnect) {
|
||||||
id = userId;
|
id = userId;
|
||||||
wsUrl = Uri.parse('ws://10.0.2.2:8000/ws/$id?is_reconnect=$isReconnect');
|
wsUrl = Uri.parse('ws://10.0.2.2:8000/ws/$id?is_reconnect=$isReconnect');
|
||||||
|
// This doesn't blcok the programe whethe it connect the server or not
|
||||||
|
// So heartBeat will be executre straightly
|
||||||
channel = WebSocketChannel.connect(wsUrl);
|
channel = WebSocketChannel.connect(wsUrl);
|
||||||
socketStatus = SocketStatus.connected;
|
|
||||||
print('websocket connected <$channel>');
|
|
||||||
if (reconnectTimer != null) {
|
|
||||||
reconnectTimer!.cancel();
|
|
||||||
reconnectTimer = null;
|
|
||||||
reconnectTimes = 0;
|
|
||||||
}
|
|
||||||
heartBeatInspect();
|
heartBeatInspect();
|
||||||
|
|
||||||
channel.stream.listen(onData, onError: onError, onDone: onDone);
|
channel.stream.listen(onData, onError: onError, onDone: onDone);
|
||||||
|
@ -54,6 +51,7 @@ class WebSocketManager extends ChangeNotifier {
|
||||||
wsUrl = Uri();
|
wsUrl = Uri();
|
||||||
id = '';
|
id = '';
|
||||||
socketStatus = SocketStatus.closed;
|
socketStatus = SocketStatus.closed;
|
||||||
|
notifyListeners();
|
||||||
heartBeatTimer?.cancel();
|
heartBeatTimer?.cancel();
|
||||||
serverTimer?.cancel();
|
serverTimer?.cancel();
|
||||||
reconnectTimer?.cancel();
|
reconnectTimer?.cancel();
|
||||||
|
@ -64,11 +62,22 @@ class WebSocketManager extends ChangeNotifier {
|
||||||
}
|
}
|
||||||
|
|
||||||
void onData(jsonData) {
|
void onData(jsonData) {
|
||||||
|
// If socket can receive msg, that means connection is estabilished
|
||||||
|
socketStatus = SocketStatus.connected;
|
||||||
|
notifyListeners();
|
||||||
|
print('websocket connected <$channel>');
|
||||||
|
if (reconnectTimer != null) {
|
||||||
|
reconnectTimer!.cancel();
|
||||||
|
reconnectTimer = null;
|
||||||
|
reconnectTimes = 0;
|
||||||
|
}
|
||||||
|
|
||||||
heartBeatInspect();
|
heartBeatInspect();
|
||||||
|
|
||||||
Map<String, dynamic> data = json.decode(jsonData);
|
Map<String, dynamic> data = json.decode(jsonData);
|
||||||
switch (data['event']) {
|
switch (data['event']) {
|
||||||
case 'friend-chat-msg':
|
case 'friend-chat-msg':
|
||||||
receiveFriendMsg(data);
|
receiveFriendMsg(data, true);
|
||||||
case 'apply-friend':
|
case 'apply-friend':
|
||||||
receiveApplyFriend(data);
|
receiveApplyFriend(data);
|
||||||
case 'friend-added':
|
case 'friend-added':
|
||||||
|
@ -80,21 +89,53 @@ class WebSocketManager extends ChangeNotifier {
|
||||||
case 'group-chat-creation':
|
case 'group-chat-creation':
|
||||||
receiveGroupChatCreation(data);
|
receiveGroupChatCreation(data);
|
||||||
case 'group-chat-msg':
|
case 'group-chat-msg':
|
||||||
receiveGroupChatMsg(data);
|
receiveGroupChatMsg(data, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// This will be trigger while server or client close the connection
|
||||||
|
// for example server is restarting
|
||||||
void onDone() {
|
void onDone() {
|
||||||
print('websocket disconnected <$channel>');
|
print('websocket disconnected <$channel>');
|
||||||
|
|
||||||
if (socketStatus == SocketStatus.closed) {
|
if (socketStatus == SocketStatus.closed) {
|
||||||
|
// Client close the connection
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (socketStatus == SocketStatus.connected) {
|
||||||
|
// Server close the connection
|
||||||
|
socketStatus = SocketStatus.reconnecting;
|
||||||
|
notifyListeners();
|
||||||
|
print(111111111111111);
|
||||||
|
reconnectTimes++;
|
||||||
reconnect();
|
reconnect();
|
||||||
}
|
}
|
||||||
|
if (reconnectTimes >= reconnectCount) {
|
||||||
|
socketStatus = SocketStatus.error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void onError(Object error) {}
|
// This will be trigger while server exactly shutdown
|
||||||
|
void onError(Object error, StackTrace st) {
|
||||||
|
print('Websocket connect occurs error: <$error>');
|
||||||
|
// print(st);
|
||||||
|
if (reconnectTimes >= reconnectCount) {
|
||||||
|
socketStatus = SocketStatus.error;
|
||||||
|
if (heartBeatTimer != null) {
|
||||||
|
heartBeatTimer!.cancel();
|
||||||
|
heartBeatTimer = null;
|
||||||
|
}
|
||||||
|
channel.sink.close();
|
||||||
|
notifyListeners();
|
||||||
|
} else {
|
||||||
|
print('${reconnectTimes}th reconnection');
|
||||||
|
reconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void heartBeatInspect() {
|
void heartBeatInspect() {
|
||||||
|
print('start heartbeat inspect......');
|
||||||
|
|
||||||
if (heartBeatTimer != null) {
|
if (heartBeatTimer != null) {
|
||||||
heartBeatTimer!.cancel();
|
heartBeatTimer!.cancel();
|
||||||
heartBeatTimer = null;
|
heartBeatTimer = null;
|
||||||
|
@ -104,32 +145,19 @@ class WebSocketManager extends ChangeNotifier {
|
||||||
serverTimer!.cancel();
|
serverTimer!.cancel();
|
||||||
serverTimer = null;
|
serverTimer = null;
|
||||||
}
|
}
|
||||||
print('start heartbeat inspect......');
|
|
||||||
heartBeatTimer = Timer(timeout, () {
|
heartBeatTimer = Timer(heartBeatTimeout, () {
|
||||||
channel.sink.add(json.encode({'event': 'ping'}));
|
channel.sink.add(json.encode({'event': 'ping'}));
|
||||||
serverTimer = Timer(timeout, () {
|
serverTimer = Timer(heartBeatTimeout, () {
|
||||||
|
// This will trigger the onDone callback
|
||||||
channel.sink.close(status.internalServerError);
|
channel.sink.close(status.internalServerError);
|
||||||
socketStatus = SocketStatus.closed;
|
socketStatus = SocketStatus.reconnecting;
|
||||||
|
notifyListeners();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void reconnect() {
|
void reconnect() {
|
||||||
if (socketStatus == SocketStatus.error) {
|
|
||||||
if (heartBeatTimer != null) {
|
|
||||||
heartBeatTimer!.cancel();
|
|
||||||
heartBeatTimer = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (serverTimer != null) {
|
|
||||||
serverTimer!.cancel();
|
|
||||||
serverTimer = null;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
print('websocket reconnecting......');
|
|
||||||
|
|
||||||
if (heartBeatTimer != null) {
|
if (heartBeatTimer != null) {
|
||||||
heartBeatTimer!.cancel();
|
heartBeatTimer!.cancel();
|
||||||
heartBeatTimer = null;
|
heartBeatTimer = null;
|
||||||
|
@ -140,23 +168,29 @@ class WebSocketManager extends ChangeNotifier {
|
||||||
serverTimer = null;
|
serverTimer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
reconnectTimer = Timer.periodic(timeout, (timer) {
|
if (reconnectTimer != null) {
|
||||||
|
reconnectTimer!.cancel();
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
reconnectTimer = Timer(reconnectTimeout, () {
|
||||||
if (reconnectTimes < reconnectCount) {
|
if (reconnectTimes < reconnectCount) {
|
||||||
connect(id, true);
|
print('websocket reconnecting......');
|
||||||
reconnectTimes++;
|
reconnectTimes++;
|
||||||
|
connect(id, true);
|
||||||
} else {
|
} else {
|
||||||
print('reconnection times exceed the max times......');
|
print('reconnection times exceed the max times......');
|
||||||
// If it is still disconnection after reconnect 30 times, set the socket
|
// If it is still disconnection after reconnect 30 times, set the socket
|
||||||
// status to error, means the network is bad, and stop reconnecting.
|
// status to error, means the network is bad, and stop reconnecting.
|
||||||
socketStatus = SocketStatus.error;
|
socketStatus = SocketStatus.error;
|
||||||
|
notifyListeners();
|
||||||
channel.sink.close();
|
channel.sink.close();
|
||||||
timer.cancel();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void receiveFriendMsg(Map<String, dynamic> msg) async {
|
void receiveFriendMsg(Map<String, dynamic> msg, bool isShowNotification) async {
|
||||||
print('=================收到了好友信息事件==================');
|
print('=================收到了好友信息事件==================');
|
||||||
print(msg);
|
print(msg);
|
||||||
print('=======================================');
|
print('=======================================');
|
||||||
|
@ -209,6 +243,10 @@ void receiveFriendMsg(Map<String, dynamic> msg) async {
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (!isShowNotification) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
String name = getIt.get<Contact>().friends[senderId]!.friendRemark.isEmpty
|
String name = getIt.get<Contact>().friends[senderId]!.friendRemark.isEmpty
|
||||||
? getIt.get<ContactAccountProfile>().friends[senderId]!.nickname
|
? getIt.get<ContactAccountProfile>().friends[senderId]!.nickname
|
||||||
: getIt.get<Contact>().friends[senderId]!.friendRemark;
|
: getIt.get<Contact>().friends[senderId]!.friendRemark;
|
||||||
|
@ -280,10 +318,6 @@ void receiveChatImages(Map<String, dynamic> msg) async {
|
||||||
await file.create(recursive: true);
|
await file.create(recursive: true);
|
||||||
await file.writeAsBytes(List<int>.from(msg['bytes']));
|
await file.writeAsBytes(List<int>.from(msg['bytes']));
|
||||||
}
|
}
|
||||||
// File file = await File('$chatImageDir/${msg['filename']}').create(
|
|
||||||
// recursive: true,
|
|
||||||
// // );
|
|
||||||
// await file.writeAsBytes(msg['bytes']);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void receiveGroupChatCreation(Map<String, dynamic> msg) {
|
void receiveGroupChatCreation(Map<String, dynamic> msg) {
|
||||||
|
@ -295,7 +329,8 @@ void receiveGroupChatCreation(Map<String, dynamic> msg) {
|
||||||
getIt.get<ContactAccountProfile>().addGroupChatProfile(groupChatId, msg);
|
getIt.get<ContactAccountProfile>().addGroupChatProfile(groupChatId, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
void receiveGroupChatMsg(Map<String, dynamic> msg) async {
|
void receiveGroupChatMsg(
|
||||||
|
Map<String, dynamic> msg, bool isShowNotification) async {
|
||||||
print('=================收到了群聊信息事件==================');
|
print('=================收到了群聊信息事件==================');
|
||||||
print(msg);
|
print(msg);
|
||||||
print('=======================================');
|
print('=======================================');
|
||||||
|
@ -349,6 +384,10 @@ void receiveGroupChatMsg(Map<String, dynamic> msg) async {
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (!isShowNotification) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
String avatar =
|
String avatar =
|
||||||
getIt.get<ContactAccountProfile>().groupChats[groupChatId]!.avatar;
|
getIt.get<ContactAccountProfile>().groupChats[groupChatId]!.avatar;
|
||||||
late String name;
|
late String name;
|
||||||
|
|
|
@ -0,0 +1,14 @@
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
|
||||||
|
import 'server.dart';
|
||||||
|
|
||||||
|
Future<Map<String, dynamic>> getUnreceivedMsg(String userId) async {
|
||||||
|
Response response = await request.get(
|
||||||
|
'/message/unreceived',
|
||||||
|
queryParameters: {
|
||||||
|
'receiver_id': userId,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
}
|
|
@ -12,7 +12,7 @@ final chatRouter = GoRoute(
|
||||||
name: 'Chat',
|
name: 'Chat',
|
||||||
builder: (context, state) {
|
builder: (context, state) {
|
||||||
getIt.get<RouteState>().changeRoute('Chat');
|
getIt.get<RouteState>().changeRoute('Chat');
|
||||||
return const ChatScreen();
|
return ChatScreen();
|
||||||
},
|
},
|
||||||
routes: [
|
routes: [
|
||||||
GoRoute(
|
GoRoute(
|
||||||
|
|
|
@ -0,0 +1,227 @@
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:cached_network_image/cached_network_image.dart';
|
||||||
|
import 'package:hive_flutter/hive_flutter.dart';
|
||||||
|
import 'package:together_mobile/database/hive_database.dart';
|
||||||
|
import 'package:together_mobile/request/message.dart';
|
||||||
|
|
||||||
|
import 'package:together_mobile/screens/chat/components/group_chat_chat_tile.dart';
|
||||||
|
import 'components/friend_chat_tile.dart';
|
||||||
|
import 'components/add_menu.dart';
|
||||||
|
import 'package:together_mobile/database/box_type.dart';
|
||||||
|
import 'package:together_mobile/models/websocket_model.dart';
|
||||||
|
import 'package:together_mobile/utils/format_datetime.dart';
|
||||||
|
import 'package:together_mobile/models/contact_model.dart';
|
||||||
|
import 'package:together_mobile/models/apply_list_model.dart';
|
||||||
|
import 'package:together_mobile/request/apply.dart';
|
||||||
|
import 'package:together_mobile/request/server.dart';
|
||||||
|
import 'package:together_mobile/request/contact.dart';
|
||||||
|
import 'package:together_mobile/models/user_model.dart';
|
||||||
|
import 'package:together_mobile/models/init_get_it.dart';
|
||||||
|
import 'package:together_mobile/request/user_profile.dart';
|
||||||
|
|
||||||
|
class ChatScreen extends StatefulWidget {
|
||||||
|
const ChatScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ChatScreen> createState() => _ChatScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ChatScreenState extends State<ChatScreen> {
|
||||||
|
Future<bool> _initData() async {
|
||||||
|
if (!getIt.get<UserProfile>().isInitialised) {
|
||||||
|
await HiveDatabase.init();
|
||||||
|
|
||||||
|
getIt.get<WebSocketManager>().connect(getIt.get<UserAccount>().id, false);
|
||||||
|
|
||||||
|
String userId = getIt.get<UserAccount>().id;
|
||||||
|
|
||||||
|
List<Map<String, dynamic>> res = await Future.wait([
|
||||||
|
getMyProfile(userId),
|
||||||
|
getApplyList(userId),
|
||||||
|
getContact(userId),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await getIt.get<UserProfile>().init(res[0]['data']);
|
||||||
|
|
||||||
|
if (res[1]['code'] == 10600) {
|
||||||
|
getIt.get<ApplyList>().init(res[1]['data']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res[2]['code'] == 10700) {
|
||||||
|
getIt.get<Contact>().init(res[2]['data']);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> contactAcctProfRes = await getContactAccountProfiles(
|
||||||
|
getIt.get<Contact>().friends.keys.toList(),
|
||||||
|
getIt.get<Contact>().groupChats.keys.toList(),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (contactAcctProfRes['code'] == 10700) {
|
||||||
|
getIt.get<ContactAccountProfile>().init(contactAcctProfRes['data']);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _getUnreceivedMsg(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Future(() => true);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _getUnreceivedMsg(String userId) async {
|
||||||
|
print('触发了获取信息事件..................');
|
||||||
|
final res = await getUnreceivedMsg(userId);
|
||||||
|
|
||||||
|
if (res['code'] == 10900) {
|
||||||
|
for (var msg in res['data'] as List<Map<String, dynamic>>) {
|
||||||
|
if (msg['event'] == 'friend-chat-msg') {
|
||||||
|
receiveFriendMsg(msg, false);
|
||||||
|
} else if (msg['event'] == 'group-chat-msg') {
|
||||||
|
receiveGroupChatMsg(msg, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return FutureBuilder(
|
||||||
|
future: _initData(),
|
||||||
|
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
|
||||||
|
if (snapshot.hasData) {
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
leading: getIt.get<UserProfile>().avatar.isEmpty
|
||||||
|
? const CircleAvatar(
|
||||||
|
backgroundImage: AssetImage('assets/images/user_2.png'),
|
||||||
|
)
|
||||||
|
: CircleAvatar(
|
||||||
|
backgroundImage: CachedNetworkImageProvider(
|
||||||
|
'$userAvatarsUrl/${getIt.get<UserProfile>().avatar}',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
title: Text(getIt.get<UserProfile>().nickname),
|
||||||
|
centerTitle: true,
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
onPressed: () {},
|
||||||
|
splashRadius: 20,
|
||||||
|
icon: const Icon(Icons.search),
|
||||||
|
),
|
||||||
|
const AddMenu(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
// Use ListView.builder because it renders list element on demand
|
||||||
|
body: RefreshIndicator(
|
||||||
|
onRefresh: () async {
|
||||||
|
String userId = getIt.get<UserAccount>().id;
|
||||||
|
if (getIt.get<WebSocketManager>().socketStatus ==
|
||||||
|
SocketStatus.closed) {
|
||||||
|
getIt.get<WebSocketManager>().connect(userId, false);
|
||||||
|
}
|
||||||
|
await _getUnreceivedMsg(userId);
|
||||||
|
},
|
||||||
|
child: ValueListenableBuilder(
|
||||||
|
valueListenable:
|
||||||
|
Hive.box<ChatSetting>('chat_setting').listenable(),
|
||||||
|
builder: (context, Box<ChatSetting> box, _) {
|
||||||
|
final List<ChatSetting> openedChat =
|
||||||
|
box.values.where((element) => element.isOpen).toList();
|
||||||
|
|
||||||
|
// latestMsg on the top
|
||||||
|
openedChat.sort(
|
||||||
|
(a, b) => b.latestDateTime.compareTo(a.latestDateTime),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (openedChat.isEmpty) {
|
||||||
|
return const Center(
|
||||||
|
child: Text(
|
||||||
|
'没有最新消息',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 18,
|
||||||
|
letterSpacing: 5.0,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return ListView.builder(
|
||||||
|
physics: const BouncingScrollPhysics(
|
||||||
|
parent: AlwaysScrollableScrollPhysics(),
|
||||||
|
),
|
||||||
|
itemCount: openedChat.length,
|
||||||
|
itemBuilder: (BuildContext context, int index) {
|
||||||
|
String contactId = openedChat[index].contactId;
|
||||||
|
String showedTime = formatTileDateTime(
|
||||||
|
openedChat[index].latestDateTime,
|
||||||
|
);
|
||||||
|
int unreadCount = openedChat[index].unreadCount;
|
||||||
|
|
||||||
|
return ValueListenableBuilder(
|
||||||
|
valueListenable:
|
||||||
|
Hive.box<MessageT>('message_$contactId')
|
||||||
|
.listenable(),
|
||||||
|
builder: (context, messageTBox, _) {
|
||||||
|
int length = messageTBox.length;
|
||||||
|
if (length > 0) {
|
||||||
|
MessageT messageT =
|
||||||
|
messageTBox.getAt(length - 1)!;
|
||||||
|
if (openedChat[index].type == 0) {
|
||||||
|
return FriendChatTile(
|
||||||
|
key: ValueKey(contactId),
|
||||||
|
index: index,
|
||||||
|
contactId: contactId,
|
||||||
|
senderId: messageT.senderId,
|
||||||
|
messageType: messageT.type,
|
||||||
|
text: messageT.text,
|
||||||
|
attachments: messageT.attachments,
|
||||||
|
dateTime: showedTime,
|
||||||
|
isShowTime: messageT.isShowTime,
|
||||||
|
unreadCount: unreadCount,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return GroupChatChatTile(
|
||||||
|
key: ValueKey(contactId),
|
||||||
|
index: index,
|
||||||
|
contactId: contactId,
|
||||||
|
senderId: messageT.senderId,
|
||||||
|
messageType: messageT.type,
|
||||||
|
text: messageT.text,
|
||||||
|
attachments: messageT.attachments,
|
||||||
|
dateTime: showedTime,
|
||||||
|
isShowTime: messageT.isShowTime,
|
||||||
|
unreadCount: unreadCount,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return const SizedBox();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return const Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 60,
|
||||||
|
height: 60,
|
||||||
|
child: CircularProgressIndicator(),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: EdgeInsets.only(top: 20),
|
||||||
|
child: Text('Loading data....'),
|
||||||
|
)
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,8 +1,11 @@
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import 'package:cached_network_image/cached_network_image.dart';
|
import 'package:cached_network_image/cached_network_image.dart';
|
||||||
|
import 'package:get_it_mixin/get_it_mixin.dart';
|
||||||
import 'package:hive_flutter/hive_flutter.dart';
|
import 'package:hive_flutter/hive_flutter.dart';
|
||||||
|
import 'package:together_mobile/common/constants.dart';
|
||||||
import 'package:together_mobile/database/hive_database.dart';
|
import 'package:together_mobile/database/hive_database.dart';
|
||||||
|
import 'package:together_mobile/request/message.dart';
|
||||||
|
|
||||||
import 'package:together_mobile/screens/chat/components/group_chat_chat_tile.dart';
|
import 'package:together_mobile/screens/chat/components/group_chat_chat_tile.dart';
|
||||||
import 'components/friend_chat_tile.dart';
|
import 'components/friend_chat_tile.dart';
|
||||||
|
@ -19,24 +22,26 @@ import 'package:together_mobile/models/user_model.dart';
|
||||||
import 'package:together_mobile/models/init_get_it.dart';
|
import 'package:together_mobile/models/init_get_it.dart';
|
||||||
import 'package:together_mobile/request/user_profile.dart';
|
import 'package:together_mobile/request/user_profile.dart';
|
||||||
|
|
||||||
class ChatScreen extends StatefulWidget {
|
class ChatScreen extends StatefulWidget with GetItStatefulWidgetMixin {
|
||||||
const ChatScreen({super.key});
|
ChatScreen({super.key});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<ChatScreen> createState() => _ChatScreenState();
|
State<ChatScreen> createState() => _ChatScreenState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _ChatScreenState extends State<ChatScreen> {
|
class _ChatScreenState extends State<ChatScreen> with GetItStateMixin {
|
||||||
Future<bool> _initData() async {
|
Future<bool> _initData() async {
|
||||||
if (!getIt.get<UserProfile>().isInitialised) {
|
if (!getIt.get<UserProfile>().isInitialised) {
|
||||||
await HiveDatabase.init();
|
await HiveDatabase.init();
|
||||||
|
|
||||||
getIt.get<WebSocketManager>().connect(getIt.get<UserAccount>().id, false);
|
getIt.get<WebSocketManager>().connect(getIt.get<UserAccount>().id, false);
|
||||||
|
|
||||||
|
String userId = getIt.get<UserAccount>().id;
|
||||||
|
|
||||||
List<Map<String, dynamic>> res = await Future.wait([
|
List<Map<String, dynamic>> res = await Future.wait([
|
||||||
getMyProfile(getIt.get<UserAccount>().id),
|
getMyProfile(userId),
|
||||||
getApplyList(getIt.get<UserAccount>().id),
|
getApplyList(userId),
|
||||||
getContact(getIt.get<UserAccount>().id),
|
getContact(userId),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await getIt.get<UserProfile>().init(res[0]['data']);
|
await getIt.get<UserProfile>().init(res[0]['data']);
|
||||||
|
@ -57,13 +62,34 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||||
if (contactAcctProfRes['code'] == 10700) {
|
if (contactAcctProfRes['code'] == 10700) {
|
||||||
getIt.get<ContactAccountProfile>().init(contactAcctProfRes['data']);
|
getIt.get<ContactAccountProfile>().init(contactAcctProfRes['data']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await _getUnreceivedMsg(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Future(() => true);
|
return Future(() => true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _getUnreceivedMsg(String userId) async {
|
||||||
|
print('触发了获取信息事件..................');
|
||||||
|
final res = await getUnreceivedMsg(userId);
|
||||||
|
|
||||||
|
if (res['code'] == 10900) {
|
||||||
|
for (var msg in res['data'] as List<Map<String, dynamic>>) {
|
||||||
|
if (msg['event'] == 'friend-chat-msg') {
|
||||||
|
receiveFriendMsg(msg, false);
|
||||||
|
} else if (msg['event'] == 'group-chat-msg') {
|
||||||
|
receiveGroupChatMsg(msg, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
SocketStatus socketStatus = watchOnly(
|
||||||
|
(WebSocketManager wm) => wm.socketStatus,
|
||||||
|
);
|
||||||
|
|
||||||
return FutureBuilder(
|
return FutureBuilder(
|
||||||
future: _initData(),
|
future: _initData(),
|
||||||
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
|
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
|
||||||
|
@ -91,24 +117,57 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
// Use ListView.builder because it renders list element on demand
|
// Use ListView.builder because it renders list element on demand
|
||||||
body: RefreshIndicator(
|
body: Column(
|
||||||
onRefresh: () async {
|
children: [
|
||||||
return Future.delayed(
|
if (socketStatus == SocketStatus.reconnecting)
|
||||||
const Duration(
|
Container(
|
||||||
seconds: 2,
|
height: 35,
|
||||||
|
width: double.maxFinite,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
color: kErrorColor.withOpacity(0.35),
|
||||||
|
child: const Text(
|
||||||
|
'网络中断,正在重新连接......',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
color: kErrorColor,
|
||||||
),
|
),
|
||||||
);
|
),
|
||||||
|
),
|
||||||
|
if (socketStatus == SocketStatus.error)
|
||||||
|
Container(
|
||||||
|
height: 35,
|
||||||
|
width: double.maxFinite,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
color: kErrorColor.withOpacity(0.35),
|
||||||
|
child: const Text(
|
||||||
|
'网络异常,请下划尝试重新连接!',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
color: kErrorColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: RefreshIndicator(
|
||||||
|
onRefresh: () async {
|
||||||
|
String userId = getIt.get<UserAccount>().id;
|
||||||
|
if (socketStatus == SocketStatus.error) {
|
||||||
|
getIt.get<WebSocketManager>().connect(userId, false);
|
||||||
|
}
|
||||||
|
await _getUnreceivedMsg(userId);
|
||||||
},
|
},
|
||||||
child: ValueListenableBuilder(
|
child: ValueListenableBuilder(
|
||||||
valueListenable:
|
valueListenable:
|
||||||
Hive.box<ChatSetting>('chat_setting').listenable(),
|
Hive.box<ChatSetting>('chat_setting').listenable(),
|
||||||
builder: (context, Box<ChatSetting> box, _) {
|
builder: (context, Box<ChatSetting> box, _) {
|
||||||
final List<ChatSetting> openedChat =
|
final List<ChatSetting> openedChat = box.values
|
||||||
box.values.where((element) => element.isOpen).toList();
|
.where((element) => element.isOpen)
|
||||||
|
.toList();
|
||||||
|
|
||||||
// latestMsg on the top
|
// latestMsg on the top
|
||||||
openedChat.sort(
|
openedChat.sort(
|
||||||
(a, b) => b.latestDateTime.compareTo(a.latestDateTime),
|
(a, b) =>
|
||||||
|
b.latestDateTime.compareTo(a.latestDateTime),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (openedChat.isEmpty) {
|
if (openedChat.isEmpty) {
|
||||||
|
@ -181,6 +240,9 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
return const Center(
|
return const Center(
|
||||||
|
|
Loading…
Reference in New Issue