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.
 
 
 
 
 
 

530 lines
16 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. class GroupChatPage extends StatefulWidget {
  34. final GroupInfoModel groupInfoModel;
  35. final int enterType; // 0默认 1图片
  36. final dynamic enterContent;
  37. GroupChatPage(
  38. {Key key, this.groupInfoModel, this.enterType = 0, this.enterContent})
  39. : super(key: key);
  40. _GroupChatPageState createState() => _GroupChatPageState();
  41. }
  42. class _GroupChatPageState extends State<GroupChatPage> {
  43. ScrollController _scrollCtrl = ScrollController();
  44. MessageMgr msgMgr = MessageMgr();
  45. List<MsgModel> msgList;
  46. KeyboardIndexProvider _keyboardIndexProvider = KeyboardIndexProvider();
  47. TextEditingController nickNameController = new TextEditingController();
  48. //统计聊天时长
  49. int startTime;
  50. //子元素的对应偏移量
  51. Map itemOffsetMap = {};
  52. @override
  53. void dispose() {
  54. var endTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  55. AnalyzeUtils.commitChatDuration(startTime, endTime);
  56. msgMgr.off('New Chat Message', receiveMsg);
  57. msgMgr.off('Keyboard Hide', dealWithKeyboardHide);
  58. msgMgr.off('Update Group Info', updateGroupInfo);
  59. msgMgr.off('Delete Select Message', _deleteItem);
  60. MsgHandler.curActiveSession = 0;
  61. SoundUtils().stop();
  62. _scrollCtrl.dispose();
  63. super.dispose();
  64. }
  65. @override
  66. void initState() {
  67. super.initState();
  68. print('init group chat page ${widget.groupInfoModel.sessionId}');
  69. getDefaultSetting();
  70. startTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  71. MsgHandler.updateActiveSesstion(widget.groupInfoModel.sessionId,
  72. isGroup: true);
  73. msgList = ChatDataMgr().getGroupRecord();
  74. for(int k=0;k<msgList.length;k++){
  75. MsgModel msg = msgList[k];
  76. print('msgList ${msg.msgType} ${msg.from}' );
  77. }
  78. msgMgr.on('New Chat Message', receiveMsg);
  79. msgMgr.on('Keyboard Hide', dealWithKeyboardHide);
  80. msgMgr.on('Update Group Info', updateGroupInfo);
  81. msgMgr.on('Delete Select Message', _deleteItem);
  82. WidgetsBinding.instance.addPostFrameCallback((_) {
  83. if (widget.enterType == 1) {
  84. print('接收到的:${widget.enterContent}');
  85. _sendFile(File(widget.enterContent));
  86. } else if (widget.enterType == 2) {
  87. //转发消息
  88. MsgModel originMsg = widget.enterContent;
  89. MsgModel msg = MsgHandler.createSendMsg(
  90. ChatType.valueOf(originMsg.msgType), originMsg.msgContent,channelType: ChatChannelType.Group);
  91. msg.extraInfo = originMsg.extraInfo;
  92. msg.extraFile = originMsg.extraFile;
  93. msg.localFile = originMsg.localFile;
  94. if (msg.localFile != null) {
  95. msg.state = MsgState.Uploaded;
  96. }
  97. sendMsg(msg);
  98. }
  99. });
  100. }
  101. void _sendFile( File file) async {
  102. // File file = await FilePicker.getFile();
  103. int fileSize = file.lengthSync();
  104. print('选择的文件 ${file.path} 大小 $fileSize');
  105. if (fileSize > 33 * 1024 * 1024) {
  106. showToast('文件大于33M');
  107. return;
  108. }
  109. var fileName = file.path.split('/').last;
  110. print('fileName $fileName');
  111. var ext = '';
  112. var extList = fileName.split('.');
  113. if (extList.length > 1) {
  114. ext = extList.last;
  115. }
  116. print('ext $ext');
  117. var fileMsg = FileChat.create();
  118. fileMsg.type = ext;
  119. fileMsg.size = fileSize;
  120. fileMsg.name = fileName;
  121. var msg = MsgHandler.createSendMsg(ChatType.FileChatType, fileMsg.writeToBuffer(),
  122. friendId: 0,
  123. localFile: file.path,
  124. channelType:
  125. 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(child: ListView.builder(
  332. reverse: true,
  333. shrinkWrap: true,
  334. itemCount: msgList.length,
  335. controller: _scrollCtrl,
  336. padding: EdgeInsets.all(8.0),
  337. itemBuilder: _buildItem,
  338. )),
  339. );
  340. }
  341. hideKeyBoard() {
  342. _keyboardIndexProvider.changeSelectIndex(-1);
  343. }
  344. readOnly() {
  345. _keyboardIndexProvider.changeReadOnlyKey(true);
  346. }
  347. sendMsg(MsgModel msg) {
  348. if (!widget.groupInfoModel.isInGroup) {
  349. //如果不在该群
  350. showToast(I18n.of(context).not_in_group);
  351. return;
  352. }
  353. MsgHandler.insertMsgToDB(msg);
  354. MsgHandler.sendChatMsg(msg);
  355. if (mounted) {
  356. setState(() {});
  357. }
  358. if (_scrollCtrl.hasClients) {
  359. _scrollCtrl.animateTo(0,
  360. duration: new Duration(milliseconds: 500), curve: Curves.ease);
  361. }
  362. }
  363. void receiveMsg(args) {
  364. if (args != widget.groupInfoModel.sessionId) {
  365. return;
  366. }
  367. if (mounted) {
  368. setState(() {});
  369. if (_scrollCtrl.hasClients) {
  370. _scrollCtrl.animateTo(0,
  371. duration: new Duration(milliseconds: 500), curve: Curves.ease);
  372. }
  373. }
  374. }
  375. _deleteItem(msg) {
  376. MessageMgr().emit('Cancel Request', msg);
  377. print('#### 开始删除--');
  378. msgList.remove(msg);
  379. setState(() {});
  380. SqlUtil().deleteSigleRecordWith(msg.sessionId, msg.time);
  381. }
  382. Widget _buildItem(BuildContext context, int index) {
  383. var lastMsgTime;
  384. if (index < msgList.length - 1) {
  385. lastMsgTime = msgList[index + 1].time;
  386. }
  387. MsgModel msg = msgList[index];
  388. if (msg.from == 0) {
  389. return GroupChatPageItem(
  390. key: Key(msg.time.toString()), msg: msg, lastMsgTime: lastMsgTime);
  391. } else {
  392. return GroupChatPageItem(
  393. key: Key(msg.time.toString()),
  394. msg: msg,
  395. memberModel: widget.groupInfoModel.getMember(msg.from),
  396. hideKeyboard: readOnly,
  397. lastMsgTime: lastMsgTime);
  398. }
  399. }
  400. quiteGroup() {
  401. var function = () {
  402. GroupInfoMgr().deleteGroup(widget.groupInfoModel.sessionId);
  403. MessageMgr().emit('Quit Group', widget.groupInfoModel.sessionId);
  404. Navigator.of(context).popUntil(ModalRoute.withName('/main'));
  405. MsgHandler.quitGroup(widget.groupInfoModel.sessionId);
  406. };
  407. showModalBottomSheet(
  408. context: context,
  409. backgroundColor: Colors.transparent,
  410. builder: (BuildContext context) {
  411. return Container(
  412. decoration: BoxDecoration(
  413. color: Colors.white,
  414. borderRadius: BorderRadius.only(
  415. topLeft: Radius.circular(13), topRight: Radius.circular(13))),
  416. height: 225,
  417. child: Column(
  418. crossAxisAlignment: CrossAxisAlignment.center,
  419. mainAxisAlignment: MainAxisAlignment.center,
  420. children: <Widget>[
  421. Padding(
  422. padding: EdgeInsets.fromLTRB(15, 15, 15, 13),
  423. child: Text(
  424. I18n.of(context).quit_group_tips,
  425. style: TextStyle(fontSize: 12, color: Color(0xff777777)),
  426. ),
  427. ),
  428. Divider(
  429. color: Color(0xffE5E5E5),
  430. ),
  431. InkWell(
  432. onTap: function,
  433. child: Container(
  434. height: 60,
  435. alignment: Alignment.center,
  436. child: Text(I18n.of(context).determine,
  437. style: TextStyle(
  438. fontSize: 18, color: Constants.ConfrimButtonColor)),
  439. ),
  440. ),
  441. Container(
  442. color: Color(0xffF2F2F2),
  443. height: 4,
  444. ),
  445. InkWell(
  446. onTap: () {
  447. Navigator.of(context).pop();
  448. },
  449. child: Container(
  450. height: 60,
  451. alignment: Alignment.center,
  452. child: Text(I18n.of(context).cancel,
  453. style: TextStyle(fontSize: 18, color: Color(0xff4B4B4B))),
  454. ),
  455. )
  456. ],
  457. ),
  458. );
  459. },
  460. );
  461. }
  462. }