AiChatWsService.js
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* 接待场景 AI 对话 WebSocket(跟随接待会话建连/断连)
*/
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import { getNativeWsBase } from '@/utils/socket'
class AiChatWsService {
static _instance = null
constructor() {
this._connectPromise = null
/** 是否由接待会话托管(仅此种情况在 stopAudio 时断开) */
this._receptionBound = false
/** 只有明确配置了该 url 才会发起 WebSocket 连接 */
this._wsUrl = ''
}
static getInstance() {
if (!AiChatWsService._instance) {
AiChatWsService._instance = new AiChatWsService()
}
return AiChatWsService._instance
}
getClient() {
return NativeWsClient.getInstance()
}
/** 显式设置 AI 对话 WS 地址;未设置时不会自动连接 */
setWsUrl(url) {
this._wsUrl = url || ''
}
isConnected() {
return this.getClient().isConnected
}
/**
* 建立 AI 对话 WS
* @param {{ fromReception?: boolean }} [options] fromReception=true 时跟随接待生命周期断连
*/
connectForReception(options = {}) {
// #ifndef APP-PLUS
return Promise.resolve(false)
// #endif
// #ifdef APP-PLUS
const wsUrl = (getNativeWsBase() || '').trim()
if (!wsUrl) {
// 未配置 WS 地址时直接跳过(本项目可纯 HTTP 模式运行)
return Promise.resolve(false)
}
if (options.fromReception) {
this._receptionBound = true
}
if (this.isConnected()) {
return Promise.resolve(true)
}
if (this._connectPromise) {
return this._connectPromise
}
this._connectPromise = (async () => {
try {
uni.$logger?.local?.info(`[AiChatWs] 接待开始,连接 ${wsUrl}`)
await this.getClient().connectDirect(wsUrl)
return true
} catch (e) {
uni.$logger?.local?.warn(`[AiChatWs] 连接失败: ${e.message || e}`)
return false
} finally {
this._connectPromise = null
}
})()
return this._connectPromise
// #endif
}
/** 结束接待:断开并停止自动重连 */
async disconnectReception() {
// #ifndef APP-PLUS
return
// #endif
// #ifdef APP-PLUS
if (!this._receptionBound) {
return
}
this._receptionBound = false
this._connectPromise = null
const client = this.getClient()
try {
uni.$logger?.local?.info('[AiChatWs] 接待结束,断开 WS')
await client.close(1000, 'reception end', true)
} catch (e) {
uni.$logger?.local?.warn(`[AiChatWs] 断开异常: ${e.message || e}`)
}
// #endif
}
/** 求助前确保已连接(接待开始时通常已连好,此处作兜底) */
async ensureConnected() {
if (this.isConnected()) {
return true
}
return this.connectForReception()
}
}
export default AiChatWsService