App.vue 10 KB

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