App.vue 14 KB

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