App.vue 12 KB

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