App.vue 12 KB

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