App.vue 11 KB

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