feat:修改客服报错问题
This commit is contained in:
@@ -1,27 +1,40 @@
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import type { CsChatWsPayload, CsMessageVo, CsSessionVo } from './support.types'
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 25000
|
||||
const RECONNECT_DELAY_MS = 25000
|
||||
const RECONNECT_DELAY_MS = 2000
|
||||
|
||||
let socketTask: UniApp.SocketTask | null = null
|
||||
let heartbeatTimer: ReturnType<typeof setInterval> | 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
|
||||
|
||||
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:'
|
||||
return `${proto}//${window.location.host}/app/cs/chat`
|
||||
}
|
||||
|
||||
if (configured) {
|
||||
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
|
||||
}
|
||||
|
||||
const envBase = import.meta.env.VITE_API_BASE_URL?.trim() || ''
|
||||
const fallback = import.meta.env.VITE_API_PROXY_TARGET?.trim() || 'http://192.168.0.212:8082'
|
||||
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`
|
||||
@@ -32,16 +45,21 @@ function resolveCsChatWsUrl(sessionId: string, token: string): string {
|
||||
return `${base}?token=${encodeURIComponent(token)}&sessionId=${encodeURIComponent(sessionId)}`
|
||||
}
|
||||
|
||||
function stopHeartbeat() {
|
||||
if (heartbeatTimer) clearInterval(heartbeatTimer)
|
||||
heartbeatTimer = null
|
||||
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 startHeartbeat() {
|
||||
stopHeartbeat()
|
||||
heartbeatTimer = setInterval(() => {
|
||||
socketTask?.send({ data: 'ping' })
|
||||
}, HEARTBEAT_INTERVAL_MS)
|
||||
function sendCsChatPong(task: UniApp.SocketTask) {
|
||||
if (!socketOpened) return
|
||||
task.send({ data: JSON.stringify({ type: 'cs:pong' }) })
|
||||
}
|
||||
|
||||
function clearReconnectTimer() {
|
||||
@@ -57,8 +75,7 @@ function scheduleReconnect() {
|
||||
}, RECONNECT_DELAY_MS)
|
||||
}
|
||||
|
||||
function cleanupSocketTask() {
|
||||
stopHeartbeat()
|
||||
function resetSocketState() {
|
||||
socketTask = null
|
||||
socketOpened = false
|
||||
connecting = false
|
||||
@@ -68,13 +85,19 @@ export 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 type = String(parsed.type ?? '').toLowerCase()
|
||||
const norm = normalizeWsType(String(parsed.type ?? ''))
|
||||
|
||||
if (type === 'message' && parsed.data && typeof parsed.data === 'object') {
|
||||
return { type: 'message', message: parsed.data as CsMessageVo }
|
||||
if (norm === 'message') {
|
||||
const data = parsed.data ?? parsed.message
|
||||
if (data && typeof data === 'object') {
|
||||
return { type: 'message', message: data as CsMessageVo }
|
||||
}
|
||||
}
|
||||
if (type === 'session' && parsed.data && typeof parsed.data === 'object') {
|
||||
return { type: 'session', session: parsed.data as CsSessionVo }
|
||||
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 }
|
||||
@@ -88,13 +111,37 @@ export function parseCsChatPayload(raw: string): CsChatWsPayload | null {
|
||||
if (parsed.status !== undefined || parsed.sessionStatus !== undefined) {
|
||||
return { type: 'session', session: parsed as CsSessionVo }
|
||||
}
|
||||
return { type: type || 'unknown', raw: parsed }
|
||||
return { type: norm || 'unknown', raw: parsed }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function handleSocketMessage(raw: string) {
|
||||
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))
|
||||
@@ -109,61 +156,104 @@ 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
|
||||
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 = getStoredToken()
|
||||
if (!token || !sessionId) return
|
||||
if (connecting) return
|
||||
if (socketOpened && socketTask && activeSessionId === sessionId) return
|
||||
|
||||
if (socketTask) {
|
||||
manualClosed = true
|
||||
socketTask.close({})
|
||||
cleanupSocketTask()
|
||||
}
|
||||
|
||||
activeSessionId = sessionId
|
||||
manualClosed = false
|
||||
connecting = true
|
||||
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: resolveCsChatWsUrl(sessionId, token),
|
||||
complete: () => {
|
||||
connecting = false
|
||||
url,
|
||||
fail: (err) => {
|
||||
if (seq !== connectionSeq) return
|
||||
if (import.meta.env.DEV) console.log('[CS Chat WS] connect fail', err)
|
||||
resetSocketState()
|
||||
scheduleReconnect()
|
||||
},
|
||||
})
|
||||
|
||||
socketTask = task
|
||||
|
||||
task.onOpen(() => {
|
||||
socketOpened = true
|
||||
startHeartbeat()
|
||||
})
|
||||
|
||||
task.onMessage((res) => {
|
||||
const raw = typeof res.data === 'string' ? res.data : ''
|
||||
handleSocketMessage(raw)
|
||||
})
|
||||
|
||||
task.onClose(() => {
|
||||
cleanupSocketTask()
|
||||
if (!task || typeof task.onOpen !== 'function') {
|
||||
connecting = false
|
||||
if (import.meta.env.DEV) console.warn('[CS Chat WS] invalid SocketTask')
|
||||
scheduleReconnect()
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
task.onError(() => {
|
||||
cleanupSocketTask()
|
||||
scheduleReconnect()
|
||||
})
|
||||
bindSocketTask(task, seq)
|
||||
}
|
||||
|
||||
export function disconnectCsChatSocket() {
|
||||
manualClosed = true
|
||||
connectionSeq += 1
|
||||
activeSessionId = ''
|
||||
clearReconnectTimer()
|
||||
stopHeartbeat()
|
||||
if (socketTask) {
|
||||
socketTask.close({})
|
||||
}
|
||||
const task = socketTask
|
||||
socketTask = null
|
||||
socketOpened = false
|
||||
connecting = false
|
||||
if (task) {
|
||||
try {
|
||||
task.close({})
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user