App.vue 12 KB

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