socket-bind.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { post } from '@/core/http/http-client'
  2. import { buildRestPath } from '@/core/config/api-paths'
  3. import { STORAGE } from '@/core/constants/storage-keys'
  4. import appSettings from '@/core/config/app-settings'
  5. /**
  6. * GatewayWorker 下发 init 后,把 client_id 绑定到当前登录用户。
  7. * 老工程 store/modules/chat.js case 'init' → POST chat/shake。
  8. */
  9. export async function bindSocketClient(clientId) {
  10. if (!clientId) return null
  11. try {
  12. const { data, raw } = await post(buildRestPath('chat/shake'), { client_id: clientId })
  13. const saved = data != null && data !== '' ? data : (raw?.res?.data ?? raw?.res ?? raw?.data)
  14. if (saved != null && saved !== '') {
  15. uni.setStorageSync(STORAGE.chatClient, saved)
  16. }
  17. if (appSettings.debug) console.log('[im] shake ok', { clientId, saved })
  18. return saved
  19. } catch (err) {
  20. if (appSettings.debug) console.warn('[im] shake failed', err)
  21. return null
  22. }
  23. }
  24. export function readStoredClientId() {
  25. return uni.getStorageSync(STORAGE.chatClient) || null
  26. }
  27. const LIVE_INNER_TYPES = [
  28. 'msg', 'coming', 'seek', 'follow', 'like', 'review',
  29. 'end', 'tip_done', 'update', 'gift', 'publish', 'publish_done', 'ban'
  30. ]
  31. /** 识别直播群组推送(兼容 type:live / 顶层 tip_done / 仅带 message.type 的包) */
  32. export function isLiveRoomPacket(packet) {
  33. if (!packet || typeof packet !== 'object') return false
  34. if (packet.type === 'live') return true
  35. // 顶层即直播事件(老工程 mock / 部分网关直推 tip_done)
  36. if (LIVE_INNER_TYPES.includes(packet.type)) return true
  37. const inner = packet.message
  38. if (!inner) return false
  39. if (typeof inner === 'object' && LIVE_INNER_TYPES.includes(inner.type)) return true
  40. // message 为 JSON 字符串时也要识别
  41. if (typeof inner === 'string') {
  42. try {
  43. const parsed = JSON.parse(inner)
  44. return !!(parsed && LIVE_INNER_TYPES.includes(parsed.type))
  45. } catch (_) {
  46. return false
  47. }
  48. }
  49. return false
  50. }