| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- import { SocketSession } from '@/store/services/socket-session'
- import appSettings from '@/core/config/app-settings'
- import { bindSocketClient, isLiveRoomPacket } from '@/features/im/socket-bind'
- let session = null
- function ensureSession(store) {
- if (session) return session
- session = new SocketSession({
- onOpen: () => {
- if (store.state && store.state.im) store.state.im.online = true
- setTimeout(() => {
- if (store.state && store.state.user && store.state.user.isLogin) {
- store.dispatch('im/fetchInbox').catch(() => {})
- }
- }, 300)
- setTimeout(() => {
- uni.$emit('im:connected')
- uni.$emit('websocket:connected')
- }, 500)
- },
- onMessage: (msg) => store.dispatch('im/dispatchPacket', msg),
- onClose: () => { if (store.state && store.state.im) store.state.im.online = false },
- onError: () => { if (store.state && store.state.im) store.state.im.online = false }
- })
- return session
- }
- export default {
- namespaced: true,
- state: {
- online: false,
- badge: 0,
- inbox: [],
- halted: false
- },
- mutations: {
- setBadge(state, n) {
- state.badge = n
- },
- setInbox(state, list) {
- state.inbox = list || []
- }
- },
- actions: {
- resume({ state }) {
- if (state.halted) {
- state.halted = false
- ensureSession(this).allowReconnect = true
- }
- ensureSession(this).open()
- },
- pause({ state }, permanent = false) {
- const sock = ensureSession(this)
- if (permanent) {
- state.halted = true
- sock.allowReconnect = false
- }
- sock.pause(!permanent)
- },
- async bindClient(_, clientId) {
- await bindSocketClient(clientId)
- },
- dispatchPacket({ dispatch }, message) {
- let packet
- try {
- packet = JSON.parse(message.data)
- } catch (_) {
- if (appSettings.debug) console.log('[im] non-json packet ignored')
- return
- }
- uni.$emit('im:packet', packet)
- switch (packet?.type) {
- case 'ping':
- ensureSession(this).send({ type: 'pong' })
- return
- case 'init':
- dispatch('bindClient', packet.client_id).catch(() => {})
- return
- case 'chat':
- uni.$emit('im:chat', packet)
- uni.$emit('onMessage', packet)
- return
- case 'service':
- uni.$emit('onService', packet)
- return
- case 'live':
- uni.$emit('onLiveMessage', packet)
- return
- case 'tip_done':
- case 'end':
- case 'gift':
- uni.$emit('onLiveMessage', packet)
- return
- default:
- break
- }
- if (isLiveRoomPacket(packet)) {
- uni.$emit('onLiveMessage', packet)
- }
- },
- async fetchInbox() {
- // 占位:登录后拉取会话列表,页面接入后实现具体接口
- }
- }
- }
|