chat-box.vue 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. <template>
  2. <view class="page chat-box">
  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'" 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 + 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. // 滚到最低部
  418. this.scrollToBottom();
  419. return true;
  420. },
  421. onUploadImageSuccess(file, res) {
  422. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  423. msgInfo.content = JSON.stringify(res.data);
  424. msgInfo.receipt = this.isReceipt
  425. this.sendMessageRequest(msgInfo).then((m) => {
  426. msgInfo.loadStatus = 'ok';
  427. msgInfo.id = m.id;
  428. this.isReceipt = false;
  429. this.chatStore.insertMessage(msgInfo, this.chat);
  430. })
  431. },
  432. onUploadImageFail(file, err) {
  433. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  434. msgInfo.loadStatus = 'fail';
  435. this.chatStore.insertMessage(msgInfo, this.chat);
  436. },
  437. onUploadFileBefore(file) {
  438. // 检查是否被封禁
  439. if (this.isBanned) {
  440. this.showBannedTip();
  441. return;
  442. }
  443. let data = {
  444. name: file.name,
  445. size: file.size,
  446. url: file.path
  447. }
  448. let msgInfo = {
  449. id: 0,
  450. tmpId: this.generateId(),
  451. sendId: this.mine.id,
  452. content: JSON.stringify(data),
  453. sendTime: new Date().getTime(),
  454. selfSend: true,
  455. type: this.$enums.MESSAGE_TYPE.FILE,
  456. readedCount: 0,
  457. loadStatus: "loading",
  458. status: this.$enums.MESSAGE_STATUS.UNSEND
  459. }
  460. // 填充对方id
  461. this.fillTargetId(msgInfo, this.chat.targetId);
  462. // 插入消息
  463. this.chatStore.insertMessage(msgInfo, this.chat);
  464. // 会话置顶
  465. this.moveChatToTop();
  466. // 借助file对象保存
  467. file.msgInfo = msgInfo;
  468. // 滚到最低部
  469. this.scrollToBottom();
  470. return true;
  471. },
  472. onUploadFileSuccess(file, res) {
  473. let data = {
  474. name: file.name,
  475. size: file.size,
  476. url: res.data
  477. }
  478. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  479. msgInfo.content = JSON.stringify(data);
  480. msgInfo.receipt = this.isReceipt
  481. this.sendMessageRequest(msgInfo).then((m) => {
  482. msgInfo.loadStatus = 'ok';
  483. msgInfo.id = m.id;
  484. this.isReceipt = false;
  485. this.chatStore.insertMessage(msgInfo, this.chat);
  486. })
  487. },
  488. onUploadFileFail(file, res) {
  489. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  490. msgInfo.loadStatus = 'fail';
  491. this.chatStore.insertMessage(msgInfo, this.chat);
  492. },
  493. onDeleteMessage(msgInfo) {
  494. uni.showModal({
  495. title: '删除消息',
  496. content: '确认删除消息?',
  497. success: (res) => {
  498. if (!res.cancel) {
  499. this.chatStore.deleteMessage(msgInfo, this.chat);
  500. uni.showToast({
  501. title: "删除成功",
  502. icon: "none"
  503. })
  504. }
  505. }
  506. })
  507. },
  508. onRecallMessage(msgInfo) {
  509. uni.showModal({
  510. title: '撤回消息',
  511. content: '确认撤回消息?',
  512. success: (res) => {
  513. if (!res.cancel) {
  514. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  515. this.$http({
  516. url: url,
  517. method: 'DELETE'
  518. }).then((m) => {
  519. m.selfSend = true;
  520. this.chatStore.recallMessage(m, this.chat);
  521. })
  522. }
  523. }
  524. })
  525. },
  526. onCopyMessage(msgInfo) {
  527. uni.setClipboardData({
  528. data: msgInfo.content,
  529. success: () => {
  530. uni.showToast({ title: '复制成功' });
  531. },
  532. fail: () => {
  533. uni.showToast({ title: '复制失败', icon: 'none' });
  534. }
  535. });
  536. },
  537. onDownloadFile(msgInfo) {
  538. let url = JSON.parse(msgInfo.content).url;
  539. uni.downloadFile({
  540. url: url,
  541. success(res) {
  542. if (res.statusCode === 200) {
  543. var filePath = encodeURI(res.tempFilePath);
  544. uni.openDocument({
  545. filePath: filePath,
  546. showMenu: true
  547. });
  548. }
  549. },
  550. fail(e) {
  551. uni.showToast({
  552. title: "文件下载失败",
  553. icon: "none"
  554. })
  555. }
  556. });
  557. },
  558. onScrollToTop() {
  559. if (this.showMinIdx == 0) {
  560. console.log("消息已滚动到顶部")
  561. return;
  562. }
  563. // #ifndef H5
  564. // 防止滚动条定格在顶部,不能一直往上滚
  565. this.scrollToMsgIdx(this.showMinIdx);
  566. // #endif
  567. // 多展示20条信息
  568. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  569. },
  570. onShowMore() {
  571. if (this.chat.type == "GROUP") {
  572. uni.navigateTo({
  573. url: "/pages/group/group-info?id=" + this.group.id
  574. })
  575. } else {
  576. uni.navigateTo({
  577. url: "/pages/common/user-info?id=" + this.userInfo.id
  578. })
  579. }
  580. },
  581. onTextInput(e) {
  582. this.isEmpty = e.detail.html == '<p><br></p>'
  583. },
  584. onEditorReady() {
  585. this.$nextTick(() => {
  586. const query = uni.createSelectorQuery().in(this);
  587. query.select('#editor').context((res) => {
  588. this.editorCtx = res.context
  589. }).exec()
  590. })
  591. },
  592. onEditorFocus(e) {
  593. this.isFocus = true;
  594. this.scrollToBottom()
  595. this.switchChatTabBox('none')
  596. },
  597. onEditorBlur(e) {
  598. this.isFocus = false;
  599. },
  600. onAudioStateChange(state, msgInfo) {
  601. const playingAudio = this.$refs['message' + msgInfo.id][0]
  602. if (state == 'PLAYING' && playingAudio != this.playingAudio) {
  603. // 停止之前的录音
  604. this.playingAudio && this.playingAudio.stopPlayAudio();
  605. // 记录当前正在播放的消息
  606. this.playingAudio = playingAudio;
  607. }
  608. },
  609. loadReaded(fid) {
  610. this.$http({
  611. url: `/message/private/maxReadedId?friendId=${fid}`,
  612. method: 'get'
  613. }).then((id) => {
  614. this.chatStore.readedMessage({
  615. friendId: fid,
  616. maxId: id
  617. });
  618. });
  619. },
  620. readedMessage() {
  621. if (this.unreadCount == 0) {
  622. return;
  623. }
  624. let url = ""
  625. if (this.chat.type == "GROUP") {
  626. url = `/message/group/readed?groupId=${this.chat.targetId}`
  627. } else {
  628. url = `/message/private/readed?friendId=${this.chat.targetId}`
  629. }
  630. this.$http({
  631. url: url,
  632. method: 'PUT'
  633. }).then(() => {
  634. this.chatStore.resetUnreadCount(this.chat)
  635. this.scrollToBottom();
  636. })
  637. },
  638. loadGroup(groupId) {
  639. this.$http({
  640. url: `/group/find/${groupId}`,
  641. method: 'GET'
  642. }).then((group) => {
  643. this.group = group;
  644. this.chatStore.updateChatFromGroup(group);
  645. this.groupStore.updateGroup(group);
  646. });
  647. this.$http({
  648. url: `/group/members/${groupId}`,
  649. method: 'GET'
  650. }).then((groupMembers) => {
  651. this.groupMembers = groupMembers;
  652. });
  653. },
  654. updateFriendInfo() {
  655. if (this.isFriend) {
  656. // store的数据不能直接修改,深拷贝一份store的数据
  657. let friend = JSON.parse(JSON.stringify(this.friend));
  658. friend.headImage = this.userInfo.headImageThumb;
  659. friend.nickName = this.userInfo.nickName;
  660. friend.showNickName = friend.remarkNickName ? friend.remarkNickName : friend.nickName;
  661. // 更新好友列表中的昵称和头像
  662. this.friendStore.updateFriend(friend);
  663. // 更新会话中的头像和昵称
  664. this.chatStore.updateChatFromFriend(friend);
  665. } else {
  666. this.chatStore.updateChatFromUser(this.userInfo);
  667. }
  668. },
  669. loadFriend(friendId) {
  670. // 获取好友用户信息
  671. this.$http({
  672. url: `/user/find/${friendId}`,
  673. method: 'GET'
  674. }).then((userInfo) => {
  675. this.userInfo = userInfo;
  676. this.updateFriendInfo();
  677. })
  678. },
  679. rpxTopx(rpx) {
  680. // rpx转换成px
  681. let info = uni.getSystemInfoSync()
  682. let px = info.windowWidth * rpx / 750;
  683. return Math.floor(rpx);
  684. },
  685. sendMessageRequest(msgInfo) {
  686. return new Promise((resolve, reject) => {
  687. // 请求入队列,防止请求"后发先至",导致消息错序
  688. this.reqQueue.push({ msgInfo, resolve, reject });
  689. this.processReqQueue();
  690. })
  691. },
  692. processReqQueue() {
  693. if (this.reqQueue.length && !this.isSending) {
  694. this.isSending = true;
  695. const reqData = this.reqQueue.shift();
  696. this.$http({
  697. url: this.messageAction,
  698. method: 'post',
  699. data: reqData.msgInfo
  700. }).then((res) => {
  701. reqData.resolve(res)
  702. }).catch((e) => {
  703. reqData.reject(e)
  704. }).finally(() => {
  705. this.isSending = false;
  706. // 发送下一条请求
  707. this.processReqQueue();
  708. })
  709. }
  710. },
  711. reCalChatMainHeight() {
  712. setTimeout(() => {
  713. let h = this.windowHeight;
  714. // 减去标题栏高度
  715. h -= 50;
  716. // 减去键盘高度
  717. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  718. console.log("减去键盘高度:", this.keyboardHeight)
  719. h -= this.keyboardHeight;
  720. this.scrollToBottom();
  721. }
  722. // #ifndef H5
  723. // h5需要减去状态栏高度
  724. h -= uni.getSystemInfoSync().statusBarHeight;
  725. // #endif
  726. this.chatMainHeight = h;
  727. console.log("窗口高度:", this.chatMainHeight)
  728. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  729. this.scrollToBottom();
  730. }
  731. // ios浏览器键盘把页面顶起后,页面长度不会变化,这里把页面拉到顶部适配一下
  732. // #ifdef H5
  733. if (uni.getSystemInfoSync().platform == 'ios') {
  734. // 不同手机需要的延时时间不一致,采用分段延时的方式处理
  735. const delays = [50, 100, 500];
  736. delays.forEach((delay) => {
  737. setTimeout(() => {
  738. uni.pageScrollTo({
  739. scrollTop: 0,
  740. duration: 10
  741. });
  742. }, delay);
  743. })
  744. }
  745. // #endif
  746. }, 30)
  747. },
  748. listenKeyBoard() {
  749. // #ifdef H5
  750. if (navigator.platform == "Win32" || navigator.platform == "MacIntel") {
  751. // 电脑端不需要弹出键盘
  752. console.log("navigator.platform:", navigator.platform)
  753. return;
  754. }
  755. if (uni.getSystemInfoSync().platform == 'ios') {
  756. // ios h5实现键盘监听
  757. window.addEventListener('focusin', this.focusInListener);
  758. window.addEventListener('focusout', this.focusOutListener);
  759. // 监听键盘高度,ios13以上开始支持
  760. if (window.visualViewport) {
  761. window.visualViewport.addEventListener('resize', this.resizeListener);
  762. }
  763. } else {
  764. // 安卓h5实现键盘监听
  765. window.addEventListener('resize', this.resizeListener);
  766. }
  767. // #endif
  768. // #ifndef H5
  769. // app实现键盘监听
  770. uni.onKeyboardHeightChange(this.keyBoardListener);
  771. // #endif
  772. },
  773. unListenKeyboard() {
  774. // #ifdef H5
  775. window.removeEventListener('resize', this.resizeListener);
  776. window.removeEventListener('focusin', this.focusInListener);
  777. window.removeEventListener('focusout', this.focusOutListener);
  778. // #endif
  779. // #ifndef H5
  780. uni.offKeyboardHeightChange(this.keyBoardListener);
  781. // #endif
  782. },
  783. keyBoardListener(res) {
  784. this.isShowKeyBoard = res.height > 0;
  785. if (this.isShowKeyBoard) {
  786. this.keyboardHeight = res.height; // 获取并保存键盘高度
  787. }
  788. this.reCalChatMainHeight();
  789. },
  790. resizeListener() {
  791. console.log("resize")
  792. let keyboardHeight = this.initHeight - window.innerHeight;
  793. this.isShowKeyBoard = keyboardHeight > 150;
  794. if (this.isShowKeyBoard) {
  795. this.keyboardHeight = keyboardHeight;
  796. }
  797. this.reCalChatMainHeight();
  798. },
  799. focusInListener() {
  800. console.log("focusInListener")
  801. this.isShowKeyBoard = true;
  802. this.reCalChatMainHeight();
  803. },
  804. focusOutListener() {
  805. console.log("focusOutListener")
  806. this.isShowKeyBoard = false;
  807. this.reCalChatMainHeight();
  808. },
  809. showBannedTip() {
  810. let msgInfo = {
  811. tmpId: this.generateId(),
  812. sendId: this.mine.id,
  813. sendTime: new Date().getTime(),
  814. type: this.$enums.MESSAGE_TYPE.TIP_TEXT
  815. }
  816. if (this.chat.type == "PRIVATE") {
  817. msgInfo.recvId = this.mine.id
  818. msgInfo.content = "该用户已被管理员封禁,原因:" + this.userInfo.reason
  819. } else {
  820. msgInfo.groupId = this.group.id;
  821. msgInfo.content = "本群聊已被管理员封禁,原因:" + this.group.reason
  822. }
  823. this.chatStore.insertMessage(msgInfo, this.chat);
  824. },
  825. generateId() {
  826. // 生成临时id
  827. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  828. }
  829. },
  830. computed: {
  831. mine() {
  832. return this.userStore.userInfo;
  833. },
  834. friend() {
  835. return this.friendStore.findFriend(this.userInfo.id);
  836. },
  837. title() {
  838. if (!this.chat) {
  839. return "";
  840. }
  841. let title = this.chat.showName;
  842. if (this.chat.type == "GROUP") {
  843. let size = this.groupMembers.filter(m => !m.quit).length;
  844. title += `(${size})`;
  845. }
  846. return title;
  847. },
  848. messageAction() {
  849. return `/message/${this.chat.type.toLowerCase()}/send`;
  850. },
  851. messageSize() {
  852. if (!this.chat || !this.chat.messages) {
  853. return 0;
  854. }
  855. return this.chat.messages.length;
  856. },
  857. unreadCount() {
  858. if (!this.chat || !this.chat.unreadCount) {
  859. return 0;
  860. }
  861. return this.chat.unreadCount;
  862. },
  863. isBanned() {
  864. return (this.chat.type == "PRIVATE" && this.userInfo.isBanned) ||
  865. (this.chat.type == "GROUP" && this.group.isBanned)
  866. },
  867. atUserItems() {
  868. let atUsers = [];
  869. this.atUserIds.forEach((id) => {
  870. if (id == -1) {
  871. atUsers.push({
  872. id: -1,
  873. showNickName: "全体成员"
  874. })
  875. return;
  876. }
  877. let member = this.groupMembers.find((m) => m.userId == id);
  878. if (member) {
  879. atUsers.push(member);
  880. }
  881. })
  882. return atUsers;
  883. }
  884. },
  885. watch: {
  886. messageSize: function(newSize, oldSize) {
  887. // 接收到消息时滚动到底部
  888. if (newSize > oldSize) {
  889. let pages = getCurrentPages();
  890. let curPage = pages[pages.length - 1].route;
  891. if (curPage == "pages/chat/chat-box") {
  892. this.scrollToBottom();
  893. } else {
  894. this.needScrollToBottom = true;
  895. }
  896. }
  897. },
  898. unreadCount: {
  899. handler(newCount, oldCount) {
  900. if (newCount > 0) {
  901. // 消息已读
  902. this.readedMessage()
  903. }
  904. }
  905. }
  906. },
  907. onLoad(options) {
  908. // 聊天数据
  909. this.chat = this.chatStore.chats[options.chatIdx];
  910. // 初始状态只显示20条消息
  911. let size = this.messageSize;
  912. this.showMinIdx = size > 20 ? size - 20 : 0;
  913. // 消息已读
  914. this.readedMessage()
  915. // 加载好友或群聊信息
  916. if (this.chat.type == "GROUP") {
  917. this.loadGroup(this.chat.targetId);
  918. } else {
  919. this.loadFriend(this.chat.targetId);
  920. this.loadReaded(this.chat.targetId)
  921. }
  922. // 激活当前会话
  923. this.chatStore.activeChat(options.chatIdx);
  924. // 复位回执消息
  925. this.isReceipt = false;
  926. // 监听键盘高度
  927. this.listenKeyBoard();
  928. // 计算聊天窗口高度
  929. this.$nextTick(() => {
  930. this.windowHeight = uni.getSystemInfoSync().windowHeight;
  931. this.reCalChatMainHeight()
  932. // 兼容ios h5:禁止页面滚动
  933. // #ifdef H5
  934. this.initHeight = window.innerHeight;
  935. document.body.addEventListener('touchmove', function(e) {
  936. e.preventDefault();
  937. }, { passive: false });
  938. // #endif
  939. });
  940. },
  941. onUnload() {
  942. this.unListenKeyboard();
  943. },
  944. onShow() {
  945. if (this.needScrollToBottom) {
  946. // 页面滚到底部
  947. this.scrollToBottom();
  948. this.needScrollToBottom = false;
  949. }
  950. }
  951. }
  952. </script>
  953. <style lang="scss">
  954. .chat-box {
  955. $icon-color: rgba(0, 0, 0, 0.88);
  956. position: relative;
  957. background-color: #fafafa;
  958. .header {
  959. display: flex;
  960. justify-content: center;
  961. align-items: center;
  962. height: 60rpx;
  963. padding: 5px;
  964. background-color: #fafafa;
  965. line-height: 50px;
  966. font-size: $im-font-size-large;
  967. box-shadow: $im-box-shadow-lighter;
  968. z-index: 1;
  969. .btn-side {
  970. position: absolute;
  971. line-height: 60rpx;
  972. cursor: pointer;
  973. &.right {
  974. right: 30rpx;
  975. }
  976. }
  977. }
  978. .chat-main-box {
  979. // #ifdef H5
  980. top: $im-nav-bar-height;
  981. // #endif
  982. // #ifndef H5
  983. top: calc($im-nav-bar-height + var(--status-bar-height));
  984. // #endif
  985. position: fixed;
  986. width: 100%;
  987. display: flex;
  988. flex-direction: column;
  989. z-index: 2;
  990. .chat-msg {
  991. flex: 1;
  992. padding: 0;
  993. overflow: hidden;
  994. position: relative;
  995. background-color: white;
  996. .scroll-box {
  997. height: 100%;
  998. }
  999. }
  1000. .chat-at-bar {
  1001. display: flex;
  1002. align-items: center;
  1003. padding: 0 10rpx;
  1004. .icon-at {
  1005. font-size: $im-font-size-larger;
  1006. color: $im-color-primary;
  1007. font-weight: bold;
  1008. }
  1009. .chat-at-scroll-box {
  1010. flex: 1;
  1011. width: 80%;
  1012. .chat-at-items {
  1013. display: flex;
  1014. align-items: center;
  1015. height: 70rpx;
  1016. .chat-at-item {
  1017. padding: 0 3rpx;
  1018. }
  1019. }
  1020. }
  1021. }
  1022. .send-bar {
  1023. display: flex;
  1024. align-items: center;
  1025. padding: 10rpx;
  1026. border-top: $im-border solid 1px;
  1027. background-color: $im-bg;
  1028. min-height: 80rpx;
  1029. margin-bottom: 14rpx;
  1030. .iconfont {
  1031. font-size: 60rpx;
  1032. margin: 0 10rpx;
  1033. color: $icon-color;
  1034. }
  1035. .chat-record {
  1036. flex: 1;
  1037. }
  1038. .send-text {
  1039. flex: 1;
  1040. overflow: auto;
  1041. padding: 14rpx 20rpx;
  1042. background-color: #fff;
  1043. border-radius: 8rpx;
  1044. font-size: $im-font-size;
  1045. box-sizing: border-box;
  1046. margin: 0 10rpx;
  1047. position: relative;
  1048. .send-text-area {
  1049. width: 100%;
  1050. height: 100%;
  1051. min-height: 40rpx;
  1052. max-height: 200rpx;
  1053. font-size: 30rpx;
  1054. }
  1055. }
  1056. .btn-send {
  1057. margin: 5rpx;
  1058. }
  1059. }
  1060. }
  1061. .chat-tab-bar {
  1062. position: fixed;
  1063. bottom: 0;
  1064. background-color: $im-bg;
  1065. .chat-tools {
  1066. display: flex;
  1067. flex-wrap: wrap;
  1068. align-items: top;
  1069. height: 310px;
  1070. padding: 40rpx;
  1071. box-sizing: border-box;
  1072. .chat-tools-item {
  1073. width: 25%;
  1074. padding: 16rpx;
  1075. box-sizing: border-box;
  1076. display: flex;
  1077. flex-direction: column;
  1078. align-items: center;
  1079. .tool-icon {
  1080. padding: 26rpx;
  1081. font-size: 54rpx;
  1082. border-radius: 20%;
  1083. background-color: white;
  1084. color: $icon-color;
  1085. &:active {
  1086. background-color: $im-bg-active;
  1087. }
  1088. }
  1089. .tool-name {
  1090. height: 60rpx;
  1091. line-height: 60rpx;
  1092. font-size: 28rpx;
  1093. }
  1094. }
  1095. }
  1096. .chat-emotion {
  1097. height: 310px;
  1098. padding: 20rpx;
  1099. box-sizing: border-box;
  1100. .emotion-item-list {
  1101. display: flex;
  1102. flex-wrap: wrap;
  1103. justify-content: space-between;
  1104. align-content: center;
  1105. .emotion-item {
  1106. text-align: center;
  1107. cursor: pointer;
  1108. padding: 5px;
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. </style>