@im-more/dsh-onebot 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/cordis.patch.yml +11 -0
- package/lib/index.js +2003 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +55 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +140 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +40 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +33 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/cqcode.d.ts +29 -0
- package/lib/types/cqcode.d.ts.map +1 -0
- package/lib/types/cqcode.js +73 -0
- package/lib/types/cqcode.js.map +1 -0
- package/lib/types/decode.d.ts +106 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +433 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +32 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +117 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +18 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +27 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +7 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +6 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/modes/segment.d.ts +16 -0
- package/lib/types/modes/segment.d.ts.map +1 -0
- package/lib/types/modes/segment.js +80 -0
- package/lib/types/modes/segment.js.map +1 -0
- package/lib/types/modes/shared.d.ts +101 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +208 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/request.d.ts +64 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +108 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +93 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +161 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/transport/http.d.ts +29 -0
- package/lib/types/transport/http.d.ts.map +1 -0
- package/lib/types/transport/http.js +158 -0
- package/lib/types/transport/http.js.map +1 -0
- package/lib/types/transport/shared.d.ts +48 -0
- package/lib/types/transport/shared.d.ts.map +1 -0
- package/lib/types/transport/shared.js +75 -0
- package/lib/types/transport/shared.js.map +1 -0
- package/lib/types/transport/ws-reverse.d.ts +42 -0
- package/lib/types/transport/ws-reverse.d.ts.map +1 -0
- package/lib/types/transport/ws-reverse.js +178 -0
- package/lib/types/transport/ws-reverse.js.map +1 -0
- package/lib/types/transport/ws.d.ts +40 -0
- package/lib/types/transport/ws.d.ts.map +1 -0
- package/lib/types/transport/ws.js +233 -0
- package/lib/types/transport/ws.js.map +1 -0
- package/lib/types/types.d.ts +495 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +191 -0
- package/lib/types/types.js.map +1 -0
- package/package.json +68 -3
- package/src/bot.ts +230 -0
- package/src/config.ts +66 -0
- package/src/cqcode.ts +85 -0
- package/src/decode.ts +524 -0
- package/src/errors.ts +134 -0
- package/src/identity.ts +34 -0
- package/src/index.ts +18 -0
- package/src/modes/segment.ts +109 -0
- package/src/modes/shared.ts +277 -0
- package/src/request.ts +128 -0
- package/src/send.ts +233 -0
- package/src/transport/http.ts +221 -0
- package/src/transport/shared.ts +98 -0
- package/src/transport/ws-reverse.ts +236 -0
- package/src/transport/ws.ts +286 -0
- package/src/types.ts +743 -0
- package/README.md +0 -3
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reverse WebSocket transport (`protocol: 'ws-reverse'`).
|
|
3
|
+
*
|
|
4
|
+
* The implementation dials the harness; the adapter owns the endpoint through the profile's `webServer` and keeps
|
|
5
|
+
* listening between connections. A connection that fails the handshake checks is refused and dropped, because the
|
|
6
|
+
* implementation's configuration can change without a restart of this process.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { Status } from '@deepseek-ai/cordis-plugin-im-core'
|
|
10
|
+
import type { IncomingMessage } from 'node:http'
|
|
11
|
+
import type { Duplex } from 'node:stream'
|
|
12
|
+
import { WebSocketServer, type WebSocket as Socket } from 'ws'
|
|
13
|
+
import type { OneBotBot } from '../bot.ts'
|
|
14
|
+
import { routePath } from '../config.ts'
|
|
15
|
+
import { decodePayload, isPayload } from '../decode.ts'
|
|
16
|
+
import {
|
|
17
|
+
ActionRequests,
|
|
18
|
+
installRequest,
|
|
19
|
+
isResponse,
|
|
20
|
+
rejectRequests,
|
|
21
|
+
} from '../request.ts'
|
|
22
|
+
import type { Payload } from '../types.ts'
|
|
23
|
+
import { headerOf, matchesSecret, rejectUpgrade } from './shared.ts'
|
|
24
|
+
|
|
25
|
+
/** The part of `ctx.webServer` this transport uses. */
|
|
26
|
+
interface WebServerLike {
|
|
27
|
+
registerUpgrade(route: {
|
|
28
|
+
path: string
|
|
29
|
+
auth: 'anonymous'
|
|
30
|
+
handler: (
|
|
31
|
+
request: IncomingMessage,
|
|
32
|
+
socket: Duplex,
|
|
33
|
+
head: Buffer,
|
|
34
|
+
) => void | Promise<void>
|
|
35
|
+
}): () => void
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The reverse WebSocket server of one bot. */
|
|
39
|
+
export class OneBotWsServer {
|
|
40
|
+
private server: WebSocketServer | undefined
|
|
41
|
+
private dispose: (() => void) | undefined
|
|
42
|
+
private connection: Socket | undefined
|
|
43
|
+
private requests: ActionRequests | undefined
|
|
44
|
+
private warnedNoToken = false
|
|
45
|
+
|
|
46
|
+
constructor(private readonly bot: OneBotBot) {}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Claim the upgrade route. The endpoint then stays available across implementation restarts.
|
|
50
|
+
*/
|
|
51
|
+
async start(): Promise<void> {
|
|
52
|
+
const webServer = this.bot.ctx.get('webServer') as WebServerLike | undefined
|
|
53
|
+
if (webServer === undefined) {
|
|
54
|
+
throw this.fail(
|
|
55
|
+
'onebot: protocol "ws-reverse" needs a profile-provided webServer; use protocol "ws" instead',
|
|
56
|
+
)
|
|
57
|
+
}
|
|
58
|
+
const path = routePath(this.bot.config.path)
|
|
59
|
+
const server = new WebSocketServer({ noServer: true })
|
|
60
|
+
try {
|
|
61
|
+
this.dispose = webServer.registerUpgrade({
|
|
62
|
+
path,
|
|
63
|
+
auth: 'anonymous',
|
|
64
|
+
handler: (request, socket, head) => {
|
|
65
|
+
this.upgrade(server, request, socket, head)
|
|
66
|
+
},
|
|
67
|
+
})
|
|
68
|
+
} catch (error) {
|
|
69
|
+
server.close()
|
|
70
|
+
throw this.fail(
|
|
71
|
+
`onebot: cannot claim the ws-reverse route ${path}: ${
|
|
72
|
+
error instanceof Error ? error.message : String(error)
|
|
73
|
+
}`,
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
this.server = server
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Release the route and close the connected implementation. */
|
|
80
|
+
async stop(): Promise<void> {
|
|
81
|
+
this.dispose?.()
|
|
82
|
+
this.dispose = undefined
|
|
83
|
+
this.closeConnection()
|
|
84
|
+
const server = this.server
|
|
85
|
+
this.server = undefined
|
|
86
|
+
if (server !== undefined) {
|
|
87
|
+
await new Promise<void>((resolve) => server.close(() => resolve()))
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Log a start failure before throwing it, because `Bot.start` only stores a connect failure on `bot.error`. */
|
|
92
|
+
private fail(message: string): Error {
|
|
93
|
+
this.bot.ctx.logger.error(message)
|
|
94
|
+
return new Error(message)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Validate one upgrade request and hand the accepted socket to `ws`. */
|
|
98
|
+
private upgrade(
|
|
99
|
+
server: WebSocketServer,
|
|
100
|
+
request: IncomingMessage,
|
|
101
|
+
socket: Duplex,
|
|
102
|
+
head: Buffer,
|
|
103
|
+
): void {
|
|
104
|
+
const { token } = this.bot.config
|
|
105
|
+
if (token === '') {
|
|
106
|
+
if (!this.warnedNoToken) {
|
|
107
|
+
this.warnedNoToken = true
|
|
108
|
+
this.bot.ctx.logger.warn(
|
|
109
|
+
'onebot: token is empty, so reverse WebSocket connections are accepted without Authorization',
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
} else {
|
|
113
|
+
const presented = headerOf(request, 'authorization')?.replace(
|
|
114
|
+
/^Bearer\s+/i,
|
|
115
|
+
'',
|
|
116
|
+
)
|
|
117
|
+
if (!matchesSecret(token, presented)) {
|
|
118
|
+
rejectUpgrade(socket, 401, 'Unauthorized')
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (headerOf(request, 'x-client-role') !== 'Universal') {
|
|
123
|
+
rejectUpgrade(socket, 403, 'Forbidden')
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
if (headerOf(request, 'x-self-id') !== this.bot.config.selfId) {
|
|
127
|
+
rejectUpgrade(socket, 403, 'Forbidden')
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
server.handleUpgrade(request, socket, head, (ws) => {
|
|
131
|
+
this.accept(ws)
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Take over one accepted socket. A newer connection replaces the previous one.
|
|
137
|
+
* @param socket - the upgraded WebSocket connection of the implementation.
|
|
138
|
+
*/
|
|
139
|
+
accept(socket: Socket): void {
|
|
140
|
+
this.closeConnection(1008, 'replaced by a new connection')
|
|
141
|
+
this.connection = socket
|
|
142
|
+
const requests = new ActionRequests(
|
|
143
|
+
(frame) => socket.send(JSON.stringify(frame)),
|
|
144
|
+
this.bot.config.ws.responseTimeout,
|
|
145
|
+
)
|
|
146
|
+
this.requests = requests
|
|
147
|
+
installRequest(this.bot, requests.request)
|
|
148
|
+
socket.on('message', (raw) => {
|
|
149
|
+
this.dispatch(raw.toString(), requests)
|
|
150
|
+
})
|
|
151
|
+
socket.on('close', () => {
|
|
152
|
+
this.drop(socket)
|
|
153
|
+
})
|
|
154
|
+
this.bot.user = {
|
|
155
|
+
id: this.bot.config.selfId,
|
|
156
|
+
name: this.bot.config.selfId,
|
|
157
|
+
isBot: true,
|
|
158
|
+
}
|
|
159
|
+
this.bot.online()
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private closeConnection(code = 1000, reason = 'adapter stopped'): void {
|
|
163
|
+
const socket = this.connection
|
|
164
|
+
const requests = this.requests
|
|
165
|
+
this.connection = undefined
|
|
166
|
+
this.requests = undefined
|
|
167
|
+
requests?.rejectAll(
|
|
168
|
+
new Error('onebot: the reverse WebSocket connection has closed'),
|
|
169
|
+
)
|
|
170
|
+
try {
|
|
171
|
+
socket?.close(code, reason)
|
|
172
|
+
} catch (error) {
|
|
173
|
+
// The socket is already closed or closing; nothing left to release.
|
|
174
|
+
void error
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The current connection closed: refuse its pending calls and wait for the implementation to dial again. */
|
|
179
|
+
private drop(socket: Socket): void {
|
|
180
|
+
if (this.connection !== socket) return
|
|
181
|
+
this.connection = undefined
|
|
182
|
+
const failure = new Error(
|
|
183
|
+
'onebot: the reverse WebSocket connection has closed',
|
|
184
|
+
)
|
|
185
|
+
this.requests?.rejectAll(failure)
|
|
186
|
+
this.requests = undefined
|
|
187
|
+
rejectRequests(this.bot, failure)
|
|
188
|
+
this.bot.status = Status.RECONNECT
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Dispatch one received frame: an event, an action answer, or noise. */
|
|
192
|
+
private dispatch(text: string, requests: ActionRequests): void {
|
|
193
|
+
let parsed: unknown
|
|
194
|
+
try {
|
|
195
|
+
parsed = JSON.parse(text)
|
|
196
|
+
} catch (error) {
|
|
197
|
+
this.bot.ctx.logger.warn(
|
|
198
|
+
'onebot: cannot parse a WebSocket frame: %s',
|
|
199
|
+
error instanceof Error ? error.message : String(error),
|
|
200
|
+
)
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
if (isPayload(parsed)) {
|
|
204
|
+
void this.receive(parsed)
|
|
205
|
+
return
|
|
206
|
+
}
|
|
207
|
+
if (isResponse(parsed) && requests.resolve(parsed)) return
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Publish one event; a failed intake is logged because the platform will not redeliver it. */
|
|
211
|
+
private async receive(data: Payload): Promise<void> {
|
|
212
|
+
if (data.post_type === 'meta_event') {
|
|
213
|
+
this.bot.ctx.logger.debug(
|
|
214
|
+
'onebot: %s heartbeat ignored',
|
|
215
|
+
data.meta_event_type ?? 'meta',
|
|
216
|
+
)
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
const session = decodePayload(this.bot, data)
|
|
220
|
+
if (session === undefined) {
|
|
221
|
+
this.bot.ctx.logger.debug(
|
|
222
|
+
'onebot: ignored %s event',
|
|
223
|
+
data.post_type ?? 'unknown',
|
|
224
|
+
)
|
|
225
|
+
return
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
await this.bot.receive(session)
|
|
229
|
+
} catch (error) {
|
|
230
|
+
this.bot.ctx.logger.error(
|
|
231
|
+
'onebot: intake failed: %s',
|
|
232
|
+
error instanceof Error ? error.message : String(error),
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Forward WebSocket transport (`protocol: 'ws'`).
|
|
3
|
+
*
|
|
4
|
+
* The adapter dials the implementation's WebSocket endpoint and dials again forever: `ws.retryTimes` is a fast-retry
|
|
5
|
+
* budget, not a give-up count, so an implementation that starts after the harness still comes online without a
|
|
6
|
+
* restart. Configuration failures are the caller's to fix and throw out of `connect()`; transport failures retry.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { Status } from '@deepseek-ai/cordis-plugin-im-core'
|
|
10
|
+
import type {} from '@deepseek-ai/cordis-plugin-http'
|
|
11
|
+
import type { OneBotBot } from '../bot.ts'
|
|
12
|
+
import { decodePayload, isPayload } from '../decode.ts'
|
|
13
|
+
import { OneBotIdentityError, verifyIdentity } from '../identity.ts'
|
|
14
|
+
import {
|
|
15
|
+
ActionRequests,
|
|
16
|
+
installRequest,
|
|
17
|
+
isResponse,
|
|
18
|
+
rejectRequests,
|
|
19
|
+
} from '../request.ts'
|
|
20
|
+
import type { Payload } from '../types.ts'
|
|
21
|
+
|
|
22
|
+
/** Waitable sleep that resolves early on abort. */
|
|
23
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
24
|
+
return new Promise((resolve) => {
|
|
25
|
+
if (signal.aborted) {
|
|
26
|
+
resolve()
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
const timer = setTimeout(() => {
|
|
30
|
+
signal.removeEventListener('abort', onAbort)
|
|
31
|
+
resolve()
|
|
32
|
+
}, ms)
|
|
33
|
+
const onAbort = (): void => {
|
|
34
|
+
clearTimeout(timer)
|
|
35
|
+
resolve()
|
|
36
|
+
}
|
|
37
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The WebSocket the `http` service opens (Node's global `WebSocket`). */
|
|
42
|
+
type OneBotSocket = ReturnType<OneBotBot['ctx']['http']['ws']>
|
|
43
|
+
|
|
44
|
+
/** Text of one WebSocket frame. */
|
|
45
|
+
function frameText(data: unknown): string {
|
|
46
|
+
return typeof data === 'string' ? data : String(data)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The forward WebSocket client of one bot. */
|
|
50
|
+
export class OneBotWsClient {
|
|
51
|
+
private controller: AbortController | undefined
|
|
52
|
+
private running: Promise<void> | undefined
|
|
53
|
+
private socket: OneBotSocket | undefined
|
|
54
|
+
|
|
55
|
+
constructor(private readonly bot: OneBotBot) {}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Validate the endpoint and start the reconnect loop.
|
|
59
|
+
*
|
|
60
|
+
* Returning before the first dial is deliberate: `Bot.start` awaits `connect()`, so waiting here would hold up
|
|
61
|
+
* plugin initialization for as long as the implementation is late.
|
|
62
|
+
*/
|
|
63
|
+
async start(): Promise<void> {
|
|
64
|
+
const endpoint = this.bot.config.endpoint
|
|
65
|
+
if (endpoint === '') {
|
|
66
|
+
throw this.fail(
|
|
67
|
+
'onebot: protocol "ws" needs endpoint (the implementation\'s ws:// URL)',
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
this.controller = new AbortController()
|
|
71
|
+
this.running = this.loop(endpoint, this.controller.signal)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Stop the loop and wait for it to unwind. */
|
|
75
|
+
async stop(): Promise<void> {
|
|
76
|
+
this.controller?.abort()
|
|
77
|
+
this.controller = undefined
|
|
78
|
+
this.closeSocket()
|
|
79
|
+
await this.running?.catch(() => undefined)
|
|
80
|
+
this.running = undefined
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Log a start failure before throwing it, because `Bot.start` only stores a connect failure on `bot.error`. */
|
|
84
|
+
private fail(message: string): Error {
|
|
85
|
+
this.bot.ctx.logger.error(message)
|
|
86
|
+
return new Error(message)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private closeSocket(): void {
|
|
90
|
+
const socket = this.socket
|
|
91
|
+
this.socket = undefined
|
|
92
|
+
try {
|
|
93
|
+
socket?.close(1000, 'adapter stopped')
|
|
94
|
+
} catch (error) {
|
|
95
|
+
// The socket is already closed or closing; nothing left to release.
|
|
96
|
+
void error
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private async loop(endpoint: string, signal: AbortSignal): Promise<void> {
|
|
101
|
+
const { config } = this.bot
|
|
102
|
+
let failures = 0
|
|
103
|
+
while (!signal.aborted) {
|
|
104
|
+
try {
|
|
105
|
+
const socket = await this.dial(endpoint, signal)
|
|
106
|
+
failures = 0
|
|
107
|
+
await this.accept(socket, signal)
|
|
108
|
+
if (signal.aborted) return
|
|
109
|
+
this.bot.ctx.logger.warn(
|
|
110
|
+
'onebot: the WebSocket connection closed; reconnecting',
|
|
111
|
+
)
|
|
112
|
+
this.bot.status = Status.RECONNECT
|
|
113
|
+
// The connection was working, so the next dial goes out at the fast interval.
|
|
114
|
+
await sleep(config.ws.retryInterval, signal)
|
|
115
|
+
} catch (error) {
|
|
116
|
+
if (signal.aborted) return
|
|
117
|
+
if (error instanceof OneBotIdentityError) {
|
|
118
|
+
// A wrong selfId cannot be fixed by reconnecting: report it and stop until the profile is edited.
|
|
119
|
+
this.bot.ctx.logger.error('onebot: %s', error.message)
|
|
120
|
+
this.bot.offline(error)
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
124
|
+
this.bot.ctx.logger.warn('onebot: %s; reconnecting', message)
|
|
125
|
+
this.bot.status = Status.RECONNECT
|
|
126
|
+
const base =
|
|
127
|
+
failures < config.ws.retryTimes
|
|
128
|
+
? config.ws.retryInterval
|
|
129
|
+
: config.ws.retryLazy
|
|
130
|
+
failures += 1
|
|
131
|
+
await sleep(base, signal)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Dial the endpoint and resolve once the socket is open. */
|
|
137
|
+
private dial(endpoint: string, signal: AbortSignal): Promise<OneBotSocket> {
|
|
138
|
+
const { token } = this.bot.config
|
|
139
|
+
const socket = this.bot.ctx.http.ws(
|
|
140
|
+
endpoint,
|
|
141
|
+
token === '' ? {} : { headers: { Authorization: `Bearer ${token}` } },
|
|
142
|
+
)
|
|
143
|
+
return new Promise<OneBotSocket>((resolve, reject) => {
|
|
144
|
+
const cleanup = (): void => {
|
|
145
|
+
socket.removeEventListener('open', onOpen)
|
|
146
|
+
socket.removeEventListener('error', onError)
|
|
147
|
+
socket.removeEventListener('close', onClose)
|
|
148
|
+
signal.removeEventListener('abort', onAbort)
|
|
149
|
+
}
|
|
150
|
+
const onOpen = (): void => {
|
|
151
|
+
cleanup()
|
|
152
|
+
resolve(socket)
|
|
153
|
+
}
|
|
154
|
+
const onError = (event: { message?: string }): void => {
|
|
155
|
+
cleanup()
|
|
156
|
+
reject(
|
|
157
|
+
new Error(
|
|
158
|
+
`onebot: WebSocket error${event.message === undefined ? '' : `: ${event.message}`}`,
|
|
159
|
+
),
|
|
160
|
+
)
|
|
161
|
+
}
|
|
162
|
+
const onClose = (event: { code: number }): void => {
|
|
163
|
+
cleanup()
|
|
164
|
+
reject(
|
|
165
|
+
new Error(
|
|
166
|
+
`onebot: WebSocket closed before opening (code ${event.code})`,
|
|
167
|
+
),
|
|
168
|
+
)
|
|
169
|
+
}
|
|
170
|
+
const onAbort = (): void => {
|
|
171
|
+
cleanup()
|
|
172
|
+
reject(signal.reason ?? new Error('onebot: adapter stopped'))
|
|
173
|
+
}
|
|
174
|
+
if (signal.aborted) {
|
|
175
|
+
onAbort()
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
socket.addEventListener('open', onOpen)
|
|
179
|
+
socket.addEventListener('error', onError)
|
|
180
|
+
socket.addEventListener('close', onClose)
|
|
181
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Take over one open socket: install the action caller, check the identity, publish events until the socket closes.
|
|
187
|
+
*/
|
|
188
|
+
private async accept(
|
|
189
|
+
socket: OneBotSocket,
|
|
190
|
+
signal: AbortSignal,
|
|
191
|
+
): Promise<void> {
|
|
192
|
+
this.socket = socket
|
|
193
|
+
const requests = new ActionRequests(
|
|
194
|
+
(frame) => socket.send(JSON.stringify(frame)),
|
|
195
|
+
this.bot.config.ws.responseTimeout,
|
|
196
|
+
)
|
|
197
|
+
installRequest(this.bot, requests.request)
|
|
198
|
+
|
|
199
|
+
const closed = new Promise<void>((resolve) => {
|
|
200
|
+
socket.addEventListener('close', () => resolve())
|
|
201
|
+
})
|
|
202
|
+
socket.addEventListener('message', (event) => {
|
|
203
|
+
this.dispatch(frameText(event.data), requests)
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
const onAbort = (): void => {
|
|
207
|
+
requests.rejectAll(new Error('onebot: adapter stopped'))
|
|
208
|
+
this.closeSocket()
|
|
209
|
+
}
|
|
210
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
211
|
+
|
|
212
|
+
try {
|
|
213
|
+
const login = await verifyIdentity(
|
|
214
|
+
this.bot.internal,
|
|
215
|
+
this.bot.config.selfId,
|
|
216
|
+
)
|
|
217
|
+
this.bot.user = {
|
|
218
|
+
id: String(login.user_id),
|
|
219
|
+
name: login.nickname,
|
|
220
|
+
isBot: true,
|
|
221
|
+
}
|
|
222
|
+
this.bot.online()
|
|
223
|
+
} catch (error) {
|
|
224
|
+
const failure = error instanceof Error ? error : new Error(String(error))
|
|
225
|
+
requests.rejectAll(failure)
|
|
226
|
+
rejectRequests(this.bot, failure)
|
|
227
|
+
this.closeSocket()
|
|
228
|
+
throw failure
|
|
229
|
+
} finally {
|
|
230
|
+
signal.removeEventListener('abort', onAbort)
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
await closed
|
|
234
|
+
const failure = new Error('onebot: the WebSocket connection has closed')
|
|
235
|
+
requests.rejectAll(failure)
|
|
236
|
+
// Calls made after the close must not hang on the dead socket.
|
|
237
|
+
rejectRequests(this.bot, failure)
|
|
238
|
+
this.socket = undefined
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Dispatch one received frame: an event, an action answer, or noise. */
|
|
242
|
+
private dispatch(text: string, requests: ActionRequests): void {
|
|
243
|
+
let parsed: unknown
|
|
244
|
+
try {
|
|
245
|
+
parsed = JSON.parse(text)
|
|
246
|
+
} catch (error) {
|
|
247
|
+
this.bot.ctx.logger.warn(
|
|
248
|
+
'onebot: cannot parse a WebSocket frame: %s',
|
|
249
|
+
error instanceof Error ? error.message : String(error),
|
|
250
|
+
)
|
|
251
|
+
return
|
|
252
|
+
}
|
|
253
|
+
if (isPayload(parsed)) {
|
|
254
|
+
void this.receive(parsed)
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
if (isResponse(parsed) && requests.resolve(parsed)) return
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Publish one event; a failed intake is logged because the platform will not redeliver it. */
|
|
261
|
+
private async receive(data: Payload): Promise<void> {
|
|
262
|
+
if (data.post_type === 'meta_event') {
|
|
263
|
+
this.bot.ctx.logger.debug(
|
|
264
|
+
'onebot: %s heartbeat ignored',
|
|
265
|
+
data.meta_event_type ?? 'meta',
|
|
266
|
+
)
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
const session = decodePayload(this.bot, data)
|
|
270
|
+
if (session === undefined) {
|
|
271
|
+
this.bot.ctx.logger.debug(
|
|
272
|
+
'onebot: ignored %s event',
|
|
273
|
+
data.post_type ?? 'unknown',
|
|
274
|
+
)
|
|
275
|
+
return
|
|
276
|
+
}
|
|
277
|
+
try {
|
|
278
|
+
await this.bot.receive(session)
|
|
279
|
+
} catch (error) {
|
|
280
|
+
this.bot.ctx.logger.error(
|
|
281
|
+
'onebot: intake failed: %s',
|
|
282
|
+
error instanceof Error ? error.message : String(error),
|
|
283
|
+
)
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|