chat_model.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import 'dart:async';
  2. import 'package:dash_chat_2/dash_chat_2.dart';
  3. import 'package:desktop_multi_window/desktop_multi_window.dart';
  4. import 'package:draggable_float_widget/draggable_float_widget.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/services.dart';
  7. import 'package:flutter_hbb/common/shared_state.dart';
  8. import 'package:flutter_hbb/desktop/widgets/tabbar_widget.dart';
  9. import 'package:flutter_hbb/mobile/pages/home_page.dart';
  10. import 'package:flutter_hbb/models/platform_model.dart';
  11. import 'package:flutter_hbb/models/state_model.dart';
  12. import 'package:get/get.dart';
  13. import 'package:uuid/uuid.dart';
  14. import 'package:window_manager/window_manager.dart';
  15. import 'package:flutter_svg/flutter_svg.dart';
  16. import '../consts.dart';
  17. import '../common.dart';
  18. import '../common/widgets/overlay.dart';
  19. import '../main.dart';
  20. import 'model.dart';
  21. class MessageKey {
  22. final String peerId;
  23. final int connId;
  24. bool get isOut => connId == ChatModel.clientModeID;
  25. MessageKey(this.peerId, this.connId);
  26. @override
  27. bool operator ==(other) {
  28. return other is MessageKey &&
  29. other.peerId == peerId &&
  30. other.isOut == isOut;
  31. }
  32. @override
  33. int get hashCode => peerId.hashCode ^ isOut.hashCode;
  34. }
  35. class MessageBody {
  36. ChatUser chatUser;
  37. List<ChatMessage> chatMessages;
  38. MessageBody(this.chatUser, this.chatMessages);
  39. void insert(ChatMessage cm) {
  40. chatMessages.insert(0, cm);
  41. }
  42. void clear() {
  43. chatMessages.clear();
  44. }
  45. }
  46. class ChatModel with ChangeNotifier {
  47. static final clientModeID = -1;
  48. OverlayEntry? chatIconOverlayEntry;
  49. OverlayEntry? chatWindowOverlayEntry;
  50. bool isConnManager = false;
  51. RxBool isWindowFocus = true.obs;
  52. BlockableOverlayState _blockableOverlayState = BlockableOverlayState();
  53. final Rx<VoiceCallStatus> _voiceCallStatus = Rx(VoiceCallStatus.notStarted);
  54. Rx<VoiceCallStatus> get voiceCallStatus => _voiceCallStatus;
  55. TextEditingController textController = TextEditingController();
  56. RxInt mobileUnreadSum = 0.obs;
  57. MessageKey? latestReceivedKey;
  58. Offset chatWindowPosition = Offset(20, 80);
  59. void setChatWindowPosition(Offset position) {
  60. chatWindowPosition = position;
  61. notifyListeners();
  62. }
  63. @override
  64. void dispose() {
  65. textController.dispose();
  66. super.dispose();
  67. }
  68. final ChatUser me = ChatUser(
  69. id: Uuid().v4().toString(),
  70. firstName: translate("Me"),
  71. );
  72. late final Map<MessageKey, MessageBody> _messages = {};
  73. MessageKey _currentKey = MessageKey('', -2); // -2 is invalid value
  74. late bool _isShowCMSidePage = false;
  75. Map<MessageKey, MessageBody> get messages => _messages;
  76. MessageKey get currentKey => _currentKey;
  77. bool get isShowCMSidePage => _isShowCMSidePage;
  78. void setOverlayState(BlockableOverlayState blockableOverlayState) {
  79. _blockableOverlayState = blockableOverlayState;
  80. _blockableOverlayState.addMiddleBlockedListener((v) {
  81. if (!v) {
  82. isWindowFocus.value = false;
  83. if (isWindowFocus.value) {
  84. isWindowFocus.toggle();
  85. }
  86. }
  87. });
  88. }
  89. final WeakReference<FFI> parent;
  90. late final SessionID sessionId;
  91. late FocusNode inputNode;
  92. ChatModel(this.parent) {
  93. sessionId = parent.target!.sessionId;
  94. inputNode = FocusNode(
  95. onKey: (_, event) {
  96. bool isShiftPressed = event.isKeyPressed(LogicalKeyboardKey.shiftLeft);
  97. bool isEnterPressed = event.isKeyPressed(LogicalKeyboardKey.enter);
  98. // don't send empty messages
  99. if (isEnterPressed && isEnterPressed && textController.text.isEmpty) {
  100. return KeyEventResult.handled;
  101. }
  102. if (isEnterPressed && !isShiftPressed) {
  103. final ChatMessage message = ChatMessage(
  104. text: textController.text,
  105. user: me,
  106. createdAt: DateTime.now(),
  107. );
  108. send(message);
  109. textController.clear();
  110. return KeyEventResult.handled;
  111. }
  112. return KeyEventResult.ignored;
  113. },
  114. );
  115. }
  116. ChatUser? get currentUser => _messages[_currentKey]?.chatUser;
  117. showChatIconOverlay({Offset offset = const Offset(200, 50)}) {
  118. if (chatIconOverlayEntry != null) {
  119. chatIconOverlayEntry!.remove();
  120. }
  121. // mobile check navigationBar
  122. final bar = navigationBarKey.currentWidget;
  123. if (bar != null) {
  124. if ((bar as BottomNavigationBar).currentIndex == 1) {
  125. return;
  126. }
  127. }
  128. final overlayState = _blockableOverlayState.state;
  129. if (overlayState == null) return;
  130. final overlay = OverlayEntry(builder: (context) {
  131. return DraggableFloatWidget(
  132. config: DraggableFloatWidgetBaseConfig(
  133. initPositionYInTop: false,
  134. initPositionYMarginBorder: 100,
  135. borderTopContainTopBar: true,
  136. ),
  137. child: FloatingActionButton(
  138. onPressed: () {
  139. if (chatWindowOverlayEntry == null) {
  140. showChatWindowOverlay();
  141. } else {
  142. hideChatWindowOverlay();
  143. }
  144. },
  145. backgroundColor: Theme.of(context).colorScheme.primary,
  146. child: SvgPicture.asset('assets/chat2.svg'),
  147. ),
  148. );
  149. });
  150. overlayState.insert(overlay);
  151. chatIconOverlayEntry = overlay;
  152. }
  153. hideChatIconOverlay() {
  154. if (chatIconOverlayEntry != null) {
  155. chatIconOverlayEntry!.remove();
  156. chatIconOverlayEntry = null;
  157. }
  158. }
  159. showChatWindowOverlay({Offset? chatInitPos}) {
  160. if (chatWindowOverlayEntry != null) return;
  161. isWindowFocus.value = true;
  162. _blockableOverlayState.setMiddleBlocked(true);
  163. final overlayState = _blockableOverlayState.state;
  164. if (overlayState == null) return;
  165. if (isMobile &&
  166. !gFFI.chatModel.currentKey.isOut && // not in remote page
  167. gFFI.chatModel.latestReceivedKey != null) {
  168. gFFI.chatModel.changeCurrentKey(gFFI.chatModel.latestReceivedKey!);
  169. gFFI.chatModel.mobileClearClientUnread(gFFI.chatModel.currentKey.connId);
  170. }
  171. final overlay = OverlayEntry(builder: (context) {
  172. return Listener(
  173. onPointerDown: (_) {
  174. if (!isWindowFocus.value) {
  175. isWindowFocus.value = true;
  176. _blockableOverlayState.setMiddleBlocked(true);
  177. }
  178. },
  179. child: DraggableChatWindow(
  180. position: chatInitPos ?? chatWindowPosition,
  181. width: 250,
  182. height: 350,
  183. chatModel: this));
  184. });
  185. overlayState.insert(overlay);
  186. chatWindowOverlayEntry = overlay;
  187. requestChatInputFocus();
  188. }
  189. hideChatWindowOverlay() {
  190. if (chatWindowOverlayEntry != null) {
  191. _blockableOverlayState.setMiddleBlocked(false);
  192. chatWindowOverlayEntry!.remove();
  193. chatWindowOverlayEntry = null;
  194. return;
  195. }
  196. }
  197. _isChatOverlayHide() =>
  198. ((!(isDesktop || isWebDesktop) && chatIconOverlayEntry == null) ||
  199. chatWindowOverlayEntry == null);
  200. toggleChatOverlay({Offset? chatInitPos}) {
  201. if (_isChatOverlayHide()) {
  202. gFFI.invokeMethod("enable_soft_keyboard", true);
  203. if (!(isDesktop || isWebDesktop)) {
  204. showChatIconOverlay();
  205. }
  206. showChatWindowOverlay(chatInitPos: chatInitPos);
  207. } else {
  208. hideChatIconOverlay();
  209. hideChatWindowOverlay();
  210. }
  211. }
  212. hideChatOverlay() {
  213. if (!_isChatOverlayHide()) {
  214. hideChatIconOverlay();
  215. hideChatWindowOverlay();
  216. }
  217. }
  218. showChatPage(MessageKey key) async {
  219. if (isDesktop) {
  220. if (isConnManager) {
  221. if (!_isShowCMSidePage) {
  222. await toggleCMChatPage(key);
  223. }
  224. } else {
  225. if (_isChatOverlayHide()) {
  226. await toggleChatOverlay();
  227. }
  228. }
  229. } else {
  230. if (key.connId == clientModeID) {
  231. if (_isChatOverlayHide()) {
  232. await toggleChatOverlay();
  233. }
  234. }
  235. }
  236. }
  237. toggleCMChatPage(MessageKey key) async {
  238. if (gFFI.chatModel.currentKey != key) {
  239. gFFI.chatModel.changeCurrentKey(key);
  240. }
  241. await toggleCMSidePage();
  242. }
  243. toggleCMFilePage() async {
  244. await toggleCMSidePage();
  245. }
  246. var _togglingCMSidePage = false; // protect order for await
  247. toggleCMSidePage() async {
  248. if (_togglingCMSidePage) return false;
  249. _togglingCMSidePage = true;
  250. if (_isShowCMSidePage) {
  251. _isShowCMSidePage = !_isShowCMSidePage;
  252. notifyListeners();
  253. await windowManager.show();
  254. await windowManager.setSizeAlignment(
  255. kConnectionManagerWindowSizeClosedChat, Alignment.topRight);
  256. } else {
  257. final currentSelectedTab =
  258. gFFI.serverModel.tabController.state.value.selectedTabInfo;
  259. final client = parent.target?.serverModel.clients.firstWhereOrNull(
  260. (client) => client.id.toString() == currentSelectedTab.key);
  261. if (client != null) {
  262. client.unreadChatMessageCount.value = 0;
  263. }
  264. requestChatInputFocus();
  265. await windowManager.show();
  266. await windowManager.setSizeAlignment(
  267. kConnectionManagerWindowSizeOpenChat, Alignment.topRight);
  268. _isShowCMSidePage = !_isShowCMSidePage;
  269. notifyListeners();
  270. }
  271. _togglingCMSidePage = false;
  272. }
  273. changeCurrentKey(MessageKey key) {
  274. updateConnIdOfKey(key);
  275. String? peerName;
  276. if (key.connId == clientModeID) {
  277. peerName = parent.target?.ffiModel.pi.username;
  278. } else {
  279. peerName = parent.target?.serverModel.clients
  280. .firstWhereOrNull((client) => client.peerId == key.peerId)
  281. ?.name;
  282. }
  283. if (!_messages.containsKey(key)) {
  284. final chatUser = ChatUser(
  285. id: key.peerId,
  286. firstName: peerName,
  287. );
  288. _messages[key] = MessageBody(chatUser, []);
  289. } else {
  290. if (peerName != null && peerName.isNotEmpty) {
  291. _messages[key]?.chatUser.firstName = peerName;
  292. }
  293. }
  294. _currentKey = key;
  295. notifyListeners();
  296. mobileClearClientUnread(key.connId);
  297. }
  298. receive(int id, String text) async {
  299. final session = parent.target;
  300. if (session == null) {
  301. debugPrint("Failed to receive msg, session state is null");
  302. return;
  303. }
  304. if (text.isEmpty) return;
  305. if (desktopType == DesktopType.cm) {
  306. await showCmWindow();
  307. }
  308. String? peerId;
  309. if (id == clientModeID) {
  310. peerId = session.id;
  311. } else {
  312. peerId = session.serverModel.clients
  313. .firstWhereOrNull((e) => e.id == id)
  314. ?.peerId;
  315. }
  316. if (peerId == null) {
  317. debugPrint("Failed to receive msg, peerId is null");
  318. return;
  319. }
  320. final messagekey = MessageKey(peerId, id);
  321. // mobile: first message show overlay icon
  322. if (!isDesktop && chatIconOverlayEntry == null) {
  323. showChatIconOverlay();
  324. }
  325. // show chat page
  326. await showChatPage(messagekey);
  327. late final ChatUser chatUser;
  328. if (id == clientModeID) {
  329. chatUser = ChatUser(
  330. firstName: session.ffiModel.pi.username,
  331. id: peerId,
  332. );
  333. if (isDesktop) {
  334. if (Get.isRegistered<DesktopTabController>()) {
  335. DesktopTabController tabController = Get.find<DesktopTabController>();
  336. var index = tabController.state.value.tabs
  337. .indexWhere((e) => e.key == session.id);
  338. final notSelected =
  339. index >= 0 && tabController.state.value.selected != index;
  340. // minisized: top and switch tab
  341. // not minisized: add count
  342. if (await WindowController.fromWindowId(stateGlobal.windowId)
  343. .isMinimized()) {
  344. windowOnTop(stateGlobal.windowId);
  345. if (notSelected) {
  346. tabController.jumpTo(index);
  347. }
  348. } else {
  349. if (notSelected) {
  350. UnreadChatCountState.find(peerId).value += 1;
  351. }
  352. }
  353. }
  354. }
  355. } else {
  356. final client = session.serverModel.clients
  357. .firstWhereOrNull((client) => client.id == id);
  358. if (client == null) {
  359. debugPrint("Failed to receive msg, client is null");
  360. return;
  361. }
  362. if (isDesktop) {
  363. windowOnTop(null);
  364. // disable auto jumpTo other tab when hasFocus, and mark unread message
  365. final currentSelectedTab =
  366. session.serverModel.tabController.state.value.selectedTabInfo;
  367. if (currentSelectedTab.key != id.toString() && inputNode.hasFocus) {
  368. client.unreadChatMessageCount.value += 1;
  369. } else {
  370. parent.target?.serverModel.jumpTo(id);
  371. }
  372. } else {
  373. if (HomePage.homeKey.currentState?.isChatPageCurrentTab != true ||
  374. _currentKey != messagekey) {
  375. client.unreadChatMessageCount.value += 1;
  376. mobileUpdateUnreadSum();
  377. }
  378. }
  379. chatUser = ChatUser(id: client.peerId, firstName: client.name);
  380. }
  381. insertMessage(messagekey,
  382. ChatMessage(text: text, user: chatUser, createdAt: DateTime.now()));
  383. if (id == clientModeID || _currentKey.peerId.isEmpty) {
  384. // client or invalid
  385. _currentKey = messagekey;
  386. mobileClearClientUnread(messagekey.connId);
  387. }
  388. latestReceivedKey = messagekey;
  389. notifyListeners();
  390. }
  391. send(ChatMessage message) {
  392. String trimmedText = message.text.trim();
  393. if (trimmedText.isEmpty) {
  394. return;
  395. }
  396. message.text = trimmedText;
  397. insertMessage(_currentKey, message);
  398. if (_currentKey.connId == clientModeID && parent.target != null) {
  399. bind.sessionSendChat(sessionId: sessionId, text: message.text);
  400. } else {
  401. bind.cmSendChat(connId: _currentKey.connId, msg: message.text);
  402. }
  403. notifyListeners();
  404. inputNode.requestFocus();
  405. }
  406. insertMessage(MessageKey key, ChatMessage message) {
  407. updateConnIdOfKey(key);
  408. if (!_messages.containsKey(key)) {
  409. _messages[key] = MessageBody(message.user, []);
  410. }
  411. _messages[key]?.insert(message);
  412. }
  413. updateConnIdOfKey(MessageKey key) {
  414. if (_messages.keys
  415. .toList()
  416. .firstWhereOrNull((e) => e == key && e.connId != key.connId) !=
  417. null) {
  418. final value = _messages.remove(key);
  419. if (value != null) {
  420. _messages[key] = value;
  421. }
  422. }
  423. if (_currentKey == key || _currentKey.peerId.isEmpty) {
  424. _currentKey = key; // hash != assign
  425. }
  426. }
  427. void mobileUpdateUnreadSum() {
  428. if (!isMobile) return;
  429. var sum = 0;
  430. parent.target?.serverModel.clients
  431. .map((e) => sum += e.unreadChatMessageCount.value)
  432. .toList();
  433. Future.delayed(Duration.zero, () {
  434. mobileUnreadSum.value = sum;
  435. });
  436. }
  437. void mobileClearClientUnread(int id) {
  438. if (!isMobile) return;
  439. final client = parent.target?.serverModel.clients
  440. .firstWhereOrNull((client) => client.id == id);
  441. if (client != null) {
  442. Future.delayed(Duration.zero, () {
  443. client.unreadChatMessageCount.value = 0;
  444. mobileUpdateUnreadSum();
  445. });
  446. }
  447. }
  448. close() {
  449. hideChatIconOverlay();
  450. hideChatWindowOverlay();
  451. notifyListeners();
  452. }
  453. resetClientMode() {
  454. _messages[clientModeID]?.clear();
  455. }
  456. void requestChatInputFocus() {
  457. Timer(Duration(milliseconds: 100), () {
  458. if (inputNode.hasListeners && inputNode.canRequestFocus) {
  459. inputNode.requestFocus();
  460. }
  461. });
  462. }
  463. void onVoiceCallWaiting() {
  464. _voiceCallStatus.value = VoiceCallStatus.waitingForResponse;
  465. }
  466. void onVoiceCallStarted() {
  467. _voiceCallStatus.value = VoiceCallStatus.connected;
  468. if (isAndroid) {
  469. parent.target?.invokeMethod("on_voice_call_started");
  470. }
  471. }
  472. void onVoiceCallClosed(String reason) {
  473. _voiceCallStatus.value = VoiceCallStatus.notStarted;
  474. if (isAndroid) {
  475. // We can always invoke "on_voice_call_closed"
  476. // no matter if the `_voiceCallStatus` was `VoiceCallStatus.notStarted` or not.
  477. parent.target?.invokeMethod("on_voice_call_closed");
  478. }
  479. }
  480. void onVoiceCallIncoming() {
  481. if (isConnManager) {
  482. _voiceCallStatus.value = VoiceCallStatus.incoming;
  483. }
  484. }
  485. void closeVoiceCall() {
  486. bind.sessionCloseVoiceCall(sessionId: sessionId);
  487. }
  488. }
  489. enum VoiceCallStatus {
  490. notStarted,
  491. waitingForResponse,
  492. connected,
  493. // Connection manager only.
  494. incoming
  495. }