privateChatWeb.vue 35 KB

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