App.vue 14 KB

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