Hibok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

546 lines
17 KiB

  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:chat/chat/group_chat_item.dart';
  4. import 'package:chat/data/UserData.dart';
  5. import 'package:chat/data/chat_data_mgr.dart';
  6. import 'package:chat/data/constants.dart';
  7. import 'package:chat/data/group_data_mgr.dart';
  8. import 'package:chat/generated/i18n.dart';
  9. import 'package:chat/home/group_setting.dart';
  10. import 'package:chat/models/ChatMsg.dart';
  11. import 'package:chat/models/group_info_model.dart';
  12. import 'package:chat/models/keyboard_provider.dart';
  13. import 'package:chat/models/money_change.dart';
  14. import 'package:chat/models/voucher_change.dart';
  15. import 'package:chat/proto/all.pbserver.dart';
  16. import 'package:chat/utils/CustomUI.dart';
  17. import 'package:chat/utils/MessageMgr.dart';
  18. import 'package:chat/utils/analyze_utils.dart';
  19. import 'package:chat/utils/msgHandler.dart';
  20. import 'package:chat/utils/net_state_widget.dart';
  21. import 'package:chat/utils/screen.dart';
  22. import 'package:chat/utils/sound_util.dart';
  23. import 'package:chat/utils/sp_utils.dart';
  24. import 'package:chat/utils/sql_util.dart';
  25. import 'package:extended_text/extended_text.dart';
  26. import 'package:flutter/cupertino.dart';
  27. import 'package:flutter/material.dart';
  28. import 'package:oktoast/oktoast.dart';
  29. import 'package:provider/provider.dart';
  30. import '../r.dart';
  31. import 'input_bar.dart';
  32. import 'package:chat/models/ref_name_provider.dart';
  33. import 'package:fixnum/fixnum.dart';
  34. class GroupChatPage extends StatefulWidget {
  35. final GroupInfoModel groupInfoModel;
  36. final int enterType; // 0默认 1图片
  37. final dynamic enterContent;
  38. GroupChatPage(
  39. {Key key, this.groupInfoModel, this.enterType = 0, this.enterContent})
  40. : super(key: key);
  41. _GroupChatPageState createState() => _GroupChatPageState();
  42. }
  43. class _GroupChatPageState extends State<GroupChatPage> {
  44. ScrollController _scrollCtrl = ScrollController();
  45. MessageMgr msgMgr = MessageMgr();
  46. List<MsgModel> msgList;
  47. KeyboardIndexProvider _keyboardIndexProvider = KeyboardIndexProvider();
  48. TextEditingController nickNameController = new TextEditingController();
  49. //统计聊天时长
  50. int startTime;
  51. //子元素的对应偏移量
  52. Map itemOffsetMap = {};
  53. @override
  54. void dispose() {
  55. var endTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  56. AnalyzeUtils.commitChatDuration(startTime, endTime);
  57. msgMgr.off('New Chat Message', receiveMsg);
  58. msgMgr.off('Keyboard Hide', dealWithKeyboardHide);
  59. msgMgr.off('Update Group Info', updateGroupInfo);
  60. msgMgr.off('Delete Select Message', _deleteItem);
  61. MsgHandler.curActiveSession = 0;
  62. SoundUtils().stop();
  63. _scrollCtrl.dispose();
  64. super.dispose();
  65. }
  66. @override
  67. void initState() {
  68. super.initState();
  69. print('init group chat page ${widget.groupInfoModel.sessionId}');
  70. getDefaultSetting();
  71. startTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  72. MsgHandler.updateActiveSesstion(widget.groupInfoModel.sessionId,
  73. isGroup: true);
  74. msgList = ChatDataMgr().getGroupRecord();
  75. for (int k = 0; k < msgList.length; k++) {
  76. MsgModel msg = msgList[k];
  77. print('msgList ${msg.msgType} ${msg.from}');
  78. }
  79. msgMgr.on('New Chat Message', receiveMsg);
  80. msgMgr.on('Keyboard Hide', dealWithKeyboardHide);
  81. msgMgr.on('Update Group Info', updateGroupInfo);
  82. msgMgr.on('Delete Select Message', _deleteItem);
  83. WidgetsBinding.instance.addPostFrameCallback((_) {
  84. if (widget.enterType == 1) {
  85. print('接收到的:${widget.enterContent}');
  86. _sendFile(File(widget.enterContent));
  87. } else if (widget.enterType == 2) {
  88. //转发消息
  89. MsgModel originMsg = widget.enterContent;
  90. MsgModel msg = MsgHandler.createSendMsg(
  91. ChatType.valueOf(originMsg.msgType), originMsg.msgContent,
  92. channelType: ChatChannelType.Group);
  93. msg.extraInfo = originMsg.extraInfo;
  94. msg.extraFile = originMsg.extraFile;
  95. msg.localFile = originMsg.localFile;
  96. if (msg.localFile != null) {
  97. msg.state = MsgState.Uploaded;
  98. }
  99. sendMsg(msg);
  100. }
  101. });
  102. }
  103. void _sendFile(File file) async {
  104. // File file = await FilePicker.getFile();
  105. int fileSize = file.lengthSync();
  106. print('选择的文件 ${file.path} 大小 $fileSize');
  107. if (fileSize > 33 * 1024 * 1024) {
  108. showToast('文件大于33M');
  109. return;
  110. }
  111. var fileName = file.path.split('/').last;
  112. print('fileName $fileName');
  113. var ext = '';
  114. var extList = fileName.split('.');
  115. if (extList.length > 1) {
  116. ext = extList.last;
  117. }
  118. print('ext $ext');
  119. var fileMsg = FileChat.create();
  120. fileMsg.type = ext;
  121. fileMsg.size = fileSize;
  122. fileMsg.name = fileName;
  123. var msg = MsgHandler.createSendMsg(
  124. ChatType.FileChatType, fileMsg.writeToBuffer(),
  125. friendId: 0, localFile: file.path, channelType: ChatChannelType.Group);
  126. sendMsg(msg);
  127. }
  128. updateGroupInfo(args) {
  129. print('更新群信息');
  130. if (mounted) {
  131. setState(() {});
  132. }
  133. }
  134. void getDefaultSetting() async {
  135. bool soundPlayMode =
  136. (await SPUtils.getBool(Constants.SOUND_PLAY_MODE)) ?? false;
  137. _keyboardIndexProvider.init(soundPlayMode);
  138. }
  139. dealWithKeyboardHide(args) {
  140. if (_keyboardIndexProvider.curKeyboardIndex == 0) {
  141. readOnly();
  142. }
  143. }
  144. @override
  145. Widget build(BuildContext context) {
  146. List<Widget> actions = [];
  147. actions.add(Row(
  148. children: <Widget>[
  149. CustomUI.buildImageLabel("assets/images/voucher.png",
  150. Provider.of<VoucherChangeProvider>(context).voucher,
  151. imgOpc: 0.5, imgHeight: 13),
  152. CustomUI.buildImageLabel(
  153. R.assetsImagesCoin, Provider.of<MoneyChangeProvider>(context).money,
  154. isLeft: false)
  155. ],
  156. ));
  157. actions.add(widget.groupInfoModel.isInGroup
  158. ? IconButton(
  159. icon: Icon(Icons.more_horiz),
  160. iconSize: 22,
  161. onPressed: () {
  162. //进入群管理界面
  163. hideKeyBoard();
  164. Navigator.of(context).push(
  165. new MaterialPageRoute(
  166. builder: (context) {
  167. return GroupSetting(
  168. groupInfoModel: widget.groupInfoModel,
  169. );
  170. },
  171. ),
  172. );
  173. },
  174. )
  175. : IconButton(
  176. icon: Icon(Icons.delete),
  177. iconSize: 22,
  178. color: Colors.redAccent,
  179. onPressed: () {
  180. //进入群管理界面
  181. quiteGroup();
  182. },
  183. ));
  184. Map refMap = Provider.of<RefNameProvider>(context).refMap;
  185. return MultiProvider(
  186. providers: [
  187. ChangeNotifierProvider(create: (_) => _keyboardIndexProvider),
  188. Provider<bool>.value(value: true),
  189. Provider<GroupInfoModel>.value(value: widget.groupInfoModel),
  190. ],
  191. child: GestureDetector(
  192. onTap: hideKeyBoard,
  193. child: ExtendedTextSelectionPointerHandler(
  194. ///选择文字,消除弹窗
  195. builder: (states) {
  196. return Listener(
  197. child: Scaffold(
  198. resizeToAvoidBottomInset: false,
  199. backgroundColor: const Color(0xFFE2E9F1),
  200. appBar: AppBar(
  201. backgroundColor: AppColors.NewAppbarBgColor,
  202. title: Text(
  203. widget.groupInfoModel.getGroupName(refMap),
  204. textScaleFactor: 1.0,
  205. style: TextStyle(
  206. color: Constants.BlackTextColor,
  207. fontSize: 16.47),
  208. ),
  209. leading: CustomUI.buildCustomLeading(context),
  210. titleSpacing: -10,
  211. elevation: 1,
  212. centerTitle: false,
  213. actions: actions),
  214. body: SafeArea(
  215. child: Column(
  216. children: <Widget>[
  217. NetStateWidget(),
  218. Expanded(child: _buildMessageList()),
  219. InputBar(sendMsg: sendMsg),
  220. ],
  221. ))),
  222. behavior: HitTestBehavior.translucent,
  223. onPointerDown: (value) {
  224. for (var state in states) {
  225. if (!state.containsPosition(value.position)) {
  226. //clear other selection
  227. state.clearSelection();
  228. }
  229. }
  230. },
  231. onPointerMove: (value) {
  232. //clear other selection
  233. for (var state in states) {
  234. if (!state.containsPosition(value.position)) {
  235. //clear other selection
  236. state.clearSelection();
  237. }
  238. }
  239. },
  240. );
  241. },
  242. )));
  243. }
  244. //更新各个子元素的偏移位置
  245. _updateMsgItemOffset() {
  246. if (msgList.length == 0) {
  247. return;
  248. }
  249. var myId = UserData().basicInfo.userId;
  250. double offset = 0;
  251. for (var i = 0; i < msgList.length; i++) {
  252. MsgModel msg = msgList[i];
  253. double itemHeight = 40;
  254. switch (ChatType.valueOf(msg.msgType)) {
  255. case ChatType.TextChatType:
  256. if (msg.from == myId) {
  257. var text = utf8.decode(msg.msgContent);
  258. itemHeight = 21 + _getTextHeight(text);
  259. } else {}
  260. break;
  261. case ChatType.ShortVoiceChatType:
  262. if (msg.from == myId) {
  263. itemHeight = 22.5 + 24;
  264. } else {}
  265. break;
  266. case ChatType.ImageChatType:
  267. itemHeight = _getImgHeight(msg);
  268. break;
  269. case ChatType.ShortVideoChatType:
  270. itemHeight = _getImgHeight(msg);
  271. break;
  272. case ChatType.EmoticonType:
  273. itemHeight = 40;
  274. break;
  275. case ChatType.RedWalletChatType:
  276. print('红包消息');
  277. itemHeight = 70;
  278. break;
  279. case ChatType.PlaceChatType:
  280. itemHeight = 100 + 40.0;
  281. break;
  282. case ChatType.GroupChatNoticeType:
  283. itemHeight = 40;
  284. break;
  285. case ChatType.GiftChatType:
  286. itemHeight = 40;
  287. break;
  288. case ChatType.FileChatType:
  289. itemHeight = 80;
  290. break;
  291. default:
  292. }
  293. itemOffsetMap[i] = offset;
  294. offset += itemHeight;
  295. }
  296. }
  297. double _getTextHeight(String text) {
  298. var tp = TextPainter(
  299. text: TextSpan(style: TextStyle(fontSize: 15), text: text),
  300. textAlign: TextAlign.left,
  301. textDirection: TextDirection.ltr,
  302. textScaleFactor: 1,
  303. );
  304. tp.layout(maxWidth: Screen.width - 140);
  305. return tp.height;
  306. }
  307. double _getImgHeight(MsgModel msg) {
  308. double aspectRatio = msg.extraInfo / 100;
  309. var maxWidth = Screen.width * 0.65;
  310. var maxHeight = Screen.height / 4;
  311. double height;
  312. if (maxWidth / maxHeight > aspectRatio) {
  313. height = maxHeight;
  314. } else {
  315. height = maxWidth / aspectRatio;
  316. }
  317. return height;
  318. }
  319. Widget _buildMessageList() {
  320. return Container(
  321. alignment: Alignment.topCenter,
  322. child: msgList.length == 0
  323. ? Padding(
  324. padding: EdgeInsets.all(10),
  325. child: Text(
  326. I18n.of(context).chat_tips,
  327. textAlign: TextAlign.center,
  328. textScaleFactor: 1.0,
  329. style: TextStyle(color: Colors.grey),
  330. ))
  331. : Scrollbar(
  332. child: ListView.builder(
  333. reverse: true,
  334. shrinkWrap: true,
  335. itemCount: msgList.length,
  336. controller: _scrollCtrl,
  337. padding: EdgeInsets.all(8.0),
  338. itemBuilder: _buildItem,
  339. )),
  340. );
  341. }
  342. hideKeyBoard() {
  343. _keyboardIndexProvider.changeSelectIndex(-1);
  344. }
  345. readOnly() {
  346. _keyboardIndexProvider.changeReadOnlyKey(true);
  347. }
  348. sendMsg(MsgModel msg) {
  349. if (!widget.groupInfoModel.isInGroup) {
  350. //如果不在该群
  351. showToast(I18n.of(context).not_in_group);
  352. return;
  353. }
  354. MsgHandler.insertMsgToDB(msg);
  355. MsgHandler.sendChatMsg(msg);
  356. if (mounted) {
  357. setState(() {});
  358. }
  359. if (_scrollCtrl.hasClients) {
  360. _scrollCtrl.animateTo(0,
  361. duration: new Duration(milliseconds: 500), curve: Curves.ease);
  362. }
  363. // testBig(msg);
  364. }
  365. MsgModel msg;
  366. int count = 0;
  367. testBig(MsgModel msg) async {
  368. for (int k = 0; k < 100; k++) {
  369. msg.msgContent = utf8.encode('测试$count');
  370. Int64 time = Int64((DateTime.now()).millisecondsSinceEpoch);
  371. msg.time = time.toInt();
  372. MsgHandler.insertMsgToDB(msg);
  373. MsgHandler.sendChatMsg(msg);
  374. await Future.delayed(Duration(milliseconds: 300), () {});
  375. count++;
  376. }
  377. count = 0;
  378. print('攻击完毕');
  379. showToast('攻击完毕');
  380. }
  381. void receiveMsg(args) {
  382. if (args != widget.groupInfoModel.sessionId) {
  383. return;
  384. }
  385. if (mounted) {
  386. setState(() {});
  387. if (_scrollCtrl.hasClients) {
  388. _scrollCtrl.animateTo(0,
  389. duration: new Duration(milliseconds: 500), curve: Curves.ease);
  390. }
  391. }
  392. }
  393. _deleteItem(msg) {
  394. MessageMgr().emit('Cancel Request', msg);
  395. print('#### 开始删除--');
  396. msgList.remove(msg);
  397. setState(() {});
  398. SqlUtil().deleteSigleRecordWith(msg.sessionId, msg.time);
  399. }
  400. Widget _buildItem(BuildContext context, int index) {
  401. var lastMsgTime;
  402. if (index < msgList.length - 1) {
  403. lastMsgTime = msgList[index + 1].time;
  404. }
  405. MsgModel msg = msgList[index];
  406. if (msg.from == 0) {
  407. return GroupChatPageItem(
  408. key: Key(msg.time.toString()), msg: msg, lastMsgTime: lastMsgTime);
  409. } else {
  410. return GroupChatPageItem(
  411. key: Key(msg.time.toString()),
  412. msg: msg,
  413. memberModel: widget.groupInfoModel.getMember(msg.from),
  414. hideKeyboard: readOnly,
  415. lastMsgTime: lastMsgTime);
  416. }
  417. }
  418. quiteGroup() {
  419. var function = () {
  420. GroupInfoMgr().deleteGroup(widget.groupInfoModel.sessionId);
  421. MessageMgr().emit('Quit Group', widget.groupInfoModel.sessionId);
  422. Navigator.of(context).popUntil(ModalRoute.withName('/main'));
  423. MsgHandler.quitGroup(widget.groupInfoModel.sessionId);
  424. };
  425. showModalBottomSheet(
  426. context: context,
  427. backgroundColor: Colors.transparent,
  428. builder: (BuildContext context) {
  429. return Container(
  430. decoration: BoxDecoration(
  431. color: Colors.white,
  432. borderRadius: BorderRadius.only(
  433. topLeft: Radius.circular(13), topRight: Radius.circular(13))),
  434. height: 225,
  435. child: Column(
  436. crossAxisAlignment: CrossAxisAlignment.center,
  437. mainAxisAlignment: MainAxisAlignment.center,
  438. children: <Widget>[
  439. Padding(
  440. padding: EdgeInsets.fromLTRB(15, 15, 15, 13),
  441. child: Text(
  442. I18n.of(context).quit_group_tips,
  443. textScaleFactor: 1.0,
  444. style: TextStyle(fontSize: 12, color: Color(0xff777777)),
  445. ),
  446. ),
  447. Divider(
  448. color: Color(0xffE5E5E5),
  449. ),
  450. InkWell(
  451. onTap: function,
  452. child: Container(
  453. height: 60,
  454. alignment: Alignment.center,
  455. child: Text(I18n.of(context).determine,
  456. textScaleFactor: 1.0,
  457. style: TextStyle(
  458. fontSize: 18, color: Constants.ConfrimButtonColor)),
  459. ),
  460. ),
  461. Container(
  462. color: Color(0xffF2F2F2),
  463. height: 4,
  464. ),
  465. InkWell(
  466. onTap: () {
  467. Navigator.of(context).pop();
  468. },
  469. child: Container(
  470. height: 60,
  471. alignment: Alignment.center,
  472. child: Text(I18n.of(context).cancel,
  473. textScaleFactor: 1.0,
  474. style: TextStyle(fontSize: 18, color: Color(0xff4B4B4B))),
  475. ),
  476. )
  477. ],
  478. ),
  479. );
  480. },
  481. );
  482. }
  483. }