App.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <script>
  2. import App from './App'
  3. import http from './common/request';
  4. import * as msgType from './common/messageType';
  5. import * as enums from './common/enums';
  6. import * as wsApi from './common/wssocket';
  7. import UNI_APP from '@/.env.js'
  8. export default {
  9. data() {
  10. return {
  11. isExit: false, // 是否已退出
  12. audioTip: null,
  13. reconnecting: false, // 正在重连标志
  14. privateMessagesBuffer: [],
  15. groupMessagesBuffer: [],
  16. }
  17. },
  18. methods: {
  19. init() {
  20. this.reconnecting = false;
  21. this.isExit = false;
  22. // 加载数据
  23. this.loadStore().then(() => {
  24. // 初始化websocket
  25. this.initWebSocket();
  26. }).catch(e => {
  27. console.log(e);
  28. this.exit();
  29. })
  30. },
  31. initWebSocket() {
  32. let loginInfo = uni.getStorageSync("loginInfo")
  33. wsApi.connect(UNI_APP.WS_URL, loginInfo.accessToken);
  34. wsApi.onConnect(() => {
  35. if (this.reconnecting) {
  36. // 重连成功
  37. this.onReconnectWs();
  38. } else {
  39. // 加载离线消息
  40. this.pullOfflineMessage();
  41. this.configStore.setAppInit(true);
  42. }
  43. });
  44. wsApi.onMessage((cmd, msgInfo) => {
  45. if (cmd == 2) {
  46. // 异地登录,强制下线
  47. uni.showModal({
  48. content: '您已在其他地方登录,将被强制下线',
  49. showCancel: false,
  50. })
  51. this.exit();
  52. } else if (cmd == 3) {
  53. if (!this.configStore.appInit || this.chatStore.loading) {
  54. // 如果正在拉取离线消息,先存入缓存区,等待消息拉取完成再处理,防止消息乱序
  55. this.privateMessagesBuffer.push(msgInfo);
  56. } else {
  57. // 插入私聊消息
  58. this.handlePrivateMessage(msgInfo);
  59. }
  60. } else if (cmd == 4) {
  61. if (!this.configStore.appInit || this.chatStore.loading) {
  62. // 如果正在拉取离线消息,先存入缓存区,等待消息拉取完成再处理,防止消息乱序
  63. this.privateMessagesBuffer.push(msgInfo);
  64. } else {
  65. // 插入群聊消息
  66. this.handleGroupMessage(msgInfo);
  67. }
  68. } else if (cmd == 5) {
  69. // 系统消息
  70. this.handleSystemMessage(msgInfo);
  71. }
  72. });
  73. wsApi.onClose((res) => {
  74. console.log("ws断开", res);
  75. // 重新连接
  76. this.reconnectWs();
  77. this.configStore.setAppInit(false);
  78. })
  79. },
  80. loadStore() {
  81. return this.userStore.loadUser().then(() => {
  82. const promises = [];
  83. promises.push(this.friendStore.loadFriend());
  84. promises.push(this.groupStore.loadGroup());
  85. promises.push(this.chatStore.loadChat());
  86. promises.push(this.configStore.loadConfig());
  87. return Promise.all(promises);
  88. })
  89. },
  90. unloadStore() {
  91. this.friendStore.clear();
  92. this.groupStore.clear();
  93. this.chatStore.clear();
  94. this.configStore.clear();
  95. this.userStore.clear();
  96. },
  97. pullOfflineMessage() {
  98. this.chatStore.setLoading(true);
  99. const promises = [];
  100. promises.push(this.pullPrivateOfflineMessage(this.chatStore.privateMsgMaxId));
  101. promises.push(this.pullGroupOfflineMessage(this.chatStore.groupMsgMaxId));
  102. Promise.all(promises).then(messages => {
  103. // 处理离线消息
  104. messages[0].forEach(m => this.handlePrivateMessage(m));
  105. messages[1].forEach(m => this.handleGroupMessage(m));
  106. // 处理缓冲区收到的实时消息
  107. this.privateMessagesBuffer.forEach(m => this.handlePrivateMessage(m));
  108. this.groupMessagesBuffer.forEach(m => this.handleGroupMessage(m));
  109. // 清空缓冲区
  110. this.privateMessagesBuffer = [];
  111. this.groupMessagesBuffer = [];
  112. // 关闭加载离线标记
  113. this.chatStore.setLoading(false);
  114. // 刷新会话
  115. this.chatStore.refreshChats();
  116. }).catch((e) => {
  117. console.log(e)
  118. this.$message.error("拉取离线消息失败");
  119. this.onExit();
  120. })
  121. },
  122. pullPrivateOfflineMessage(minId) {
  123. return this.$http({
  124. url: "/message/private/loadOfflineMessage?minId=" + minId,
  125. method: 'GET',
  126. timeout: 60000
  127. })
  128. },
  129. pullGroupOfflineMessage(minId) {
  130. return this.$http({
  131. url: "/message/group/loadOfflineMessage?minId=" + minId,
  132. method: 'GET',
  133. timeout: 60000
  134. })
  135. },
  136. handlePrivateMessage(msg) {
  137. // 标记这条消息是不是自己发的
  138. msg.selfSend = msg.sendId == this.userStore.userInfo.id;
  139. // 好友id
  140. let friendId = msg.selfSend ? msg.recvId : msg.sendId;
  141. // 会话信息
  142. let chatInfo = {
  143. type: 'PRIVATE',
  144. targetId: friendId
  145. }
  146. // 消息已读处理,清空已读数量
  147. if (msg.type == enums.MESSAGE_TYPE.READED) {
  148. this.chatStore.resetUnreadCount(chatInfo);
  149. return;
  150. }
  151. // 消息回执处理,改消息状态为已读
  152. if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
  153. this.chatStore.readedMessage({
  154. friendId: msg.sendId
  155. })
  156. return;
  157. }
  158. // 消息撤回
  159. if (msg.type == enums.MESSAGE_TYPE.RECALL) {
  160. this.chatStore.recallMessage(msg, chatInfo);
  161. return;
  162. }
  163. // 新增好友
  164. if (msg.type == enums.MESSAGE_TYPE.FRIEND_NEW) {
  165. this.friendStore.addFriend(JSON.parse(msg.content));
  166. return;
  167. }
  168. // 删除好友
  169. if (msg.type == enums.MESSAGE_TYPE.FRIEND_DEL) {
  170. this.friendStore.removeFriend(friendId);
  171. return;
  172. }
  173. // 对好友设置免打扰
  174. if (msg.type == enums.MESSAGE_TYPE.FRIEND_DND) {
  175. this.friendStore.setDnd(friendId, JSON.parse(msg.content));
  176. this.chatStore.setDnd(chatInfo, JSON.parse(msg.content));
  177. return;
  178. }
  179. // 消息插入
  180. let friend = this.loadFriendInfo(friendId);
  181. this.insertPrivateMessage(friend, msg);
  182. },
  183. insertPrivateMessage(friend, msg) {
  184. // 单人视频信令
  185. if (msgType.isRtcPrivate(msg.type)) {
  186. // #ifdef MP-WEIXIN
  187. // 小程序不支持音视频
  188. return;
  189. // #endif
  190. // 被呼叫,弹出视频页面
  191. let delayTime = 100;
  192. if (msg.type == enums.MESSAGE_TYPE.RTC_CALL_VOICE ||
  193. msg.type == enums.MESSAGE_TYPE.RTC_CALL_VIDEO) {
  194. let mode = msg.type == enums.MESSAGE_TYPE.RTC_CALL_VIDEO ? "video" : "voice";
  195. let pages = getCurrentPages();
  196. let curPage = pages[pages.length - 1].route;
  197. if (curPage != "pages/chat/chat-private-video") {
  198. const friendInfo = encodeURIComponent(JSON.stringify(friend));
  199. uni.navigateTo({
  200. url: `/pages/chat/chat-private-video?mode=${mode}&friend=${friendInfo}&isHost=false`
  201. })
  202. delayTime = 500;
  203. }
  204. }
  205. setTimeout(() => {
  206. uni.$emit('WS_RTC_PRIVATE', msg);
  207. }, delayTime)
  208. return;
  209. }
  210. // 插入消息
  211. if (msgType.isNormal(msg.type) || msgType.isTip(msg.type) || msgType.isAction(msg.type)) {
  212. let chatInfo = {
  213. type: 'PRIVATE',
  214. targetId: friend.id,
  215. showName: friend.nickName,
  216. headImage: friend.headImage,
  217. isDnd: friend.isDnd
  218. };
  219. // 打开会话
  220. this.chatStore.openChat(chatInfo);
  221. // 插入消息
  222. this.chatStore.insertMessage(msg, chatInfo);
  223. // 播放提示音
  224. if (!friend.isDnd && !this.chatStore.loading &&
  225. !msg.selfSend && msgType.isNormal(msg.type) &&
  226. msg.status != enums.MESSAGE_STATUS.READED) {
  227. this.playAudioTip();
  228. }
  229. }
  230. },
  231. handleGroupMessage(msg) {
  232. // 标记这条消息是不是自己发的
  233. msg.selfSend = msg.sendId == this.userStore.userInfo.id;
  234. let chatInfo = {
  235. type: 'GROUP',
  236. targetId: msg.groupId
  237. }
  238. // 消息已读处理
  239. if (msg.type == enums.MESSAGE_TYPE.READED) {
  240. // 我已读对方的消息,清空已读数量
  241. this.chatStore.resetUnreadCount(chatInfo)
  242. return;
  243. }
  244. // 消息回执处理
  245. if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
  246. // 更新消息已读人数
  247. let msgInfo = {
  248. id: msg.id,
  249. groupId: msg.groupId,
  250. readedCount: msg.readedCount,
  251. receiptOk: msg.receiptOk
  252. };
  253. this.chatStore.updateMessage(msgInfo, chatInfo)
  254. return;
  255. }
  256. // 消息撤回
  257. if (msg.type == enums.MESSAGE_TYPE.RECALL) {
  258. this.chatStore.recallMessage(msg, chatInfo)
  259. return;
  260. }
  261. // 新增群
  262. if (msg.type == enums.MESSAGE_TYPE.GROUP_NEW) {
  263. this.groupStore.addGroup(JSON.parse(msg.content));
  264. return;
  265. }
  266. // 删除群
  267. if (msg.type == enums.MESSAGE_TYPE.GROUP_DEL) {
  268. this.groupStore.removeGroup(msg.groupId);
  269. return;
  270. }
  271. // 对群设置免打扰
  272. if (msg.type == enums.MESSAGE_TYPE.GROUP_DND) {
  273. this.groupStore.setDnd(msg.groupId, JSON.parse(msg.content));
  274. this.chatStore.setDnd(chatInfo, JSON.parse(msg.content));
  275. return;
  276. }
  277. // 插入消息
  278. let group = this.loadGroupInfo(msg.groupId);
  279. this.insertGroupMessage(group, msg);
  280. },
  281. handleSystemMessage(msg) {
  282. if (msg.type == enums.MESSAGE_TYPE.USER_BANNED) {
  283. // 用户被封禁
  284. wsApi.close(3099);
  285. uni.showModal({
  286. content: '您的账号已被管理员封禁,原因:' + msg.content,
  287. showCancel: false,
  288. })
  289. this.exit();
  290. }
  291. },
  292. insertGroupMessage(group, msg) {
  293. // 群视频信令
  294. if (msgType.isRtcGroup(msg.type)) {
  295. // #ifdef MP-WEIXIN
  296. // 小程序不支持音视频
  297. return;
  298. // #endif
  299. // 被呼叫,弹出视频页面
  300. let delayTime = 100;
  301. if (msg.type == enums.MESSAGE_TYPE.RTC_GROUP_SETUP) {
  302. let pages = getCurrentPages();
  303. let curPage = pages[pages.length - 1].route;
  304. if (curPage != "pages/chat/chat-group-video") {
  305. const userInfos = encodeURIComponent(msg.content);
  306. const inviterId = msg.sendId;
  307. const groupId = msg.groupId
  308. uni.navigateTo({
  309. url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=false
  310. &inviterId=${inviterId}&userInfos=${userInfos}`
  311. })
  312. delayTime = 500;
  313. }
  314. }
  315. // 消息转发到chat-group-video页面进行处理
  316. setTimeout(() => {
  317. uni.$emit('WS_RTC_GROUP', msg);
  318. }, delayTime)
  319. return;
  320. }
  321. // 插入消息
  322. if (msgType.isNormal(msg.type) || msgType.isTip(msg.type) || msgType.isAction(msg.type)) {
  323. let chatInfo = {
  324. type: 'GROUP',
  325. targetId: group.id,
  326. showName: group.showGroupName,
  327. headImage: group.headImageThumb,
  328. isDnd: group.isDnd
  329. };
  330. // 打开会话
  331. this.chatStore.openChat(chatInfo);
  332. // 插入消息
  333. this.chatStore.insertMessage(msg, chatInfo);
  334. // 播放提示音
  335. if (!group.isDnd && !this.chatStore.loading &&
  336. !msg.selfSend && msgType.isNormal(msg.type) &&
  337. msg.status != enums.MESSAGE_STATUS.READED) {
  338. this.playAudioTip();
  339. }
  340. }
  341. },
  342. loadFriendInfo(id, callback) {
  343. let friend = this.friendStore.findFriend(id);
  344. if (!friend) {
  345. console.log("未知用户:", id)
  346. friend = {
  347. id: id,
  348. showNickName: "未知用户",
  349. headImage: ""
  350. }
  351. }
  352. return friend;
  353. },
  354. loadGroupInfo(id) {
  355. let group = this.groupStore.findGroup(id);
  356. if (!group) {
  357. group = {
  358. id: id,
  359. showGroupName: "未知群聊",
  360. headImageThumb: ""
  361. }
  362. }
  363. return group;
  364. },
  365. exit() {
  366. console.log("exit");
  367. this.isExit = true;
  368. wsApi.close(3099);
  369. uni.removeStorageSync("loginInfo");
  370. uni.reLaunch({
  371. url: "/pages/login/login"
  372. })
  373. this.unloadStore();
  374. },
  375. playAudioTip() {
  376. // 音频播放无法成功
  377. // this.audioTip = uni.createInnerAudioContext();
  378. // this.audioTip.src = "/static/audio/tip.wav";
  379. // this.audioTip.play();
  380. },
  381. refreshToken(loginInfo) {
  382. return new Promise((resolve, reject) => {
  383. if (!loginInfo || !loginInfo.refreshToken) {
  384. reject();
  385. return;
  386. }
  387. http({
  388. url: '/refreshToken',
  389. method: 'PUT',
  390. header: {
  391. refreshToken: loginInfo.refreshToken
  392. }
  393. }).then((newLoginInfo) => {
  394. uni.setStorageSync("loginInfo", newLoginInfo)
  395. resolve()
  396. }).catch((e) => {
  397. reject(e)
  398. })
  399. })
  400. },
  401. reconnectWs() {
  402. // 已退出则不再重连
  403. if (this.isExit) {
  404. return;
  405. }
  406. // 记录标志
  407. this.reconnecting = true;
  408. // 重新加载一次个人信息,目的是为了保证网络已经正常且token有效
  409. this.userStore.loadUser().then((userInfo) => {
  410. uni.showToast({
  411. title: '连接已断开,尝试重新连接...',
  412. icon: 'none'
  413. })
  414. // 重新连接
  415. let loginInfo = uni.getStorageSync("loginInfo")
  416. wsApi.reconnect(UNI_APP.WS_URL, loginInfo.accessToken);
  417. }).catch(() => {
  418. // 5s后重试
  419. setTimeout(() => {
  420. this.reconnectWs();
  421. }, 5000)
  422. })
  423. },
  424. onReconnectWs() {
  425. this.reconnecting = false;
  426. // 重新加载好友和群聊
  427. const promises = [];
  428. promises.push(this.friendStore.loadFriend());
  429. promises.push(this.groupStore.loadGroup());
  430. Promise.all(promises).then(() => {
  431. uni.showToast({
  432. title: "已重新连接",
  433. icon: 'none'
  434. })
  435. // 加载离线消息
  436. this.pullPrivateOfflineMessage(this.chatStore.privateMsgMaxId);
  437. this.pullGroupOfflineMessage(this.chatStore.groupMsgMaxId);
  438. this.configStore.setAppInit(true);
  439. }).catch((e) => {
  440. console.log(e);
  441. this.exit();
  442. })
  443. },
  444. closeSplashscreen(delay) {
  445. // #ifdef APP-PLUS
  446. // 关闭开机动画
  447. setTimeout(() => {
  448. plus.navigator.closeSplashscreen()
  449. }, delay)
  450. // #endif
  451. }
  452. },
  453. onLaunch() {
  454. this.$mountStore();
  455. // 延迟1s,避免用户看到页面跳转
  456. this.closeSplashscreen(1000);
  457. // 登录状态校验
  458. let loginInfo = uni.getStorageSync("loginInfo")
  459. this.refreshToken(loginInfo).then(() => {
  460. // #ifdef H5
  461. // 跳转到聊天页
  462. uni.switchTab({
  463. url: "/pages/chat/chat"
  464. })
  465. // #endif
  466. // 初始化
  467. this.init();
  468. this.closeSplashscreen(0);
  469. }).catch(() => {
  470. // 跳转到登录页
  471. uni.navigateTo({
  472. url: "/pages/login/login"
  473. })
  474. })
  475. }
  476. }
  477. </script>
  478. <style lang="scss">
  479. @import "@/uni_modules/uview-plus/index.scss";
  480. @import "@/im.scss";
  481. @import url('./static/icon/iconfont.css');
  482. // #ifdef H5
  483. uni-page-head {
  484. display: none; // h5浏览器本身就有标题
  485. }
  486. // #endif
  487. page {
  488. background-color: $im-bg;
  489. }
  490. .tab-page {
  491. position: relative;
  492. display: flex;
  493. flex-direction: column;
  494. // #ifdef H5
  495. height: calc(100vh - 50px - $im-nav-bar-height); // h5平台100vh是包含了底部高度,需要减去
  496. top: $im-nav-bar-height;
  497. // #endif
  498. // #ifdef APP-PLUS
  499. height: calc(100vh - var(--status-bar-height) - $im-nav-bar-height); // app平台还要减去顶部手机状态栏高度
  500. top: calc($im-nav-bar-height + var(--status-bar-height));
  501. // #endif
  502. // #ifdef MP-WEIXIN
  503. height: calc(100vh - $im-nav-bar-height);
  504. top: $im-nav-bar-height;
  505. // #endif
  506. color: $im-text-color;
  507. background-color: $im-bg;
  508. font-size: $im-font-size;
  509. font-family: $font-family;
  510. }
  511. .page {
  512. position: relative;
  513. // #ifdef H5
  514. height: calc(100vh - $im-nav-bar-height); // h5平台100vh是包含了底部高度,需要减去
  515. top: $im-nav-bar-height;
  516. // #endif
  517. // #ifdef APP-PLUS
  518. height: calc(100vh - var(--status-bar-height) - $im-nav-bar-height); // app平台还要减去顶部手机状态栏高度
  519. top: calc($im-nav-bar-height + var(--status-bar-height));
  520. // #endif
  521. // #ifdef MP-WEIXIN
  522. height: calc(100vh - $im-nav-bar-height);
  523. top: $im-nav-bar-height;
  524. // #endif
  525. color: $im-text-color;
  526. background-color: $im-bg;
  527. font-size: $im-font-size;
  528. font-family: $font-family;
  529. }
  530. </style>