App.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. import { getCurrentInstance } from 'vue'
  9. export default {
  10. data() {
  11. return {
  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. }).catch((e) => {
  25. console.log(e);
  26. this.exit();
  27. })
  28. },
  29. initWebSocket() {
  30. let loginInfo = uni.getStorageSync("loginInfo")
  31. wsApi.init();
  32. wsApi.connect(UNI_APP.WS_URL, loginInfo.accessToken);
  33. wsApi.onConnect(() => {
  34. // 重连成功提示
  35. if (this.reconnecting) {
  36. this.reconnecting = false;
  37. uni.showToast({
  38. title: "已重新连接",
  39. icon: 'none'
  40. })
  41. }
  42. // 加载离线消息
  43. this.pullPrivateOfflineMessage(this.chatStore.privateMsgMaxId);
  44. this.pullGroupOfflineMessage(this.chatStore.groupMsgMaxId);
  45. });
  46. wsApi.onMessage((cmd, msgInfo) => {
  47. if (cmd == 2) {
  48. // 异地登录,强制下线
  49. uni.showModal({
  50. content: '您已在其他地方登陆,将被强制下线',
  51. showCancel: false,
  52. })
  53. this.exit();
  54. } else if (cmd == 3) {
  55. // 私聊消息
  56. this.handlePrivateMessage(msgInfo);
  57. } else if (cmd == 4) {
  58. // 群聊消息
  59. this.handleGroupMessage(msgInfo);
  60. } else if (cmd == 5) {
  61. // 系统消息
  62. this.handleSystemMessage(msgInfo);
  63. }
  64. });
  65. wsApi.onClose((res) => {
  66. console.log("ws断开", res);
  67. // 重新连接
  68. this.reconnectWs();
  69. })
  70. },
  71. loadStore(){
  72. return this.userStore.loadUser().then(() => {
  73. const promises = [];
  74. promises.push(this.friendStore.loadFriend());
  75. promises.push(this.groupStore.loadGroup());
  76. promises.push(this.chatStore.loadChat());
  77. promises.push(this.configStore.loadConfig());
  78. return Promise.all(promises);
  79. })
  80. },
  81. unloadStore(){
  82. this.friendStore.clear();
  83. this.groupStore.clear();
  84. this.chatStore.clear();
  85. this.configStore.clear();
  86. this.userStore.clear();
  87. },
  88. pullPrivateOfflineMessage(minId) {
  89. this.chatStore.setLoadingPrivateMsg(true)
  90. http({
  91. url: "/message/private/pullOfflineMessage?minId=" + minId,
  92. method: 'GET'
  93. }).catch(() => {
  94. this.chatStore.setLoadingPrivateMsg(false)
  95. })
  96. },
  97. pullGroupOfflineMessage(minId) {
  98. this.chatStore.setLoadingGroupMsg(true)
  99. http({
  100. url: "/message/group/pullOfflineMessage?minId=" + minId,
  101. method: 'GET'
  102. }).catch(() => {
  103. this.chatStore.setLoadingGroupMsg(false)
  104. })
  105. },
  106. handlePrivateMessage(msg) {
  107. // 消息加载标志
  108. if (msg.type == enums.MESSAGE_TYPE.LOADING) {
  109. this.chatStore.setLoadingPrivateMsg(JSON.parse(msg.content))
  110. return;
  111. }
  112. // 消息已读处理,清空已读数量
  113. if (msg.type == enums.MESSAGE_TYPE.READED) {
  114. this.chatStore.resetUnreadCount( {
  115. type: 'PRIVATE',
  116. targetId: msg.recvId
  117. })
  118. return;
  119. }
  120. // 消息回执处理,改消息状态为已读
  121. if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
  122. this.chatStore.readedMessage( {
  123. friendId: msg.sendId
  124. })
  125. return;
  126. }
  127. // 标记这条消息是不是自己发的
  128. msg.selfSend = msg.sendId == this.userStore.userInfo.id;
  129. // 好友id
  130. let friendId = msg.selfSend ? msg.recvId : msg.sendId;
  131. this.loadFriendInfo(friendId).then((friend) => {
  132. this.insertPrivateMessage(friend, msg);
  133. })
  134. },
  135. insertPrivateMessage(friend, msg) {
  136. // 单人视频信令
  137. if (msgType.isRtcPrivate(msg.type)) {
  138. // #ifdef MP-WEIXIN
  139. // 小程序不支持音视频
  140. return;
  141. // #endif
  142. // 被呼叫,弹出视频页面
  143. let delayTime = 100;
  144. if (msg.type == enums.MESSAGE_TYPE.RTC_CALL_VOICE ||
  145. msg.type == enums.MESSAGE_TYPE.RTC_CALL_VIDEO) {
  146. let mode = msg.type == enums.MESSAGE_TYPE.RTC_CALL_VIDEO ? "video" : "voice";
  147. let pages = getCurrentPages();
  148. let curPage = pages[pages.length - 1].route;
  149. if (curPage != "pages/chat/chat-private-video") {
  150. const friendInfo = encodeURIComponent(JSON.stringify(friend));
  151. uni.navigateTo({
  152. url: `/pages/chat/chat-private-video?mode=${mode}&friend=${friendInfo}&isHost=false`
  153. })
  154. delayTime = 500;
  155. }
  156. }
  157. setTimeout(() => {
  158. uni.$emit('WS_RTC_PRIVATE', msg);
  159. }, delayTime)
  160. return;
  161. }
  162. let chatInfo = {
  163. type: 'PRIVATE',
  164. targetId: friend.id,
  165. showName: friend.nickName,
  166. headImage: friend.headImage
  167. };
  168. // 打开会话
  169. this.chatStore.openChat(chatInfo);
  170. // 插入消息
  171. this.chatStore.insertMessage(msg);
  172. // 播放提示音
  173. this.playAudioTip();
  174. },
  175. handleGroupMessage(msg) {
  176. // 消息加载标志
  177. if (msg.type == enums.MESSAGE_TYPE.LOADING) {
  178. this.chatStore.setLoadingGroupMsg(JSON.parse(msg.content))
  179. return;
  180. }
  181. // 消息已读处理
  182. if (msg.type == enums.MESSAGE_TYPE.READED) {
  183. // 我已读对方的消息,清空已读数量
  184. let chatInfo = {
  185. type: 'GROUP',
  186. targetId: msg.groupId
  187. }
  188. this.chatStore.resetUnreadCount(chatInfo)
  189. return;
  190. }
  191. // 消息回执处理
  192. if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
  193. // 更新消息已读人数
  194. let msgInfo = {
  195. id: msg.id,
  196. groupId: msg.groupId,
  197. readedCount: msg.readedCount,
  198. receiptOk: msg.receiptOk
  199. };
  200. this.chatStore.updateMessage(msgInfo)
  201. return;
  202. }
  203. // 标记这条消息是不是自己发的
  204. msg.selfSend = msg.sendId == this.userStore.userInfo.id;
  205. this.loadGroupInfo(msg.groupId).then((group) => {
  206. // 插入群聊消息
  207. this.insertGroupMessage(group, msg);
  208. })
  209. },
  210. handleSystemMessage(msg) {
  211. if (msg.type == enums.MESSAGE_TYPE.USER_BANNED) {
  212. // 用户被封禁
  213. wsApi.close(3099);
  214. uni.showModal({
  215. content: '您的账号已被管理员封禁,原因:' + msg.content,
  216. showCancel: false,
  217. })
  218. this.exit();
  219. }
  220. },
  221. insertGroupMessage(group, msg) {
  222. // 群视频信令
  223. if (msgType.isRtcGroup(msg.type)) {
  224. // #ifdef MP-WEIXIN
  225. // 小程序不支持音视频
  226. return;
  227. // #endif
  228. // 被呼叫,弹出视频页面
  229. let delayTime = 100;
  230. if (msg.type == enums.MESSAGE_TYPE.RTC_GROUP_SETUP) {
  231. let pages = getCurrentPages();
  232. let curPage = pages[pages.length - 1].route;
  233. if (curPage != "pages/chat/chat-group-video") {
  234. const userInfos = encodeURIComponent(msg.content);
  235. const inviterId = msg.sendId;
  236. const groupId = msg.groupId
  237. uni.navigateTo({
  238. url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=false
  239. &inviterId=${inviterId}&userInfos=${userInfos}`
  240. })
  241. delayTime = 500;
  242. }
  243. }
  244. // 消息转发到chat-group-video页面进行处理
  245. setTimeout(() => {
  246. uni.$emit('WS_RTC_GROUP', msg);
  247. }, delayTime)
  248. return;
  249. }
  250. let chatInfo = {
  251. type: 'GROUP',
  252. targetId: group.id,
  253. showName: group.showGroupName,
  254. headImage: group.headImageThumb
  255. };
  256. // 打开会话
  257. this.chatStore.openChat(chatInfo);
  258. // 插入消息
  259. this.chatStore.insertMessage( msg);
  260. // 播放提示音
  261. this.playAudioTip();
  262. },
  263. loadFriendInfo(id) {
  264. return new Promise((resolve, reject) => {
  265. let friend = this.friendStore.findFriend(id);
  266. if (friend) {
  267. resolve(friend);
  268. } else {
  269. http({
  270. url: `/friend/find/${id}`,
  271. method: 'GET'
  272. }).then((friend) => {
  273. this.friendStore.addFriend(friend);
  274. resolve(friend)
  275. })
  276. }
  277. });
  278. },
  279. loadGroupInfo(id) {
  280. return new Promise((resolve, reject) => {
  281. let group = this.groupStore.groups.find((g) => g.id == id);
  282. if (group) {
  283. resolve(group);
  284. } else {
  285. http({
  286. url: `/group/find/${id}`,
  287. method: 'GET'
  288. }).then((group) => {
  289. this.groupStore.addGroup(group);
  290. resolve(group)
  291. })
  292. }
  293. });
  294. },
  295. exit() {
  296. console.log("exit");
  297. this.isExit = true;
  298. wsApi.close(3099);
  299. uni.removeStorageSync("loginInfo");
  300. uni.reLaunch({
  301. url: "/pages/login/login"
  302. })
  303. this.unloadStore();
  304. },
  305. playAudioTip() {
  306. // 音频播放无法成功
  307. // this.audioTip = uni.createInnerAudioContext();
  308. // this.audioTip.src = "/static/audio/tip.wav";
  309. // this.audioTip.play();
  310. },
  311. isExpired(loginInfo) {
  312. if (!loginInfo || !loginInfo.expireTime) {
  313. return true;
  314. }
  315. return loginInfo.expireTime < new Date().getTime();
  316. },
  317. reconnectWs() {
  318. // 已退出则不再重连
  319. if (this.isExit) {
  320. return;
  321. }
  322. // 记录标志
  323. this.reconnecting = true;
  324. // 重新加载一次个人信息,目的是为了保证网络已经正常且token有效
  325. this.reloadUserInfo().then((userInfo) => {
  326. uni.showToast({
  327. title: '连接已断开,尝试重新连接...',
  328. icon: 'none',
  329. })
  330. this.userStore.setUserInfo(userInfo);
  331. // 重新连接
  332. let loginInfo = uni.getStorageSync("loginInfo")
  333. wsApi.reconnect(UNI_APP.WS_URL, loginInfo.accessToken);
  334. }).catch(() => {
  335. // 5s后重试
  336. setTimeout(() => {
  337. this.reconnectWs();
  338. }, 5000)
  339. })
  340. },
  341. reloadUserInfo() {
  342. return http({
  343. url: '/user/self',
  344. method: 'GET'
  345. })
  346. }
  347. },
  348. onLaunch() {
  349. this.$mountStore();
  350. // 登录状态校验
  351. let loginInfo = uni.getStorageSync("loginInfo")
  352. if (!this.isExpired(loginInfo)) {
  353. // 初始化
  354. this.init();
  355. // 跳转到聊天页面
  356. uni.switchTab({
  357. url: "/pages/chat/chat"
  358. })
  359. } else {
  360. // 跳转到登录页
  361. // #ifdef H5
  362. uni.navigateTo({
  363. url: "/pages/login/login"
  364. })
  365. // #endif
  366. }
  367. }
  368. }
  369. </script>
  370. <style lang="scss">
  371. @import "@/uni_modules/uview-plus/index.scss";
  372. @import url('./static/icon/iconfont.css');
  373. // #ifdef H5
  374. uni-page-head {
  375. display: none; // h5浏览器本身就有标题
  376. }
  377. // #endif
  378. .tab-page {
  379. // #ifdef H5
  380. height: calc(100vh - 50px); // h5平台100vh是包含了底部高度,需要减去
  381. // #endif
  382. // #ifndef H5
  383. height: calc(100vh);
  384. // #endif
  385. background-color: #f8f8f8;
  386. }
  387. .page {
  388. height: calc(100vh);
  389. background-color: #f8f8f8;
  390. }
  391. </style>