chat-box.vue 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. <template>
  2. <view class="page chat-box" id="chatBox">
  3. <nav-bar back more @more="onShowMore">{{ title }}</nav-bar>
  4. <view class="chat-main-box" :style="{height: chatMainHeight+'px'}">
  5. <view class="chat-msg" @click="switchChatTabBox('none')">
  6. <scroll-view class="scroll-box" scroll-y="true" upper-threshold="200" @scrolltoupper="onScrollToTop"
  7. :scroll-into-view="'chat-item-' + scrollMsgIdx">
  8. <view v-if="chat" v-for="(msgInfo, idx) in chat.messages" :key="idx">
  9. <chat-message-item :ref="'message'+msgInfo.id" v-if="idx >= showMinIdx"
  10. :headImage="headImage(msgInfo)" @call="onRtCall(msgInfo)" :showName="showName(msgInfo)"
  11. @recall="onRecallMessage" @delete="onDeleteMessage" @copy="onCopyMessage"
  12. @longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile"
  13. @audioStateChange="onAudioStateChange" :id="'chat-item-' + idx" :msgInfo="msgInfo"
  14. :groupMembers="groupMembers">
  15. </chat-message-item>
  16. </view>
  17. </scroll-view>
  18. </view>
  19. <view v-if="atUserIds.length > 0" class="chat-at-bar" @click="openAtBox()">
  20. <view class="iconfont icon-at">&nbsp;</view>
  21. <scroll-view v-if="atUserIds.length > 0" class="chat-at-scroll-box" scroll-x="true" scroll-left="120">
  22. <view class="chat-at-items">
  23. <view v-for="m in atUserItems" class="chat-at-item" :key="m.userId">
  24. <head-image :name="m.showNickName" :url="m.headImage" size="minier"></head-image>
  25. </view>
  26. </view>
  27. </scroll-view>
  28. </view>
  29. <view class="send-bar">
  30. <view v-if="!showRecord" class="iconfont icon-voice-circle" @click="onRecorderInput()"></view>
  31. <view v-else class="iconfont icon-keyboard" @click="onKeyboardInput()"></view>
  32. <chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"></chat-record>
  33. <view v-else class="send-text">
  34. <editor id="editor" class="send-text-area" :placeholder="isReceipt ? '[回执消息]' : ''"
  35. :read-only="isReadOnly" @focus="onEditorFocus" @blur="onEditorBlur" @ready="onEditorReady"
  36. @input="onTextInput">
  37. </editor>
  38. </view>
  39. <view v-if="chat && chat.type == 'GROUP'" class="iconfont icon-at" @click="openAtBox()"></view>
  40. <view class="iconfont icon-icon_emoji" @click="onShowEmoChatTab()"></view>
  41. <view v-if="isEmpty" class="iconfont icon-add" @click="onShowToolsChatTab()">
  42. </view>
  43. <button v-if="!isEmpty || atUserIds.length" class="btn-send" type="primary"
  44. @touchend.prevent="sendTextMessage()" size="mini">发送</button>
  45. </view>
  46. </view>
  47. <view class="chat-tab-bar">
  48. <view v-if="chatTabBox == 'tools'" class="chat-tools" :style="{height: keyboardHeight+'px'}">
  49. <view class="chat-tools-item">
  50. <file-upload ref="fileUpload" :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
  51. :onError="onUploadFileFail">
  52. <view class="tool-icon iconfont icon-folder"></view>
  53. </file-upload>
  54. <view class="tool-name">文件</view>
  55. </view>
  56. <view class="chat-tools-item">
  57. <image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore"
  58. :onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
  59. <view class="tool-icon iconfont icon-picture"></view>
  60. </image-upload>
  61. <view class="tool-name">相册</view>
  62. </view>
  63. <view class="chat-tools-item">
  64. <image-upload sourceType="camera" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess"
  65. :onError="onUploadImageFail">
  66. <view class="tool-icon iconfont icon-camera"></view>
  67. </image-upload>
  68. <view class="tool-name">拍摄</view>
  69. </view>
  70. <view class="chat-tools-item" @click="onRecorderInput()">
  71. <view class="tool-icon iconfont icon-microphone"></view>
  72. <view class="tool-name">语音消息</view>
  73. </view>
  74. <view v-if="chat.type == 'GROUP' && memberSize<=500" class="chat-tools-item" @click="switchReceipt()">
  75. <view class="tool-icon iconfont icon-receipt" :class="isReceipt ? 'active' : ''"></view>
  76. <view class="tool-name">回执消息</view>
  77. </view>
  78. <!-- #ifndef MP-WEIXIN -->
  79. <!-- 音视频不支持小程序 -->
  80. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVideo()">
  81. <view class="tool-icon iconfont icon-video"></view>
  82. <view class="tool-name">视频通话</view>
  83. </view>
  84. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVoice()">
  85. <view class="tool-icon iconfont icon-call"></view>
  86. <view class="tool-name">语音通话</view>
  87. </view>
  88. <view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="onGroupVideo()">
  89. <view class="tool-icon iconfont icon-call"></view>
  90. <view class="tool-name">语音通话</view>
  91. </view>
  92. <!-- #endif -->
  93. </view>
  94. <scroll-view v-if="chatTabBox === 'emo'" class="chat-emotion" scroll-y="true"
  95. :style="{height: keyboardHeight+'px'}">
  96. <view class="emotion-item-list">
  97. <image class="emotion-item emoji-large" :title="emoText" :src="$emo.textToPath(emoText)"
  98. v-for="(emoText, i) in $emo.emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit"
  99. lazy-load="true"></image>
  100. </view>
  101. </scroll-view>
  102. </view>
  103. <!-- @用户时选择成员 -->
  104. <chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers"
  105. @complete="onAtComplete"></chat-at-box>
  106. <!-- 群语音通话时选择成员 -->
  107. <!-- #ifndef MP-WEIXIN -->
  108. <group-member-selector ref="selBox" :members="groupMembers" :maxSize="configStore.webrtc.maxChannel"
  109. @complete="onInviteOk"></group-member-selector>
  110. <group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
  111. <!-- #endif -->
  112. </view>
  113. </template>
  114. <script>
  115. import UNI_APP from '@/.env.js';
  116. export default {
  117. data() {
  118. return {
  119. chat: {},
  120. userInfo: {},
  121. group: {},
  122. groupMembers: [],
  123. isReceipt: false, // 是否回执消息
  124. scrollMsgIdx: 0, // 滚动条定位为到哪条消息
  125. chatTabBox: 'none',
  126. showRecord: false,
  127. chatMainHeight: 0, // 聊天窗口高度
  128. keyboardHeight: 290, // 键盘高度
  129. windowHeight: 1000, // 窗口高度
  130. initHeight: 1000, // h5初始高度
  131. atUserIds: [],
  132. needScrollToBottom: false, // 需要滚动到底部
  133. showMinIdx: 0, // 下标小于showMinIdx的消息不显示,否则可能很卡
  134. reqQueue: [], // 请求队列
  135. isSending: false, // 是否正在发送请求
  136. isShowKeyBoard: false, // 键盘是否正在弹起
  137. editorCtx: null, // 编辑器上下文
  138. isEmpty: true, // 编辑器是否为空
  139. isFocus: false, // 编辑器是否焦点
  140. isReadOnly: false, // 编辑器是否只读
  141. playingAudio: null // 当前正在播放的录音消息
  142. }
  143. },
  144. methods: {
  145. onRecorderInput() {
  146. this.showRecord = true;
  147. this.switchChatTabBox('none');
  148. },
  149. onKeyboardInput() {
  150. this.showRecord = false;
  151. this.switchChatTabBox('none');
  152. },
  153. onSendRecord(data) {
  154. // 检查是否被封禁
  155. if (this.isBanned) {
  156. this.showBannedTip();
  157. return;
  158. }
  159. let msgInfo = {
  160. content: JSON.stringify(data),
  161. type: this.$enums.MESSAGE_TYPE.AUDIO,
  162. receipt: this.isReceipt
  163. }
  164. // 填充对方id
  165. this.fillTargetId(msgInfo, this.chat.targetId);
  166. this.sendMessageRequest(msgInfo).then((m) => {
  167. m.selfSend = true;
  168. this.chatStore.insertMessage(m, this.chat);
  169. // 会话置顶
  170. this.moveChatToTop();
  171. // 滚动到底部
  172. this.scrollToBottom();
  173. this.isReceipt = false;
  174. })
  175. },
  176. onRtCall(msgInfo) {
  177. if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
  178. this.onPriviteVoice();
  179. } else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
  180. this.onPriviteVideo();
  181. }
  182. },
  183. onPriviteVideo() {
  184. const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
  185. uni.navigateTo({
  186. url: `/pages/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true`
  187. })
  188. },
  189. onPriviteVoice() {
  190. const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
  191. uni.navigateTo({
  192. url: `/pages/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true`
  193. })
  194. },
  195. onGroupVideo() {
  196. // 邀请成员发起通话
  197. let ids = [this.mine.id];
  198. this.$refs.selBox.init(ids, ids, []);
  199. this.$refs.selBox.open();
  200. },
  201. onInviteOk(ids) {
  202. if (ids.length < 2) {
  203. return;
  204. }
  205. let users = [];
  206. ids.forEach(id => {
  207. let m = this.groupMembers.find(m => m.userId == id);
  208. // 只取部分字段,压缩url长度
  209. users.push({
  210. id: m.userId,
  211. nickName: m.showNickName,
  212. headImage: m.headImage,
  213. isCamera: false,
  214. isMicroPhone: true
  215. })
  216. })
  217. const groupId = this.group.id;
  218. const inviterId = this.mine.id;
  219. const userInfos = encodeURIComponent(JSON.stringify(users));
  220. uni.navigateTo({
  221. url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true
  222. &inviterId=${inviterId}&userInfos=${userInfos}`
  223. })
  224. },
  225. moveChatToTop() {
  226. let chatIdx = this.chatStore.findChatIdx(this.chat);
  227. this.chatStore.moveTop(chatIdx);
  228. },
  229. switchReceipt() {
  230. this.isReceipt = !this.isReceipt;
  231. },
  232. openAtBox() {
  233. this.$refs.atBox.init(this.atUserIds);
  234. this.$refs.atBox.open();
  235. },
  236. onAtComplete(atUserIds) {
  237. this.atUserIds = atUserIds;
  238. },
  239. onLongPressHead(msgInfo) {
  240. if (!msgInfo.selfSend && this.chat.type == "GROUP" && this.atUserIds.indexOf(msgInfo.sendId) < 0) {
  241. this.atUserIds.push(msgInfo.sendId);
  242. }
  243. },
  244. headImage(msgInfo) {
  245. if (this.chat.type == 'GROUP') {
  246. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  247. return member ? member.headImage : "";
  248. } else {
  249. return msgInfo.selfSend ? this.mine.headImageThumb : this.chat.headImage
  250. }
  251. },
  252. showName(msgInfo) {
  253. if (this.chat.type == 'GROUP') {
  254. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  255. return member ? member.showNickName : "";
  256. } else {
  257. return msgInfo.selfSend ? this.mine.nickName : this.chat.showName
  258. }
  259. },
  260. sendTextMessage() {
  261. this.editorCtx.getContents({
  262. success: (e) => {
  263. // 清空编辑框数据
  264. this.editorCtx.clear();
  265. // 检查是否被封禁
  266. if (this.isBanned) {
  267. this.showBannedTip();
  268. return;
  269. }
  270. let sendText = "";
  271. e.delta.ops.forEach((op) => {
  272. if (op.insert.image) {
  273. // emo表情
  274. sendText += `#${op.attributes.alt};`
  275. } else(
  276. // 文字
  277. sendText += op.insert
  278. )
  279. })
  280. if (!sendText.trim() && this.atUserIds.length == 0) {
  281. return uni.showToast({
  282. title: "不能发送空白信息",
  283. icon: "none"
  284. });
  285. }
  286. let receiptText = this.isReceipt ? "【回执消息】" : "";
  287. let atText = this.createAtText();
  288. let msgInfo = {
  289. content: receiptText + this.html2Escape(sendText) + atText,
  290. atUserIds: this.atUserIds,
  291. receipt: this.isReceipt,
  292. type: 0
  293. }
  294. // 清空@成员和回执标记
  295. this.atUserIds = [];
  296. this.isReceipt = false;
  297. // 填充对方id
  298. this.fillTargetId(msgInfo, this.chat.targetId);
  299. this.sendMessageRequest(msgInfo).then((m) => {
  300. m.selfSend = true;
  301. this.chatStore.insertMessage(m, this.chat);
  302. // 会话置顶
  303. this.moveChatToTop();
  304. }).finally(() => {
  305. // 滚动到底部
  306. this.scrollToBottom();
  307. });
  308. }
  309. })
  310. },
  311. createAtText() {
  312. let atText = "";
  313. this.atUserIds.forEach((id) => {
  314. if (id == -1) {
  315. atText += ` @全体成员`;
  316. } else {
  317. let member = this.groupMembers.find((m) => m.userId == id);
  318. if (member) {
  319. atText += ` @${member.showNickName}`;
  320. }
  321. }
  322. })
  323. return atText;
  324. },
  325. fillTargetId(msgInfo, targetId) {
  326. if (this.chat.type == "GROUP") {
  327. msgInfo.groupId = targetId;
  328. } else {
  329. msgInfo.recvId = targetId;
  330. }
  331. },
  332. scrollToBottom() {
  333. let size = this.messageSize;
  334. if (size > 0) {
  335. this.scrollToMsgIdx(size - 1);
  336. }
  337. },
  338. scrollToMsgIdx(idx) {
  339. // 如果scrollMsgIdx值没变化,滚动条不会移动
  340. if (idx == this.scrollMsgIdx && idx > 0) {
  341. this.$nextTick(() => {
  342. // 先滚动到上一条
  343. this.scrollMsgIdx = idx - 1;
  344. // 再滚动目标位置
  345. this.scrollToMsgIdx(idx);
  346. });
  347. return;
  348. }
  349. this.$nextTick(() => {
  350. this.scrollMsgIdx = idx;
  351. });
  352. },
  353. onShowEmoChatTab() {
  354. this.showRecord = false;
  355. this.switchChatTabBox('emo')
  356. },
  357. onShowToolsChatTab() {
  358. this.showRecord = false;
  359. this.switchChatTabBox('tools')
  360. },
  361. switchChatTabBox(chatTabBox) {
  362. this.chatTabBox = chatTabBox;
  363. this.reCalChatMainHeight();
  364. if (chatTabBox != 'tools' && this.$refs.fileUpload) {
  365. this.$refs.fileUpload.hide()
  366. }
  367. },
  368. selectEmoji(emoText) {
  369. let path = this.$emo.textToPath(emoText)
  370. // 先把键盘禁用了,否则会重新弹出键盘
  371. this.isReadOnly = true;
  372. this.isEmpty = false;
  373. this.$nextTick(() => {
  374. this.editorCtx.insertImage({
  375. src: path,
  376. alt: emoText,
  377. extClass: 'emoji-small',
  378. nowrap: true,
  379. complete: () => {
  380. this.isReadOnly = false;
  381. this.editorCtx.blur();
  382. }
  383. });
  384. })
  385. },
  386. onUploadImageBefore(file) {
  387. // 检查是否被封禁
  388. if (this.isBanned) {
  389. this.showBannedTip();
  390. return;
  391. }
  392. let data = {
  393. originUrl: file.path,
  394. thumbUrl: file.path
  395. }
  396. let msgInfo = {
  397. id: 0,
  398. tmpId: this.generateId(),
  399. fileId: file.uid,
  400. sendId: this.mine.id,
  401. content: JSON.stringify(data),
  402. sendTime: new Date().getTime(),
  403. selfSend: true,
  404. type: this.$enums.MESSAGE_TYPE.IMAGE,
  405. readedCount: 0,
  406. loadStatus: "loading",
  407. status: this.$enums.MESSAGE_STATUS.UNSEND
  408. }
  409. // 填充对方id
  410. this.fillTargetId(msgInfo, this.chat.targetId);
  411. // 插入消息
  412. this.chatStore.insertMessage(msgInfo, this.chat);
  413. // 会话置顶
  414. this.moveChatToTop();
  415. // 借助file对象保存
  416. file.msgInfo = msgInfo;
  417. file.chat = this.chat;
  418. // 滚到最低部
  419. this.scrollToBottom();
  420. return true;
  421. },
  422. onUploadImageSuccess(file, res) {
  423. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  424. msgInfo.content = JSON.stringify(res.data);
  425. msgInfo.receipt = this.isReceipt
  426. this.sendMessageRequest(msgInfo).then((m) => {
  427. msgInfo.loadStatus = 'ok';
  428. msgInfo.id = m.id;
  429. this.isReceipt = false;
  430. this.chatStore.insertMessage(msgInfo, file.chat);
  431. })
  432. },
  433. onUploadImageFail(file, err) {
  434. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  435. msgInfo.loadStatus = 'fail';
  436. this.chatStore.insertMessage(msgInfo, file.chat);
  437. },
  438. onUploadFileBefore(file) {
  439. // 检查是否被封禁
  440. if (this.isBanned) {
  441. this.showBannedTip();
  442. return;
  443. }
  444. let data = {
  445. name: file.name,
  446. size: file.size,
  447. url: file.path
  448. }
  449. let msgInfo = {
  450. id: 0,
  451. tmpId: this.generateId(),
  452. sendId: this.mine.id,
  453. content: JSON.stringify(data),
  454. sendTime: new Date().getTime(),
  455. selfSend: true,
  456. type: this.$enums.MESSAGE_TYPE.FILE,
  457. readedCount: 0,
  458. loadStatus: "loading",
  459. status: this.$enums.MESSAGE_STATUS.UNSEND
  460. }
  461. // 填充对方id
  462. this.fillTargetId(msgInfo, this.chat.targetId);
  463. // 插入消息
  464. this.chatStore.insertMessage(msgInfo, this.chat);
  465. // 会话置顶
  466. this.moveChatToTop();
  467. // 借助file对象保存
  468. file.msgInfo = msgInfo;
  469. file.chat = this.chat;
  470. // 滚到最低部
  471. this.scrollToBottom();
  472. return true;
  473. },
  474. onUploadFileSuccess(file, res) {
  475. let data = {
  476. name: file.name,
  477. size: file.size,
  478. url: res.data
  479. }
  480. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  481. msgInfo.content = JSON.stringify(data);
  482. msgInfo.receipt = this.isReceipt
  483. this.sendMessageRequest(msgInfo).then((m) => {
  484. msgInfo.loadStatus = 'ok';
  485. msgInfo.id = m.id;
  486. this.isReceipt = false;
  487. this.chatStore.insertMessage(msgInfo, file.chat);
  488. })
  489. },
  490. onUploadFileFail(file, res) {
  491. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  492. msgInfo.loadStatus = 'fail';
  493. this.chatStore.insertMessage(msgInfo, file.chat);
  494. },
  495. onDeleteMessage(msgInfo) {
  496. uni.showModal({
  497. title: '删除消息',
  498. content: '确认删除消息?',
  499. success: (res) => {
  500. if (!res.cancel) {
  501. this.chatStore.deleteMessage(msgInfo, this.chat);
  502. uni.showToast({
  503. title: "删除成功",
  504. icon: "none"
  505. })
  506. }
  507. }
  508. })
  509. },
  510. onRecallMessage(msgInfo) {
  511. uni.showModal({
  512. title: '撤回消息',
  513. content: '确认撤回消息?',
  514. success: (res) => {
  515. if (!res.cancel) {
  516. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  517. this.$http({
  518. url: url,
  519. method: 'DELETE'
  520. }).then((m) => {
  521. m.selfSend = true;
  522. this.chatStore.recallMessage(m, this.chat);
  523. })
  524. }
  525. }
  526. })
  527. },
  528. onCopyMessage(msgInfo) {
  529. uni.setClipboardData({
  530. data: msgInfo.content,
  531. success: () => {
  532. uni.showToast({ title: '复制成功' });
  533. },
  534. fail: () => {
  535. uni.showToast({ title: '复制失败', icon: 'none' });
  536. }
  537. });
  538. },
  539. onDownloadFile(msgInfo) {
  540. let url = JSON.parse(msgInfo.content).url;
  541. uni.downloadFile({
  542. url: url,
  543. success(res) {
  544. if (res.statusCode === 200) {
  545. var filePath = encodeURI(res.tempFilePath);
  546. uni.openDocument({
  547. filePath: filePath,
  548. showMenu: true
  549. });
  550. }
  551. },
  552. fail(e) {
  553. uni.showToast({
  554. title: "文件下载失败",
  555. icon: "none"
  556. })
  557. }
  558. });
  559. },
  560. onScrollToTop() {
  561. if (this.showMinIdx == 0) {
  562. console.log("消息已滚动到顶部")
  563. return;
  564. }
  565. // #ifndef H5
  566. // 防止滚动条定格在顶部,不能一直往上滚
  567. this.scrollToMsgIdx(this.showMinIdx);
  568. // #endif
  569. // 多展示20条信息
  570. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  571. },
  572. onShowMore() {
  573. if (this.chat.type == "GROUP") {
  574. uni.navigateTo({
  575. url: "/pages/group/group-info?id=" + this.group.id
  576. })
  577. } else {
  578. uni.navigateTo({
  579. url: "/pages/common/user-info?id=" + this.userInfo.id
  580. })
  581. }
  582. },
  583. onTextInput(e) {
  584. this.isEmpty = e.detail.html == '<p><br></p>'
  585. },
  586. onEditorReady() {
  587. this.$nextTick(() => {
  588. const query = uni.createSelectorQuery().in(this);
  589. query.select('#editor').context((res) => {
  590. this.editorCtx = res.context
  591. }).exec()
  592. })
  593. },
  594. onEditorFocus(e) {
  595. this.isFocus = true;
  596. this.scrollToBottom()
  597. this.switchChatTabBox('none')
  598. },
  599. onEditorBlur(e) {
  600. this.isFocus = false;
  601. },
  602. onAudioStateChange(state, msgInfo) {
  603. const playingAudio = this.$refs['message' + msgInfo.id][0]
  604. if (state == 'PLAYING' && playingAudio != this.playingAudio) {
  605. // 停止之前的录音
  606. this.playingAudio && this.playingAudio.stopPlayAudio();
  607. // 记录当前正在播放的消息
  608. this.playingAudio = playingAudio;
  609. }
  610. },
  611. loadReaded(fid) {
  612. this.$http({
  613. url: `/message/private/maxReadedId?friendId=${fid}`,
  614. method: 'get'
  615. }).then((id) => {
  616. this.chatStore.readedMessage({
  617. friendId: fid,
  618. maxId: id
  619. });
  620. });
  621. },
  622. readedMessage() {
  623. if (this.unreadCount == 0) {
  624. return;
  625. }
  626. let url = ""
  627. if (this.chat.type == "GROUP") {
  628. url = `/message/group/readed?groupId=${this.chat.targetId}`
  629. } else {
  630. url = `/message/private/readed?friendId=${this.chat.targetId}`
  631. }
  632. this.$http({
  633. url: url,
  634. method: 'PUT'
  635. }).then(() => {
  636. this.chatStore.resetUnreadCount(this.chat)
  637. this.scrollToBottom();
  638. })
  639. },
  640. loadGroup(groupId) {
  641. this.$http({
  642. url: `/group/find/${groupId}`,
  643. method: 'GET'
  644. }).then((group) => {
  645. this.group = group;
  646. this.chatStore.updateChatFromGroup(group);
  647. this.groupStore.updateGroup(group);
  648. });
  649. this.$http({
  650. url: `/group/members/${groupId}`,
  651. method: 'GET'
  652. }).then((groupMembers) => {
  653. this.groupMembers = groupMembers;
  654. });
  655. },
  656. updateFriendInfo() {
  657. if (this.isFriend) {
  658. // store的数据不能直接修改,深拷贝一份store的数据
  659. let friend = JSON.parse(JSON.stringify(this.friend));
  660. friend.headImage = this.userInfo.headImageThumb;
  661. friend.nickName = this.userInfo.nickName;
  662. friend.showNickName = friend.remarkNickName ? friend.remarkNickName : friend.nickName;
  663. // 更新好友列表中的昵称和头像
  664. this.friendStore.updateFriend(friend);
  665. // 更新会话中的头像和昵称
  666. this.chatStore.updateChatFromFriend(friend);
  667. } else {
  668. this.chatStore.updateChatFromUser(this.userInfo);
  669. }
  670. },
  671. loadFriend(friendId) {
  672. // 获取好友用户信息
  673. this.$http({
  674. url: `/user/find/${friendId}`,
  675. method: 'GET'
  676. }).then((userInfo) => {
  677. this.userInfo = userInfo;
  678. this.updateFriendInfo();
  679. })
  680. },
  681. rpxTopx(rpx) {
  682. // rpx转换成px
  683. let info = uni.getSystemInfoSync()
  684. let px = info.windowWidth * rpx / 750;
  685. return Math.floor(rpx);
  686. },
  687. html2Escape(strHtml) {
  688. return strHtml.replace(/[<>&"]/g, function(c) {
  689. return {
  690. '<': '&lt;',
  691. '>': '&gt;',
  692. '&': '&amp;',
  693. '"': '&quot;'
  694. } [c];
  695. });
  696. },
  697. sendMessageRequest(msgInfo) {
  698. return new Promise((resolve, reject) => {
  699. // 请求入队列,防止请求"后发先至",导致消息错序
  700. this.reqQueue.push({ msgInfo, resolve, reject });
  701. this.processReqQueue();
  702. })
  703. },
  704. processReqQueue() {
  705. if (this.reqQueue.length && !this.isSending) {
  706. this.isSending = true;
  707. const reqData = this.reqQueue.shift();
  708. this.$http({
  709. url: this.messageAction,
  710. method: 'post',
  711. data: reqData.msgInfo
  712. }).then((res) => {
  713. reqData.resolve(res)
  714. }).catch((e) => {
  715. reqData.reject(e)
  716. }).finally(() => {
  717. this.isSending = false;
  718. // 发送下一条请求
  719. this.processReqQueue();
  720. })
  721. }
  722. },
  723. reCalChatMainHeight() {
  724. setTimeout(() => {
  725. let h = this.windowHeight;
  726. // 减去标题栏高度
  727. h -= 50;
  728. // 减去键盘高度
  729. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  730. h -= this.keyboardHeight;
  731. this.scrollToBottom();
  732. }
  733. // #ifndef H5
  734. // h5需要减去状态栏高度
  735. h -= uni.getSystemInfoSync().statusBarHeight;
  736. // #endif
  737. this.chatMainHeight = h;
  738. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  739. this.scrollToBottom();
  740. }
  741. // ios浏览器键盘把页面顶起后,页面长度不会变化,这里把页面拉到顶部适配一下
  742. // #ifdef H5
  743. if (uni.getSystemInfoSync().platform == 'ios') {
  744. // 不同手机需要的延时时间不一致,采用分段延时的方式处理
  745. const delays = [50, 100, 500];
  746. delays.forEach((delay) => {
  747. setTimeout(() => {
  748. uni.pageScrollTo({
  749. scrollTop: 0,
  750. duration: 10
  751. });
  752. }, delay);
  753. })
  754. }
  755. // #endif
  756. }, 30)
  757. },
  758. listenKeyBoard() {
  759. // #ifdef H5
  760. if (navigator.platform == "Win32") {
  761. // 电脑端不需要弹出键盘
  762. console.log("navigator.platform:", navigator.platform)
  763. return;
  764. }
  765. if (uni.getSystemInfoSync().platform == 'ios') {
  766. // ios h5实现键盘监听
  767. window.addEventListener('focusin', this.focusInListener);
  768. window.addEventListener('focusout', this.focusOutListener);
  769. // 监听键盘高度,ios13以上开始支持
  770. if (window.visualViewport) {
  771. window.visualViewport.addEventListener('resize', this.resizeListener);
  772. }
  773. } else {
  774. // 安卓h5实现键盘监听
  775. window.addEventListener('resize', this.resizeListener);
  776. }
  777. // #endif
  778. // #ifndef H5
  779. // app实现键盘监听
  780. uni.onKeyboardHeightChange(this.keyBoardListener);
  781. // #endif
  782. },
  783. unListenKeyboard() {
  784. // #ifdef H5
  785. window.removeEventListener('resize', this.resizeListener);
  786. window.removeEventListener('focusin', this.focusInListener);
  787. window.removeEventListener('focusout', this.focusOutListener);
  788. // #endif
  789. // #ifndef H5
  790. uni.offKeyboardHeightChange(this.keyBoardListener);
  791. // #endif
  792. },
  793. keyBoardListener(res) {
  794. this.isShowKeyBoard = res.height > 0;
  795. if (this.isShowKeyBoard) {
  796. this.keyboardHeight = res.height; // 获取并保存键盘高度
  797. }
  798. this.reCalChatMainHeight();
  799. },
  800. resizeListener() {
  801. let keyboardHeight = this.initHeight - window.innerHeight;
  802. // 兼容部分ios浏览器
  803. if (window.visualViewport && uni.getSystemInfoSync().platform == 'ios') {
  804. keyboardHeight = this.initHeight - window.visualViewport.height;
  805. }
  806. console.log("resizeListener:", window.visualViewport.height)
  807. this.isShowKeyBoard = keyboardHeight > 150;
  808. if (this.isShowKeyBoard) {
  809. this.keyboardHeight = keyboardHeight;
  810. }
  811. this.reCalChatMainHeight();
  812. },
  813. focusInListener() {
  814. this.isShowKeyBoard = true;
  815. this.reCalChatMainHeight();
  816. },
  817. focusOutListener() {
  818. this.isShowKeyBoard = false;
  819. this.reCalChatMainHeight();
  820. },
  821. showBannedTip() {
  822. let msgInfo = {
  823. tmpId: this.generateId(),
  824. sendId: this.mine.id,
  825. sendTime: new Date().getTime(),
  826. type: this.$enums.MESSAGE_TYPE.TIP_TEXT
  827. }
  828. if (this.chat.type == "PRIVATE") {
  829. msgInfo.recvId = this.mine.id
  830. msgInfo.content = "该用户已被管理员封禁,原因:" + this.userInfo.reason
  831. } else {
  832. msgInfo.groupId = this.group.id;
  833. msgInfo.content = "本群聊已被管理员封禁,原因:" + this.group.reason
  834. }
  835. this.chatStore.insertMessage(msgInfo, this.chat);
  836. },
  837. generateId() {
  838. // 生成临时id
  839. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  840. }
  841. },
  842. computed: {
  843. mine() {
  844. return this.userStore.userInfo;
  845. },
  846. friend() {
  847. return this.friendStore.findFriend(this.userInfo.id);
  848. },
  849. title() {
  850. if (!this.chat) {
  851. return "";
  852. }
  853. let title = this.chat.showName;
  854. if (this.chat.type == "GROUP") {
  855. let size = this.groupMembers.filter(m => !m.quit).length;
  856. title += `(${size})`;
  857. }
  858. return title;
  859. },
  860. messageAction() {
  861. return `/message/${this.chat.type.toLowerCase()}/send`;
  862. },
  863. messageSize() {
  864. if (!this.chat || !this.chat.messages) {
  865. return 0;
  866. }
  867. return this.chat.messages.length;
  868. },
  869. unreadCount() {
  870. if (!this.chat || !this.chat.unreadCount) {
  871. return 0;
  872. }
  873. return this.chat.unreadCount;
  874. },
  875. isBanned() {
  876. return (this.chat.type == "PRIVATE" && this.userInfo.isBanned) ||
  877. (this.chat.type == "GROUP" && this.group.isBanned)
  878. },
  879. atUserItems() {
  880. let atUsers = [];
  881. this.atUserIds.forEach((id) => {
  882. if (id == -1) {
  883. atUsers.push({
  884. id: -1,
  885. showNickName: "全体成员"
  886. })
  887. return;
  888. }
  889. let member = this.groupMembers.find((m) => m.userId == id);
  890. if (member) {
  891. atUsers.push(member);
  892. }
  893. })
  894. return atUsers;
  895. },
  896. memberSize() {
  897. return this.groupMembers.filter(m => !m.quit).length;
  898. }
  899. },
  900. watch: {
  901. messageSize: function(newSize, oldSize) {
  902. // 接收到消息时滚动到底部
  903. if (newSize > oldSize) {
  904. let pages = getCurrentPages();
  905. let curPage = pages[pages.length - 1].route;
  906. if (curPage == "pages/chat/chat-box") {
  907. this.scrollToBottom();
  908. } else {
  909. this.needScrollToBottom = true;
  910. }
  911. }
  912. },
  913. unreadCount: {
  914. handler(newCount, oldCount) {
  915. if (newCount > 0) {
  916. // 消息已读
  917. this.readedMessage()
  918. }
  919. }
  920. }
  921. },
  922. onLoad(options) {
  923. // 聊天数据
  924. this.chat = this.chatStore.chats[options.chatIdx];
  925. // 初始状态只显示20条消息
  926. let size = this.messageSize;
  927. this.showMinIdx = size > 20 ? size - 20 : 0;
  928. // 消息已读
  929. this.readedMessage()
  930. // 加载好友或群聊信息
  931. if (this.chat.type == "GROUP") {
  932. this.loadGroup(this.chat.targetId);
  933. } else {
  934. this.loadFriend(this.chat.targetId);
  935. this.loadReaded(this.chat.targetId)
  936. }
  937. // 激活当前会话
  938. this.chatStore.activeChat(options.chatIdx);
  939. // 复位回执消息
  940. this.isReceipt = false;
  941. // 监听键盘高度
  942. this.listenKeyBoard();
  943. // 计算聊天窗口高度
  944. this.$nextTick(() => {
  945. this.windowHeight = uni.getSystemInfoSync().windowHeight;
  946. this.reCalChatMainHeight()
  947. // #ifdef H5
  948. this.initHeight = window.innerHeight;
  949. // 兼容ios的h5:禁止页面滚动
  950. const chatBox = document.getElementById('chatBox')
  951. chatBox.addEventListener('touchmove', e => {
  952. e.preventDefault()
  953. }, { passive: false });
  954. // #endif
  955. });
  956. },
  957. onUnload() {
  958. this.unListenKeyboard();
  959. },
  960. onShow() {
  961. if (this.needScrollToBottom) {
  962. // 页面滚到底部
  963. this.scrollToBottom();
  964. this.needScrollToBottom = false;
  965. }
  966. }
  967. }
  968. </script>
  969. <style lang="scss">
  970. .chat-box {
  971. $icon-color: rgba(0, 0, 0, 0.88);
  972. position: relative;
  973. background-color: #fafafa;
  974. .header {
  975. display: flex;
  976. justify-content: center;
  977. align-items: center;
  978. height: 60rpx;
  979. padding: 5px;
  980. background-color: #fafafa;
  981. line-height: 50px;
  982. font-size: $im-font-size-large;
  983. box-shadow: $im-box-shadow-lighter;
  984. z-index: 1;
  985. .btn-side {
  986. position: absolute;
  987. line-height: 60rpx;
  988. cursor: pointer;
  989. &.right {
  990. right: 30rpx;
  991. }
  992. }
  993. }
  994. .chat-main-box {
  995. // #ifdef H5
  996. top: $im-nav-bar-height;
  997. // #endif
  998. // #ifndef H5
  999. top: calc($im-nav-bar-height + var(--status-bar-height));
  1000. // #endif
  1001. position: fixed;
  1002. width: 100%;
  1003. display: flex;
  1004. flex-direction: column;
  1005. z-index: 2;
  1006. .chat-msg {
  1007. flex: 1;
  1008. padding: 0;
  1009. overflow: hidden;
  1010. position: relative;
  1011. background-color: white;
  1012. .scroll-box {
  1013. height: 100%;
  1014. }
  1015. }
  1016. .chat-at-bar {
  1017. display: flex;
  1018. align-items: center;
  1019. padding: 0 10rpx;
  1020. .icon-at {
  1021. font-size: $im-font-size-larger;
  1022. color: $im-color-primary;
  1023. font-weight: bold;
  1024. }
  1025. .chat-at-scroll-box {
  1026. flex: 1;
  1027. width: 80%;
  1028. .chat-at-items {
  1029. display: flex;
  1030. align-items: center;
  1031. height: 70rpx;
  1032. .chat-at-item {
  1033. padding: 0 3rpx;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. .send-bar {
  1039. display: flex;
  1040. align-items: center;
  1041. padding: 10rpx;
  1042. border-top: $im-border solid 1px;
  1043. background-color: $im-bg;
  1044. min-height: 80rpx;
  1045. margin-bottom: 14rpx;
  1046. .iconfont {
  1047. font-size: 60rpx;
  1048. margin: 0 10rpx;
  1049. color: $icon-color;
  1050. }
  1051. .chat-record {
  1052. flex: 1;
  1053. }
  1054. .send-text {
  1055. flex: 1;
  1056. overflow: auto;
  1057. padding: 14rpx 20rpx;
  1058. background-color: #fff;
  1059. border-radius: 8rpx;
  1060. font-size: $im-font-size;
  1061. box-sizing: border-box;
  1062. margin: 0 10rpx;
  1063. position: relative;
  1064. .send-text-area {
  1065. width: 100%;
  1066. height: 100%;
  1067. min-height: 40rpx;
  1068. max-height: 200rpx;
  1069. font-size: 30rpx;
  1070. }
  1071. }
  1072. .btn-send {
  1073. margin: 5rpx;
  1074. }
  1075. }
  1076. }
  1077. .chat-tab-bar {
  1078. position: fixed;
  1079. bottom: 0;
  1080. background-color: $im-bg;
  1081. .chat-tools {
  1082. display: flex;
  1083. flex-wrap: wrap;
  1084. align-items: top;
  1085. height: 310px;
  1086. padding: 40rpx;
  1087. box-sizing: border-box;
  1088. .chat-tools-item {
  1089. width: 25%;
  1090. padding: 16rpx;
  1091. box-sizing: border-box;
  1092. display: flex;
  1093. flex-direction: column;
  1094. align-items: center;
  1095. .tool-icon {
  1096. padding: 26rpx;
  1097. font-size: 54rpx;
  1098. border-radius: 20%;
  1099. background-color: white;
  1100. color: $icon-color;
  1101. &:active {
  1102. background-color: $im-bg-active;
  1103. }
  1104. }
  1105. .tool-name {
  1106. height: 60rpx;
  1107. line-height: 60rpx;
  1108. font-size: 28rpx;
  1109. }
  1110. }
  1111. }
  1112. .chat-emotion {
  1113. height: 310px;
  1114. padding: 20rpx;
  1115. box-sizing: border-box;
  1116. .emotion-item-list {
  1117. display: flex;
  1118. flex-wrap: wrap;
  1119. justify-content: space-between;
  1120. align-content: center;
  1121. .emotion-item {
  1122. text-align: center;
  1123. cursor: pointer;
  1124. padding: 5px;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. }
  1130. </style>