@im-more/dsh-milky 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 +2311 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +127 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +303 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +24 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +39 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +43 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +277 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +66 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +170 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +24 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +33 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/ids.d.ts +110 -0
- package/lib/types/ids.d.ts.map +1 -0
- package/lib/types/ids.js +166 -0
- package/lib/types/ids.js.map +1 -0
- package/lib/types/index.d.ts +10 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +9 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/internal.d.ts +2002 -0
- package/lib/types/internal.d.ts.map +1 -0
- package/lib/types/internal.js +408 -0
- package/lib/types/internal.js.map +1 -0
- package/lib/types/modes/text.d.ts +66 -0
- package/lib/types/modes/text.d.ts.map +1 -0
- package/lib/types/modes/text.js +275 -0
- package/lib/types/modes/text.js.map +1 -0
- package/lib/types/reads.d.ts +57 -0
- package/lib/types/reads.d.ts.map +1 -0
- package/lib/types/reads.js +219 -0
- package/lib/types/reads.js.map +1 -0
- package/lib/types/request.d.ts +55 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +174 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +34 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +99 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/types/schema.d.ts +11726 -0
- package/lib/types/types/schema.d.ts.map +1 -0
- package/lib/types/types/schema.js +1422 -0
- package/lib/types/types/schema.js.map +1 -0
- package/lib/types/ws.d.ts +60 -0
- package/lib/types/ws.d.ts.map +1 -0
- package/lib/types/ws.js +335 -0
- package/lib/types/ws.js.map +1 -0
- package/package.json +62 -3
- package/src/bot.ts +431 -0
- package/src/config.ts +61 -0
- package/src/decode.ts +367 -0
- package/src/errors.ts +195 -0
- package/src/identity.ts +43 -0
- package/src/ids.ts +226 -0
- package/src/index.ts +44 -0
- package/src/internal.ts +657 -0
- package/src/modes/text.ts +368 -0
- package/src/reads.ts +315 -0
- package/src/request.ts +230 -0
- package/src/send.ts +175 -0
- package/src/types/schema.ts +1827 -0
- package/src/ws.ts +383 -0
- package/README.md +0 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,2311 @@
|
|
|
1
|
+
import { Adapter, ElementRegistry, PlatformError, Status, defineMode, h, normalize } from "@deepseek-ai/cordis-plugin-im-core";
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
// lib/types/config.js
|
|
4
|
+
/** Milky adapter configuration: the protocol endpoint, its optional access token, the bot account and the WS budget. */
|
|
5
|
+
/** Validated Milky adapter configuration. */
|
|
6
|
+
const Config = z.object({
|
|
7
|
+
endpoint: z.string().role("url").required().description("协议端根 URL,例如 http://127.0.0.1:3000;只使用其 origin。"),
|
|
8
|
+
token: z.string().role("secret").default("").description("协议端 access_token;留空表示未设置。"),
|
|
9
|
+
selfId: z.string().pattern(/^\d+$/).required().description("机器人 QQ 号,必须与 get_login_info.uin 一致。"),
|
|
10
|
+
ws: z.object({
|
|
11
|
+
retryTimes: z.natural().default(6).description("快重试预算;用完后改用惰性间隔,但永不放弃。"),
|
|
12
|
+
retryIntervalMs: z.natural().role("ms").default(5e3).description("快重试间隔。"),
|
|
13
|
+
retryLazyMs: z.natural().role("ms").default(6e4).description("快重试预算用完后的惰性间隔。")
|
|
14
|
+
}).default({})
|
|
15
|
+
});
|
|
16
|
+
// lib/types/errors.js
|
|
17
|
+
/**
|
|
18
|
+
* Milky failures and their mapping onto the core platform taxonomy.
|
|
19
|
+
*
|
|
20
|
+
* `MilkyApiError` carries the facts the classification table of the design needs: the API name, the HTTP status, the
|
|
21
|
+
* protocol envelope status and retcode, and whether the call reached the protocol endpoint at all.
|
|
22
|
+
*/
|
|
23
|
+
/** A configuration value that can never work (bad `endpoint`, bad `selfId`). */
|
|
24
|
+
var MilkyConfigError = class extends Error {
|
|
25
|
+
name = "MilkyConfigError";
|
|
26
|
+
/**
|
|
27
|
+
* @param message - what is wrong with the configuration.
|
|
28
|
+
* @param options - the caught cause, when any.
|
|
29
|
+
*/
|
|
30
|
+
constructor(message, options) {
|
|
31
|
+
super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The protocol endpoint is logged into a different account than the configured `selfId`.
|
|
36
|
+
*
|
|
37
|
+
* Runtime permanent: retrying cannot fix a misconfigured endpoint, and continuing would admit another account's events.
|
|
38
|
+
*/
|
|
39
|
+
var MilkyIdentityError = class extends Error {
|
|
40
|
+
name = "MilkyIdentityError";
|
|
41
|
+
/**
|
|
42
|
+
* @param message - which account was expected and which one answered.
|
|
43
|
+
*/
|
|
44
|
+
constructor(message) {
|
|
45
|
+
super(message);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/** One failed Milky API call. */
|
|
49
|
+
var MilkyApiError = class extends Error {
|
|
50
|
+
name = "MilkyApiError";
|
|
51
|
+
api;
|
|
52
|
+
httpStatus;
|
|
53
|
+
status;
|
|
54
|
+
retcode;
|
|
55
|
+
/**
|
|
56
|
+
* @param message - human-readable failure, already carrying the API name.
|
|
57
|
+
* @param init - what the call observed.
|
|
58
|
+
*/
|
|
59
|
+
constructor(message, init) {
|
|
60
|
+
super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
|
|
61
|
+
this.api = init.api;
|
|
62
|
+
this.httpStatus = init.httpStatus;
|
|
63
|
+
this.status = init.status;
|
|
64
|
+
this.retcode = init.retcode;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Map any failure onto the core platform taxonomy.
|
|
69
|
+
*
|
|
70
|
+
* HTTP 401 / 404 / 415 and every `status: 'failed'` answer are refusals of a request the endpoint understood, so
|
|
71
|
+
* nothing was published; a 5xx, a transport failure or a 2xx answer that cannot be parsed leaves the outcome unknown.
|
|
72
|
+
*
|
|
73
|
+
* @param error - the caught failure.
|
|
74
|
+
* @returns the classified platform error.
|
|
75
|
+
*/
|
|
76
|
+
function classifyMilkyError(error) {
|
|
77
|
+
if (error instanceof PlatformError) return error;
|
|
78
|
+
if (error instanceof MilkyApiError) {
|
|
79
|
+
const code = error.retcode ?? error.httpStatus;
|
|
80
|
+
const init = {
|
|
81
|
+
...code === void 0 ? {} : { code },
|
|
82
|
+
cause: error
|
|
83
|
+
};
|
|
84
|
+
const httpStatus = error.httpStatus;
|
|
85
|
+
if (httpStatus === void 0) return new PlatformError("retryable", error.message, {
|
|
86
|
+
...init,
|
|
87
|
+
published: "unknown"
|
|
88
|
+
});
|
|
89
|
+
if (httpStatus < 200 || httpStatus >= 300) {
|
|
90
|
+
if (httpStatus === 401) return new PlatformError("permission", error.message, {
|
|
91
|
+
...init,
|
|
92
|
+
published: "no"
|
|
93
|
+
});
|
|
94
|
+
if (httpStatus === 404) return new PlatformError("fatal", error.message, {
|
|
95
|
+
...init,
|
|
96
|
+
published: "no"
|
|
97
|
+
});
|
|
98
|
+
if (httpStatus === 415) return new PlatformError("fatal", error.message, {
|
|
99
|
+
...init,
|
|
100
|
+
published: "no"
|
|
101
|
+
});
|
|
102
|
+
if (httpStatus >= 500) return new PlatformError("retryable", error.message, {
|
|
103
|
+
...init,
|
|
104
|
+
published: "unknown"
|
|
105
|
+
});
|
|
106
|
+
if (httpStatus >= 400) return new PlatformError("invalid", error.message, {
|
|
107
|
+
...init,
|
|
108
|
+
published: "no"
|
|
109
|
+
});
|
|
110
|
+
return new PlatformError("retryable", error.message, {
|
|
111
|
+
...init,
|
|
112
|
+
published: "unknown"
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
if (error.status === "failed") switch (error.retcode) {
|
|
116
|
+
case -400: return new PlatformError("invalid", error.message, {
|
|
117
|
+
...init,
|
|
118
|
+
published: "no"
|
|
119
|
+
});
|
|
120
|
+
case -403: return new PlatformError("permission", error.message, {
|
|
121
|
+
...init,
|
|
122
|
+
published: "no"
|
|
123
|
+
});
|
|
124
|
+
case -404: return new PlatformError("not-found", error.message, {
|
|
125
|
+
...init,
|
|
126
|
+
published: "no"
|
|
127
|
+
});
|
|
128
|
+
default: return new PlatformError("invalid", error.message, {
|
|
129
|
+
...init,
|
|
130
|
+
published: "no"
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return new PlatformError("invalid", error.message, {
|
|
134
|
+
...init,
|
|
135
|
+
published: "unknown"
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
if (error instanceof MilkyConfigError) return new PlatformError("fatal", error.message, {
|
|
139
|
+
published: "no",
|
|
140
|
+
cause: error
|
|
141
|
+
});
|
|
142
|
+
if (error instanceof MilkyIdentityError) return new PlatformError("permission", error.message, {
|
|
143
|
+
published: "no",
|
|
144
|
+
cause: error
|
|
145
|
+
});
|
|
146
|
+
if (isAbortError(error)) return new PlatformError("fatal", error.message, {
|
|
147
|
+
published: "unknown",
|
|
148
|
+
cause: error
|
|
149
|
+
});
|
|
150
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
151
|
+
return new PlatformError("retryable", `milky request failed: ${message}`, {
|
|
152
|
+
published: "unknown",
|
|
153
|
+
cause: error
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/** Whether a caught value is an abort, including the `DOMException` an aborted signal produces. */
|
|
157
|
+
function isAbortError(error) {
|
|
158
|
+
return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
|
|
159
|
+
}
|
|
160
|
+
// lib/types/identity.js
|
|
161
|
+
/** Bot identity: `get_login_info` must name the configured QQ account, and the endpoint version is reported, not trusted. */
|
|
162
|
+
/**
|
|
163
|
+
* Verify a `get_login_info` answer against the configured account.
|
|
164
|
+
* @param selfId - configured QQ number.
|
|
165
|
+
* @param login - `get_login_info` result.
|
|
166
|
+
* @returns the bot's own user.
|
|
167
|
+
* @throws MilkyIdentityError when the endpoint is logged into another account.
|
|
168
|
+
*/
|
|
169
|
+
function verifyIdentity(selfId, login) {
|
|
170
|
+
const actual = String(login.uin);
|
|
171
|
+
if (actual !== selfId) throw new MilkyIdentityError(`milky: the endpoint is logged into account ${actual}, but this adapter is configured for ${selfId}`);
|
|
172
|
+
return {
|
|
173
|
+
id: actual,
|
|
174
|
+
name: login.nickname
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Whether the endpoint implements the Milky major version this adapter targets.
|
|
179
|
+
* @param version - `milky_version` of `get_impl_info`.
|
|
180
|
+
* @returns true for a `1.x` implementation.
|
|
181
|
+
*/
|
|
182
|
+
function implementsMilky1(version) {
|
|
183
|
+
return /^1\./.test(version);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Describe one `get_impl_info` answer for a warning about an unexpected version.
|
|
187
|
+
* @param info - `get_impl_info` result.
|
|
188
|
+
* @returns the diagnostic line.
|
|
189
|
+
*/
|
|
190
|
+
function versionWarning(info) {
|
|
191
|
+
return `milky: the endpoint implements Milky ${info.milky_version} (${info.impl_name} ${info.impl_version}); this adapter targets 1.x`;
|
|
192
|
+
}
|
|
193
|
+
// lib/types/request.js
|
|
194
|
+
/**
|
|
195
|
+
* Milky wire transport: `POST <origin>/api/<name>` with the protocol's JSON envelope and a bearer token.
|
|
196
|
+
*
|
|
197
|
+
* The HTTP and WebSocket addresses are derived from the `origin` of `endpoint` only: the protocol endpoint serves
|
|
198
|
+
* `/api` and `/event` next to each other at its root, so a path, query or hash of the configured URL is ignored (the
|
|
199
|
+
* same rule the upstream adapter applies).
|
|
200
|
+
*/
|
|
201
|
+
/**
|
|
202
|
+
* Normalize the configured endpoint: drop trailing slashes, keep everything else for {@link milkyOrigin} to judge.
|
|
203
|
+
* @param endpoint - `config.endpoint` as given.
|
|
204
|
+
* @returns the endpoint without a trailing slash.
|
|
205
|
+
*/
|
|
206
|
+
function normalizeEndpoint(endpoint) {
|
|
207
|
+
return endpoint.replace(/\/+$/, "");
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Origin (scheme + host + port) of the protocol endpoint.
|
|
211
|
+
* @param endpoint - normalized endpoint.
|
|
212
|
+
* @returns the origin both the API and the event socket are built from.
|
|
213
|
+
* @throws MilkyConfigError when the endpoint is not a URL or does not use `http:` / `https:`.
|
|
214
|
+
*/
|
|
215
|
+
function milkyOrigin(endpoint) {
|
|
216
|
+
let url;
|
|
217
|
+
try {
|
|
218
|
+
url = new URL(endpoint);
|
|
219
|
+
} catch (cause) {
|
|
220
|
+
throw new MilkyConfigError(`milky: endpoint "${endpoint}" is not a valid URL`, { cause });
|
|
221
|
+
}
|
|
222
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new MilkyConfigError(`milky: endpoint must use http: or https:, got "${url.protocol}"`);
|
|
223
|
+
return url.origin;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Build the shared request endpoints of one bot.
|
|
227
|
+
* @param ctx - context whose isolated `http` service performs the calls.
|
|
228
|
+
* @param token - configured access token.
|
|
229
|
+
* @param origin - origin of the protocol endpoint.
|
|
230
|
+
* @returns the request endpoints.
|
|
231
|
+
*/
|
|
232
|
+
function createMilkyRequest(ctx, token, origin) {
|
|
233
|
+
return {
|
|
234
|
+
ctx,
|
|
235
|
+
token,
|
|
236
|
+
origin
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Event socket address of one request endpoint.
|
|
241
|
+
* @param request - request endpoints of the bot.
|
|
242
|
+
* @returns `ws(s)://<origin>/event`.
|
|
243
|
+
*/
|
|
244
|
+
function eventUrl(request) {
|
|
245
|
+
const url = new URL(request.origin);
|
|
246
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
247
|
+
url.pathname = "/event";
|
|
248
|
+
return url.href;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Call one Milky API method through the shared envelope and error path.
|
|
252
|
+
*
|
|
253
|
+
* @param request - request endpoints of the bot.
|
|
254
|
+
* @param api - API name (`send_group_message`).
|
|
255
|
+
* @param payload - JSON request body; `{}` for the parameterless APIs.
|
|
256
|
+
* @param signal - cancellation of the caller.
|
|
257
|
+
* @returns the `data` field of a `status: 'ok'` answer.
|
|
258
|
+
* @throws MilkyApiError for every non-ok answer, including an unparsable one.
|
|
259
|
+
*/
|
|
260
|
+
async function invoke(request, api, payload = {}, signal) {
|
|
261
|
+
const headers = { "content-type": "application/json" };
|
|
262
|
+
if (request.token !== "") headers.authorization = `Bearer ${request.token}`;
|
|
263
|
+
let response;
|
|
264
|
+
try {
|
|
265
|
+
response = await request.ctx.http(`${request.origin}/api/${api}`, {
|
|
266
|
+
method: "POST",
|
|
267
|
+
data: payload,
|
|
268
|
+
headers,
|
|
269
|
+
...signal === void 0 ? {} : { signal }
|
|
270
|
+
});
|
|
271
|
+
} catch (cause) {
|
|
272
|
+
if (isCancellation(cause, signal)) throw cancellation(cause, signal);
|
|
273
|
+
throw new MilkyApiError(`milky ${api} request failed`, {
|
|
274
|
+
api,
|
|
275
|
+
cause
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
let text;
|
|
279
|
+
try {
|
|
280
|
+
text = await response.text();
|
|
281
|
+
} catch (cause) {
|
|
282
|
+
if (signal?.aborted === true) throw cancellation(cause, signal);
|
|
283
|
+
throw new MilkyApiError(`milky ${api} answered ${response.status} with an unreadable body`, {
|
|
284
|
+
api,
|
|
285
|
+
httpStatus: response.status,
|
|
286
|
+
cause
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
if (signal?.aborted === true) throw cancellation(signal.reason, signal);
|
|
290
|
+
const envelope = parseEnvelope(text);
|
|
291
|
+
const reported = typeof envelope?.message === "string" ? envelope.message : void 0;
|
|
292
|
+
const retcode = typeof envelope?.retcode === "number" ? envelope.retcode : void 0;
|
|
293
|
+
if (response.status < 200 || response.status >= 300) throw new MilkyApiError(`milky ${api} answered ${response.status}${reported === void 0 ? "" : `: ${reported}`}`, {
|
|
294
|
+
api,
|
|
295
|
+
httpStatus: response.status,
|
|
296
|
+
...envelope?.status === "failed" || envelope?.status === "ok" ? { status: envelope.status } : {},
|
|
297
|
+
...retcode === void 0 ? {} : { retcode }
|
|
298
|
+
});
|
|
299
|
+
if (envelope === void 0) throw new MilkyApiError(`milky ${api} answered ${response.status} without a JSON envelope`, {
|
|
300
|
+
api,
|
|
301
|
+
httpStatus: response.status
|
|
302
|
+
});
|
|
303
|
+
if (envelope.status === "failed") throw new MilkyApiError(`milky ${api} failed${retcode === void 0 ? "" : ` with retcode ${retcode}`}${reported === void 0 ? "" : `: ${reported}`}`, {
|
|
304
|
+
api,
|
|
305
|
+
httpStatus: response.status,
|
|
306
|
+
status: "failed",
|
|
307
|
+
...retcode === void 0 ? {} : { retcode }
|
|
308
|
+
});
|
|
309
|
+
if (envelope.status !== "ok") throw new MilkyApiError(`milky ${api} answered ${response.status} without an envelope status`, {
|
|
310
|
+
api,
|
|
311
|
+
httpStatus: response.status
|
|
312
|
+
});
|
|
313
|
+
return envelope.data;
|
|
314
|
+
}
|
|
315
|
+
/** Parse a response body as an envelope object; anything else is `undefined`. */
|
|
316
|
+
function parseEnvelope(text) {
|
|
317
|
+
let value;
|
|
318
|
+
try {
|
|
319
|
+
value = JSON.parse(text);
|
|
320
|
+
} catch (error) {
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
324
|
+
return value;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Whether a failed request was cancelled rather than refused by the transport.
|
|
328
|
+
* @param cause - the value `ctx.http` rejected with.
|
|
329
|
+
* @param signal - the cancellation signal handed to the request.
|
|
330
|
+
* @returns true when the caller cancelled the request.
|
|
331
|
+
*/
|
|
332
|
+
function isCancellation(cause, signal) {
|
|
333
|
+
if (signal?.aborted === true) return true;
|
|
334
|
+
if ((cause instanceof Error || cause instanceof DOMException) && cause.name === "AbortError") return true;
|
|
335
|
+
return signal?.reason !== void 0 && cause === signal.reason;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* The value a cancelled request rejects with: the signal's reason, so the classifier recognises the cancellation
|
|
339
|
+
* instead of a wrapped transport failure.
|
|
340
|
+
* @param cause - the value `ctx.http` rejected with.
|
|
341
|
+
* @param signal - the cancellation signal handed to the request.
|
|
342
|
+
* @returns the abort error to rethrow.
|
|
343
|
+
*/
|
|
344
|
+
function cancellation(cause, signal) {
|
|
345
|
+
return signal?.aborted === true ? signal.reason : cause;
|
|
346
|
+
}
|
|
347
|
+
// lib/types/internal.js
|
|
348
|
+
var Internal = class {
|
|
349
|
+
client;
|
|
350
|
+
constructor(client) {
|
|
351
|
+
this.client = client;
|
|
352
|
+
}
|
|
353
|
+
async request(urlPath, data) {
|
|
354
|
+
return await invoke(this.client, urlPath.replace(/^\/api\//, ""), data ?? {});
|
|
355
|
+
}
|
|
356
|
+
/** 获取登录信息 */
|
|
357
|
+
async getLoginInfo() {
|
|
358
|
+
return await this.request("/api/get_login_info", {});
|
|
359
|
+
}
|
|
360
|
+
/** 获取协议端信息 */
|
|
361
|
+
async getImplInfo() {
|
|
362
|
+
return await this.request("/api/get_impl_info", {});
|
|
363
|
+
}
|
|
364
|
+
/** 获取用户个人信息 */
|
|
365
|
+
async getUserProfile(user_id) {
|
|
366
|
+
return await this.request("/api/get_user_profile", { user_id });
|
|
367
|
+
}
|
|
368
|
+
/** 获取好友列表 */
|
|
369
|
+
async getFriendList(no_cache) {
|
|
370
|
+
return await this.request("/api/get_friend_list", { no_cache });
|
|
371
|
+
}
|
|
372
|
+
/** 获取好友信息 */
|
|
373
|
+
async getFriendInfo(user_id, no_cache) {
|
|
374
|
+
return await this.request("/api/get_friend_info", {
|
|
375
|
+
user_id,
|
|
376
|
+
no_cache
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
/** 获取群列表 */
|
|
380
|
+
async getGroupList(no_cache) {
|
|
381
|
+
return await this.request("/api/get_group_list", { no_cache });
|
|
382
|
+
}
|
|
383
|
+
/** 获取群信息 */
|
|
384
|
+
async getGroupInfo(group_id, no_cache) {
|
|
385
|
+
return await this.request("/api/get_group_info", {
|
|
386
|
+
group_id,
|
|
387
|
+
no_cache
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
/** 获取群成员列表 */
|
|
391
|
+
async getGroupMemberList(group_id, no_cache) {
|
|
392
|
+
return await this.request("/api/get_group_member_list", {
|
|
393
|
+
group_id,
|
|
394
|
+
no_cache
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
/** 获取群成员信息 */
|
|
398
|
+
async getGroupMemberInfo(group_id, user_id, no_cache) {
|
|
399
|
+
return await this.request("/api/get_group_member_info", {
|
|
400
|
+
group_id,
|
|
401
|
+
user_id,
|
|
402
|
+
no_cache
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
/** 获取置顶的好友和群列表 */
|
|
406
|
+
async getPeerPins() {
|
|
407
|
+
return await this.request("/api/get_peer_pins", {});
|
|
408
|
+
}
|
|
409
|
+
/** 设置好友或群的置顶状态 */
|
|
410
|
+
async setPeerPin(message_scene, peer_id, is_pinned) {
|
|
411
|
+
return await this.request("/api/set_peer_pin", {
|
|
412
|
+
message_scene,
|
|
413
|
+
peer_id,
|
|
414
|
+
is_pinned
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
/** 设置 QQ 账号头像 */
|
|
418
|
+
async setAvatar(uri) {
|
|
419
|
+
return await this.request("/api/set_avatar", { uri });
|
|
420
|
+
}
|
|
421
|
+
/** 设置 QQ 账号昵称 */
|
|
422
|
+
async setNickname(new_nickname) {
|
|
423
|
+
return await this.request("/api/set_nickname", { new_nickname });
|
|
424
|
+
}
|
|
425
|
+
/** 设置 QQ 账号个性签名 */
|
|
426
|
+
async setBio(new_bio) {
|
|
427
|
+
return await this.request("/api/set_bio", { new_bio });
|
|
428
|
+
}
|
|
429
|
+
/** 获取自定义表情 URL 列表 */
|
|
430
|
+
async getCustomFaceUrlList() {
|
|
431
|
+
return await this.request("/api/get_custom_face_url_list", {});
|
|
432
|
+
}
|
|
433
|
+
/** 获取 Cookies */
|
|
434
|
+
async getCookies(domain) {
|
|
435
|
+
return await this.request("/api/get_cookies", { domain });
|
|
436
|
+
}
|
|
437
|
+
/** 获取 CSRF Token */
|
|
438
|
+
async getCSRFToken() {
|
|
439
|
+
return await this.request("/api/get_csrf_token", {});
|
|
440
|
+
}
|
|
441
|
+
/** 发送私聊消息 */
|
|
442
|
+
async sendPrivateMessage(user_id, message) {
|
|
443
|
+
return await this.request("/api/send_private_message", {
|
|
444
|
+
user_id,
|
|
445
|
+
message
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
/** 发送群消息 */
|
|
449
|
+
async sendGroupMessage(group_id, message) {
|
|
450
|
+
return await this.request("/api/send_group_message", {
|
|
451
|
+
group_id,
|
|
452
|
+
message
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
/** 获取消息 */
|
|
456
|
+
async getMessage(message_scene, peer_id, message_seq) {
|
|
457
|
+
return await this.request("/api/get_message", {
|
|
458
|
+
message_scene,
|
|
459
|
+
peer_id,
|
|
460
|
+
message_seq
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
/** 获取历史消息 */
|
|
464
|
+
async getHistoryMessages(message_scene, peer_id, start_message_seq, limit) {
|
|
465
|
+
return await this.request("/api/get_history_messages", {
|
|
466
|
+
message_scene,
|
|
467
|
+
peer_id,
|
|
468
|
+
start_message_seq,
|
|
469
|
+
limit
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
/** 获取临时资源链接 */
|
|
473
|
+
async getResourceTempUrl(resource_id) {
|
|
474
|
+
return await this.request("/api/get_resource_temp_url", { resource_id });
|
|
475
|
+
}
|
|
476
|
+
/** 获取合并转发消息内容 */
|
|
477
|
+
async getForwardedMessages(forward_id) {
|
|
478
|
+
return await this.request("/api/get_forwarded_messages", { forward_id });
|
|
479
|
+
}
|
|
480
|
+
/** 撤回私聊消息 */
|
|
481
|
+
async recallPrivateMessage(user_id, message_seq) {
|
|
482
|
+
return await this.request("/api/recall_private_message", {
|
|
483
|
+
user_id,
|
|
484
|
+
message_seq
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
/** 撤回群消息 */
|
|
488
|
+
async recallGroupMessage(group_id, message_seq) {
|
|
489
|
+
return await this.request("/api/recall_group_message", {
|
|
490
|
+
group_id,
|
|
491
|
+
message_seq
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
/** 标记消息为已读 */
|
|
495
|
+
async markMessageAsRead(message_scene, peer_id, message_seq) {
|
|
496
|
+
return await this.request("/api/mark_message_as_read", {
|
|
497
|
+
message_scene,
|
|
498
|
+
peer_id,
|
|
499
|
+
message_seq
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
/** 发送好友戳一戳 */
|
|
503
|
+
async sendFriendNudge(user_id, is_self) {
|
|
504
|
+
return await this.request("/api/send_friend_nudge", {
|
|
505
|
+
user_id,
|
|
506
|
+
is_self
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
/** 发送名片点赞 */
|
|
510
|
+
async sendProfileLike(user_id, count) {
|
|
511
|
+
return await this.request("/api/send_profile_like", {
|
|
512
|
+
user_id,
|
|
513
|
+
count
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
/** 删除好友 */
|
|
517
|
+
async deleteFriend(user_id) {
|
|
518
|
+
return await this.request("/api/delete_friend", { user_id });
|
|
519
|
+
}
|
|
520
|
+
/** 获取好友请求列表 */
|
|
521
|
+
async getFriendRequests(limit, is_filtered) {
|
|
522
|
+
return await this.request("/api/get_friend_requests", {
|
|
523
|
+
limit,
|
|
524
|
+
is_filtered
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
/** 同意好友请求 */
|
|
528
|
+
async acceptFriendRequest(initiator_uid, is_filtered) {
|
|
529
|
+
return await this.request("/api/accept_friend_request", {
|
|
530
|
+
initiator_uid,
|
|
531
|
+
is_filtered
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
/** 拒绝好友请求 */
|
|
535
|
+
async rejectFriendRequest(initiator_uid, is_filtered, reason) {
|
|
536
|
+
return await this.request("/api/reject_friend_request", {
|
|
537
|
+
initiator_uid,
|
|
538
|
+
is_filtered,
|
|
539
|
+
reason
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
/** 设置群名称 */
|
|
543
|
+
async setGroupName(group_id, new_group_name) {
|
|
544
|
+
return await this.request("/api/set_group_name", {
|
|
545
|
+
group_id,
|
|
546
|
+
new_group_name
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
/** 设置群头像 */
|
|
550
|
+
async setGroupAvatar(group_id, image_uri) {
|
|
551
|
+
return await this.request("/api/set_group_avatar", {
|
|
552
|
+
group_id,
|
|
553
|
+
image_uri
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
/** 设置群名片 */
|
|
557
|
+
async setGroupMemberCard(group_id, user_id, card) {
|
|
558
|
+
return await this.request("/api/set_group_member_card", {
|
|
559
|
+
group_id,
|
|
560
|
+
user_id,
|
|
561
|
+
card
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
/** 设置群成员专属头衔 */
|
|
565
|
+
async setGroupMemberSpecialTitle(group_id, user_id, special_title) {
|
|
566
|
+
return await this.request("/api/set_group_member_special_title", {
|
|
567
|
+
group_id,
|
|
568
|
+
user_id,
|
|
569
|
+
special_title
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
/** 设置群管理员 */
|
|
573
|
+
async setGroupMemberAdmin(group_id, user_id, is_set) {
|
|
574
|
+
return await this.request("/api/set_group_member_admin", {
|
|
575
|
+
group_id,
|
|
576
|
+
user_id,
|
|
577
|
+
is_set
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
/** 设置群成员禁言 */
|
|
581
|
+
async setGroupMemberMute(group_id, user_id, duration) {
|
|
582
|
+
return await this.request("/api/set_group_member_mute", {
|
|
583
|
+
group_id,
|
|
584
|
+
user_id,
|
|
585
|
+
duration
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
/** 设置群全员禁言 */
|
|
589
|
+
async setGroupWholeMute(group_id, is_mute) {
|
|
590
|
+
return await this.request("/api/set_group_whole_mute", {
|
|
591
|
+
group_id,
|
|
592
|
+
is_mute
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
/** 踢出群成员 */
|
|
596
|
+
async kickGroupMember(group_id, user_id, reject_add_request) {
|
|
597
|
+
return await this.request("/api/kick_group_member", {
|
|
598
|
+
group_id,
|
|
599
|
+
user_id,
|
|
600
|
+
reject_add_request
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
/** 获取群公告列表 */
|
|
604
|
+
async getGroupAnnouncements(group_id) {
|
|
605
|
+
return await this.request("/api/get_group_announcements", { group_id });
|
|
606
|
+
}
|
|
607
|
+
/** 发送群公告 */
|
|
608
|
+
async sendGroupAnnouncement(group_id, content, image_uri) {
|
|
609
|
+
return await this.request("/api/send_group_announcement", {
|
|
610
|
+
group_id,
|
|
611
|
+
content,
|
|
612
|
+
image_uri
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
/** 删除群公告 */
|
|
616
|
+
async deleteGroupAnnouncement(group_id, announcement_id) {
|
|
617
|
+
return await this.request("/api/delete_group_announcement", {
|
|
618
|
+
group_id,
|
|
619
|
+
announcement_id
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
/** 获取群精华消息列表 */
|
|
623
|
+
async getGroupEssenceMessages(group_id, page_index, page_size) {
|
|
624
|
+
return await this.request("/api/get_group_essence_messages", {
|
|
625
|
+
group_id,
|
|
626
|
+
page_index,
|
|
627
|
+
page_size
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
/** 设置群精华消息 */
|
|
631
|
+
async setGroupEssenceMessage(group_id, message_seq, is_set) {
|
|
632
|
+
return await this.request("/api/set_group_essence_message", {
|
|
633
|
+
group_id,
|
|
634
|
+
message_seq,
|
|
635
|
+
is_set
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
/** 退出群 */
|
|
639
|
+
async quitGroup(group_id) {
|
|
640
|
+
return await this.request("/api/quit_group", { group_id });
|
|
641
|
+
}
|
|
642
|
+
/** 发送群消息表情回应 */
|
|
643
|
+
async sendGroupMessageReaction(group_id, message_seq, reaction, reaction_type, is_add) {
|
|
644
|
+
return await this.request("/api/send_group_message_reaction", {
|
|
645
|
+
group_id,
|
|
646
|
+
message_seq,
|
|
647
|
+
reaction,
|
|
648
|
+
reaction_type,
|
|
649
|
+
is_add
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
/** 发送群戳一戳 */
|
|
653
|
+
async sendGroupNudge(group_id, user_id) {
|
|
654
|
+
return await this.request("/api/send_group_nudge", {
|
|
655
|
+
group_id,
|
|
656
|
+
user_id
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
/** 获取群通知列表 */
|
|
660
|
+
async getGroupNotifications(start_notification_seq, is_filtered, limit) {
|
|
661
|
+
return await this.request("/api/get_group_notifications", {
|
|
662
|
+
start_notification_seq,
|
|
663
|
+
is_filtered,
|
|
664
|
+
limit
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
/** 同意入群/邀请他人入群请求 */
|
|
668
|
+
async acceptGroupRequest(notification_seq, notification_type, group_id, is_filtered) {
|
|
669
|
+
return await this.request("/api/accept_group_request", {
|
|
670
|
+
notification_seq,
|
|
671
|
+
notification_type,
|
|
672
|
+
group_id,
|
|
673
|
+
is_filtered
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
/** 拒绝入群/邀请他人入群请求 */
|
|
677
|
+
async rejectGroupRequest(notification_seq, notification_type, group_id, is_filtered, reason) {
|
|
678
|
+
return await this.request("/api/reject_group_request", {
|
|
679
|
+
notification_seq,
|
|
680
|
+
notification_type,
|
|
681
|
+
group_id,
|
|
682
|
+
is_filtered,
|
|
683
|
+
reason
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
/** 同意他人邀请自身入群 */
|
|
687
|
+
async acceptGroupInvitation(group_id, invitation_seq) {
|
|
688
|
+
return await this.request("/api/accept_group_invitation", {
|
|
689
|
+
group_id,
|
|
690
|
+
invitation_seq
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
/** 拒绝他人邀请自身入群 */
|
|
694
|
+
async rejectGroupInvitation(group_id, invitation_seq) {
|
|
695
|
+
return await this.request("/api/reject_group_invitation", {
|
|
696
|
+
group_id,
|
|
697
|
+
invitation_seq
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
/** 上传私聊文件 */
|
|
701
|
+
async uploadPrivateFile(user_id, file_uri, file_name) {
|
|
702
|
+
return await this.request("/api/upload_private_file", {
|
|
703
|
+
user_id,
|
|
704
|
+
file_uri,
|
|
705
|
+
file_name
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
/** 上传群文件 */
|
|
709
|
+
async uploadGroupFile(group_id, parent_folder_id, file_uri, file_name) {
|
|
710
|
+
return await this.request("/api/upload_group_file", {
|
|
711
|
+
group_id,
|
|
712
|
+
parent_folder_id,
|
|
713
|
+
file_uri,
|
|
714
|
+
file_name
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
/** 获取私聊文件下载链接 */
|
|
718
|
+
async getPrivateFileDownloadUrl(user_id, file_id, file_hash, is_self_send) {
|
|
719
|
+
return await this.request("/api/get_private_file_download_url", {
|
|
720
|
+
user_id,
|
|
721
|
+
file_id,
|
|
722
|
+
file_hash,
|
|
723
|
+
is_self_send
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
/** 获取群文件下载链接 */
|
|
727
|
+
async getGroupFileDownloadUrl(group_id, file_id) {
|
|
728
|
+
return await this.request("/api/get_group_file_download_url", {
|
|
729
|
+
group_id,
|
|
730
|
+
file_id
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
/** 获取群文件列表 */
|
|
734
|
+
async getGroupFiles(group_id, parent_folder_id) {
|
|
735
|
+
return await this.request("/api/get_group_files", {
|
|
736
|
+
group_id,
|
|
737
|
+
parent_folder_id
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
/** 移动群文件 */
|
|
741
|
+
async moveGroupFile(group_id, file_id, parent_folder_id, target_folder_id) {
|
|
742
|
+
return await this.request("/api/move_group_file", {
|
|
743
|
+
group_id,
|
|
744
|
+
file_id,
|
|
745
|
+
parent_folder_id,
|
|
746
|
+
target_folder_id
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
/** 重命名群文件 */
|
|
750
|
+
async renameGroupFile(group_id, file_id, parent_folder_id, new_file_name) {
|
|
751
|
+
return await this.request("/api/rename_group_file", {
|
|
752
|
+
group_id,
|
|
753
|
+
file_id,
|
|
754
|
+
parent_folder_id,
|
|
755
|
+
new_file_name
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
/** 删除群文件 */
|
|
759
|
+
async deleteGroupFile(group_id, file_id) {
|
|
760
|
+
return await this.request("/api/delete_group_file", {
|
|
761
|
+
group_id,
|
|
762
|
+
file_id
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
/** 转存群文件为永久文件 */
|
|
766
|
+
async persistGroupFile(group_id, file_id) {
|
|
767
|
+
return await this.request("/api/persist_group_file", {
|
|
768
|
+
group_id,
|
|
769
|
+
file_id
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
/** 创建群文件夹 */
|
|
773
|
+
async createGroupFolder(group_id, folder_name) {
|
|
774
|
+
return await this.request("/api/create_group_folder", {
|
|
775
|
+
group_id,
|
|
776
|
+
folder_name
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
/** 重命名群文件夹 */
|
|
780
|
+
async renameGroupFolder(group_id, folder_id, new_folder_name) {
|
|
781
|
+
return await this.request("/api/rename_group_folder", {
|
|
782
|
+
group_id,
|
|
783
|
+
folder_id,
|
|
784
|
+
new_folder_name
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
/** 删除群文件夹 */
|
|
788
|
+
async deleteGroupFolder(group_id, folder_id) {
|
|
789
|
+
return await this.request("/api/delete_group_folder", {
|
|
790
|
+
group_id,
|
|
791
|
+
folder_id
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
// lib/types/ids.js
|
|
796
|
+
/**
|
|
797
|
+
* Identifiers shared by decode, send and the reads.
|
|
798
|
+
*
|
|
799
|
+
* Milky names a conversation by `(message_scene, peer_id)` and a message by `message_seq`, which is only unique inside
|
|
800
|
+
* that conversation. DSH needs ids that are globally unique per bot, readable in logs, and decomposable before a
|
|
801
|
+
* platform call, so both are compound text:
|
|
802
|
+
*
|
|
803
|
+
* - chat: `group:<group_id>` / `private:<user_id>` / `temporary:<user_id>`;
|
|
804
|
+
* - message: `g|f|t:<peer_id>:<message_seq>`;
|
|
805
|
+
* - file part (an upload to the file area, not a message): `g|f|t:<peer_id>:file:<file_id>`.
|
|
806
|
+
*/
|
|
807
|
+
/** Scene letter of a message / file part id. */
|
|
808
|
+
const SCENE_PREFIX = {
|
|
809
|
+
group: "g",
|
|
810
|
+
friend: "f",
|
|
811
|
+
temp: "t"
|
|
812
|
+
};
|
|
813
|
+
const PREFIX_SCENE = {
|
|
814
|
+
g: "group",
|
|
815
|
+
f: "friend",
|
|
816
|
+
t: "temp"
|
|
817
|
+
};
|
|
818
|
+
/** Chat id prefix of a scene. */
|
|
819
|
+
const CHAT_PREFIX = {
|
|
820
|
+
group: "group",
|
|
821
|
+
friend: "private",
|
|
822
|
+
temp: "temporary"
|
|
823
|
+
};
|
|
824
|
+
const CHAT_SCENE = {
|
|
825
|
+
group: "group",
|
|
826
|
+
private: "friend",
|
|
827
|
+
temporary: "temp"
|
|
828
|
+
};
|
|
829
|
+
/** Chat type DSH sees for a scene. */
|
|
830
|
+
function chatTypeOf(scene) {
|
|
831
|
+
return scene === "group" ? "group" : "direct";
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Chat id of one scene and peer.
|
|
835
|
+
* @param scene - Milky message scene.
|
|
836
|
+
* @param peerId - group number or user number.
|
|
837
|
+
* @returns the stable chat id.
|
|
838
|
+
*/
|
|
839
|
+
function chatIdOf(scene, peerId) {
|
|
840
|
+
return `${CHAT_PREFIX[scene]}:${peerId}`;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Split a chat id back into its scene and peer.
|
|
844
|
+
* @param chatId - chat id as this adapter writes it.
|
|
845
|
+
* @returns the parts, or `undefined` for a chat id of another adapter.
|
|
846
|
+
*/
|
|
847
|
+
function decodeChatId(chatId) {
|
|
848
|
+
const match = /^(group|private|temporary):(\d+)$/.exec(chatId);
|
|
849
|
+
if (!match) return;
|
|
850
|
+
const scene = CHAT_SCENE[match[1]];
|
|
851
|
+
const peerId = Number(match[2]);
|
|
852
|
+
if (!Number.isSafeInteger(peerId)) return;
|
|
853
|
+
return {
|
|
854
|
+
scene,
|
|
855
|
+
peerId
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Chat reference of one scene and peer.
|
|
860
|
+
* @param scene - Milky message scene.
|
|
861
|
+
* @param peerId - group number or user number.
|
|
862
|
+
* @param name - chat name, when the event carries one.
|
|
863
|
+
* @returns the chat reference.
|
|
864
|
+
*/
|
|
865
|
+
function chatRefOf(scene, peerId, name) {
|
|
866
|
+
return {
|
|
867
|
+
id: chatIdOf(scene, peerId),
|
|
868
|
+
type: chatTypeOf(scene),
|
|
869
|
+
...name === void 0 || name === "" ? {} : { name }
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Message id of one platform message.
|
|
874
|
+
* @param scene - Milky message scene.
|
|
875
|
+
* @param peerId - group number or user number.
|
|
876
|
+
* @param messageSeq - `message_seq` inside that conversation.
|
|
877
|
+
* @returns the message id.
|
|
878
|
+
*/
|
|
879
|
+
function messageIdOf(scene, peerId, messageSeq) {
|
|
880
|
+
return `${SCENE_PREFIX[scene]}:${peerId}:${messageSeq}`;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Split a message id back into scene, peer and sequence.
|
|
884
|
+
* @param id - message id as this adapter writes it.
|
|
885
|
+
* @returns the parts, or `undefined` when `id` is not a message id (a file part id included).
|
|
886
|
+
*/
|
|
887
|
+
function decodeMessageId(id) {
|
|
888
|
+
const match = /^([gft]):(\d+):(\d+)$/.exec(id);
|
|
889
|
+
if (!match) return;
|
|
890
|
+
const scene = PREFIX_SCENE[match[1]];
|
|
891
|
+
const peerId = Number(match[2]);
|
|
892
|
+
const messageSeq = Number(match[3]);
|
|
893
|
+
if (!Number.isSafeInteger(peerId) || !Number.isSafeInteger(messageSeq)) return;
|
|
894
|
+
return {
|
|
895
|
+
scene,
|
|
896
|
+
peerId,
|
|
897
|
+
messageSeq
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* File part id of one upload to the QQ file area.
|
|
902
|
+
* @param scene - Milky message scene of the chat.
|
|
903
|
+
* @param peerId - group number or user number.
|
|
904
|
+
* @param fileId - platform `file_id` the upload returned.
|
|
905
|
+
* @returns the file part id.
|
|
906
|
+
*/
|
|
907
|
+
function filePartIdOf(scene, peerId, fileId) {
|
|
908
|
+
return `${SCENE_PREFIX[scene]}:${peerId}:file:${fileId}`;
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* Split a file part id back into scene, peer and file id.
|
|
912
|
+
* @param id - part id as this adapter writes it.
|
|
913
|
+
* @returns the parts, or `undefined` when `id` is not a file part id.
|
|
914
|
+
*/
|
|
915
|
+
function decodeFilePartId(id) {
|
|
916
|
+
const match = /^([gft]):(\d+):file:(.+)$/.exec(id);
|
|
917
|
+
if (!match) return;
|
|
918
|
+
return {
|
|
919
|
+
scene: PREFIX_SCENE[match[1]],
|
|
920
|
+
peerId: Number(match[2]),
|
|
921
|
+
fileId: match[3]
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Whether a decomposed id names the given chat.
|
|
926
|
+
* @param scene - scene of the id.
|
|
927
|
+
* @param peerId - peer of the id.
|
|
928
|
+
* @param chat - chat id the caller is sending into.
|
|
929
|
+
* @returns true when they describe the same conversation.
|
|
930
|
+
*/
|
|
931
|
+
function idNamesChat(scene, peerId, chat) {
|
|
932
|
+
return chat !== void 0 && chat.scene === scene && chat.peerId === peerId;
|
|
933
|
+
}
|
|
934
|
+
/** Scene token of the `/files/:scene/:peer/:fileId` internal route. */
|
|
935
|
+
function fileSceneToken(scene) {
|
|
936
|
+
return scene === "group" ? "group" : scene === "friend" ? "private" : "temp";
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Event id of one recall, unique per recalled message.
|
|
940
|
+
* @param scene - scene of the recalled message.
|
|
941
|
+
* @param peerId - peer of the recalled message.
|
|
942
|
+
* @param messageSeq - sequence of the recalled message.
|
|
943
|
+
* @returns the event id.
|
|
944
|
+
*/
|
|
945
|
+
function recallEventId(scene, peerId, messageSeq) {
|
|
946
|
+
return `recall:${SCENE_PREFIX[scene]}:${peerId}:${messageSeq}`;
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* Event id of one reaction change. `isAdd` is part of the key because the same user may add and remove the same
|
|
950
|
+
* reaction more than once.
|
|
951
|
+
*
|
|
952
|
+
* @param groupId - group the reaction happened in.
|
|
953
|
+
* @param messageSeq - reacted message sequence.
|
|
954
|
+
* @param userId - user who reacted.
|
|
955
|
+
* @param reactionType - `face` or `emoji`.
|
|
956
|
+
* @param faceId - reaction id.
|
|
957
|
+
* @param isAdd - whether the reaction was added (`false` = removed).
|
|
958
|
+
* @returns the event id.
|
|
959
|
+
*/
|
|
960
|
+
function reactionEventId(groupId, messageSeq, userId, reactionType, faceId, isAdd) {
|
|
961
|
+
return `reaction:${groupId}:${messageSeq}:${userId}:${reactionType}:${faceId}:${isAdd ? 1 : 0}`;
|
|
962
|
+
}
|
|
963
|
+
// lib/types/modes/text.js
|
|
964
|
+
/**
|
|
965
|
+
* The one `text` mode: a Milky message is a JSON array of segments, so there is no markup dialect to choose between.
|
|
966
|
+
*
|
|
967
|
+
* The mode collects the segments of one logical message. Text, mentions and media ride one `send_*_message` request;
|
|
968
|
+
* a `<file>` cannot be a segment (Milky's `OutgoingSegment` has no file type) and becomes its own draft, uploaded to
|
|
969
|
+
* the QQ file area by `sendPayload`.
|
|
970
|
+
*/
|
|
971
|
+
/** Register `text`, `p` and `br` (the mandatory base tags) plus every element Milky can render natively. */
|
|
972
|
+
function buildRegistry() {
|
|
973
|
+
return new ElementRegistry().register("text", (el) => ({
|
|
974
|
+
type: "text",
|
|
975
|
+
text: el.attrs.content
|
|
976
|
+
})).register("p", (el, ctx) => [...ctx.render(el.children), {
|
|
977
|
+
type: "text",
|
|
978
|
+
text: "\n"
|
|
979
|
+
}]).register("br", () => ({
|
|
980
|
+
type: "text",
|
|
981
|
+
text: "\n"
|
|
982
|
+
})).register("at", (el) => {
|
|
983
|
+
const type = el.attrs.type ?? "user";
|
|
984
|
+
const { id, name } = el.attrs;
|
|
985
|
+
if (type === "all") return { type: "mention_all" };
|
|
986
|
+
if (type === "user" && id !== void 0 && /^\d+$/.test(id)) return {
|
|
987
|
+
type: "mention",
|
|
988
|
+
userId: id
|
|
989
|
+
};
|
|
990
|
+
return {
|
|
991
|
+
type: "text",
|
|
992
|
+
text: `@${name ?? id ?? type}`
|
|
993
|
+
};
|
|
994
|
+
}, { variants: ["user", "all"] }).register("img", (el, ctx) => ({
|
|
995
|
+
type: "media",
|
|
996
|
+
kind: "image",
|
|
997
|
+
ref: ctx.resource("image", el.attrs.src, {
|
|
998
|
+
...el.attrs.width === void 0 ? {} : { width: el.attrs.width },
|
|
999
|
+
...el.attrs.height === void 0 ? {} : { height: el.attrs.height }
|
|
1000
|
+
})
|
|
1001
|
+
}), { variants: ["inline"] }).register("audio", (el, ctx) => ({
|
|
1002
|
+
type: "media",
|
|
1003
|
+
kind: "record",
|
|
1004
|
+
ref: ctx.resource("audio", el.attrs.src, {
|
|
1005
|
+
...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration },
|
|
1006
|
+
...el.attrs.name === void 0 ? {} : { name: el.attrs.name }
|
|
1007
|
+
})
|
|
1008
|
+
})).register("video", (el, ctx) => ({
|
|
1009
|
+
type: "media",
|
|
1010
|
+
kind: "video",
|
|
1011
|
+
ref: ctx.resource("video", el.attrs.src, {
|
|
1012
|
+
...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration },
|
|
1013
|
+
...el.attrs.name === void 0 ? {} : { name: el.attrs.name }
|
|
1014
|
+
})
|
|
1015
|
+
})).register("file", (el, ctx) => ({
|
|
1016
|
+
type: "file",
|
|
1017
|
+
ref: ctx.resource("file", el.attrs.src, { ...el.attrs.name === void 0 ? {} : { name: el.attrs.name } })
|
|
1018
|
+
})).fallback("a", (el) => [...el.children, `(${el.attrs.href})`]);
|
|
1019
|
+
}
|
|
1020
|
+
/** Strip leading and trailing newlines of the message text (a `p` always ends with one) and drop empty text nodes. */
|
|
1021
|
+
function trimMessage(draft) {
|
|
1022
|
+
const first = draft.segments[0];
|
|
1023
|
+
if (first?.type === "text") first.text = first.text.replace(/^\n+/, "");
|
|
1024
|
+
const last = draft.segments[draft.segments.length - 1];
|
|
1025
|
+
if (last?.type === "text") last.text = last.text.replace(/\n+$/, "");
|
|
1026
|
+
for (let index = draft.segments.length - 1; index >= 0; index--) {
|
|
1027
|
+
const node = draft.segments[index];
|
|
1028
|
+
if (node.type === "text" && node.text === "") draft.segments.splice(index, 1);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* Build the `text` mode.
|
|
1033
|
+
* @returns the mode (registered under `text`).
|
|
1034
|
+
*/
|
|
1035
|
+
function createMilkyTextMode() {
|
|
1036
|
+
return defineMode()({
|
|
1037
|
+
id: "text",
|
|
1038
|
+
elements: buildRegistry(),
|
|
1039
|
+
limits: { "limit.message.parts": 1 },
|
|
1040
|
+
assemble: (nodes, envelope, ctx) => {
|
|
1041
|
+
const drafts = [];
|
|
1042
|
+
const state = {};
|
|
1043
|
+
const messageDraft = () => {
|
|
1044
|
+
if (state.message === void 0) {
|
|
1045
|
+
const draft = {
|
|
1046
|
+
kind: "message",
|
|
1047
|
+
segments: []
|
|
1048
|
+
};
|
|
1049
|
+
state.message = draft;
|
|
1050
|
+
drafts.push(draft);
|
|
1051
|
+
}
|
|
1052
|
+
return state.message;
|
|
1053
|
+
};
|
|
1054
|
+
for (const node of nodes) {
|
|
1055
|
+
if (node.type === "file") {
|
|
1056
|
+
drafts.push({
|
|
1057
|
+
kind: "file",
|
|
1058
|
+
ref: node.ref,
|
|
1059
|
+
name: node.ref.meta.name ?? "file"
|
|
1060
|
+
});
|
|
1061
|
+
continue;
|
|
1062
|
+
}
|
|
1063
|
+
const draft = messageDraft();
|
|
1064
|
+
if (node.type === "text") {
|
|
1065
|
+
const last = draft.segments[draft.segments.length - 1];
|
|
1066
|
+
if (last?.type === "text") last.text += node.text;
|
|
1067
|
+
else draft.segments.push({ ...node });
|
|
1068
|
+
} else draft.segments.push(node);
|
|
1069
|
+
}
|
|
1070
|
+
const message = state.message;
|
|
1071
|
+
if (message !== void 0) trimMessage(message);
|
|
1072
|
+
attachQuote(state.message, envelope.quote, ctx);
|
|
1073
|
+
if (drafts.length === 0) drafts.push({
|
|
1074
|
+
kind: "message",
|
|
1075
|
+
segments: []
|
|
1076
|
+
});
|
|
1077
|
+
return drafts;
|
|
1078
|
+
},
|
|
1079
|
+
serialize: (prepared, ctx) => serializeDraft(prepared, ctx),
|
|
1080
|
+
check: (draft) => {
|
|
1081
|
+
if (draft.kind === "file") return [];
|
|
1082
|
+
if (draft.segments.length > 0) return [];
|
|
1083
|
+
return [{
|
|
1084
|
+
kind: "size",
|
|
1085
|
+
key: "limit.elements",
|
|
1086
|
+
limit: 1,
|
|
1087
|
+
actual: 0,
|
|
1088
|
+
message: "milky: empty message"
|
|
1089
|
+
}];
|
|
1090
|
+
}
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Decide what happens to an envelope `<quote id>`.
|
|
1095
|
+
*
|
|
1096
|
+
* A quote that parses as a Milky message id or a file part id is kept for {@link serializeDraft}, which owns the
|
|
1097
|
+
* chat-membership check and its precise refusal (a quote of another conversation, or a file part that has no
|
|
1098
|
+
* sequence, must not be sent here). A quote that is neither cannot have been published by this adapter, so the reply
|
|
1099
|
+
* is dropped and reported — the content still sends, and a `strict` send rejects the report.
|
|
1100
|
+
*
|
|
1101
|
+
* @param message - the segment draft that would carry the reply, if the content produced one.
|
|
1102
|
+
* @param quote - the quoted platform message id.
|
|
1103
|
+
* @param ctx - render context (target chat and report).
|
|
1104
|
+
*/
|
|
1105
|
+
function attachQuote(message, quote, ctx) {
|
|
1106
|
+
if (quote === void 0) return;
|
|
1107
|
+
if (message === void 0) {
|
|
1108
|
+
ctx.report.dropped.push({
|
|
1109
|
+
what: "quote",
|
|
1110
|
+
reason: "milky-file-only"
|
|
1111
|
+
});
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
if (decodeMessageId(quote) === void 0 && decodeFilePartId(quote) === void 0) {
|
|
1115
|
+
ctx.report.dropped.push({
|
|
1116
|
+
what: "quote",
|
|
1117
|
+
reason: "milky-quote-unparseable"
|
|
1118
|
+
});
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
message.replyTo = quote;
|
|
1122
|
+
}
|
|
1123
|
+
/** Resolved URI of one resource; a draft reaching serialize unprepared is an adapter bug. */
|
|
1124
|
+
function resolvedKey(prepared, ref) {
|
|
1125
|
+
const resolved = prepared.resolved.get(ref);
|
|
1126
|
+
if (resolved === void 0) throw new PlatformError("invalid", `milky: ${ref.kind} "${ref.src}" was not prepared before serialize`, { published: "no" });
|
|
1127
|
+
return resolved.key;
|
|
1128
|
+
}
|
|
1129
|
+
/** Sequence of the quoted message, which must belong to the chat the payload goes to. */
|
|
1130
|
+
function replySeqOf(replyTo, chatId) {
|
|
1131
|
+
if (decodeFilePartId(replyTo) !== void 0) throw new PlatformError("invalid", `milky: "${replyTo}" is a file part id, not a message, and cannot be quoted`, { published: "no" });
|
|
1132
|
+
const decoded = decodeMessageId(replyTo);
|
|
1133
|
+
const chat = decodeChatId(chatId);
|
|
1134
|
+
if (decoded === void 0 || !idNamesChat(decoded.scene, decoded.peerId, chat)) throw new PlatformError("invalid", `milky: quoted message "${replyTo}" is not a message of chat "${chatId}" and cannot be answered here`, { published: "no" });
|
|
1135
|
+
return decoded.messageSeq;
|
|
1136
|
+
}
|
|
1137
|
+
/** One node → its outgoing segment; media take their prepared URI. */
|
|
1138
|
+
function segmentOf(prepared, node) {
|
|
1139
|
+
switch (node.type) {
|
|
1140
|
+
case "text": return {
|
|
1141
|
+
type: "text",
|
|
1142
|
+
data: { text: node.text }
|
|
1143
|
+
};
|
|
1144
|
+
case "mention": return {
|
|
1145
|
+
type: "mention",
|
|
1146
|
+
data: { user_id: Number(node.userId) }
|
|
1147
|
+
};
|
|
1148
|
+
case "mention_all": return {
|
|
1149
|
+
type: "mention_all",
|
|
1150
|
+
data: {}
|
|
1151
|
+
};
|
|
1152
|
+
case "media": {
|
|
1153
|
+
const uri = resolvedKey(prepared, node.ref);
|
|
1154
|
+
switch (node.kind) {
|
|
1155
|
+
case "image": return {
|
|
1156
|
+
type: "image",
|
|
1157
|
+
data: {
|
|
1158
|
+
uri,
|
|
1159
|
+
sub_type: "normal"
|
|
1160
|
+
}
|
|
1161
|
+
};
|
|
1162
|
+
case "record": return {
|
|
1163
|
+
type: "record",
|
|
1164
|
+
data: { uri }
|
|
1165
|
+
};
|
|
1166
|
+
case "video": return {
|
|
1167
|
+
type: "video",
|
|
1168
|
+
data: { uri }
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
case "file": throw new PlatformError("invalid", "milky: a file cannot ride a message segment", { published: "no" });
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
/** Name an uploaded file: the element's `name`, else the fetched name recorded by `upload`, else `file`. */
|
|
1176
|
+
function fileNameOf(prepared, ref) {
|
|
1177
|
+
const name = ref.meta.name;
|
|
1178
|
+
if (name !== void 0 && name !== "") return name;
|
|
1179
|
+
const extra = prepared.resolved.get(ref)?.extra;
|
|
1180
|
+
if (extra && typeof extra === "object" && "name" in extra) {
|
|
1181
|
+
const fetched = extra.name;
|
|
1182
|
+
if (typeof fetched === "string" && fetched !== "") return fetched;
|
|
1183
|
+
}
|
|
1184
|
+
return "file";
|
|
1185
|
+
}
|
|
1186
|
+
/** Serialize one prepared draft into the exact request body. */
|
|
1187
|
+
function serializeDraft(prepared, ctx) {
|
|
1188
|
+
const { draft } = prepared;
|
|
1189
|
+
const chatId = ctx.target.chat.id;
|
|
1190
|
+
if (draft.kind === "file") return {
|
|
1191
|
+
kind: "file",
|
|
1192
|
+
chatId,
|
|
1193
|
+
uri: resolvedKey(prepared, draft.ref),
|
|
1194
|
+
name: fileNameOf(prepared, draft.ref)
|
|
1195
|
+
};
|
|
1196
|
+
const segments = [];
|
|
1197
|
+
if (draft.replyTo !== void 0) segments.push({
|
|
1198
|
+
type: "reply",
|
|
1199
|
+
data: { message_seq: replySeqOf(draft.replyTo, chatId) }
|
|
1200
|
+
});
|
|
1201
|
+
for (const node of draft.segments) segments.push(segmentOf(prepared, node));
|
|
1202
|
+
return {
|
|
1203
|
+
kind: "message",
|
|
1204
|
+
chatId,
|
|
1205
|
+
segments
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
// lib/types/decode.js
|
|
1209
|
+
/**
|
|
1210
|
+
* Inbound decoding: one Milky event or message becomes a DSH session without any platform I/O.
|
|
1211
|
+
*
|
|
1212
|
+
* Media never carries bytes or a `temp_url` into the session: both expire, so a segment decodes to a `satori:` route
|
|
1213
|
+
* of this bot (`/resources/:resourceId`, `/files/:scene/:peer/:fileId`) that the host fetches when it needs the bytes.
|
|
1214
|
+
*/
|
|
1215
|
+
/**
|
|
1216
|
+
* Decode one event frame into a session.
|
|
1217
|
+
*
|
|
1218
|
+
* Only `message_receive`, `message_recall` and `group_message_reaction` have DSH consumers; every other event is left
|
|
1219
|
+
* for the transport to log at debug level.
|
|
1220
|
+
*
|
|
1221
|
+
* @param bot - receiving bot (`selfId` decides `mentions.self`, the platform prefix names internal routes).
|
|
1222
|
+
* @param event - one decoded protocol event.
|
|
1223
|
+
* @returns the session, or `undefined` for an event this adapter does not surface.
|
|
1224
|
+
*/
|
|
1225
|
+
function decodeFrame(bot, event) {
|
|
1226
|
+
switch (event.event_type) {
|
|
1227
|
+
case "message_receive": {
|
|
1228
|
+
const message = decodeMessage(bot, event.data);
|
|
1229
|
+
return bot.session({
|
|
1230
|
+
type: "message",
|
|
1231
|
+
id: message.id,
|
|
1232
|
+
timestamp: message.time,
|
|
1233
|
+
message
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
case "message_recall": {
|
|
1237
|
+
const { message_scene, peer_id, message_seq, operator_id } = event.data;
|
|
1238
|
+
return bot.session({
|
|
1239
|
+
type: "message-deleted",
|
|
1240
|
+
id: recallEventId(message_scene, peer_id, message_seq),
|
|
1241
|
+
timestamp: event.time * 1e3,
|
|
1242
|
+
deleted: {
|
|
1243
|
+
id: messageIdOf(message_scene, peer_id, message_seq),
|
|
1244
|
+
chat: chatRefOf(message_scene, peer_id),
|
|
1245
|
+
operator: { id: String(operator_id) }
|
|
1246
|
+
}
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
1249
|
+
case "group_message_reaction": {
|
|
1250
|
+
const { group_id, message_seq, user_id, reaction_type, face_id, is_add } = event.data;
|
|
1251
|
+
return bot.session({
|
|
1252
|
+
type: is_add ? "reaction-added" : "reaction-removed",
|
|
1253
|
+
id: reactionEventId(group_id, message_seq, user_id, reaction_type, face_id, is_add),
|
|
1254
|
+
timestamp: event.time * 1e3,
|
|
1255
|
+
reaction: {
|
|
1256
|
+
message: {
|
|
1257
|
+
id: messageIdOf("group", group_id, message_seq),
|
|
1258
|
+
chat: chatRefOf("group", group_id)
|
|
1259
|
+
},
|
|
1260
|
+
emoji: `${reaction_type}|${face_id}`,
|
|
1261
|
+
user: { id: String(user_id) }
|
|
1262
|
+
}
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
default: return;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Decode one received message.
|
|
1270
|
+
*
|
|
1271
|
+
* @param bot - receiving bot.
|
|
1272
|
+
* @param input - `IncomingMessage` of the event (or of a `get_message` answer).
|
|
1273
|
+
* @returns the inbound message; its content is never empty.
|
|
1274
|
+
*/
|
|
1275
|
+
function decodeMessage(bot, input) {
|
|
1276
|
+
const scene = input.message_scene;
|
|
1277
|
+
const chat = chatOf$1(input);
|
|
1278
|
+
const segments = input.segments;
|
|
1279
|
+
const mentions = {
|
|
1280
|
+
self: false,
|
|
1281
|
+
all: false,
|
|
1282
|
+
users: []
|
|
1283
|
+
};
|
|
1284
|
+
const nodes = [];
|
|
1285
|
+
let quote;
|
|
1286
|
+
for (const segment of segments) {
|
|
1287
|
+
if (segment.type === "reply") {
|
|
1288
|
+
quote = decodeQuote(bot, input, segment.data);
|
|
1289
|
+
continue;
|
|
1290
|
+
}
|
|
1291
|
+
nodes.push(...segmentNodes(bot, scene, input.peer_id, segment, mentions, "element"));
|
|
1292
|
+
}
|
|
1293
|
+
return {
|
|
1294
|
+
id: messageIdOf(scene, input.peer_id, input.message_seq),
|
|
1295
|
+
chat,
|
|
1296
|
+
sender: senderOf(input),
|
|
1297
|
+
content: decodeContent(input, nodes),
|
|
1298
|
+
mentions,
|
|
1299
|
+
time: input.time * 1e3,
|
|
1300
|
+
referrer: referrerOf(input),
|
|
1301
|
+
...quote === void 0 ? {} : { quote }
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
/** The chat a message names (`group:…` / `private:…` / `temporary:…`), with its display name when the event has one. */
|
|
1305
|
+
function chatOf$1(input) {
|
|
1306
|
+
switch (input.message_scene) {
|
|
1307
|
+
case "group": return chatRefOf("group", input.peer_id, input.group.group_name);
|
|
1308
|
+
case "friend": return chatRefOf("friend", input.peer_id, input.friend.nickname);
|
|
1309
|
+
case "temp": return chatRefOf("temp", input.peer_id);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
/** The sender, with the group card preferred over the account nickname and the group role when known. */
|
|
1313
|
+
function senderOf(input) {
|
|
1314
|
+
const id = String(input.sender_id);
|
|
1315
|
+
switch (input.message_scene) {
|
|
1316
|
+
case "group": {
|
|
1317
|
+
const member = input.group_member;
|
|
1318
|
+
const name = member.card || member.nickname;
|
|
1319
|
+
return {
|
|
1320
|
+
id,
|
|
1321
|
+
...name === "" ? {} : { name },
|
|
1322
|
+
role: member.role
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
case "friend": {
|
|
1326
|
+
const name = input.friend.nickname;
|
|
1327
|
+
return {
|
|
1328
|
+
id,
|
|
1329
|
+
...name === "" ? {} : { name }
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
case "temp": return { id };
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
/** The reply context: the quoted message is always in the same conversation as the reply. */
|
|
1336
|
+
function referrerOf(input) {
|
|
1337
|
+
return {
|
|
1338
|
+
scene: input.message_scene,
|
|
1339
|
+
peerId: input.peer_id,
|
|
1340
|
+
messageSeq: input.message_seq,
|
|
1341
|
+
senderId: input.sender_id,
|
|
1342
|
+
time: input.time
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Normalize the decoded segments, falling back to the raw payload when nothing rendered.
|
|
1347
|
+
*
|
|
1348
|
+
* @param input - the message the segments belong to.
|
|
1349
|
+
* @param nodes - nodes the segment decoder produced.
|
|
1350
|
+
* @returns non-empty content.
|
|
1351
|
+
*/
|
|
1352
|
+
function decodeContent(input, nodes) {
|
|
1353
|
+
const content = normalize(nodes);
|
|
1354
|
+
if (content.children.length > 0) return content;
|
|
1355
|
+
return normalize([h("raw", {
|
|
1356
|
+
platform: "milky",
|
|
1357
|
+
type: "message",
|
|
1358
|
+
data: input
|
|
1359
|
+
})]);
|
|
1360
|
+
}
|
|
1361
|
+
/** One `reply` segment → the quoted message; its `segments` are used when the endpoint sent them (Milky ≥ 1.2). */
|
|
1362
|
+
function decodeQuote(bot, input, data) {
|
|
1363
|
+
const id = messageIdOf(input.message_scene, input.peer_id, data.message_seq);
|
|
1364
|
+
const sender = {
|
|
1365
|
+
id: String(data.sender_id),
|
|
1366
|
+
...data.sender_name === void 0 || data.sender_name === null || data.sender_name === "" ? {} : { name: data.sender_name }
|
|
1367
|
+
};
|
|
1368
|
+
const segments = data.segments;
|
|
1369
|
+
if (!Array.isArray(segments) || segments.length === 0) return {
|
|
1370
|
+
id,
|
|
1371
|
+
sender
|
|
1372
|
+
};
|
|
1373
|
+
const mentions = {
|
|
1374
|
+
self: false,
|
|
1375
|
+
all: false,
|
|
1376
|
+
users: []
|
|
1377
|
+
};
|
|
1378
|
+
const nodes = [];
|
|
1379
|
+
for (const segment of segments) {
|
|
1380
|
+
if (segment.type === "reply") continue;
|
|
1381
|
+
nodes.push(...segmentNodes(bot, input.message_scene, input.peer_id, segment, mentions, "element"));
|
|
1382
|
+
}
|
|
1383
|
+
const content = normalize(nodes);
|
|
1384
|
+
if (content.children.length === 0) return {
|
|
1385
|
+
id,
|
|
1386
|
+
sender
|
|
1387
|
+
};
|
|
1388
|
+
return {
|
|
1389
|
+
id,
|
|
1390
|
+
sender,
|
|
1391
|
+
content
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Map one segment to elements.
|
|
1396
|
+
*
|
|
1397
|
+
* @param bot - receiving bot, used for internal media routes and `mentions.self`.
|
|
1398
|
+
* @param scene - scene of the message the segment belongs to.
|
|
1399
|
+
* @param peerId - peer of that message.
|
|
1400
|
+
* @param segment - one incoming segment.
|
|
1401
|
+
* @param mentions - accumulator of the message's mention facts.
|
|
1402
|
+
* @param forwardStyle - how a merged forward segment renders.
|
|
1403
|
+
* @returns the elements of the segment (possibly none).
|
|
1404
|
+
*/
|
|
1405
|
+
function segmentNodes(bot, scene, peerId, segment, mentions, forwardStyle) {
|
|
1406
|
+
switch (segment.type) {
|
|
1407
|
+
case "text": return [h("text", { content: segment.data.text })];
|
|
1408
|
+
case "mention": {
|
|
1409
|
+
const id = String(segment.data.user_id);
|
|
1410
|
+
const name = segment.data.name;
|
|
1411
|
+
if (!mentions.users.some((user) => user.id === id)) mentions.users.push({
|
|
1412
|
+
id,
|
|
1413
|
+
...name === "" ? {} : { name }
|
|
1414
|
+
});
|
|
1415
|
+
if (id === bot.selfId) mentions.self = true;
|
|
1416
|
+
return [h("at", {
|
|
1417
|
+
type: "user",
|
|
1418
|
+
id,
|
|
1419
|
+
...name === "" ? {} : { name }
|
|
1420
|
+
})];
|
|
1421
|
+
}
|
|
1422
|
+
case "mention_all":
|
|
1423
|
+
mentions.all = true;
|
|
1424
|
+
return [h("at", { type: "all" })];
|
|
1425
|
+
case "image": return [h("img", {
|
|
1426
|
+
src: resourceRoute(bot, segment.data.resource_id),
|
|
1427
|
+
width: segment.data.width,
|
|
1428
|
+
height: segment.data.height
|
|
1429
|
+
})];
|
|
1430
|
+
case "record": return [h("audio", {
|
|
1431
|
+
src: resourceRoute(bot, segment.data.resource_id),
|
|
1432
|
+
duration: segment.data.duration
|
|
1433
|
+
})];
|
|
1434
|
+
case "video": return [h("video", {
|
|
1435
|
+
src: resourceRoute(bot, segment.data.resource_id),
|
|
1436
|
+
duration: segment.data.duration
|
|
1437
|
+
})];
|
|
1438
|
+
case "file": return [fileElement(bot, scene, peerId, segment.data)];
|
|
1439
|
+
case "face": return [h("emoji", {
|
|
1440
|
+
id: segment.data.face_id,
|
|
1441
|
+
name: "[表情]"
|
|
1442
|
+
})];
|
|
1443
|
+
case "market_face": return segment.data.url === "" ? [h("text", { content: "[表情]" })] : [h("img", { src: segment.data.url })];
|
|
1444
|
+
case "forward": return forwardStyle === "text" ? [h("text", { content: `[合并转发 #${segment.data.forward_id}]` })] : [h("forward", { id: segment.data.forward_id })];
|
|
1445
|
+
case "light_app": return [h("raw", {
|
|
1446
|
+
platform: "milky",
|
|
1447
|
+
type: "light_app",
|
|
1448
|
+
data: segment.data
|
|
1449
|
+
})];
|
|
1450
|
+
case "xml": return [h("raw", {
|
|
1451
|
+
platform: "milky",
|
|
1452
|
+
type: "xml",
|
|
1453
|
+
data: segment.data
|
|
1454
|
+
})];
|
|
1455
|
+
case "markdown": return [h("text", { content: segment.data.content })];
|
|
1456
|
+
default: {
|
|
1457
|
+
const unknown = segment;
|
|
1458
|
+
const type = typeof unknown.type === "string" ? unknown.type : "unknown";
|
|
1459
|
+
return [h("text", { content: `[不支持的${type}消息]` })];
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
/** Internal route of one message resource (`resource_id` is stable; `temp_url` is not). */
|
|
1464
|
+
function resourceRoute(bot, resourceId) {
|
|
1465
|
+
return bot.getInternalUrl(`/resources/${encodeURIComponent(resourceId)}`);
|
|
1466
|
+
}
|
|
1467
|
+
/** An inbound file, routed through the `/files/:scene/:peer/:fileId` internal route (with its hash when private). */
|
|
1468
|
+
function fileElement(bot, scene, peerId, data) {
|
|
1469
|
+
const hash = data.file_hash;
|
|
1470
|
+
return h("file", {
|
|
1471
|
+
src: bot.getInternalUrl(`/files/${fileSceneToken(scene)}/${peerId}/${encodeURIComponent(data.file_id)}`, hash === void 0 || hash === null || hash === "" ? void 0 : { hash }),
|
|
1472
|
+
name: data.file_name
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
// lib/types/reads.js
|
|
1476
|
+
/**
|
|
1477
|
+
* The read surface: members, one message by id (with merged forwards expanded) and group reactions.
|
|
1478
|
+
*
|
|
1479
|
+
* These are the only platform reads the adapter performs on request; inbound decoding itself does none.
|
|
1480
|
+
*/
|
|
1481
|
+
/**
|
|
1482
|
+
* One page of the people a chat lists as its members.
|
|
1483
|
+
*
|
|
1484
|
+
* Milky's member API has no paging parameters, so the cursor is the adapter's own index into the full list; a private
|
|
1485
|
+
* chat lists its single peer.
|
|
1486
|
+
*
|
|
1487
|
+
* @param internal - platform API client.
|
|
1488
|
+
* @param chat - chat to list.
|
|
1489
|
+
* @param cursor - `next` of the previous page.
|
|
1490
|
+
* @param limit - page-size hint from the host.
|
|
1491
|
+
* @returns one page.
|
|
1492
|
+
* @throws PlatformError `invalid` for a chat id this adapter did not write or a cursor that is not an index.
|
|
1493
|
+
*/
|
|
1494
|
+
async function members(internal, chat, cursor, limit) {
|
|
1495
|
+
const decoded = decodeChatId(chat.id);
|
|
1496
|
+
if (decoded === void 0) throw new PlatformError("invalid", `milky: "${chat.id}" is not a milky chat id`);
|
|
1497
|
+
const offset = cursor === void 0 ? 0 : Number(cursor);
|
|
1498
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new PlatformError("invalid", `milky: "${cursor}" is not a member-list cursor of chat "${chat.id}"`);
|
|
1499
|
+
if (decoded.scene !== "group") {
|
|
1500
|
+
if (offset > 0) return { data: [] };
|
|
1501
|
+
const name = (await internal.getUserProfile(decoded.peerId))?.nickname;
|
|
1502
|
+
return { data: [{
|
|
1503
|
+
id: String(decoded.peerId),
|
|
1504
|
+
...name === void 0 || name === "" ? {} : { name }
|
|
1505
|
+
}] };
|
|
1506
|
+
}
|
|
1507
|
+
const result = await internal.getGroupMemberList(decoded.peerId);
|
|
1508
|
+
const list = Array.isArray(result?.members) ? result.members : [];
|
|
1509
|
+
const size = limit === void 0 || limit <= 0 ? list.length : limit;
|
|
1510
|
+
const data = list.slice(offset, offset + size).map((member) => ({
|
|
1511
|
+
id: String(member.user_id),
|
|
1512
|
+
name: member.card || member.nickname,
|
|
1513
|
+
role: member.role
|
|
1514
|
+
}));
|
|
1515
|
+
const next = offset + size < list.length ? String(offset + size) : void 0;
|
|
1516
|
+
return {
|
|
1517
|
+
data,
|
|
1518
|
+
...next === void 0 ? {} : { next }
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* Read one message by id.
|
|
1523
|
+
*
|
|
1524
|
+
* @param bot - bot whose platform prefix names internal media routes.
|
|
1525
|
+
* @param chat - the chat the caller asked about; the id must belong to it.
|
|
1526
|
+
* @param id - platform message id (`g|f|t:<peer>:<seq>`).
|
|
1527
|
+
* @returns the message, with merged-forward entries expanded.
|
|
1528
|
+
* @throws PlatformError `invalid` for an id of another chat or a file part id (those carry no `message_seq`).
|
|
1529
|
+
*/
|
|
1530
|
+
async function getMessage(bot, chat, id) {
|
|
1531
|
+
const decoded = decodeMessageId(id);
|
|
1532
|
+
const target = decodeChatId(chat.id);
|
|
1533
|
+
if (decoded === void 0 || !idNamesChat(decoded.scene, decoded.peerId, target)) throw new PlatformError("invalid", `milky: "${id}" is not a message of chat "${chat.id}" and cannot be read there`);
|
|
1534
|
+
const input = (await bot.internal.getMessage(decoded.scene, decoded.peerId, decoded.messageSeq))?.message;
|
|
1535
|
+
if (input === void 0 || input === null) throw new PlatformError("invalid", `milky: get_message answered without a message for "${id}"`);
|
|
1536
|
+
const message = decodeMessage(bot, input);
|
|
1537
|
+
if (message.chat.id !== chat.id) throw new PlatformError("invalid", `milky: "${id}" belongs to chat "${message.chat.id}", not "${chat.id}"`);
|
|
1538
|
+
await expandForward(bot, message);
|
|
1539
|
+
return message;
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* Fill the entries of a root merged-forward placeholder.
|
|
1543
|
+
*
|
|
1544
|
+
* A `<forward>` from decoding carries only its id; only a platform read knows the entries, so the host asks for the
|
|
1545
|
+
* expansion when it needs the content (`im_read`). Entries become one text line each; a nested forward stays a
|
|
1546
|
+
* `[合并转发 #id]` placeholder so one read cannot fan out without bound.
|
|
1547
|
+
*
|
|
1548
|
+
* @param bot - platform API client of the reading bot.
|
|
1549
|
+
* @param message - the message whose forward placeholder to expand.
|
|
1550
|
+
*/
|
|
1551
|
+
async function expandForward(bot, message) {
|
|
1552
|
+
const forward = message.content.children.find((el) => el.type === "forward" && el.children.length === 0);
|
|
1553
|
+
if (forward === void 0) return;
|
|
1554
|
+
const result = await bot.internal.getForwardedMessages(forward.attrs.id);
|
|
1555
|
+
const entries = Array.isArray(result?.messages) ? result.messages : [];
|
|
1556
|
+
const children = [];
|
|
1557
|
+
entries.forEach((entry, index) => {
|
|
1558
|
+
if (index > 0) children.push(h("br"));
|
|
1559
|
+
const text = forwardedText(entry.segments);
|
|
1560
|
+
children.push(h("text", { content: `${entry.sender_name}: ${text}` }));
|
|
1561
|
+
});
|
|
1562
|
+
forward.children = children;
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Inline text of one forwarded entry: blocks flattened into one line, media and nested forwards as placeholders.
|
|
1566
|
+
* @param segments - segments of the forwarded message.
|
|
1567
|
+
* @returns its text, without line breaks.
|
|
1568
|
+
*/
|
|
1569
|
+
function forwardedText(segments) {
|
|
1570
|
+
const parts = [];
|
|
1571
|
+
for (const segment of segments) switch (segment.type) {
|
|
1572
|
+
case "text":
|
|
1573
|
+
parts.push(segment.data.text);
|
|
1574
|
+
break;
|
|
1575
|
+
case "mention":
|
|
1576
|
+
parts.push(`@${segment.data.name}`);
|
|
1577
|
+
break;
|
|
1578
|
+
case "mention_all":
|
|
1579
|
+
parts.push("@全体");
|
|
1580
|
+
break;
|
|
1581
|
+
case "face":
|
|
1582
|
+
case "market_face":
|
|
1583
|
+
parts.push("[表情]");
|
|
1584
|
+
break;
|
|
1585
|
+
case "image":
|
|
1586
|
+
parts.push("[图片]");
|
|
1587
|
+
break;
|
|
1588
|
+
case "record":
|
|
1589
|
+
parts.push("[语音]");
|
|
1590
|
+
break;
|
|
1591
|
+
case "video":
|
|
1592
|
+
parts.push("[视频]");
|
|
1593
|
+
break;
|
|
1594
|
+
case "file":
|
|
1595
|
+
parts.push(`[文件${segment.data.file_name === "" ? "" : `: ${segment.data.file_name}`}]`);
|
|
1596
|
+
break;
|
|
1597
|
+
case "forward":
|
|
1598
|
+
parts.push(`[合并转发 #${segment.data.forward_id}]`);
|
|
1599
|
+
break;
|
|
1600
|
+
case "light_app":
|
|
1601
|
+
parts.push(`[小程序${segment.data.app_name === "" ? "" : `: ${segment.data.app_name}`}]`);
|
|
1602
|
+
break;
|
|
1603
|
+
case "xml":
|
|
1604
|
+
parts.push("[XML 消息]");
|
|
1605
|
+
break;
|
|
1606
|
+
case "markdown":
|
|
1607
|
+
parts.push(segment.data.content);
|
|
1608
|
+
break;
|
|
1609
|
+
case "reply": break;
|
|
1610
|
+
default: {
|
|
1611
|
+
const unknown = segment;
|
|
1612
|
+
const type = typeof unknown.type === "string" ? unknown.type : "unknown";
|
|
1613
|
+
parts.push(`[不支持的${type}消息]`);
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
return parts.join("").replace(/\s+/g, " ").trim();
|
|
1617
|
+
}
|
|
1618
|
+
/** The group and sequence one reaction targets, refusing anything that is not a group message of this chat. */
|
|
1619
|
+
function reactionTarget(message) {
|
|
1620
|
+
const decoded = decodeMessageId(message.id);
|
|
1621
|
+
const chat = decodeChatId(message.chat.id);
|
|
1622
|
+
if (message.chat.type !== "group" || chat?.scene !== "group") throw new PlatformError("invalid", "milky: reactions are only available in group chats", { published: "no" });
|
|
1623
|
+
if (decoded === void 0 || decoded.scene !== "group" || !idNamesChat(decoded.scene, decoded.peerId, chat)) throw new PlatformError("invalid", `milky: "${message.id}" is not a message of group "${message.chat.id}"`, { published: "no" });
|
|
1624
|
+
return {
|
|
1625
|
+
groupId: chat.peerId,
|
|
1626
|
+
messageSeq: decoded.messageSeq
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Parse the adapter's `<reaction_type>|<reaction_id>` reaction encoding; a bare value is a QQ face id.
|
|
1631
|
+
* @param emoji - reaction the host asked for.
|
|
1632
|
+
* @returns the protocol reaction type and id.
|
|
1633
|
+
* @throws PlatformError `invalid` for an unknown reaction type prefix.
|
|
1634
|
+
*/
|
|
1635
|
+
function parseReaction(emoji) {
|
|
1636
|
+
const index = emoji.indexOf("|");
|
|
1637
|
+
if (index < 0) return {
|
|
1638
|
+
type: "face",
|
|
1639
|
+
id: emoji
|
|
1640
|
+
};
|
|
1641
|
+
const type = emoji.slice(0, index);
|
|
1642
|
+
if (type !== "face" && type !== "emoji") throw new PlatformError("invalid", `milky: "${emoji}" does not name a reaction type (expected face|<id> or emoji|<id>)`, { published: "no" });
|
|
1643
|
+
return {
|
|
1644
|
+
type,
|
|
1645
|
+
id: emoji.slice(index + 1)
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
/**
|
|
1649
|
+
* Add one group reaction.
|
|
1650
|
+
* @param internal - platform API client.
|
|
1651
|
+
* @param message - the reacted message.
|
|
1652
|
+
* @param emoji - `<reaction_type>|<reaction_id>`, or a bare face id.
|
|
1653
|
+
*/
|
|
1654
|
+
async function createReaction(internal, message, emoji) {
|
|
1655
|
+
const { groupId, messageSeq } = reactionTarget(message);
|
|
1656
|
+
const reaction = parseReaction(emoji);
|
|
1657
|
+
await internal.sendGroupMessageReaction(groupId, messageSeq, reaction.id, reaction.type, true);
|
|
1658
|
+
}
|
|
1659
|
+
/**
|
|
1660
|
+
* Remove one group reaction.
|
|
1661
|
+
* @param internal - platform API client.
|
|
1662
|
+
* @param message - the reacted message.
|
|
1663
|
+
* @param emoji - `<reaction_type>|<reaction_id>`, or a bare face id.
|
|
1664
|
+
*/
|
|
1665
|
+
async function deleteReaction(internal, message, emoji) {
|
|
1666
|
+
const { groupId, messageSeq } = reactionTarget(message);
|
|
1667
|
+
const reaction = parseReaction(emoji);
|
|
1668
|
+
await internal.sendGroupMessageReaction(groupId, messageSeq, reaction.id, reaction.type, false);
|
|
1669
|
+
}
|
|
1670
|
+
// lib/types/send.js
|
|
1671
|
+
/**
|
|
1672
|
+
* Outbound calls: one segment message (`send_group_message` / `send_private_message`), one file upload to the QQ file
|
|
1673
|
+
* area (`upload_group_file` / `upload_private_file`), and the two deletion paths (`recall_*_message`,
|
|
1674
|
+
* `delete_group_file`).
|
|
1675
|
+
*
|
|
1676
|
+
* Milky's `OutgoingSegment` has no file type, so a `<file>` is not a chat message at all: it is a real upload that
|
|
1677
|
+
* returns a `file_id`, and the sent part carries `<scene>:<peer>:file:<file_id>` with `kind: 'file'`.
|
|
1678
|
+
*/
|
|
1679
|
+
/** Whether the target asked for a thread, which Milky cannot follow. */
|
|
1680
|
+
function refuseThread(target) {
|
|
1681
|
+
if (typeof target.thread === "string") throw new PlatformError("invalid", `milky: message threads are not supported (thread "${target.thread}")`, { published: "no" });
|
|
1682
|
+
}
|
|
1683
|
+
/** The chat a payload names, refusing an id this adapter did not write. */
|
|
1684
|
+
function chatOf(chatId) {
|
|
1685
|
+
const chat = decodeChatId(chatId);
|
|
1686
|
+
if (chat === void 0) throw new PlatformError("invalid", `milky: "${chatId}" is not a milky chat id (expected group:, private: or temporary:)`, { published: "no" });
|
|
1687
|
+
return chat;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Send one serialized payload.
|
|
1691
|
+
*
|
|
1692
|
+
* @param deps - adapter services.
|
|
1693
|
+
* @param payload - the serialized draft.
|
|
1694
|
+
* @param target - the chat the payload goes to.
|
|
1695
|
+
* @param ctx - core send context (cancellation, part index).
|
|
1696
|
+
* @returns the published part.
|
|
1697
|
+
*/
|
|
1698
|
+
async function sendPayload(deps, payload, target, _ctx) {
|
|
1699
|
+
refuseThread(target);
|
|
1700
|
+
const chat = chatOf(payload.chatId);
|
|
1701
|
+
if (payload.kind === "file") {
|
|
1702
|
+
const fileId = (chat.scene === "group" ? await deps.internal.uploadGroupFile(chat.peerId, void 0, payload.uri, payload.name) : await deps.internal.uploadPrivateFile(chat.peerId, payload.uri, payload.name))?.file_id;
|
|
1703
|
+
if (typeof fileId !== "string" || fileId === "") throw new PlatformError("invalid", "milky: the file upload answered without a file_id", { published: "unknown" });
|
|
1704
|
+
return {
|
|
1705
|
+
id: filePartIdOf(chat.scene, chat.peerId, fileId),
|
|
1706
|
+
kind: "file",
|
|
1707
|
+
time: Date.now()
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
const response = chat.scene === "group" ? await deps.internal.sendGroupMessage(chat.peerId, payload.segments) : await deps.internal.sendPrivateMessage(chat.peerId, payload.segments);
|
|
1711
|
+
const messageSeq = response?.message_seq;
|
|
1712
|
+
if (typeof messageSeq !== "number" || !Number.isSafeInteger(messageSeq)) throw new PlatformError("invalid", "milky: the send answered without a message_seq", { published: "unknown" });
|
|
1713
|
+
return {
|
|
1714
|
+
id: messageIdOf(chat.scene, chat.peerId, messageSeq),
|
|
1715
|
+
kind: "message",
|
|
1716
|
+
time: typeof response?.time === "number" ? response.time * 1e3 : Date.now()
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Delete one published part: recall a message, or remove a group file from the file area.
|
|
1721
|
+
*
|
|
1722
|
+
* @param deps - adapter services.
|
|
1723
|
+
* @param part - the published part.
|
|
1724
|
+
* @param handle - the message handle (carries the target chat).
|
|
1725
|
+
*/
|
|
1726
|
+
async function deletePart(deps, part, handle) {
|
|
1727
|
+
const chat = chatOf(handle.target.chat.id);
|
|
1728
|
+
if (part.kind === "file") {
|
|
1729
|
+
const decoded = decodeFilePartId(part.id);
|
|
1730
|
+
if (decoded === void 0 || !idNamesChat(decoded.scene, decoded.peerId, chat)) throw new PlatformError("invalid", `milky: file part "${part.id}" does not belong to chat "${handle.target.chat.id}"`, { published: "no" });
|
|
1731
|
+
if (chat.scene !== "group") throw new PlatformError("invalid", "milky: a file uploaded to a private chat cannot be deleted", { published: "no" });
|
|
1732
|
+
await deps.internal.deleteGroupFile(chat.peerId, decoded.fileId);
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
const decoded = decodeMessageId(part.id);
|
|
1736
|
+
if (decoded === void 0 || !idNamesChat(decoded.scene, decoded.peerId, chat)) throw new PlatformError("invalid", `milky: message part "${part.id}" does not belong to chat "${handle.target.chat.id}"`, { published: "no" });
|
|
1737
|
+
if (chat.scene === "group") await deps.internal.recallGroupMessage(chat.peerId, decoded.messageSeq);
|
|
1738
|
+
else await deps.internal.recallPrivateMessage(chat.peerId, decoded.messageSeq);
|
|
1739
|
+
}
|
|
1740
|
+
// lib/types/ws.js
|
|
1741
|
+
/**
|
|
1742
|
+
* The client WebSocket to `<origin>/event`: a self-written loop because core's `WsClientBase` treats `retryTimes` as
|
|
1743
|
+
* a give-up limit.
|
|
1744
|
+
*
|
|
1745
|
+
* Three failure classes are kept apart:
|
|
1746
|
+
* - configuration failures are found by `connect()` before the loop starts and thrown there;
|
|
1747
|
+
* - transport failures (dial, handshake, socket close, identity read) log a warning and enter the reconnect loop;
|
|
1748
|
+
* - runtime permanent failures (the endpoint is logged into another account, or a frame names another `self_id`)
|
|
1749
|
+
* log an error, take the bot offline and stop the loop.
|
|
1750
|
+
*
|
|
1751
|
+
* Frames are handled one at a time in arrival order. A frame whose intake throws is logged and dropped — the protocol
|
|
1752
|
+
* has no acknowledgement and no redelivery, so retrying it would only delay the frames behind it.
|
|
1753
|
+
*/
|
|
1754
|
+
/** Resolve after `ms`, or as soon as `signal` aborts. */
|
|
1755
|
+
function sleep(ms, signal) {
|
|
1756
|
+
return new Promise((resolve) => {
|
|
1757
|
+
if (signal.aborted) {
|
|
1758
|
+
resolve();
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
const onAbort = () => {
|
|
1762
|
+
clearTimeout(timer);
|
|
1763
|
+
resolve();
|
|
1764
|
+
};
|
|
1765
|
+
const timer = setTimeout(() => {
|
|
1766
|
+
signal.removeEventListener("abort", onAbort);
|
|
1767
|
+
resolve();
|
|
1768
|
+
}, ms);
|
|
1769
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1770
|
+
});
|
|
1771
|
+
}
|
|
1772
|
+
/** A settled promise nobody waits for. */
|
|
1773
|
+
const noop = () => {};
|
|
1774
|
+
/** Describe a caught value for a log line. */
|
|
1775
|
+
function messageOf$1(error) {
|
|
1776
|
+
return error instanceof Error ? error.message : String(error);
|
|
1777
|
+
}
|
|
1778
|
+
/** The event stream of one Milky protocol endpoint. */
|
|
1779
|
+
var MilkyWs = class {
|
|
1780
|
+
bot;
|
|
1781
|
+
controller;
|
|
1782
|
+
running;
|
|
1783
|
+
socket;
|
|
1784
|
+
queue = [];
|
|
1785
|
+
draining;
|
|
1786
|
+
processing = false;
|
|
1787
|
+
stopping = false;
|
|
1788
|
+
warnedDepth = 0;
|
|
1789
|
+
/**
|
|
1790
|
+
* @param bot - the adapter whose identity, configuration and logger the loop uses.
|
|
1791
|
+
*/
|
|
1792
|
+
constructor(bot) {
|
|
1793
|
+
this.bot = bot;
|
|
1794
|
+
}
|
|
1795
|
+
/** Start the reconnect loop; resolves immediately, without waiting for the first connection. */
|
|
1796
|
+
start() {
|
|
1797
|
+
if (this.controller !== void 0) return;
|
|
1798
|
+
const controller = new AbortController();
|
|
1799
|
+
this.controller = controller;
|
|
1800
|
+
this.stopping = false;
|
|
1801
|
+
const running = this.loop(controller.signal);
|
|
1802
|
+
this.running = running;
|
|
1803
|
+
running.catch(noop);
|
|
1804
|
+
}
|
|
1805
|
+
/**
|
|
1806
|
+
* Stop the stream: abort the loop, close the socket, drop the frames that have not started, and wait for the frame
|
|
1807
|
+
* being handled to finish.
|
|
1808
|
+
*/
|
|
1809
|
+
async stop() {
|
|
1810
|
+
this.stopping = true;
|
|
1811
|
+
this.controller?.abort(/* @__PURE__ */ new Error("adapter stopped"));
|
|
1812
|
+
this.controller = void 0;
|
|
1813
|
+
this.closeSocket(1e3, "adapter stopped");
|
|
1814
|
+
this.dropQueue();
|
|
1815
|
+
await this.running?.catch(noop);
|
|
1816
|
+
this.running = void 0;
|
|
1817
|
+
await this.draining?.catch(noop);
|
|
1818
|
+
this.draining = void 0;
|
|
1819
|
+
}
|
|
1820
|
+
/** The reconnect loop: dial, identify, consume, then retry at the fast or lazy interval. */
|
|
1821
|
+
async loop(signal) {
|
|
1822
|
+
let failures = 0;
|
|
1823
|
+
while (!signal.aborted) try {
|
|
1824
|
+
const socket = await this.dial(signal);
|
|
1825
|
+
if (signal.aborted) {
|
|
1826
|
+
this.closeSocketOf(socket, 1e3, "adapter stopped");
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
this.socket = socket;
|
|
1830
|
+
await this.bot.identify();
|
|
1831
|
+
failures = 0;
|
|
1832
|
+
this.bot.online();
|
|
1833
|
+
const closed = await this.consume(socket, signal);
|
|
1834
|
+
if (signal.aborted) return;
|
|
1835
|
+
throw new Error(`websocket closed with ${closed.code}${closed.reason === "" ? "" : `: ${closed.reason}`}`);
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
this.closeSocket(3e3, "milky connection failed");
|
|
1838
|
+
if (signal.aborted) return;
|
|
1839
|
+
if (error instanceof MilkyIdentityError) {
|
|
1840
|
+
this.bot.ctx.logger.error("milky: %s", error.message);
|
|
1841
|
+
this.bot.offline(error);
|
|
1842
|
+
this.stopping = true;
|
|
1843
|
+
return;
|
|
1844
|
+
}
|
|
1845
|
+
this.bot.ctx.logger.warn("milky: connection failed: %s", messageOf$1(error));
|
|
1846
|
+
this.bot.status = Status.RECONNECT;
|
|
1847
|
+
const delay = failures < this.bot.config.ws.retryTimes ? this.bot.config.ws.retryIntervalMs : this.bot.config.ws.retryLazyMs;
|
|
1848
|
+
failures += 1;
|
|
1849
|
+
await sleep(delay, signal);
|
|
1850
|
+
} finally {
|
|
1851
|
+
this.socket = void 0;
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
/** Open one socket and wait for its `open` event; a close or error before that is a transport failure. */
|
|
1855
|
+
dial(signal) {
|
|
1856
|
+
return new Promise((resolve, reject) => {
|
|
1857
|
+
let socket;
|
|
1858
|
+
try {
|
|
1859
|
+
socket = this.bot.openEventSocket();
|
|
1860
|
+
} catch (error) {
|
|
1861
|
+
reject(error);
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
const cleanup = () => {
|
|
1865
|
+
socket.removeEventListener("open", onOpen);
|
|
1866
|
+
socket.removeEventListener("close", onClose);
|
|
1867
|
+
socket.removeEventListener("error", onError);
|
|
1868
|
+
signal.removeEventListener("abort", onAbort);
|
|
1869
|
+
};
|
|
1870
|
+
const onOpen = () => {
|
|
1871
|
+
cleanup();
|
|
1872
|
+
resolve(socket);
|
|
1873
|
+
};
|
|
1874
|
+
const onClose = (event) => {
|
|
1875
|
+
cleanup();
|
|
1876
|
+
reject(/* @__PURE__ */ new Error(`websocket closed with ${event.code} before it opened`));
|
|
1877
|
+
};
|
|
1878
|
+
const onError = (event) => {
|
|
1879
|
+
cleanup();
|
|
1880
|
+
reject(new Error(event.message ?? "websocket transport error before it opened"));
|
|
1881
|
+
};
|
|
1882
|
+
const onAbort = () => {
|
|
1883
|
+
cleanup();
|
|
1884
|
+
this.closeSocketOf(socket, 1e3, "adapter stopped");
|
|
1885
|
+
reject(signal.reason ?? /* @__PURE__ */ new Error("adapter stopped"));
|
|
1886
|
+
};
|
|
1887
|
+
socket.addEventListener("open", onOpen);
|
|
1888
|
+
socket.addEventListener("close", onClose);
|
|
1889
|
+
socket.addEventListener("error", onError);
|
|
1890
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1891
|
+
if (signal.aborted) onAbort();
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
/** Deliver every frame of one open socket until it closes; resolves with the close details. */
|
|
1895
|
+
consume(socket, signal) {
|
|
1896
|
+
return new Promise((resolve) => {
|
|
1897
|
+
const cleanup = () => {
|
|
1898
|
+
socket.removeEventListener("message", onMessage);
|
|
1899
|
+
socket.removeEventListener("close", onClose);
|
|
1900
|
+
socket.removeEventListener("error", onError);
|
|
1901
|
+
signal.removeEventListener("abort", onAbort);
|
|
1902
|
+
};
|
|
1903
|
+
const onMessage = (event) => {
|
|
1904
|
+
if (typeof event.data === "string") this.accept(event.data);
|
|
1905
|
+
else this.bot.ctx.logger.warn("milky: ignored a websocket frame that was not text");
|
|
1906
|
+
};
|
|
1907
|
+
const onClose = (event) => {
|
|
1908
|
+
cleanup();
|
|
1909
|
+
resolve({
|
|
1910
|
+
code: event.code,
|
|
1911
|
+
reason: event.reason
|
|
1912
|
+
});
|
|
1913
|
+
};
|
|
1914
|
+
const onError = () => {
|
|
1915
|
+
this.bot.ctx.logger.warn("milky: websocket transport error");
|
|
1916
|
+
};
|
|
1917
|
+
const onAbort = () => {
|
|
1918
|
+
cleanup();
|
|
1919
|
+
this.closeSocketOf(socket, 1e3, "adapter stopped");
|
|
1920
|
+
resolve({
|
|
1921
|
+
code: 1e3,
|
|
1922
|
+
reason: "adapter stopped"
|
|
1923
|
+
});
|
|
1924
|
+
};
|
|
1925
|
+
socket.addEventListener("message", onMessage);
|
|
1926
|
+
socket.addEventListener("close", onClose);
|
|
1927
|
+
socket.addEventListener("error", onError);
|
|
1928
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1929
|
+
if (signal.aborted) onAbort();
|
|
1930
|
+
else if (socket.readyState === 3) {
|
|
1931
|
+
cleanup();
|
|
1932
|
+
resolve({
|
|
1933
|
+
code: 1006,
|
|
1934
|
+
reason: "closed before the frame listener"
|
|
1935
|
+
});
|
|
1936
|
+
}
|
|
1937
|
+
});
|
|
1938
|
+
}
|
|
1939
|
+
/** Parse, validate and queue one frame. */
|
|
1940
|
+
accept(raw) {
|
|
1941
|
+
let parsed;
|
|
1942
|
+
try {
|
|
1943
|
+
parsed = JSON.parse(raw);
|
|
1944
|
+
} catch (error) {
|
|
1945
|
+
this.bot.ctx.logger.warn("milky: ignored a frame that is not JSON: %s", messageOf$1(error));
|
|
1946
|
+
return;
|
|
1947
|
+
}
|
|
1948
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1949
|
+
this.bot.ctx.logger.warn("milky: ignored a frame that is not an event object");
|
|
1950
|
+
return;
|
|
1951
|
+
}
|
|
1952
|
+
const event = parsed;
|
|
1953
|
+
if (typeof event.event_type !== "string" || typeof event.self_id !== "number" || typeof event.time !== "number") {
|
|
1954
|
+
this.bot.ctx.logger.warn("milky: ignored a frame without event_type, self_id or time");
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
if (String(event.self_id) !== this.bot.selfId) {
|
|
1958
|
+
this.halt(new MilkyIdentityError(`milky: a frame names account ${String(event.self_id)}, but this adapter is configured for ${this.bot.selfId}`));
|
|
1959
|
+
return;
|
|
1960
|
+
}
|
|
1961
|
+
this.enqueue(event);
|
|
1962
|
+
}
|
|
1963
|
+
/** Queue one frame behind the frames already waiting, warning once per doubling of the backlog. */
|
|
1964
|
+
enqueue(event) {
|
|
1965
|
+
this.queue.push(event);
|
|
1966
|
+
const depth = this.queue.length;
|
|
1967
|
+
if (depth >= 2 && (depth & depth - 1) === 0 && depth > this.warnedDepth) {
|
|
1968
|
+
this.warnedDepth = depth;
|
|
1969
|
+
this.bot.ctx.logger.warn("milky: %d events are waiting for intake", depth);
|
|
1970
|
+
}
|
|
1971
|
+
if (this.processing) return;
|
|
1972
|
+
const draining = this.drain();
|
|
1973
|
+
this.draining = draining;
|
|
1974
|
+
draining.finally(() => {
|
|
1975
|
+
if (this.draining === draining) this.draining = void 0;
|
|
1976
|
+
});
|
|
1977
|
+
}
|
|
1978
|
+
/** Handle queued frames one at a time, in arrival order. */
|
|
1979
|
+
async drain() {
|
|
1980
|
+
if (this.processing) return;
|
|
1981
|
+
this.processing = true;
|
|
1982
|
+
try {
|
|
1983
|
+
while (this.queue.length > 0) {
|
|
1984
|
+
if (this.stopping) {
|
|
1985
|
+
this.dropQueue();
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
const event = this.queue.shift();
|
|
1989
|
+
await this.handle(event);
|
|
1990
|
+
}
|
|
1991
|
+
this.warnedDepth = 0;
|
|
1992
|
+
} finally {
|
|
1993
|
+
this.processing = false;
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
/** Decode and receive one frame; a failure drops that frame and nothing else. */
|
|
1997
|
+
async handle(event) {
|
|
1998
|
+
if (event.event_type === "bot_offline") {
|
|
1999
|
+
this.bot.ctx.logger.warn("milky: the protocol endpoint reports the account offline: %s", event.data.reason);
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
let session;
|
|
2003
|
+
try {
|
|
2004
|
+
session = decodeFrame(this.bot, event);
|
|
2005
|
+
} catch (error) {
|
|
2006
|
+
this.bot.ctx.logger.error("milky: a %s frame could not be decoded: %s", event.event_type, messageOf$1(error));
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
if (session === void 0) {
|
|
2010
|
+
this.bot.ctx.logger.debug("milky: ignored event %s", event.event_type);
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
try {
|
|
2014
|
+
await this.bot.receive(session);
|
|
2015
|
+
} catch (error) {
|
|
2016
|
+
this.bot.ctx.logger.error("milky: event %s could not be received: %s", session.event.id ?? event.event_type, messageOf$1(error));
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
/** Stop the loop for a failure that reconnecting cannot fix. */
|
|
2020
|
+
halt(error) {
|
|
2021
|
+
this.bot.ctx.logger.error("milky: %s", error.message);
|
|
2022
|
+
this.bot.offline(error);
|
|
2023
|
+
this.stopping = true;
|
|
2024
|
+
this.controller?.abort(error);
|
|
2025
|
+
this.closeSocket(1e3, "milky identity mismatch");
|
|
2026
|
+
}
|
|
2027
|
+
/** Drop every frame that has not started; the frame being handled still finishes. */
|
|
2028
|
+
dropQueue() {
|
|
2029
|
+
const count = this.queue.length;
|
|
2030
|
+
if (count === 0) return;
|
|
2031
|
+
this.queue = [];
|
|
2032
|
+
this.warnedDepth = 0;
|
|
2033
|
+
this.bot.ctx.logger.warn("milky: dropped %d event(s) that had not started yet", count);
|
|
2034
|
+
}
|
|
2035
|
+
/** Close the current socket, ignoring a socket that is already gone. */
|
|
2036
|
+
closeSocket(code, reason) {
|
|
2037
|
+
const socket = this.socket;
|
|
2038
|
+
this.socket = void 0;
|
|
2039
|
+
if (socket !== void 0) this.closeSocketOf(socket, code, reason);
|
|
2040
|
+
}
|
|
2041
|
+
/** Close one socket, ignoring a close that the transport refuses because it is already closed. */
|
|
2042
|
+
closeSocketOf(socket, code, reason) {
|
|
2043
|
+
try {
|
|
2044
|
+
socket.close(code, reason);
|
|
2045
|
+
} catch (error) {
|
|
2046
|
+
this.bot.ctx.logger.debug("milky: a closed socket was closed again: %s", messageOf$1(error));
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
// lib/types/bot.js
|
|
2051
|
+
/**
|
|
2052
|
+
* The Milky adapter: an application-side client of one protocol endpoint (LLOneBot, NapCat, …).
|
|
2053
|
+
*
|
|
2054
|
+
* The endpoint is a plain HTTP server with `/api` for calls and `/event` for the event stream. This adapter is an HTTP
|
|
2055
|
+
* client and a WebSocket client; it never serves anything and registers no `webServer` route. Its only inbound surface
|
|
2056
|
+
* is the `satori:` media routes it defines for the host to fetch lazily.
|
|
2057
|
+
*/
|
|
2058
|
+
/**
|
|
2059
|
+
* Milky adapter for one protocol endpoint.
|
|
2060
|
+
*
|
|
2061
|
+
* Identity comes from the required `selfId`, verified against `get_login_info.uin` on every connection; events arrive
|
|
2062
|
+
* over a reconnecting client WebSocket, while every write is an independent HTTP call.
|
|
2063
|
+
*/
|
|
2064
|
+
var MilkyBot = class extends Adapter {
|
|
2065
|
+
/** The adapter waits for the Satori service; the Loader row isolates `http` for this adapter. */
|
|
2066
|
+
static inject = ["satori", "http"];
|
|
2067
|
+
/** The Loader applies this schema to a profile row's `config` before the constructor runs. */
|
|
2068
|
+
static Config = Config;
|
|
2069
|
+
modes = { text: createMilkyTextMode() };
|
|
2070
|
+
modeOrder = ["text"];
|
|
2071
|
+
/** API endpoints derived from the origin of `endpoint`. */
|
|
2072
|
+
request;
|
|
2073
|
+
/** The whole Milky API surface, including the methods the DSH host does not call. */
|
|
2074
|
+
internal;
|
|
2075
|
+
endpointError;
|
|
2076
|
+
ws;
|
|
2077
|
+
/**
|
|
2078
|
+
* @param ctx - plugin context.
|
|
2079
|
+
* @param config - validated configuration; the constructor still asserts `selfId` against a config that bypassed the
|
|
2080
|
+
* schema, because `bot.id` must be stable before any connection.
|
|
2081
|
+
* @throws MilkyConfigError when `selfId` is not a QQ number.
|
|
2082
|
+
*/
|
|
2083
|
+
constructor(ctx, config) {
|
|
2084
|
+
const selfId = String(config.selfId);
|
|
2085
|
+
if (!/^\d+$/.test(selfId)) throw new MilkyConfigError(`milky: selfId must be the bot QQ number (digits only), got "${config.selfId}"`);
|
|
2086
|
+
const endpoint = normalizeEndpoint(config.endpoint);
|
|
2087
|
+
let origin = "";
|
|
2088
|
+
let endpointError;
|
|
2089
|
+
try {
|
|
2090
|
+
origin = milkyOrigin(endpoint);
|
|
2091
|
+
} catch (error) {
|
|
2092
|
+
endpointError = error instanceof Error ? error : new Error(String(error));
|
|
2093
|
+
}
|
|
2094
|
+
super(ctx, {
|
|
2095
|
+
...config,
|
|
2096
|
+
endpoint
|
|
2097
|
+
}, {
|
|
2098
|
+
id: `milky:${selfId}`,
|
|
2099
|
+
platform: "milky",
|
|
2100
|
+
adapter: "milky"
|
|
2101
|
+
});
|
|
2102
|
+
this.selfId = selfId;
|
|
2103
|
+
this.request = createMilkyRequest(ctx, config.token, origin);
|
|
2104
|
+
this.internal = new Internal(this.request);
|
|
2105
|
+
this.endpointError = endpointError;
|
|
2106
|
+
this.defineInternalRoute("/resources/:resourceId", async ({ params }) => this.serveResource(params.resourceId));
|
|
2107
|
+
this.defineInternalRoute("/files/:scene/:peer/:fileId", async ({ params, query }) => this.serveFile(params.scene, params.peer, params.fileId, query.get("hash")));
|
|
2108
|
+
}
|
|
2109
|
+
/**
|
|
2110
|
+
* Validate the endpoint and start the reconnect loop. Returns immediately: the loop dials in the background, so a
|
|
2111
|
+
* protocol endpoint that starts later does not hold up the plugin row.
|
|
2112
|
+
* @throws MilkyConfigError when `endpoint` is not an http(s) URL.
|
|
2113
|
+
*/
|
|
2114
|
+
async connect() {
|
|
2115
|
+
if (this.endpointError !== void 0) {
|
|
2116
|
+
this.ctx.logger.error("milky: %s", this.endpointError.message);
|
|
2117
|
+
throw this.endpointError;
|
|
2118
|
+
}
|
|
2119
|
+
const ws = new MilkyWs(this);
|
|
2120
|
+
this.ws = ws;
|
|
2121
|
+
ws.start();
|
|
2122
|
+
}
|
|
2123
|
+
/** Stop the event stream and wait for the frame being handled. */
|
|
2124
|
+
async disconnect() {
|
|
2125
|
+
const ws = this.ws;
|
|
2126
|
+
this.ws = void 0;
|
|
2127
|
+
await ws?.stop();
|
|
2128
|
+
}
|
|
2129
|
+
/** Address of the event socket (`ws(s)://<origin>/event`) with the configured bearer token. */
|
|
2130
|
+
openEventSocket() {
|
|
2131
|
+
return this.ctx.http.ws(eventUrl(this.request), { ...this.config.token === "" ? {} : { headers: { authorization: `Bearer ${this.config.token}` } } });
|
|
2132
|
+
}
|
|
2133
|
+
/**
|
|
2134
|
+
* Read and verify the endpoint identity, then report an unexpected protocol version.
|
|
2135
|
+
* @throws MilkyIdentityError when the endpoint is logged into another account.
|
|
2136
|
+
* @throws MilkyApiError when `get_login_info` itself fails (a transport failure, retried by the loop).
|
|
2137
|
+
*/
|
|
2138
|
+
async identify() {
|
|
2139
|
+
const login = await this.internal.getLoginInfo();
|
|
2140
|
+
if (login === void 0 || login === null || typeof login.uin !== "number") throw new MilkyApiError("milky: get_login_info answered without a uin", {
|
|
2141
|
+
api: "get_login_info",
|
|
2142
|
+
httpStatus: 200
|
|
2143
|
+
});
|
|
2144
|
+
this.user = verifyIdentity(this.selfId, login);
|
|
2145
|
+
try {
|
|
2146
|
+
const info = await this.internal.getImplInfo();
|
|
2147
|
+
if (!implementsMilky1(info.milky_version)) this.ctx.logger.warn("%s", versionWarning(info));
|
|
2148
|
+
} catch (error) {
|
|
2149
|
+
this.ctx.logger.warn("milky: reading the endpoint implementation failed: %s", messageOf(error));
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
/**
|
|
2153
|
+
* Turn a media source into a URI the protocol endpoint can read.
|
|
2154
|
+
*
|
|
2155
|
+
* Milky has no message-media upload endpoint: image / record / video segments take a `file://`, `http(s)://` or
|
|
2156
|
+
* `base64://` URI and the endpoint fetches it itself. No size limit is applied here; the endpoint decides what it
|
|
2157
|
+
* accepts.
|
|
2158
|
+
*
|
|
2159
|
+
* @param ref - the resource placeholder produced by the mode.
|
|
2160
|
+
* @param _scope - cache scope from {@link resourceScope} (unused: the key is the source itself).
|
|
2161
|
+
* @param ctx - prepare context (byte fetch for `data:` / `satori:` sources).
|
|
2162
|
+
* @returns the URI to place in the segment.
|
|
2163
|
+
*/
|
|
2164
|
+
async upload(ref, _scope, ctx) {
|
|
2165
|
+
const src = ref.src;
|
|
2166
|
+
if (/^https?:/i.test(src) || src.startsWith("file:") || src.startsWith("base64:")) return { key: src };
|
|
2167
|
+
if (/^data:/i.test(src)) {
|
|
2168
|
+
const base64 = /^data:[^,]*;base64,([\s\S]*)$/.exec(src);
|
|
2169
|
+
if (base64 !== null) return { key: `base64://${base64[1]}` };
|
|
2170
|
+
return await this.fetchAsBase64(src, ctx);
|
|
2171
|
+
}
|
|
2172
|
+
if (src.startsWith("satori:")) return await this.fetchAsBase64(src, ctx);
|
|
2173
|
+
throw new PlatformError("invalid", `milky: unsupported media source "${preview(src)}"`, { published: "no" });
|
|
2174
|
+
}
|
|
2175
|
+
/** No platform-side resource is reused by this adapter; the scope only separates bots in the prepare cache. */
|
|
2176
|
+
resourceScope(_target, _kind) {
|
|
2177
|
+
return this.id;
|
|
2178
|
+
}
|
|
2179
|
+
/**
|
|
2180
|
+
* Publish one serialized payload: a segment message, or one file uploaded to the QQ file area.
|
|
2181
|
+
* @param payload - the payload `serialize` produced.
|
|
2182
|
+
* @param target - destination chat.
|
|
2183
|
+
* @param ctx - core send context.
|
|
2184
|
+
* @returns the published part.
|
|
2185
|
+
*/
|
|
2186
|
+
async sendPayload(payload, target, ctx) {
|
|
2187
|
+
return await sendPayload({ internal: this.internal }, payload, target, ctx);
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Delete one published part: recall a message, or delete a group file.
|
|
2191
|
+
* @param part - the published part.
|
|
2192
|
+
* @param handle - the message handle (carries the target chat).
|
|
2193
|
+
*/
|
|
2194
|
+
async deletePart(part, handle) {
|
|
2195
|
+
await deletePart({ internal: this.internal }, part, handle);
|
|
2196
|
+
}
|
|
2197
|
+
classify(error) {
|
|
2198
|
+
return classifyMilkyError(error);
|
|
2199
|
+
}
|
|
2200
|
+
/**
|
|
2201
|
+
* List the people a chat lists as its members.
|
|
2202
|
+
* @param chat - chat to list.
|
|
2203
|
+
* @param cursor - `next` of the previous page.
|
|
2204
|
+
* @param limit - page-size hint from the host.
|
|
2205
|
+
* @returns one page.
|
|
2206
|
+
*/
|
|
2207
|
+
async members(chat, cursor, limit) {
|
|
2208
|
+
return await members(this.internal, chat, cursor, limit);
|
|
2209
|
+
}
|
|
2210
|
+
/**
|
|
2211
|
+
* Read one message by id, expanding a merged forward placeholder.
|
|
2212
|
+
* @param chat - chat the caller asks about.
|
|
2213
|
+
* @param id - platform message id.
|
|
2214
|
+
* @returns the message.
|
|
2215
|
+
*/
|
|
2216
|
+
async getMessage(chat, id) {
|
|
2217
|
+
return await getMessage(this, chat, id);
|
|
2218
|
+
}
|
|
2219
|
+
/**
|
|
2220
|
+
* Add one reaction (group chats only).
|
|
2221
|
+
* @param message - the reacted message.
|
|
2222
|
+
* @param emoji - `<reaction_type>|<reaction_id>`, or a bare face id.
|
|
2223
|
+
*/
|
|
2224
|
+
async createReaction(message, emoji) {
|
|
2225
|
+
await createReaction(this.internal, message, emoji);
|
|
2226
|
+
}
|
|
2227
|
+
/**
|
|
2228
|
+
* Remove one reaction (group chats only).
|
|
2229
|
+
* @param message - the reacted message.
|
|
2230
|
+
* @param emoji - `<reaction_type>|<reaction_id>`, or a bare face id.
|
|
2231
|
+
*/
|
|
2232
|
+
async deleteReaction(message, emoji) {
|
|
2233
|
+
await deleteReaction(this.internal, message, emoji);
|
|
2234
|
+
}
|
|
2235
|
+
/** Fetch a source into a `base64://` URI, keeping the name the source reported. */
|
|
2236
|
+
async fetchAsBase64(src, ctx) {
|
|
2237
|
+
const fetched = await ctx.fetch(src, ctx.signal);
|
|
2238
|
+
return {
|
|
2239
|
+
key: `base64://${Buffer.from(fetched.data).toString("base64")}`,
|
|
2240
|
+
...fetched.name === void 0 || fetched.name === "" ? {} : { extra: { name: fetched.name } }
|
|
2241
|
+
};
|
|
2242
|
+
}
|
|
2243
|
+
/** Serve one `resource_id` by resolving it to a temporary URL when the host reads it. */
|
|
2244
|
+
async serveResource(resourceId) {
|
|
2245
|
+
const id = decodeURIComponentOrUndefined(resourceId);
|
|
2246
|
+
if (id === void 0) return new Response(null, { status: 400 });
|
|
2247
|
+
try {
|
|
2248
|
+
const url = (await this.internal.getResourceTempUrl(id))?.url;
|
|
2249
|
+
if (typeof url !== "string" || url === "") return new Response(null, { status: 502 });
|
|
2250
|
+
return await this.proxy(url);
|
|
2251
|
+
} catch (error) {
|
|
2252
|
+
this.ctx.logger.warn("milky: resource %s could not be served (%s)", id, failureOf(error));
|
|
2253
|
+
return new Response(null, { status: 502 });
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
/** Serve one file of the file area through `get_*_file_download_url`. */
|
|
2257
|
+
async serveFile(scene, peer, fileId, hash) {
|
|
2258
|
+
const file = decodeURIComponentOrUndefined(fileId);
|
|
2259
|
+
if (file === void 0) return new Response(null, { status: 400 });
|
|
2260
|
+
const peerId = Number(peer);
|
|
2261
|
+
if (!Number.isSafeInteger(peerId) || peerId <= 0) return new Response(null, { status: 400 });
|
|
2262
|
+
try {
|
|
2263
|
+
let url;
|
|
2264
|
+
if (scene === "group") url = (await this.internal.getGroupFileDownloadUrl(peerId, file))?.download_url;
|
|
2265
|
+
else if (scene === "private" || scene === "temp") {
|
|
2266
|
+
if (hash === null || hash === "") return new Response(null, { status: 400 });
|
|
2267
|
+
url = (await this.internal.getPrivateFileDownloadUrl(peerId, file, hash))?.download_url;
|
|
2268
|
+
} else return new Response(null, { status: 400 });
|
|
2269
|
+
if (typeof url !== "string" || url === "") return new Response(null, { status: 502 });
|
|
2270
|
+
return await this.proxy(url);
|
|
2271
|
+
} catch (error) {
|
|
2272
|
+
this.ctx.logger.warn("milky: file %s could not be served (%s)", file, failureOf(error));
|
|
2273
|
+
return new Response(null, { status: 502 });
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
/** Fetch an upstream URL and pass its status, body and content type through. */
|
|
2277
|
+
async proxy(url) {
|
|
2278
|
+
const response = await this.ctx.http(url, {});
|
|
2279
|
+
const headers = new Headers();
|
|
2280
|
+
const contentType = response.headers.get("content-type");
|
|
2281
|
+
if (contentType !== null) headers.set("content-type", contentType);
|
|
2282
|
+
return new Response(response.body, {
|
|
2283
|
+
status: response.status,
|
|
2284
|
+
headers
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
};
|
|
2288
|
+
/** Decode one URL path parameter, or refuse a malformed escape. */
|
|
2289
|
+
function decodeURIComponentOrUndefined(value) {
|
|
2290
|
+
try {
|
|
2291
|
+
return decodeURIComponent(value);
|
|
2292
|
+
} catch (error) {
|
|
2293
|
+
return;
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
/** A short, token-free description of a caught failure for a log line. */
|
|
2297
|
+
function failureOf(error) {
|
|
2298
|
+
if (error instanceof MilkyApiError) return `${error.api} failed (${error.httpStatus ?? error.retcode ?? "no status"})`;
|
|
2299
|
+
return error instanceof Error ? error.name : "unknown error";
|
|
2300
|
+
}
|
|
2301
|
+
/** Describe a caught value for a log line. */
|
|
2302
|
+
function messageOf(error) {
|
|
2303
|
+
return error instanceof Error ? error.message : String(error);
|
|
2304
|
+
}
|
|
2305
|
+
/** A source shortened for a diagnostic (a data: URL can be megabytes long). */
|
|
2306
|
+
function preview(src) {
|
|
2307
|
+
return src.length <= 120 ? src : `${src.slice(0, 120)}…`;
|
|
2308
|
+
}
|
|
2309
|
+
export { Config, Internal, MilkyApiError, MilkyBot, MilkyBot as default, MilkyConfigError, MilkyIdentityError, chatIdOf, chatRefOf, classifyMilkyError, createMilkyTextMode, decodeChatId, decodeFilePartId, decodeMessageId, eventUrl, filePartIdOf, messageIdOf, milkyOrigin, normalizeEndpoint };
|
|
2310
|
+
|
|
2311
|
+
//# sourceMappingURL=index.js.map
|