App.vue 15 KB

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