@botharness/im-provider 4.32.0-botharness.4 → 4.32.0-botharness.7
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/PROVENANCE.json +6 -6
- package/lib/client.js +3 -3
- package/lib/index.js +284 -284
- package/package.json +3 -3
- package/src/channels/shared/exclusive-inbound-consumers.mjs +5 -3
- package/src/channels/weixin/external-consumer.mjs +42 -6
- package/src/channels/weixin/external-files.mjs +73 -0
- package/src/channels/weixin/weixin-api.mjs +30 -5
- package/src/channels/weixin/weixin-controller.mjs +19 -6
- package/src/channels/weixin/weixin-runtime.mjs +16 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botharness/im-provider",
|
|
3
|
-
"version": "4.32.0-botharness.
|
|
3
|
+
"version": "4.32.0-botharness.7",
|
|
4
4
|
"icon": "./assets/logo-plugin-message-link-gradient.webp",
|
|
5
5
|
"description": "BotHarness-qualified IM Provider, maintained from dsh-im",
|
|
6
6
|
"keywords": [
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
"type": "module",
|
|
105
105
|
"repository": {
|
|
106
106
|
"type": "git",
|
|
107
|
-
"url": "git+https://github.com/
|
|
107
|
+
"url": "git+https://github.com/BotHarness/BotHarness.git"
|
|
108
108
|
},
|
|
109
109
|
"homepage": "https://botharness.ai/docs/lark-connection/",
|
|
110
110
|
"bugs": {
|
|
@@ -176,6 +176,6 @@
|
|
|
176
176
|
},
|
|
177
177
|
"botharness": {
|
|
178
178
|
"managedByProduct": true,
|
|
179
|
-
"upstreamSource": "
|
|
179
|
+
"upstreamSource": "6f8cc9b2713a03b1340e604461900a474adacfa3"
|
|
180
180
|
}
|
|
181
181
|
}
|
|
@@ -6,15 +6,17 @@ export class ExclusiveInboundConsumers {
|
|
|
6
6
|
#entries = new Map();
|
|
7
7
|
|
|
8
8
|
acceptsFiles(botId) { return this.#entries.get(botId)?.sourceFiles === true; }
|
|
9
|
+
acceptsImages(botId) { return this.#entries.get(botId)?.sourceImages === true; }
|
|
10
|
+
acceptsVoiceTranscripts(botId) { return this.#entries.get(botId)?.sourceVoiceTranscripts === true; }
|
|
9
11
|
acceptsOrdinary(botId) { return this.#entries.get(botId)?.ordinaryText === true; }
|
|
10
12
|
|
|
11
|
-
register(botId, { fingerprint, onEvent, signal, sourceFiles = false, ordinaryText = false, onEcho }) {
|
|
13
|
+
register(botId, { fingerprint, onEvent, signal, sourceFiles = false, sourceImages = false, sourceVoiceTranscripts = false, ordinaryText = false, onEcho }) {
|
|
12
14
|
if (this.#entries.has(botId)) throw refusal('consumer-conflict');
|
|
13
|
-
if (!/^[a-f0-9]{64}$/.test(fingerprint ?? '') || typeof onEvent !== 'function' || typeof sourceFiles !== 'boolean' || typeof ordinaryText !== 'boolean' || (onEcho !== undefined && typeof onEcho !== 'function'))
|
|
15
|
+
if (!/^[a-f0-9]{64}$/.test(fingerprint ?? '') || typeof onEvent !== 'function' || typeof sourceFiles !== 'boolean' || typeof sourceImages !== 'boolean' || typeof sourceVoiceTranscripts !== 'boolean' || typeof ordinaryText !== 'boolean' || (onEcho !== undefined && typeof onEcho !== 'function'))
|
|
14
16
|
throw refusal('bad-request');
|
|
15
17
|
signal?.throwIfAborted();
|
|
16
18
|
const controller = new AbortController();
|
|
17
|
-
const entry = { fingerprint, onEvent, onEcho, sourceFiles, ordinaryText, controller, dispose: undefined };
|
|
19
|
+
const entry = { fingerprint, onEvent, onEcho, sourceFiles, sourceImages, sourceVoiceTranscripts, ordinaryText, controller, dispose: undefined };
|
|
18
20
|
const dispose = () => {
|
|
19
21
|
if (this.#entries.get(botId) === entry) this.#entries.delete(botId);
|
|
20
22
|
controller.abort(refusal('consumer-unavailable'));
|
|
@@ -19,24 +19,60 @@ export function pairedWeixinAccount(config, token) {
|
|
|
19
19
|
fingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex') });
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
export function normalizeWeixinExternalText(message, { botId, account }) {
|
|
24
|
-
if (message?.message_type !== 1 || message.from_user_id !== account.ownerUserId) return null;
|
|
22
|
+
/** Paired-owner text and opt-in native files/images. No group, mention, or thread is invented. */
|
|
23
|
+
export function normalizeWeixinExternalText(message, { botId, account, sourceFiles = false, sourceImages = false, sourceVoiceTranscripts = false }) {
|
|
24
|
+
if (message?.message_type !== 1 || message.from_user_id !== account.ownerUserId || message.group_id) return null;
|
|
25
25
|
if (message.to_user_id !== account.accountId) throw weixinRefusal('account-changed');
|
|
26
26
|
if (!Array.isArray(message.item_list) || !message.item_list.length
|
|
27
|
-
|| message.item_list.some(item => item?.type !== 1)) return null;
|
|
27
|
+
|| message.item_list.some(item => item?.type !== 1 && !(sourceFiles && item?.type === 4) && !(sourceImages && item?.type === 2) && !(sourceVoiceTranscripts && item?.type === 3))) return null;
|
|
28
28
|
const messageId = weixinMessageId(message);
|
|
29
|
-
const
|
|
29
|
+
const voiceItems = message.item_list.filter(item => item?.type === 3);
|
|
30
|
+
let voice;
|
|
31
|
+
let transcript;
|
|
32
|
+
if (voiceItems.length) {
|
|
33
|
+
if (voiceItems.length !== 1 || message.item_list.length !== 1) throw weixinRefusal('invalid-inbound');
|
|
34
|
+
const item = voiceItems[0];
|
|
35
|
+
if (item.is_completed === false || message.message_state === 1) return null;
|
|
36
|
+
const native = item.voice_item;
|
|
37
|
+
if (!native || typeof native !== 'object' || (native.text !== undefined && typeof native.text !== 'string')
|
|
38
|
+
|| (item.msg_id !== undefined && !id(item.msg_id))
|
|
39
|
+
|| (native.playtime !== undefined && (!Number.isSafeInteger(native.playtime) || native.playtime < 0)))
|
|
40
|
+
throw weixinRefusal('invalid-inbound');
|
|
41
|
+
transcript = native.text?.trim();
|
|
42
|
+
voice = Object.freeze({ transcript: transcript ? 'platform' : 'unavailable',
|
|
43
|
+
...(item.msg_id === undefined ? {} : { itemId: item.msg_id }),
|
|
44
|
+
...(native.playtime === undefined ? {} : { durationMs: native.playtime }) });
|
|
45
|
+
}
|
|
46
|
+
const files = message.item_list.filter(item => item?.type === 4 || item?.type === 2);
|
|
47
|
+
const image = files[0]?.type === 2 ? files[0].image_item : undefined;
|
|
48
|
+
if (files[0]?.type === 2 && (!image || typeof image !== 'object')) throw weixinRefusal('resource-unavailable');
|
|
49
|
+
if (files.length > 1) throw weixinRefusal('resource-unavailable');
|
|
50
|
+
const nativeFile = image ? { file_name: 'image', image: true } : files[0]?.file_item;
|
|
51
|
+
if (files.length && (!nativeFile || !id(nativeFile.file_name)
|
|
52
|
+
|| /[\x00-\x1f\x7f/\\]/.test(nativeFile.file_name))) throw weixinRefusal('resource-unavailable');
|
|
53
|
+
const text = voice ? (transcript || '[WeChat voice message: platform did not provide a transcript]')
|
|
54
|
+
: extractWeixinText(message) || (nativeFile ? (image ? '[Image]' : `[File: ${nativeFile.file_name}]`) : '');
|
|
30
55
|
const time = typeof message.create_time_ms === 'string' ? Number(message.create_time_ms) : message.create_time_ms;
|
|
31
56
|
if (!messageId || !/^\d+$/.test(messageId) || !text?.trim() || text.length > 16000
|
|
32
57
|
|| !Number.isSafeInteger(time) || time <= 0 || !continuation(message.context_token)) throw weixinRefusal('invalid-inbound');
|
|
33
58
|
const at = new Date(time);
|
|
34
59
|
if (!Number.isFinite(at.getTime())) throw weixinRefusal('invalid-inbound');
|
|
35
60
|
const conversationId = account.ownerUserId;
|
|
61
|
+
const resourceKey = nativeFile ? createHash('sha256').update(JSON.stringify([
|
|
62
|
+
account.fingerprint, conversationId, messageId, nativeFile.file_name, nativeFile.len ?? null, ...(image ? ['image'] : []),
|
|
63
|
+
])).digest('hex') : undefined;
|
|
64
|
+
const size = nativeFile?.len === undefined ? undefined : Number(nativeFile.len);
|
|
65
|
+
if (nativeFile?.len !== undefined && (!/^\d+$/.test(String(nativeFile.len))
|
|
66
|
+
|| !Number.isSafeInteger(size) || size < 0)) throw weixinRefusal('resource-unavailable');
|
|
67
|
+
const attachments = nativeFile ? Object.freeze([Object.freeze({
|
|
68
|
+
id: createHash('sha256').update(JSON.stringify([account.fingerprint, conversationId, messageId, resourceKey])).digest('hex'),
|
|
69
|
+
messageId, resourceKey, name: nativeFile.file_name,
|
|
70
|
+
...(size > 0 ? { sizeBytes: size } : {}), mediaType: image ? 'image/unknown' : 'application/octet-stream',
|
|
71
|
+
})]) : undefined;
|
|
36
72
|
return Object.freeze({ version: 1, channel: 'weixin', botId, fingerprint: account.fingerprint,
|
|
37
73
|
eventId: messageId, messageId, actor: Object.freeze({ kind: 'user', id: account.ownerUserId }),
|
|
38
74
|
conversation: Object.freeze({ kind: 'dm', id: conversationId }), mentions: Object.freeze([]),
|
|
39
|
-
mentionedAccount: false, at: at.toISOString(), text,
|
|
75
|
+
mentionedAccount: false, at: at.toISOString(), text, ...(voice ? { voice } : {}), ...(attachments ? { attachments } : {}),
|
|
40
76
|
reply: Object.freeze({ messageId, conversationId, actorId: account.ownerUserId }),
|
|
41
77
|
replay: Object.freeze({ kind: 'provider-redelivery', resumeCursor: false, gapPossible: true }) });
|
|
42
78
|
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { detectedImageMediaType } from '../shared/image-prompt.mjs';
|
|
2
|
+
import { weixinRefusal } from './external-consumer.mjs';
|
|
3
|
+
|
|
4
|
+
export const WEIXIN_EXTERNAL_FILE_LIMIT = 25 * 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
/** A source-scoped file ticket is private state, not a model-readable download URL. */
|
|
7
|
+
export function privateWeixinFile(message, event) {
|
|
8
|
+
if (!event.attachments?.length) return undefined;
|
|
9
|
+
const native = message.item_list.find(item => item.type === 4 || item.type === 2);
|
|
10
|
+
const image = native?.type === 2;
|
|
11
|
+
const file = image ? native.image_item : native?.file_item;
|
|
12
|
+
const media = file?.media;
|
|
13
|
+
if (!media || typeof media !== 'object'
|
|
14
|
+
|| (!(image && typeof file.aeskey === 'string' && /^[a-fA-F0-9]{32}$/.test(file.aeskey))
|
|
15
|
+
&& (typeof media.aes_key !== 'string' || !media.aes_key || media.aes_key.length > 128))
|
|
16
|
+
|| ![media.encrypt_query_param, media.full_url].some(value => typeof value === 'string' && value.length > 0 && value.length <= 16384))
|
|
17
|
+
throw weixinRefusal('resource-unavailable');
|
|
18
|
+
return { attachment: event.attachments[0], ...(image ? { kind: 'image' } : {}), item: {
|
|
19
|
+
...(image ? (typeof file.aeskey === 'string' ? { aeskey: file.aeskey } : {}) : { file_name: file.file_name }),
|
|
20
|
+
...(file.len === undefined ? {} : { len: String(file.len) }),
|
|
21
|
+
media: { aes_key: media.aes_key, encrypt_type: media.encrypt_type,
|
|
22
|
+
...(typeof media.encrypt_query_param === 'string' && media.encrypt_query_param.length <= 16384
|
|
23
|
+
? { encrypt_query_param: media.encrypt_query_param } : {}),
|
|
24
|
+
...(typeof media.full_url === 'string' && media.full_url.length <= 16384
|
|
25
|
+
? { full_url: media.full_url } : {}) } } };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function readWeixinExternalFile(api, source, attachment, { signal, assertCurrent }) {
|
|
29
|
+
assertCurrent();
|
|
30
|
+
const saved = source.file;
|
|
31
|
+
if (!saved || !attachment || Object.keys(attachment).some(key => !['id', 'messageId', 'resourceKey', 'name', 'sizeBytes', 'mediaType'].includes(key))
|
|
32
|
+
|| ['id', 'messageId', 'resourceKey', 'name', 'sizeBytes', 'mediaType'].some(key => attachment[key] !== saved.attachment[key]))
|
|
33
|
+
throw weixinRefusal('stale-route');
|
|
34
|
+
if (attachment.sizeBytes > WEIXIN_EXTERNAL_FILE_LIMIT) throw weixinRefusal('artifact-too-large');
|
|
35
|
+
const image = saved.kind === 'image';
|
|
36
|
+
const file = image
|
|
37
|
+
? api.inboundImages({ item_list: [{ type: 2, image_item: saved.item }] })[0]
|
|
38
|
+
: api.inboundFiles({ item_list: [{ type: 4, file_item: saved.item }] })[0];
|
|
39
|
+
if (!file) throw weixinRefusal('resource-unavailable');
|
|
40
|
+
const data = await file.load({ signal, maxBytes: WEIXIN_EXTERNAL_FILE_LIMIT });
|
|
41
|
+
assertCurrent();
|
|
42
|
+
if (!(data instanceof Uint8Array) || data.byteLength === 0) throw weixinRefusal('resource-unavailable');
|
|
43
|
+
if (data.byteLength > WEIXIN_EXTERNAL_FILE_LIMIT) throw weixinRefusal('artifact-too-large');
|
|
44
|
+
if (image && !detectedImageMediaType(data)) throw weixinRefusal('resource-unavailable');
|
|
45
|
+
if (saved.item.len !== undefined && data.byteLength !== Number(saved.item.len)) throw weixinRefusal('resource-unavailable');
|
|
46
|
+
return (async function* () { assertCurrent(); yield new Uint8Array(data); assertCurrent(); })();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function replyWeixinExternalFile(api, request, file, { signal, assertCurrent }) {
|
|
50
|
+
if (typeof file?.id !== 'string' || !file.id || file.id.length > 512
|
|
51
|
+
|| typeof file.name !== 'string' || !file.name.trim() || file.name.length > 512
|
|
52
|
+
|| /[\x00-\x1f\x7f/\\]/.test(file.name) || !(file.bytes instanceof Uint8Array)
|
|
53
|
+
|| !file.bytes.byteLength || file.bytes.byteLength > WEIXIN_EXTERNAL_FILE_LIMIT) throw weixinRefusal('bad-request');
|
|
54
|
+
assertCurrent();
|
|
55
|
+
try {
|
|
56
|
+
const image = typeof file.mediaType === 'string' && file.mediaType.startsWith('image/');
|
|
57
|
+
if (image && file.mediaType !== detectedImageMediaType(file.bytes)) throw weixinRefusal('bad-request');
|
|
58
|
+
const send = image ? api.sendImage : api.sendFile;
|
|
59
|
+
if (typeof send !== 'function') throw weixinRefusal('capability-unavailable');
|
|
60
|
+
const result = await send({ ...request, signal,
|
|
61
|
+
file: { artifactId: file.id, fileName: file.name, bytes: Buffer.from(file.bytes) },
|
|
62
|
+
beforeSend: assertCurrent });
|
|
63
|
+
assertCurrent();
|
|
64
|
+
if (typeof result?.messageId !== 'string' || !result.messageId.startsWith('dsh-weixin-'))
|
|
65
|
+
throw weixinRefusal('provider-result-unknown');
|
|
66
|
+
return { sent: true };
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (error?.code === 'artifact-provider-failed') throw weixinRefusal('file-upload-failed');
|
|
69
|
+
if (['artifact-permission-required', 'artifact-too-large', 'artifact-provider-rejected', 'artifact-rate-limited'].includes(error?.code))
|
|
70
|
+
throw weixinRefusal('file-provider-rejected');
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -205,7 +205,7 @@ export function extractWeixinImages(message, { fetchImpl = fetch } = {}) {
|
|
|
205
205
|
return images;
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
-
async function fetchWeixinFileCiphertext(url, { fetchImpl, signal }) {
|
|
208
|
+
async function fetchWeixinFileCiphertext(url, { fetchImpl, signal, maxBytes }) {
|
|
209
209
|
const response = await fetchImpl(new URL(url), {
|
|
210
210
|
method: 'GET',
|
|
211
211
|
signal,
|
|
@@ -219,7 +219,25 @@ async function fetchWeixinFileCiphertext(url, { fetchImpl, signal }) {
|
|
|
219
219
|
{ status: response?.status },
|
|
220
220
|
);
|
|
221
221
|
}
|
|
222
|
-
|
|
222
|
+
const tooLarge = () => Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
|
|
223
|
+
const declared = Number(response.headers?.get?.('content-length'));
|
|
224
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
225
|
+
await response.body?.cancel?.().catch(() => undefined);
|
|
226
|
+
throw tooLarge();
|
|
227
|
+
}
|
|
228
|
+
if (!response.body?.[Symbol.asyncIterator]) throw Object.assign(new Error('resource-unavailable'), { code: 'resource-unavailable' });
|
|
229
|
+
const chunks = [];
|
|
230
|
+
let size = 0;
|
|
231
|
+
try {
|
|
232
|
+
for await (const chunk of response.body) {
|
|
233
|
+
signal?.throwIfAborted();
|
|
234
|
+
size += chunk.byteLength;
|
|
235
|
+
if (size > maxBytes) throw tooLarge();
|
|
236
|
+
chunks.push(Buffer.from(chunk));
|
|
237
|
+
}
|
|
238
|
+
signal?.throwIfAborted();
|
|
239
|
+
return Buffer.concat(chunks, size);
|
|
240
|
+
} finally { await response.body.cancel?.().catch(() => undefined); }
|
|
223
241
|
}
|
|
224
242
|
|
|
225
243
|
/** Convert native iLink file items into lazily downloaded, decrypted file references. */
|
|
@@ -233,13 +251,17 @@ export function extractWeixinFiles(message, { fetchImpl = fetch } = {}) {
|
|
|
233
251
|
files.push({
|
|
234
252
|
name: nonEmptyString(fileItem.file_name) ?? (files.length === 0 ? 'file' : `file-${files.length + 1}`),
|
|
235
253
|
...(Number.isFinite(declaredSize) && declaredSize >= 0 ? { size: declaredSize } : {}),
|
|
236
|
-
load: async ({ signal } = {}) => {
|
|
254
|
+
load: async ({ signal, maxBytes = 25 * 1024 * 1024 } = {}) => {
|
|
237
255
|
signal?.throwIfAborted();
|
|
256
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > 25 * 1024 * 1024) throw new TypeError('Invalid file byte limit');
|
|
257
|
+
if (Number.isFinite(declaredSize) && declaredSize > maxBytes) throw Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
|
|
238
258
|
const key = parseWeixinImageAesKey(fileItem);
|
|
239
259
|
const url = weixinImageDownloadUrl(fileItem.media);
|
|
240
|
-
const ciphertext = await fetchWeixinFileCiphertext(url, { fetchImpl, signal });
|
|
260
|
+
const ciphertext = await fetchWeixinFileCiphertext(url, { fetchImpl, signal, maxBytes: maxBytes + 16 });
|
|
241
261
|
signal?.throwIfAborted();
|
|
242
|
-
|
|
262
|
+
const plaintext = decryptWeixinImage(ciphertext, key);
|
|
263
|
+
if (plaintext.length > maxBytes) throw Object.assign(new Error('artifact-too-large'), { code: 'artifact-too-large' });
|
|
264
|
+
return plaintext;
|
|
243
265
|
},
|
|
244
266
|
});
|
|
245
267
|
}
|
|
@@ -527,6 +549,7 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
|
|
|
527
549
|
contextToken,
|
|
528
550
|
runId,
|
|
529
551
|
signal,
|
|
552
|
+
beforeSend,
|
|
530
553
|
}, { mediaType, createItem }) {
|
|
531
554
|
const recipient = nonEmptyString(toUserId);
|
|
532
555
|
if (!recipient || !file || typeof file !== 'object'
|
|
@@ -600,6 +623,8 @@ export function createWeixinApi({ fetchImpl = fetch, uploadFetchImpl = fetchImpl
|
|
|
600
623
|
aes_key: Buffer.from(aesKey.toString('hex')).toString('base64'),
|
|
601
624
|
encrypt_type: 1,
|
|
602
625
|
};
|
|
626
|
+
await beforeSend?.();
|
|
627
|
+
signal?.throwIfAborted();
|
|
603
628
|
let response;
|
|
604
629
|
try {
|
|
605
630
|
response = await requestJson(fetchImpl, {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ExclusiveInboundConsumers } from '../shared/exclusive-inbound-consumers.mjs';
|
|
2
2
|
import { pairedWeixinAccount, normalizeWeixinExternalText, weixinRefusal } from './external-consumer.mjs';
|
|
3
|
+
import { privateWeixinFile } from './external-files.mjs';
|
|
3
4
|
import { randomUUID } from 'node:crypto';
|
|
4
5
|
import { createWeixinDiagnostics, knownWeixinErrorCode, weixinStageError } from './connection-error.mjs';
|
|
5
6
|
|
|
@@ -162,18 +163,19 @@ export class WeixinController {
|
|
|
162
163
|
return { version: 1, botId, channel: 'weixin', account,
|
|
163
164
|
connected: this.#runtimes.get(botId)?.status?.ready === true,
|
|
164
165
|
capabilities: ['proactive-text-checked', 'exclusive-text-consumer', 'reply-text-checked',
|
|
165
|
-
'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked'
|
|
166
|
+
'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked',
|
|
167
|
+
'source-file-checked', 'reply-file-checked', 'reply-file-fence-checked',
|
|
168
|
+
'source-image-checked', 'reply-image-fence-checked', 'source-voice-transcript-checked'] };
|
|
166
169
|
});
|
|
167
170
|
}
|
|
168
171
|
|
|
169
|
-
async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false } = {}) {
|
|
172
|
+
async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false, sourceImages = false, sourceVoiceTranscripts = false } = {}) {
|
|
170
173
|
return this.#withBotTransition(botId, async () => {
|
|
171
|
-
if (sourceFiles) throw weixinRefusal('capability-unavailable');
|
|
172
174
|
const config = this.#configStore.get(botId);
|
|
173
175
|
if (!config) throw weixinRefusal('unknown-bot');
|
|
174
176
|
const account = await this.#deliveryAccount(config, signal);
|
|
175
177
|
if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
|
|
176
|
-
const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal });
|
|
178
|
+
const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceFiles, sourceImages, sourceVoiceTranscripts });
|
|
177
179
|
try {
|
|
178
180
|
const saved = await this.#configStore.save({ ...config, consumerMode: 'external-consumer' });
|
|
179
181
|
await this.#startRuntime(saved, await this.#resolveToken(saved.tokenRef));
|
|
@@ -208,6 +210,13 @@ export class WeixinController {
|
|
|
208
210
|
});
|
|
209
211
|
}
|
|
210
212
|
|
|
213
|
+
async externalFileChecked(botId, route, file, options = {}) {
|
|
214
|
+
return this.#withBotTransition(botId, async () => {
|
|
215
|
+
const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
|
|
216
|
+
return checked.runtime.externalFileChecked(route, file, { ...options, ...checked });
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
211
220
|
async startProvisioning() {
|
|
212
221
|
if (this.#closed) throw new Error('dsh-weixin controller is closed');
|
|
213
222
|
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
|
|
@@ -666,11 +675,15 @@ export class WeixinController {
|
|
|
666
675
|
const current = await this.#deliveryAccount(this.#configStore.get(config.botId), signal);
|
|
667
676
|
if (current.fingerprint !== account.fingerprint) throw weixinRefusal('account-changed');
|
|
668
677
|
this.#inboundConsumers.signalFor(config.botId, account.fingerprint).throwIfAborted();
|
|
669
|
-
const event = normalizeWeixinExternalText(message, { botId: config.botId, account
|
|
678
|
+
const event = normalizeWeixinExternalText(message, { botId: config.botId, account,
|
|
679
|
+
sourceFiles: this.#inboundConsumers.acceptsFiles(config.botId),
|
|
680
|
+
sourceImages: this.#inboundConsumers.acceptsImages(config.botId),
|
|
681
|
+
sourceVoiceTranscripts: this.#inboundConsumers.acceptsVoiceTranscripts(config.botId) });
|
|
670
682
|
if (!event) return { accepted: true, ignored: true };
|
|
671
683
|
await state.rememberExternalReplySource({ messageId: event.messageId, actorId: event.actor.id,
|
|
672
684
|
fingerprint: account.fingerprint, contextToken: message.context_token,
|
|
673
|
-
expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000
|
|
685
|
+
expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000,
|
|
686
|
+
...(event.attachments?.length ? { file: privateWeixinFile(message, event) } : {}) });
|
|
674
687
|
return this.#inboundConsumers.accept(config.botId, event, signal);
|
|
675
688
|
} });
|
|
676
689
|
} catch (error) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { checkedWeixinRoute, weixinRefusal } from './external-consumer.mjs';
|
|
2
|
+
import { readWeixinExternalFile, replyWeixinExternalFile } from './external-files.mjs';
|
|
2
3
|
import { createWeixinDiagnostics } from './connection-error.mjs';
|
|
3
4
|
import { DEFAULT_WEIXIN_MAX_MESSAGE_CHARS, WeixinApiError, rejectedProviderResponse } from './weixin-api.mjs';
|
|
4
5
|
import {
|
|
@@ -331,6 +332,21 @@ export class WeixinRuntime {
|
|
|
331
332
|
conversationId: checked.conversationId, identityKind: 'client-acknowledgement' } } : {}) };
|
|
332
333
|
}
|
|
333
334
|
|
|
335
|
+
async externalFileChecked(route, file, { account, signal, reply = false, beforeSend } = {}) {
|
|
336
|
+
const source = this.#state.externalReplySource(route?.messageId);
|
|
337
|
+
checkedWeixinRoute(route, account, source);
|
|
338
|
+
const assertCurrent = () => {
|
|
339
|
+
signal?.throwIfAborted();
|
|
340
|
+
checkedWeixinRoute(route, account, this.#state.externalReplySource(route.messageId));
|
|
341
|
+
if (reply && (!beforeSend || beforeSend() !== true)) throw weixinRefusal('stale-route');
|
|
342
|
+
};
|
|
343
|
+
return reply ? replyWeixinExternalFile(this.#api, {
|
|
344
|
+
baseUrl: this.#config.baseUrl, token: this.#token, toUserId: route.actorId,
|
|
345
|
+
contextToken: source.contextToken,
|
|
346
|
+
}, file, { signal, assertCurrent })
|
|
347
|
+
: readWeixinExternalFile(this.#api, source, file, { signal, assertCurrent });
|
|
348
|
+
}
|
|
349
|
+
|
|
334
350
|
async stop() {
|
|
335
351
|
const warnings = [];
|
|
336
352
|
const monitor = this.#monitor;
|