App.vue 11 KB

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