App.vue 13 KB

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