privateChat.vue 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. <template>
  2. <view class="chatInterface" @contextmenu.prevent="">
  3. <view class="scroll-view">
  4. <image v-if="history.loading" class="history-loaded" src="/static/images/loading.svg"/>
  5. <view v-else :class="history.allLoaded ? 'history-loaded':'load'" @click="loadHistoryMessage(false)">
  6. <view>{{ history.allLoaded ? '已经没有更多的历史消息' : '点击获取历史消息' }}</view>
  7. </view>
  8. <checkbox-group @change="selectMessages">
  9. <!--消息记录-->
  10. <view v-for="(message,index) in history.messages" :key="message.messageId">
  11. <!--时间显示,类似于微信,隔5分钟不发言,才显示时间-->
  12. <view class="time-lag">
  13. {{ renderMessageDate(message, index) }}
  14. </view>
  15. <view class="message-recalled" v-if="message.recalled">
  16. <view v-if="message.recaller.id === currentUser.id" class="message-recalled-self">
  17. <view>你撤回了一条消息</view>
  18. <span v-if="message.type === 'text' && Date.now()-message.timestamp< 60 * 1000 "
  19. @click="editRecalledMessage(message.payload.text)">重新编辑</span>
  20. </view>
  21. <view v-else>{{ message.recaller.data.name }}撤回了一条消息</view>
  22. </view>
  23. <view class="message-item" v-else>
  24. <view class="message-item-checkbox">
  25. <checkbox v-show="messageSelector.visible && message.status !== 'sending'" :value="message.messageId"
  26. :checked="messageSelector.messages.includes(message)"/>
  27. </view>
  28. <view class="message-item-content" :class="{'self' : message.senderId === currentUser.id}">
  29. <view class="avatar">
  30. <image :src="message.senderId === currentUser.id? currentUser.avatar : friend.avatar"></image>
  31. </view>
  32. <view class="content" @click.right="showActionPopup(message)" @longpress="showActionPopup(message)">
  33. <view class="message-payload">
  34. <b class="pending" v-if="message.status === 'sending'"></b>
  35. <b class="send-fail" v-if="message.status === 'fail'"></b>
  36. <view v-if="message.type === 'text'" class="text-content" v-html="renderTextMessage(message)"></view>
  37. <image v-if="message.type === 'image'"
  38. :data-url="message.payload.url"
  39. :src="message.payload.thumbnail"
  40. class="image-content"
  41. mode="heightFix"
  42. @click="showImageFullScreen"
  43. ></image>
  44. <view class="video-snapshot" v-if="message.type === 'video'" :data-url="message.payload.video.url"
  45. @click="playVideo">
  46. <image
  47. :src="message.payload.thumbnail.url"
  48. :style="{height: getImageHeight(message.payload.thumbnail.width,message.payload.thumbnail.height)+'rpx' }"
  49. mode="heightFix"
  50. ></image>
  51. <view class="video-play-icon"></view>
  52. </view>
  53. <view class="file-content" v-if="message.type === 'file'">
  54. <view class="file-info">
  55. <span class="file-name">{{ message.payload.name }}</span>
  56. <span class="file-size">{{ (message.payload.size / 1024).toFixed(2) }}KB</span>
  57. </view>
  58. <image class="file-img" src="/static/images/file-icon.png"></image>
  59. </view>
  60. <view v-if="message.type ==='audio'" class="audio-content" @click="playAudio(message)">
  61. <view class="audio-facade" :style="{width:Math.ceil(message.payload.duration)*7 + 50 + 'px'}">
  62. <view
  63. class="audio-facade-bg"
  64. :class="{'play-icon':audioPlayer.playingMessage && audioPlayer.playingMessage.messageId === message.messageId}"
  65. ></view>
  66. <view>{{Math.ceil(message.payload.duration) || 1}}<span>"</span></view>
  67. </view>
  68. </view>
  69. <view v-if="message.type === 'order'" class="order-content">
  70. <view class="order-id">订单号:{{ message.payload.id }}</view>
  71. <view class="order-body">
  72. <image :src="message.payload.url" class="order-img"></image>
  73. <view>
  74. <view class="order-name">{{ message.payload.name }}</view>
  75. <view class="order-info">
  76. <view class="order-price">{{ message.payload.price }}</view>
  77. <view class="order-count">共{{ message.payload.count }}件</view>
  78. </view>
  79. </view>
  80. </view>
  81. </view>
  82. </view>
  83. <view v-if="message.senderId === currentUser.id" :class="message.read ?'message-read':'message-unread'">
  84. <view v-if="message.status === 'success'">{{ message.read ? '已读' : '未读' }}</view>
  85. </view>
  86. </view>
  87. </view>
  88. </view>
  89. </view>
  90. </checkbox-group>
  91. </view>
  92. <view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
  93. <view class="action-top">
  94. <view @click="switchAudioKeyboard">
  95. <image class="more" v-if="audio.visible" src="/static/images/jianpan.png"></image>
  96. <image class="more" v-else src="/static/images/audio.png"></image>
  97. </view>
  98. <view v-if="audio.visible" class="record-input" @touchend.stop="onRecordEnd" @touchstart.stop="onRecordStart">
  99. {{ recorderManager.recording ? '松开发送' : '按住录音' }}
  100. </view>
  101. <!-- GoEasyIM最大支持3k的文本消息,如需发送长文本,需调整输入框maxlength值 -->
  102. <input v-else v-model="text" @confirm="sendTextMessage" class="consult-input" maxlength="700" placeholder="发送消息" type="text" />
  103. <view @click="switchEmojiKeyboard">
  104. <image class="more" v-if="emoji.visible" src="/static/images/jianpan.png"></image>
  105. <image class="more" v-else src="/static/images/emoji.png"></image>
  106. </view>
  107. <view>
  108. <image @click="showOtherTypesMessagePanel()" class="more" src="/static/images/more.png"/>
  109. </view>
  110. <view v-if="text" class="send-btn-box">
  111. <text class="btn" @click="sendTextMessage()">发送</text>
  112. </view>
  113. </view>
  114. <!--展示表情列表-->
  115. <view class="action-bottom action-bottom-emoji" v-if="emoji.visible">
  116. <image class="emoji-item" v-for="(emojiItem, emojiKey, index) in emoji.map" :key="index"
  117. :src="emoji.url + emojiItem" @click="chooseEmoji(emojiKey)"></image>
  118. </view>
  119. <!--其他类型消息面板-->
  120. <view v-if="otherTypesMessagePanelVisible" class="action-bottom">
  121. <view class="more-icon">
  122. <image @click="sendImageMessage()" class="operation-icon" src="/static/images/picture.png"></image>
  123. <view class="operation-title">图片</view>
  124. </view>
  125. <view class="more-icon">
  126. <image @click="sendVideoMessage()" class="operation-icon" src="/static/images/video.png"></image>
  127. <view class="operation-title">视频</view>
  128. </view>
  129. <view class="more-icon">
  130. <image @click="showOrderMessageList()" class="operation-icon" src="/static/images/order.png"></image>
  131. <view class="operation-title">订单</view>
  132. </view>
  133. <view class="more-icon">
  134. <image @click="privateCall()" class="operation-icon" src="/static/images/rtc.png"></image>
  135. <view class="operation-title">视频通话</view>
  136. </view>
  137. </view>
  138. </view>
  139. <view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
  140. <view class="layer"></view>
  141. <view class="action-list">
  142. <view class="action-item" @click="deleteSingleMessage">删除</view>
  143. <view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
  144. <view class="action-item" @click="showCheckBox">多选</view>
  145. <view class="action-item" @click="hideActionPopup">取消</view>
  146. </view>
  147. </view>
  148. <view class="messageSelector-box" v-if="messageSelector.visible">
  149. <image class="messageSelector-btn" @click="deleteMultipleMessages" src="/static/images/delete.png"></image>
  150. </view>
  151. <view class="record-loading" v-if="recorderManager.recording"></view>
  152. <video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer"
  153. @fullscreenchange="onVideoFullScreenChange"></video>
  154. <view v-if="orderList.visible" class="order-list">
  155. <view class="orders-content">
  156. <view class="title">
  157. <view>请选择一个订单</view>
  158. <view class="close" @click="hideOrderMessageList">×</view>
  159. </view>
  160. <view class="orders">
  161. <view
  162. v-for="(order, index) in orderList.orders"
  163. :key="index" class="order-item"
  164. @click="sendOrderMessage(order)"
  165. >
  166. <view class="order-id">订单号:{{ order.id }}</view>
  167. <view class="order-body">
  168. <image :src="order.url" class="order-img"></image>
  169. <view class="order-name">{{ order.name }}</view>
  170. <view class="order-right">
  171. <view class="order-price">{{ order.price }}</view>
  172. <view class="order-count">共{{ order.count }}件</view>
  173. </view>
  174. </view>
  175. </view>
  176. </view>
  177. </view>
  178. </view>
  179. </view>
  180. </template>
  181. <script>
  182. import EmojiDecoder from '../lib/EmojiDecoder';
  183. import restApi from '../lib/restapi';
  184. import {formatDate} from '../lib/utils';
  185. import RecorderManager from '../lib/RecorderManager';
  186. const IMAGE_MAX_WIDTH = 200;
  187. const IMAGE_MAX_HEIGHT = 150;
  188. const recorderManager = new RecorderManager();
  189. const GoEasy = uni.$GoEasy;
  190. const GRTC = uni.$GRTC;
  191. export default {
  192. name: 'privateChat',
  193. data() {
  194. const emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
  195. const emojiMap = {
  196. '[么么哒]': 'emoji_3@2x.png',
  197. '[乒乓]': 'emoji_4@2x.png',
  198. '[便便]': 'emoji_5@2x.png',
  199. '[信封]': 'emoji_6@2x.png',
  200. '[偷笑]': 'emoji_7@2x.png',
  201. '[傲慢]': 'emoji_8@2x.png'
  202. };
  203. return {
  204. //聊天文本框
  205. text: '',
  206. friend: null,
  207. to: {},// 作为createMessage的参数
  208. currentUser: null,
  209. //定义表情列表
  210. emoji: {
  211. url: emojiUrl,
  212. map: emojiMap,
  213. visible: false,
  214. decoder: new EmojiDecoder(emojiUrl, emojiMap),
  215. },
  216. //是否展示‘其他消息类型面板’
  217. otherTypesMessagePanelVisible: false,
  218. orderList: {
  219. orders: [],
  220. visible: false
  221. },
  222. history: {
  223. messages: [],
  224. allLoaded: false,
  225. loading: false
  226. },
  227. recorderManager: recorderManager,
  228. audio: {
  229. //录音按钮展示
  230. visible: false
  231. },
  232. audioPlayer: {
  233. innerAudioContext: null,
  234. playingMessage: null,
  235. },
  236. videoPlayer: {
  237. visible: false,
  238. url: '',
  239. context: null
  240. },
  241. // 展示消息删除弹出框
  242. actionPopup: {
  243. visible: false,
  244. message: null,
  245. recallable: false,
  246. },
  247. // 消息选择
  248. messageSelector: {
  249. visible: false,
  250. messages: []
  251. }
  252. }
  253. },
  254. onLoad(options) {
  255. //聊天对象
  256. let id = options.to;
  257. this.friend = uni.getStorageSync("friend");
  258. //this.friend = restApi.findUserById(id);
  259. //this.currentUser = uni.$currentUser;
  260. this.currentUser = uni.getStorageSync("currentUser");
  261. this.to = {
  262. id: this.friend.id,
  263. type: GoEasy.IM_SCENE.PRIVATE,
  264. data: {
  265. name: this.friend.supplierName,
  266. avatar: '/static/images/Avatar-1.png'
  267. }
  268. };
  269. this.initGoEasyListeners();
  270. // 语音播放器
  271. this.initialAudioPlayer();
  272. // 录音监听器
  273. this.initRecorderListeners();
  274. },
  275. onShow() {
  276. this.otherTypesMessagePanelVisible = false;
  277. this.emoji.visible = false;
  278. },
  279. onReady() {
  280. this.loadHistoryMessage(true);
  281. this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
  282. // https://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle
  283. uni.setNavigationBarTitle({ title: this.friend.supplierName });
  284. },
  285. onPullDownRefresh(e) {
  286. this.loadHistoryMessage(false);
  287. },
  288. onUnload() {
  289. //退出聊天页面之前,清空监听器
  290. GoEasy.im.off(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this.onMessageReceived);
  291. GoEasy.im.off(GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
  292. GoEasy.im.off(GoEasy.IM_EVENT.HISTORY_EXPIRED, this.onHistoryExpired);
  293. },
  294. methods: {
  295. //渲染文本消息,如果包含表情,替换为图片
  296. //todo:本不需要该方法,可以在标签里完成,但小程序有兼容性问题,被迫这样实现
  297. renderTextMessage(message) {
  298. return '<span>' + this.emoji.decoder.decode(message.payload.text) + '</span>'
  299. },
  300. //像微信那样显示时间,如果有几分钟没发消息了,才显示时间
  301. //todo:本不需要该方法,可以在标签里完成,但小程序有兼容性问题,被迫这样实现
  302. renderMessageDate(message, index) {
  303. if (index === 0) {
  304. return formatDate(message.timestamp)
  305. } else {
  306. if (message.timestamp - this.history.messages[index - 1].timestamp > 5 * 60 * 1000) {
  307. return formatDate(message.timestamp)
  308. }
  309. }
  310. return '';
  311. },
  312. initGoEasyListeners() {
  313. // 监听私聊消息
  314. GoEasy.im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this.onMessageReceived);
  315. //监听消息删除
  316. GoEasy.im.on(GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
  317. // 监听断网重连
  318. GoEasy.im.on(GoEasy.IM_EVENT.HISTORY_EXPIRED, this.onHistoryExpired);
  319. },
  320. onMessageReceived (message) {
  321. let senderId = message.senderId;
  322. let receiverId = message.receiverId;
  323. let friendId = this.currentUser.id === senderId ? receiverId : senderId;
  324. if (friendId === this.friend.id) {
  325. this.history.messages.push(message);
  326. //聊天时,收到消息标记为已读
  327. this.markPrivateMessageAsRead();
  328. //收到新消息,是滚动到最底部
  329. this.scrollToBottom();
  330. }
  331. },
  332. onMessageDeleted (deletedMessages) {
  333. deletedMessages.forEach(message => {
  334. let senderId = message.senderId;
  335. let receiverId = message.receiverId;
  336. let friendId = this.currentUser.id === senderId ? receiverId : senderId;
  337. if (friendId === this.friend.id) {
  338. let index = this.history.messages.indexOf(message);
  339. if (index > -1) {
  340. this.history.messages.splice(index, 1);
  341. }
  342. }
  343. });
  344. },
  345. onHistoryExpired() {
  346. this.history.messages = [];
  347. this.loadHistoryMessage(true);
  348. },
  349. initialAudioPlayer () {
  350. this.audioPlayer.innerAudioContext = uni.createInnerAudioContext();
  351. this.audioPlayer.innerAudioContext.onEnded(() => {
  352. this.audioPlayer.playingMessage = null;
  353. });
  354. this.audioPlayer.innerAudioContext.onStop(() => {
  355. this.audioPlayer.playingMessage = null;
  356. });
  357. },
  358. initRecorderListeners() {
  359. recorderManager.onRecordComplete((file, duration) => {
  360. if (duration < 1000) {
  361. uni.showToast({
  362. icon: 'none',
  363. title: '录音时间太短',
  364. duration: 500
  365. });
  366. return;
  367. }
  368. GoEasy.im.createAudioMessage({
  369. to: this.to,
  370. file: file,
  371. notification: {
  372. title: this.currentUser.name + '发来一段语音',
  373. body: '[语音消息]', // 字段最长 50 字符
  374. sound: 'message',
  375. badge: '+1'
  376. },
  377. onProgress: function (progress) {
  378. console.log(progress)
  379. },
  380. onSuccess: (message) => {
  381. this.sendMessage(message);
  382. },
  383. onFailed: (e) => {
  384. console.log('error :', e);
  385. }
  386. });
  387. });
  388. },
  389. /**
  390. * 核心就是设置高度,产生明确占位
  391. *
  392. * 小 (宽度和高度都小于预设尺寸)
  393. * 设高=原始高度
  394. * 宽 (宽度>高度)
  395. * 高度= 根据宽度等比缩放
  396. * 窄 (宽度<高度)或方(宽度=高度)
  397. * 设高=MAX height
  398. *
  399. * @param width,height
  400. * @returns number
  401. */
  402. getImageHeight(width, height) {
  403. if (width < IMAGE_MAX_WIDTH && height < IMAGE_MAX_HEIGHT) {
  404. return height * 2;
  405. } else if (width > height) {
  406. return (IMAGE_MAX_WIDTH / width * height) * 2;
  407. } else if (width === height || width < height) {
  408. return IMAGE_MAX_HEIGHT * 2;
  409. }
  410. },
  411. sendMessage(message) {
  412. this.history.messages.push(message);
  413. this.scrollToBottom();
  414. GoEasy.im.sendMessage({
  415. message: message,
  416. onSuccess: function () {
  417. console.log('发送成功.', message);
  418. },
  419. onFailed: function (error) {
  420. if (error.code === 507) {
  421. console.log('发送语音/图片/视频/文件失败,没有配置OSS存储,详情参考:https://docs.goeasy.io/2.x/im/message/media/alioss');
  422. } else {
  423. console.log('发送失败:', error);
  424. }
  425. }
  426. });
  427. },
  428. sendTextMessage() {
  429. if (this.text.trim() !== '') {
  430. let body = this.text;
  431. if (this.text.length >= 50) {
  432. body = this.text.substring(0, 30) + '...';
  433. }
  434. GoEasy.im.createTextMessage({
  435. text: this.text,
  436. to: this.to,
  437. notification: {
  438. title: this.currentUser.name + '发来一段文字',
  439. body: body,
  440. sound: 'message',
  441. badge: '+1'
  442. },
  443. onSuccess: (message) => {
  444. this.sendMessage(message);
  445. },
  446. onFailed: (e) => {
  447. console.log('error :', e);
  448. }
  449. });
  450. }
  451. this.text = '';
  452. },
  453. sendVideoMessage() {
  454. uni.chooseVideo({
  455. success: (res) => {
  456. GoEasy.im.createVideoMessage({
  457. to: this.to,
  458. file: res,
  459. notification: {
  460. title: this.currentUser.name + '发来一个视频',
  461. body: '[视频消息]', // 字段最长 50 字符
  462. sound: 'message',
  463. badge: '+1'
  464. },
  465. onProgress: function (progress) {
  466. console.log(progress)
  467. },
  468. onSuccess: (message) => {
  469. this.otherTypesMessagePanelVisible = false;
  470. this.sendMessage(message);
  471. },
  472. onFailed: (e) => {
  473. console.log('error :', e);
  474. }
  475. });
  476. }
  477. })
  478. },
  479. sendImageMessage() {
  480. uni.chooseImage({
  481. count: 9,
  482. success: (res) => {
  483. res.tempFiles.forEach(file => {
  484. GoEasy.im.createImageMessage({
  485. to: this.to,
  486. file: file,
  487. notification: {
  488. title: this.currentUser.name + '发来一张图片',
  489. body: '[图片消息]', // 字段最长 50 字符
  490. sound: 'message',
  491. badge: '+1'
  492. },
  493. onProgress: function (progress) {
  494. console.log(progress)
  495. },
  496. onSuccess: (message) => {
  497. this.otherTypesMessagePanelVisible = false;
  498. this.sendMessage(message);
  499. },
  500. onFailed: (e) => {
  501. console.log('error :', e);
  502. }
  503. });
  504. })
  505. }
  506. });
  507. },
  508. sendOrderMessage(order) {
  509. //GoEasyIM自定义消息,实现订单发送
  510. GoEasy.im.createCustomMessage({
  511. type: 'order',
  512. payload: order,
  513. to: this.to,
  514. notification: {
  515. title: this.currentUser.name + '发来一个订单',
  516. body: '[订单消息]',
  517. sound: 'message',
  518. badge: '+1'
  519. },
  520. onSuccess: (message) => {
  521. this.otherTypesMessagePanelVisible = false;
  522. this.sendMessage(message);
  523. },
  524. onFailed: (e) => {
  525. console.log('error :', e);
  526. }
  527. });
  528. this.orderList.visible = false;
  529. },
  530. showActionPopup(message) {
  531. const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
  532. this.messageSelector.messages = [message];
  533. if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId === this.currentUser.id && message.status === 'success') {
  534. this.actionPopup.recallable = true;
  535. } else {
  536. this.actionPopup.recallable = false;
  537. }
  538. this.actionPopup.visible = true;
  539. },
  540. hideActionPopup () {
  541. this.actionPopup.visible = false;
  542. this.actionPopup.message = null;
  543. },
  544. deleteSingleMessage() {
  545. uni.showModal({
  546. content: '确认删除?',
  547. success: (res) => {
  548. this.actionPopup.visible = false;
  549. if (res.confirm) {
  550. this.deleteMessage();
  551. }
  552. },
  553. })
  554. },
  555. deleteMultipleMessages() {
  556. if (this.messageSelector.messages.length > 0) {
  557. uni.showModal({
  558. content: '确认删除?',
  559. success: (res) => {
  560. this.messageSelector.visible = false;
  561. if (res.confirm) {
  562. this.deleteMessage();
  563. }
  564. },
  565. })
  566. }
  567. },
  568. deleteMessage() {
  569. GoEasy.im.deleteMessage({
  570. messages: this.messageSelector.messages,
  571. onSuccess: (result) => {
  572. this.messageSelector.messages.forEach(message => {
  573. let index = this.history.messages.indexOf(message);
  574. if (index > -1) {
  575. this.history.messages.splice(index, 1);
  576. }
  577. });
  578. this.messageSelector.messages = [];
  579. },
  580. onFailed: (error) => {
  581. console.log('error:', error);
  582. }
  583. });
  584. },
  585. recallMessage() {
  586. this.actionPopup.visible = false;
  587. GoEasy.im.recallMessage({
  588. messages: this.messageSelector.messages,
  589. onSuccess: () => {
  590. console.log('撤回成功');
  591. },
  592. onFailed: (error) => {
  593. console.log('撤回失败,error:', error);
  594. }
  595. });
  596. },
  597. editRecalledMessage(text) {
  598. if (this.audio.visible) {
  599. this.audio.visible = false;
  600. }
  601. this.text = text;
  602. },
  603. showCheckBox() {
  604. this.messageSelector.messages = [];
  605. this.messageSelector.visible = true;
  606. this.actionPopup.visible = false;
  607. },
  608. selectMessages(e) {
  609. const selectedMessageIds = e.detail.value;
  610. let selectedMessages = [];
  611. this.history.messages.forEach(message => {
  612. if (selectedMessageIds.includes(message.messageId)) {
  613. selectedMessages.push(message);
  614. }
  615. })
  616. this.messageSelector.messages = selectedMessages;
  617. },
  618. loadHistoryMessage(scrollToBottom) {//历史消息
  619. this.history.loading = true;
  620. let lastMessageTimeStamp = null;
  621. let lastMessage = this.history.messages[0];
  622. if (lastMessage) {
  623. lastMessageTimeStamp = lastMessage.timestamp;
  624. }
  625. GoEasy.im.history({
  626. id: this.friend.id,
  627. type: GoEasy.IM_SCENE.PRIVATE,
  628. lastTimestamp: lastMessageTimeStamp,
  629. limit: 10,
  630. onSuccess: (result) => {
  631. uni.stopPullDownRefresh();
  632. this.history.loading = false;
  633. let messages = result.content;
  634. if (messages.length === 0) {
  635. this.history.allLoaded = true;
  636. } else {
  637. if (lastMessageTimeStamp) {
  638. this.history.messages = messages.concat(this.history.messages);
  639. } else {
  640. this.history.messages = messages;
  641. }
  642. if (messages.length < 10) {
  643. this.history.allLoaded = true;
  644. }
  645. if (scrollToBottom) {
  646. this.scrollToBottom();
  647. //收到的消息设置为已读
  648. this.markPrivateMessageAsRead();
  649. }
  650. }
  651. },
  652. onFailed: (error) => {
  653. //获取失败
  654. console.log('获取历史消息失败:', error);
  655. uni.stopPullDownRefresh();
  656. this.history.loading = false;
  657. }
  658. });
  659. },
  660. //语音录制按钮和键盘输入的切换
  661. switchAudioKeyboard() {
  662. if (!this.audio.visible) {
  663. recorderManager.authorize().then(() => {
  664. console.log('录音权限获取成功');
  665. this.audio.visible = true;
  666. }).catch((err) => {
  667. console.log('err:', err)
  668. uni.showModal({
  669. title: '获取录音权限失败',
  670. content: '请先打开麦克风权限'
  671. });
  672. });
  673. } else {
  674. this.audio.visible = false;
  675. }
  676. },
  677. onRecordStart() {
  678. recorderManager.start();
  679. },
  680. onRecordEnd() {
  681. recorderManager.stop();
  682. },
  683. showImageFullScreen(e) {
  684. let imagesUrl = [e.currentTarget.dataset.url];
  685. uni.previewImage({
  686. urls: imagesUrl
  687. });
  688. },
  689. playVideo(e) {
  690. this.videoPlayer.visible = true;
  691. this.videoPlayer.url = e.currentTarget.dataset.url;
  692. this.$nextTick(() => {
  693. this.videoPlayer.context.requestFullScreen({
  694. direction: 0
  695. });
  696. this.videoPlayer.context.play();
  697. });
  698. },
  699. playAudio (audioMessage) {
  700. let playingMessage = this.audioPlayer.playingMessage;
  701. if (playingMessage) {
  702. this.audioPlayer.innerAudioContext.stop();
  703. // 如果点击的消息正在播放,就认为是停止播放操作
  704. if (playingMessage === audioMessage) {
  705. return;
  706. }
  707. }
  708. this.audioPlayer.playingMessage = audioMessage;
  709. this.audioPlayer.innerAudioContext.src = audioMessage.payload.url;
  710. this.audioPlayer.innerAudioContext.play();
  711. },
  712. onVideoFullScreenChange(e) {
  713. //当退出全屏播放时,隐藏播放器
  714. if (this.videoPlayer.visible && !e.detail.fullScreen) {
  715. this.videoPlayer.visible = false;
  716. this.videoPlayer.context.stop();
  717. }
  718. },
  719. messageInputFocusin() {
  720. this.otherTypesMessagePanelVisible = false;
  721. this.emoji.visible = false;
  722. },
  723. switchEmojiKeyboard() {
  724. this.emoji.visible = !this.emoji.visible;
  725. this.otherTypesMessagePanelVisible = false;
  726. },
  727. showOtherTypesMessagePanel() {
  728. this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
  729. this.emoji.visible = false;
  730. },
  731. chooseEmoji(emojiKey) {
  732. this.text += emojiKey;
  733. },
  734. showOrderMessageList() {
  735. this.orderList.orders = restApi.getOrderList();
  736. this.orderList.visible = true;
  737. },
  738. hideOrderMessageList() {
  739. this.orderList.visible = false;
  740. },
  741. privateCall() {
  742. uni.showActionSheet({
  743. itemList: ['视频通话', '音频通话'],
  744. success: (res) => {
  745. const mediaType = res.tapIndex === 0 ? 1 : 0;
  746. const notificationBody = res.tapIndex === 0 ? '邀请你视频通话' : '邀请你语音通话';
  747. GRTC.call({
  748. calleeId: this.friend.id,
  749. mediaType: mediaType,
  750. notification: {
  751. title: this.currentUser.name,
  752. body: notificationBody,
  753. sound: 'ring',
  754. badge: '+1'
  755. },
  756. }).then(() => {
  757. uni.navigateTo({
  758. url: `./rtc/private/dial`,
  759. })
  760. }).catch((error)=>{
  761. console.log("呼叫失败:", error);
  762. uni.showToast({
  763. icon: "error",
  764. title: "呼叫失败:" + error,
  765. duration: 2000
  766. })
  767. })
  768. },
  769. fail: (res) => {
  770. console.log(res.errMsg);
  771. }
  772. });
  773. },
  774. scrollToBottom() {
  775. this.$nextTick(() => {
  776. uni.pageScrollTo({
  777. scrollTop: 2000000,
  778. duration: 0
  779. });
  780. });
  781. },
  782. markPrivateMessageAsRead() {
  783. GoEasy.im.markMessageAsRead({
  784. id: this.to.id,
  785. type: this.to.type,
  786. onSuccess: function () {
  787. console.log('标记私聊已读成功');
  788. },
  789. onFailed: function (error) {
  790. console.log("标记私聊已读失败", error);
  791. }
  792. });
  793. }
  794. }
  795. }
  796. </script>
  797. <style>
  798. @import url('../static/style/chatInterface.css');
  799. </style>