278 lines
8.1 KiB
TypeScript
278 lines
8.1 KiB
TypeScript
import { resolveCsAppToken } from '@/api/request'
|
||
import type { CsChatWsPayload, CsMessageVo, CsSessionVo } from './support.types'
|
||
|
||
/** 断线后首次重连等待(非轮询;连接成功后会保持长连接) */
|
||
const RECONNECT_BASE_MS = 10000
|
||
const RECONNECT_MAX_MS = 30000
|
||
|
||
let socketTask: UniApp.SocketTask | null = null
|
||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||
let connecting = false
|
||
let manualClosed = false
|
||
let activeSessionId = ''
|
||
let socketOpened = false
|
||
/** 每次 connect / disconnect 递增,忽略已废弃连接的 onClose */
|
||
let connectionSeq = 0
|
||
let reconnectAttempt = 0
|
||
|
||
const listeners = new Set<(payload: CsChatWsPayload) => void>()
|
||
|
||
function isH5Dev(): boolean {
|
||
return import.meta.env.DEV && typeof window !== 'undefined' && !!window.location?.host
|
||
}
|
||
|
||
function resolveCsChatWsBase(): string {
|
||
const configured = import.meta.env.VITE_CS_CHAT_WS_URL?.trim()
|
||
const forceDirect =
|
||
String(import.meta.env.VITE_CS_CHAT_WS_DIRECT ?? '').toLowerCase() === 'true'
|
||
|
||
if (isH5Dev() && !forceDirect) {
|
||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||
const useCsHost = !!import.meta.env.VITE_CS_API_BASE_URL?.trim()
|
||
const path = useCsHost ? '/cs-app/cs/chat' : '/app/cs/chat'
|
||
return `${proto}//${window.location.host}${path}`
|
||
}
|
||
|
||
if (configured) {
|
||
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
|
||
}
|
||
|
||
const csBase = import.meta.env.VITE_CS_API_BASE_URL?.trim()
|
||
if (csBase) {
|
||
const wsBase = csBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws').replace(/\/$/, '')
|
||
return `${wsBase}/app/cs/chat`
|
||
}
|
||
|
||
const envBase = import.meta.env.VITE_API_BASE_URL?.trim() || ''
|
||
const fallback =
|
||
import.meta.env.VITE_API_PROXY_TARGET?.trim() || 'http://192.168.0.222:8082'
|
||
const httpBase = envBase || fallback
|
||
const wsBase = httpBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws')
|
||
return `${wsBase}/app/cs/chat`
|
||
}
|
||
|
||
function resolveCsChatWsUrl(sessionId: string, token: string): string {
|
||
const base = resolveCsChatWsBase()
|
||
return `${base}?token=${encodeURIComponent(token)}&sessionId=${encodeURIComponent(sessionId)}`
|
||
}
|
||
|
||
function normalizeWsType(type: string): string {
|
||
const t = type.toLowerCase().trim()
|
||
if (!t) return ''
|
||
if (t === 'cserror' || t === 'cs:error' || t === 'error') return 'error'
|
||
if (t === 'csping' || t === 'cs:ping') return 'ping'
|
||
if (t === 'cspong' || t === 'cs:pong') return 'pong'
|
||
if (t === 'csmessage' || t === 'cs:message') return 'message'
|
||
if (t === 'cssession' || t === 'cs:session') return 'session'
|
||
if (t === 'message' || t === 'session') return t
|
||
return t.replace(/^cs:/, '')
|
||
}
|
||
|
||
function sendCsChatPong(task: UniApp.SocketTask) {
|
||
if (!socketOpened) return
|
||
task.send({ data: JSON.stringify({ type: 'cs:pong' }) })
|
||
}
|
||
|
||
function clearReconnectTimer() {
|
||
if (reconnectTimer) clearTimeout(reconnectTimer)
|
||
reconnectTimer = null
|
||
}
|
||
|
||
function scheduleReconnect() {
|
||
if (manualClosed || !resolveCsAppToken() || !activeSessionId) return
|
||
clearReconnectTimer()
|
||
const delay = Math.min(
|
||
RECONNECT_BASE_MS * Math.pow(1.5, reconnectAttempt),
|
||
RECONNECT_MAX_MS,
|
||
)
|
||
reconnectAttempt += 1
|
||
reconnectTimer = setTimeout(() => {
|
||
connectCsChatSocket(activeSessionId)
|
||
}, delay)
|
||
}
|
||
|
||
function resetSocketState() {
|
||
socketTask = null
|
||
socketOpened = false
|
||
connecting = false
|
||
}
|
||
|
||
function parseCsChatPayload(raw: string): CsChatWsPayload | null {
|
||
if (!raw || raw === 'ping' || raw === 'pong') return null
|
||
try {
|
||
const parsed = JSON.parse(raw) as Record<string, unknown>
|
||
const norm = normalizeWsType(String(parsed.type ?? ''))
|
||
|
||
if (norm === 'message') {
|
||
const data = parsed.data ?? parsed.message
|
||
if (data && typeof data === 'object') {
|
||
return { type: 'message', message: data as CsMessageVo }
|
||
}
|
||
}
|
||
if (norm === 'session') {
|
||
const data = parsed.data ?? parsed.session
|
||
if (data && typeof data === 'object') {
|
||
return { type: 'session', session: data as CsSessionVo }
|
||
}
|
||
}
|
||
if (parsed.message && typeof parsed.message === 'object') {
|
||
return { type: 'message', message: parsed.message as CsMessageVo }
|
||
}
|
||
if (parsed.session && typeof parsed.session === 'object') {
|
||
return { type: 'session', session: parsed.session as CsSessionVo }
|
||
}
|
||
if (parsed.content !== undefined || parsed.seq !== undefined || parsed.messageId !== undefined) {
|
||
return { type: 'message', message: parsed as CsMessageVo }
|
||
}
|
||
if (parsed.status !== undefined || parsed.sessionStatus !== undefined) {
|
||
return { type: 'session', session: parsed as CsSessionVo }
|
||
}
|
||
return { type: norm || 'unknown', raw: parsed }
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
function handleSocketMessage(task: UniApp.SocketTask, raw: string) {
|
||
if (!raw) return
|
||
if (raw === 'ping') {
|
||
sendCsChatPong(task)
|
||
return
|
||
}
|
||
if (raw === 'pong') return
|
||
|
||
try {
|
||
const parsed = JSON.parse(raw) as Record<string, unknown>
|
||
const norm = normalizeWsType(String(parsed.type ?? ''))
|
||
if (norm === 'ping') {
|
||
sendCsChatPong(task)
|
||
return
|
||
}
|
||
if (norm === 'pong' || norm === 'error') {
|
||
if (norm === 'error' && import.meta.env.DEV) {
|
||
console.warn('[CS Chat WS] server error:', parsed.msg ?? parsed.message ?? parsed)
|
||
}
|
||
return
|
||
}
|
||
} catch {
|
||
// fall through
|
||
}
|
||
|
||
const payload = parseCsChatPayload(raw)
|
||
if (!payload) return
|
||
listeners.forEach((listener) => listener(payload))
|
||
}
|
||
|
||
export function onCsChatPush(listener: (payload: CsChatWsPayload) => void) {
|
||
listeners.add(listener)
|
||
return () => listeners.delete(listener)
|
||
}
|
||
|
||
export function isCsChatSocketConnected(): boolean {
|
||
return socketOpened
|
||
}
|
||
|
||
function bindSocketTask(task: UniApp.SocketTask, seq: number) {
|
||
socketTask = task
|
||
|
||
task.onOpen(() => {
|
||
if (seq !== connectionSeq) return
|
||
socketOpened = true
|
||
connecting = false
|
||
reconnectAttempt = 0
|
||
if (import.meta.env.DEV) console.log('[CS Chat WS] connected')
|
||
})
|
||
|
||
task.onMessage((res) => {
|
||
if (seq !== connectionSeq) return
|
||
const raw = typeof res.data === 'string' ? res.data : ''
|
||
handleSocketMessage(task, raw)
|
||
})
|
||
|
||
task.onClose((res) => {
|
||
if (seq !== connectionSeq) return
|
||
if (import.meta.env.DEV) {
|
||
const code = (res as { code?: number })?.code
|
||
const reason = (res as { reason?: string })?.reason
|
||
console.log('[CS Chat WS] closed', code ?? '', reason ?? '')
|
||
}
|
||
resetSocketState()
|
||
scheduleReconnect()
|
||
})
|
||
|
||
task.onError(() => {
|
||
if (seq !== connectionSeq) return
|
||
if (import.meta.env.DEV) console.log('[CS Chat WS] error')
|
||
resetSocketState()
|
||
scheduleReconnect()
|
||
})
|
||
}
|
||
|
||
export function connectCsChatSocket(sessionId: string) {
|
||
const token = resolveCsAppToken()
|
||
if (!token || !sessionId) return
|
||
if (connecting) return
|
||
if (socketOpened && socketTask && activeSessionId === sessionId) return
|
||
|
||
manualClosed = false
|
||
activeSessionId = sessionId
|
||
const seq = ++connectionSeq
|
||
clearReconnectTimer()
|
||
|
||
const previousTask = socketTask
|
||
socketTask = null
|
||
socketOpened = false
|
||
if (previousTask) {
|
||
try {
|
||
previousTask.close({})
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
connecting = true
|
||
const url = resolveCsChatWsUrl(sessionId, token)
|
||
if (import.meta.env.DEV) {
|
||
console.log('[CS Chat WS] connect', url.replace(/token=[^&]+/, 'token=***'))
|
||
}
|
||
|
||
// H5:必须带 fail/success 之一,否则返回 Promise 无 onOpen(见 message-socket.ts)
|
||
const task = uni.connectSocket({
|
||
url,
|
||
fail: (err) => {
|
||
if (seq !== connectionSeq) return
|
||
if (import.meta.env.DEV) console.log('[CS Chat WS] connect fail', err)
|
||
resetSocketState()
|
||
scheduleReconnect()
|
||
},
|
||
})
|
||
|
||
if (!task || typeof task.onOpen !== 'function') {
|
||
connecting = false
|
||
if (import.meta.env.DEV) console.warn('[CS Chat WS] invalid SocketTask')
|
||
scheduleReconnect()
|
||
return
|
||
}
|
||
|
||
bindSocketTask(task, seq)
|
||
}
|
||
|
||
export function disconnectCsChatSocket() {
|
||
manualClosed = true
|
||
connectionSeq += 1
|
||
activeSessionId = ''
|
||
reconnectAttempt = 0
|
||
clearReconnectTimer()
|
||
const task = socketTask
|
||
socketTask = null
|
||
socketOpened = false
|
||
connecting = false
|
||
if (task) {
|
||
try {
|
||
task.close({})
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
}
|