rustdesk/lib/models/chat_model.dart

104 lines
2.5 KiB
Dart
Raw Normal View History

import 'dart:convert';
import 'package:dash_chat/dash_chat.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/pages/chat_page.dart';
import 'model.dart';
class ChatModel with ChangeNotifier {
static final clientModeID = -1;
final Map<int, List<ChatMessage>> _messages = Map()..[clientModeID] = [];
final ChatUser me = ChatUser(
2022-04-05 00:51:47 +08:00
uid: "",
name: "Me",
);
2022-03-25 16:34:27 +08:00
final _scroller = ScrollController();
var _currentID = clientModeID;
2022-03-25 16:34:27 +08:00
ScrollController get scroller => _scroller;
Map<int, List<ChatMessage>> get messages => _messages;
int get currentID => _currentID;
ChatUser get currentUser =>
FFI.serverModel.clients[_currentID]?.chatUser ?? me;
2022-04-05 00:51:47 +08:00
changeCurrentID(int id) {
if (_messages.containsKey(id)) {
2022-03-25 16:34:27 +08:00
_currentID = id;
notifyListeners();
} else {
final chatUser = FFI.serverModel.clients[id]?.chatUser;
2022-04-05 00:51:47 +08:00
if (chatUser == null) {
return debugPrint(
"Failed to changeCurrentID,remote user doesn't exist");
}
_messages[id] = [];
_currentID = id;
2022-03-25 16:34:27 +08:00
}
}
receive(int id, String text) {
if (text.isEmpty) return;
// first message show overlay icon
if (iconOverlayEntry == null) {
showChatIconOverlay();
}
2022-03-25 16:34:27 +08:00
late final chatUser;
2022-04-05 00:51:47 +08:00
if (id == clientModeID) {
2022-03-25 16:34:27 +08:00
chatUser = ChatUser(
name: FFI.ffiModel.pi.username,
uid: FFI.getId(),
);
2022-04-05 00:51:47 +08:00
} else {
2022-03-25 16:34:27 +08:00
chatUser = FFI.serverModel.clients[id]?.chatUser;
}
2022-04-05 00:51:47 +08:00
if (chatUser == null) {
2022-03-25 16:34:27 +08:00
return debugPrint("Failed to receive msg,user doesn't exist");
}
2022-04-05 00:51:47 +08:00
if (!_messages.containsKey(id)) {
_messages[id] = [];
}
2022-04-05 00:51:47 +08:00
_messages[id]!.add(ChatMessage(text: text, user: chatUser));
_currentID = id;
notifyListeners();
2022-03-25 16:34:27 +08:00
scrollToBottom();
}
2022-04-05 00:51:47 +08:00
scrollToBottom() {
2022-03-25 16:34:27 +08:00
Future.delayed(Duration(milliseconds: 500), () {
2022-04-05 00:51:47 +08:00
_scroller.animateTo(_scroller.position.maxScrollExtent,
2022-03-25 16:34:27 +08:00
duration: Duration(milliseconds: 200),
curve: Curves.fastLinearToSlowEaseIn);
});
}
send(ChatMessage message) {
if (message.text != null && message.text!.isNotEmpty) {
_messages[_currentID]?.add(message);
if (_currentID == clientModeID) {
2022-03-24 17:58:33 +08:00
FFI.setByName("chat_client_mode", message.text!);
} else {
final msg = Map()
..["id"] = _currentID
..["text"] = message.text!;
2022-03-24 17:58:33 +08:00
FFI.setByName("chat_server_mode", jsonEncode(msg));
}
}
notifyListeners();
2022-03-25 16:34:27 +08:00
scrollToBottom();
}
2022-03-25 16:34:27 +08:00
close() {
hideChatIconOverlay();
hideChatWindowOverlay();
notifyListeners();
}
}