chat-box.vue 30 KB

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