App.vue 13 KB

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