App.vue 15 KB

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