App.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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);
  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. // 更新消息已读人数
  193. let msgInfo = {
  194. id: msg.id,
  195. groupId: msg.groupId,
  196. readedCount: msg.readedCount,
  197. receiptOk: msg.receiptOk
  198. };
  199. this.chatStore.updateMessage(msgInfo)
  200. return;
  201. }
  202. // 标记这条消息是不是自己发的
  203. msg.selfSend = msg.sendId == this.userStore.userInfo.id;
  204. this.loadGroupInfo(msg.groupId, (group) => {
  205. // 插入群聊消息
  206. this.insertGroupMessage(group, msg);
  207. })
  208. },
  209. handleSystemMessage(msg) {
  210. if (msg.type == enums.MESSAGE_TYPE.USER_BANNED) {
  211. // 用户被封禁
  212. wsApi.close(3099);
  213. uni.showModal({
  214. content: '您的账号已被管理员封禁,原因:' + msg.content,
  215. showCancel: false,
  216. })
  217. this.exit();
  218. }
  219. },
  220. insertGroupMessage(group, msg) {
  221. // 群视频信令
  222. if (msgType.isRtcGroup(msg.type)) {
  223. // #ifdef MP-WEIXIN
  224. // 小程序不支持音视频
  225. return;
  226. // #endif
  227. // 被呼叫,弹出视频页面
  228. let delayTime = 100;
  229. if (msg.type == enums.MESSAGE_TYPE.RTC_GROUP_SETUP) {
  230. let pages = getCurrentPages();
  231. let curPage = pages[pages.length - 1].route;
  232. if (curPage != "pages/chat/chat-group-video") {
  233. const userInfos = encodeURIComponent(msg.content);
  234. const inviterId = msg.sendId;
  235. const groupId = msg.groupId
  236. uni.navigateTo({
  237. url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=false
  238. &inviterId=${inviterId}&userInfos=${userInfos}`
  239. })
  240. delayTime = 500;
  241. }
  242. }
  243. // 消息转发到chat-group-video页面进行处理
  244. setTimeout(() => {
  245. uni.$emit('WS_RTC_GROUP', msg);
  246. }, delayTime)
  247. return;
  248. }
  249. let chatInfo = {
  250. type: 'GROUP',
  251. targetId: group.id,
  252. showName: group.showGroupName,
  253. headImage: group.headImageThumb
  254. };
  255. // 打开会话
  256. this.chatStore.openChat(chatInfo);
  257. // 插入消息
  258. this.chatStore.insertMessage(msg);
  259. // 播放提示音
  260. this.playAudioTip();
  261. },
  262. loadFriendInfo(id, callback) {
  263. let friend = this.friendStore.findFriend(id);
  264. if (friend) {
  265. callback(friend);
  266. } else {
  267. http({
  268. url: `/friend/find/${id}`,
  269. method: 'GET'
  270. }).then((friend) => {
  271. this.friendStore.addFriend(friend);
  272. callback(friend)
  273. })
  274. }
  275. },
  276. loadGroupInfo(id, callback) {
  277. let group = this.groupStore.findGroup(id);
  278. if (group) {
  279. callback(group);
  280. } else {
  281. http({
  282. url: `/group/find/${id}`,
  283. method: 'GET'
  284. }).then((group) => {
  285. this.groupStore.addGroup(group);
  286. callback(group)
  287. })
  288. }
  289. },
  290. exit() {
  291. console.log("exit");
  292. this.isExit = true;
  293. wsApi.close(3099);
  294. uni.removeStorageSync("loginInfo");
  295. uni.reLaunch({
  296. url: "/pages/login/login"
  297. })
  298. this.unloadStore();
  299. },
  300. playAudioTip() {
  301. // 音频播放无法成功
  302. // this.audioTip = uni.createInnerAudioContext();
  303. // this.audioTip.src = "/static/audio/tip.wav";
  304. // this.audioTip.play();
  305. },
  306. refreshToken(loginInfo) {
  307. return new Promise((resolve, reject) => {
  308. if (!loginInfo || !loginInfo.refreshToken) {
  309. reject();
  310. return;
  311. }
  312. http({
  313. url: '/refreshToken',
  314. method: 'PUT',
  315. header: {
  316. refreshToken: loginInfo.refreshToken
  317. }
  318. }).then((newLoginInfo) => {
  319. uni.setStorageSync("loginInfo", newLoginInfo)
  320. resolve()
  321. }).catch((e) => {
  322. reject(e)
  323. })
  324. })
  325. },
  326. reconnectWs() {
  327. // 已退出则不再重连
  328. if (this.isExit) {
  329. return;
  330. }
  331. // 记录标志
  332. this.reconnecting = true;
  333. // 重新加载一次个人信息,目的是为了保证网络已经正常且token有效
  334. this.reloadUserInfo().then((userInfo) => {
  335. uni.showToast({
  336. title: '连接已断开,尝试重新连接...',
  337. icon: 'none',
  338. })
  339. this.userStore.setUserInfo(userInfo);
  340. // 重新连接
  341. let loginInfo = uni.getStorageSync("loginInfo")
  342. wsApi.reconnect(UNI_APP.WS_URL, loginInfo.accessToken);
  343. }).catch(() => {
  344. // 5s后重试
  345. setTimeout(() => {
  346. this.reconnectWs();
  347. }, 5000)
  348. })
  349. },
  350. reloadUserInfo() {
  351. return http({
  352. url: '/user/self',
  353. method: 'GET'
  354. })
  355. },
  356. closeSplashscreen(delay) {
  357. // #ifdef APP-PLUS
  358. // 关闭开机动画
  359. setTimeout(() => {
  360. console.log("plus.navigator.closeSplashscreen()")
  361. plus.navigator.closeSplashscreen()
  362. }, delay)
  363. // #endif
  364. }
  365. },
  366. onLaunch() {
  367. this.$mountStore();
  368. // 登录状态校验
  369. let loginInfo = uni.getStorageSync("loginInfo")
  370. this.refreshToken(loginInfo).then(() => {
  371. // 初始化
  372. this.init();
  373. this.closeSplashscreen(0);
  374. }).catch(() => {
  375. // 跳转到登录页
  376. uni.navigateTo({
  377. url: "/pages/login/login"
  378. })
  379. // 延迟1s,避免用户看到页面跳转动画
  380. this.closeSplashscreen(1000);
  381. })
  382. }
  383. }
  384. </script>
  385. <style lang="scss">
  386. @import "@/uni_modules/uview-plus/index.scss";
  387. @import "@/im.scss";
  388. @import url('./static/icon/iconfont.css');
  389. // #ifdef H5
  390. uni-page-head {
  391. display: none; // h5浏览器本身就有标题
  392. }
  393. // #endif
  394. .tab-page {
  395. position: relative;
  396. display: flex;
  397. flex-direction: column;
  398. // #ifdef H5
  399. height: calc(100vh - 50px - $im-nav-bar-height); // h5平台100vh是包含了底部高度,需要减去
  400. top: $im-nav-bar-height;
  401. // #endif
  402. // #ifndef H5
  403. height: calc(100vh - var(--status-bar-height) - $im-nav-bar-height); // app平台还要减去顶部手机状态栏高度
  404. top: calc($im-nav-bar-height + var(--status-bar-height));
  405. // #endif
  406. color: $im-text-color;
  407. background-color: $im-bg;
  408. font-size: $im-font-size;
  409. font-family: $font-family;
  410. }
  411. .page {
  412. position: relative;
  413. // #ifdef H5
  414. height: calc(100vh - $im-nav-bar-height); // app平台还要减去顶部手机状态栏高度
  415. top: $im-nav-bar-height;
  416. // #endif
  417. // #ifndef H5
  418. height: calc(100vh - var(--status-bar-height) - $im-nav-bar-height); // app平台还要减去顶部手机状态栏高度
  419. top: calc($im-nav-bar-height + var(--status-bar-height));
  420. // #endif
  421. color: $im-text-color;
  422. background-color: $im-bg;
  423. font-size: $im-font-size;
  424. font-family: $font-family;
  425. }
  426. </style>