dsh-message-gateway 0.1.33 → 0.1.35
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/README.en.md +32 -3
- package/README.es.md +32 -3
- package/README.md +33 -3
- package/lib/client.js +108 -27
- package/lib/client.js.map +2 -2
- package/lib/index.js +970 -65
- package/lib/index.js.map +4 -4
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -8,19 +8,88 @@ var __export = (target, all) => {
|
|
|
8
8
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
+
// src/host/incoming.ts
|
|
12
|
+
async function downloadBytes(url, opts = {}) {
|
|
13
|
+
const { timeoutMs = 6e4, maxBytes = 100 * 1024 * 1024, headers } = opts;
|
|
14
|
+
if (!/^https?:\/\//i.test(url)) throw new Error("\u975E\u6CD5\u4E0B\u8F7D\u5730\u5740");
|
|
15
|
+
const controller = new AbortController();
|
|
16
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
17
|
+
try {
|
|
18
|
+
const response = await fetch(url, { headers, signal: controller.signal });
|
|
19
|
+
if (!response.ok) throw new Error(`\u4E0B\u8F7D\u5931\u8D25 HTTP ${response.status}`);
|
|
20
|
+
const contentLength = Number(response.headers.get("content-length") ?? "0");
|
|
21
|
+
if (contentLength > maxBytes) throw new Error("\u9644\u4EF6\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
|
|
22
|
+
const buf = new Uint8Array(await response.arrayBuffer());
|
|
23
|
+
if (buf.byteLength > maxBytes) throw new Error("\u9644\u4EF6\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
|
|
24
|
+
return buf;
|
|
25
|
+
} finally {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function collectStream(stream) {
|
|
30
|
+
const chunks = [];
|
|
31
|
+
let total = 0;
|
|
32
|
+
const iterable = stream;
|
|
33
|
+
for await (const chunk of iterable) {
|
|
34
|
+
chunks.push(chunk);
|
|
35
|
+
total += chunk.byteLength;
|
|
36
|
+
}
|
|
37
|
+
const out = new Uint8Array(total);
|
|
38
|
+
let offset = 0;
|
|
39
|
+
for (const chunk of chunks) {
|
|
40
|
+
out.set(chunk, offset);
|
|
41
|
+
offset += chunk.byteLength;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
var init_incoming = __esm({
|
|
46
|
+
"src/host/incoming.ts"() {
|
|
47
|
+
"use strict";
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
|
|
11
51
|
// src/host/wechat-ilink-bridge.ts
|
|
12
52
|
var wechat_ilink_bridge_exports = {};
|
|
13
53
|
__export(wechat_ilink_bridge_exports, {
|
|
14
54
|
WechatIlinkBridge: () => WechatIlinkBridge
|
|
15
55
|
});
|
|
16
56
|
import crypto from "node:crypto";
|
|
17
|
-
|
|
57
|
+
function parseIlinkAesKey(aesKeyBase64) {
|
|
58
|
+
const decoded = Buffer.from(aesKeyBase64, "base64");
|
|
59
|
+
if (decoded.length === 16) return decoded;
|
|
60
|
+
if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(decoded.toString("ascii"))) {
|
|
61
|
+
return Buffer.from(decoded.toString("ascii"), "hex");
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`aes_key \u65E0\u6CD5\u8BC6\u522B\uFF08\u89E3\u7801\u540E ${decoded.length} \u5B57\u8282\uFF09`);
|
|
64
|
+
}
|
|
65
|
+
function ilinkMediaUrl(media) {
|
|
66
|
+
if (typeof media.full_url === "string" && media.full_url !== "") return media.full_url;
|
|
67
|
+
const param = typeof media.encrypt_query_param === "string" ? media.encrypt_query_param : "";
|
|
68
|
+
return `${ILINK_CDN_BASE}/download?encrypted_query_param=${encodeURIComponent(param)}`;
|
|
69
|
+
}
|
|
70
|
+
async function downloadIlinkMedia(media) {
|
|
71
|
+
const encrypted = await downloadBytes(ilinkMediaUrl(media), { maxBytes: ILINK_MEDIA_MAX_BYTES });
|
|
72
|
+
const aesKey = typeof media.aes_key === "string" ? media.aes_key : "";
|
|
73
|
+
if (aesKey === "") return encrypted;
|
|
74
|
+
const key = parseIlinkAesKey(aesKey);
|
|
75
|
+
const decipher = crypto.createDecipheriv("aes-128-ecb", key, null);
|
|
76
|
+
return new Uint8Array(Buffer.concat([decipher.update(Buffer.from(encrypted)), decipher.final()]));
|
|
77
|
+
}
|
|
78
|
+
var ILINK_BASE_URL, ILINK_APP_ID, ILINK_CLIENT_VERSION, ILINK_CDN_BASE, ILINK_MEDIA_MAX_BYTES, ITEM_TEXT, ITEM_IMAGE, ITEM_VOICE, ITEM_FILE, ITEM_VIDEO, WechatIlinkBridge;
|
|
18
79
|
var init_wechat_ilink_bridge = __esm({
|
|
19
80
|
"src/host/wechat-ilink-bridge.ts"() {
|
|
20
81
|
"use strict";
|
|
82
|
+
init_incoming();
|
|
21
83
|
ILINK_BASE_URL = "https://ilinkai.weixin.qq.com";
|
|
22
84
|
ILINK_APP_ID = "bot";
|
|
23
85
|
ILINK_CLIENT_VERSION = (2 & 255) << 16 | (4 & 255) << 8 | 8 & 255;
|
|
86
|
+
ILINK_CDN_BASE = "https://novac2c.cdn.weixin.qq.com/c2c";
|
|
87
|
+
ILINK_MEDIA_MAX_BYTES = 100 * 1024 * 1024;
|
|
88
|
+
ITEM_TEXT = 1;
|
|
89
|
+
ITEM_IMAGE = 2;
|
|
90
|
+
ITEM_VOICE = 3;
|
|
91
|
+
ITEM_FILE = 4;
|
|
92
|
+
ITEM_VIDEO = 5;
|
|
24
93
|
WechatIlinkBridge = class _WechatIlinkBridge {
|
|
25
94
|
stopped = false;
|
|
26
95
|
pollController = null;
|
|
@@ -148,7 +217,7 @@ var init_wechat_ilink_bridge = __esm({
|
|
|
148
217
|
const msgs = data.msgs ?? [];
|
|
149
218
|
for (const msg of msgs) {
|
|
150
219
|
if (msg.message_type !== 1) continue;
|
|
151
|
-
this.handleInboundMessage(msg);
|
|
220
|
+
void this.handleInboundMessage(msg);
|
|
152
221
|
}
|
|
153
222
|
} catch (err) {
|
|
154
223
|
if (this.stopped) break;
|
|
@@ -163,18 +232,62 @@ var init_wechat_ilink_bridge = __esm({
|
|
|
163
232
|
/**
|
|
164
233
|
* 处理单条从微信拉取到的消息。
|
|
165
234
|
*/
|
|
166
|
-
handleInboundMessage(msg) {
|
|
235
|
+
async handleInboundMessage(msg) {
|
|
167
236
|
const fromUser = String(msg.from_user_id ?? "");
|
|
168
237
|
if (!fromUser) return;
|
|
169
238
|
let text = "";
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
239
|
+
const attachments = [];
|
|
240
|
+
const notes = [];
|
|
241
|
+
const items = Array.isArray(msg.item_list) ? msg.item_list : [];
|
|
242
|
+
for (const item of items) {
|
|
243
|
+
if (item.type === ITEM_TEXT && item.text_item?.text) {
|
|
244
|
+
text += (text ? "\n" : "") + String(item.text_item.text).trim();
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (item.type === ITEM_IMAGE) {
|
|
248
|
+
const img = item.image_item;
|
|
249
|
+
if (img?.media === void 0) continue;
|
|
250
|
+
try {
|
|
251
|
+
const aesKey = typeof img.aeskey === "string" && img.aeskey !== "" ? Buffer.from(img.aeskey, "hex").toString("base64") : img.media.aes_key;
|
|
252
|
+
const data = await downloadIlinkMedia({ ...img.media, aes_key: aesKey });
|
|
253
|
+
attachments.push({ kind: "image", data });
|
|
254
|
+
} catch (error) {
|
|
255
|
+
notes.push(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
174
256
|
}
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (item.type === ITEM_VOICE) {
|
|
260
|
+
const voice = item.voice_item;
|
|
261
|
+
if (typeof voice?.text === "string" && voice.text.trim() !== "") {
|
|
262
|
+
text += (text ? "\n" : "") + voice.text.trim();
|
|
263
|
+
}
|
|
264
|
+
if (voice?.media !== void 0) {
|
|
265
|
+
try {
|
|
266
|
+
const data = await downloadIlinkMedia(voice.media);
|
|
267
|
+
attachments.push({ kind: "file", data, name: "voice.silk" });
|
|
268
|
+
} catch (error) {
|
|
269
|
+
notes.push(`\uFF08\u8BED\u97F3\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (item.type === ITEM_FILE || item.type === ITEM_VIDEO) {
|
|
275
|
+
const node = item.type === ITEM_FILE ? item.file_item : item.video_item;
|
|
276
|
+
if (node?.media === void 0) continue;
|
|
277
|
+
const fallbackName = item.type === ITEM_FILE ? "file.bin" : "video.mp4";
|
|
278
|
+
const name = typeof node.file_name === "string" && node.file_name !== "" ? node.file_name : fallbackName;
|
|
279
|
+
try {
|
|
280
|
+
const data = await downloadIlinkMedia(node.media);
|
|
281
|
+
attachments.push({ kind: "file", data, name });
|
|
282
|
+
} catch (error) {
|
|
283
|
+
notes.push(`\uFF08${item.type === ITEM_FILE ? "\u6587\u4EF6" : "\u89C6\u9891"}\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
284
|
+
}
|
|
285
|
+
continue;
|
|
175
286
|
}
|
|
176
287
|
}
|
|
177
|
-
if (
|
|
288
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
289
|
+
${notes.join("\n")}`;
|
|
290
|
+
if (text === "" && attachments.length === 0) return;
|
|
178
291
|
const contextToken = msg.context_token ?? "";
|
|
179
292
|
const sessionId = msg.session_id || fromUser;
|
|
180
293
|
const frame = {
|
|
@@ -219,7 +332,7 @@ var init_wechat_ilink_bridge = __esm({
|
|
|
219
332
|
sink,
|
|
220
333
|
chatType: msg.group_id ? "group" : "single"
|
|
221
334
|
};
|
|
222
|
-
this.callbacks.onText(text, identity);
|
|
335
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
223
336
|
}
|
|
224
337
|
/**
|
|
225
338
|
* 获取微信用户的 typing_ticket(打字态凭证)。
|
|
@@ -695,6 +808,64 @@ var WecomBridge = class {
|
|
|
695
808
|
const content = frame.body?.text?.content ?? "";
|
|
696
809
|
if (content.trim() !== "") this.callbacks.onText(content, frame);
|
|
697
810
|
});
|
|
811
|
+
client.on("message.image", async (frame) => {
|
|
812
|
+
const img = frame.body?.image;
|
|
813
|
+
if (img?.url === void 0 || img.url === "") return;
|
|
814
|
+
try {
|
|
815
|
+
const { buffer, filename } = await client.downloadFile(img.url, img.aeskey);
|
|
816
|
+
if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
|
|
817
|
+
this.callbacks.onText("", frame, [{ kind: "image", data: new Uint8Array(buffer), name: filename }]);
|
|
818
|
+
} catch (err) {
|
|
819
|
+
this.callbacks.onText(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
|
|
820
|
+
}
|
|
821
|
+
});
|
|
822
|
+
client.on("message.file", async (frame) => {
|
|
823
|
+
const f = frame.body?.file;
|
|
824
|
+
if (f?.url === void 0 || f.url === "") return;
|
|
825
|
+
try {
|
|
826
|
+
const { buffer, filename } = await client.downloadFile(f.url, f.aeskey);
|
|
827
|
+
if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
|
|
828
|
+
this.callbacks.onText("", frame, [{ kind: "file", data: new Uint8Array(buffer), name: filename }]);
|
|
829
|
+
} catch (err) {
|
|
830
|
+
this.callbacks.onText(`\uFF08\u6587\u4EF6\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
client.on("message.video", async (frame) => {
|
|
834
|
+
const v = frame.body?.video;
|
|
835
|
+
if (v?.url === void 0 || v.url === "") return;
|
|
836
|
+
try {
|
|
837
|
+
const { buffer, filename } = await client.downloadFile(v.url, v.aeskey);
|
|
838
|
+
if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
|
|
839
|
+
this.callbacks.onText("", frame, [{ kind: "file", data: new Uint8Array(buffer), name: filename ?? "video.mp4" }]);
|
|
840
|
+
} catch (err) {
|
|
841
|
+
this.callbacks.onText(`\uFF08\u89C6\u9891\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
|
|
842
|
+
}
|
|
843
|
+
});
|
|
844
|
+
client.on("message.mixed", async (frame) => {
|
|
845
|
+
const items = frame.body?.mixed?.msg_item ?? [];
|
|
846
|
+
const texts = [];
|
|
847
|
+
const attachments = [];
|
|
848
|
+
for (const item of items) {
|
|
849
|
+
if (item.msgtype === "text") {
|
|
850
|
+
const t = item.text?.content ?? "";
|
|
851
|
+
if (t.trim() !== "") texts.push(t.trim());
|
|
852
|
+
} else if (item.msgtype === "image" && item.image?.url) {
|
|
853
|
+
try {
|
|
854
|
+
const { buffer } = await client.downloadFile(item.image.url, item.image.aeskey);
|
|
855
|
+
if (buffer.byteLength > 0) {
|
|
856
|
+
attachments.push({ kind: "image", data: new Uint8Array(buffer) });
|
|
857
|
+
}
|
|
858
|
+
} catch (err) {
|
|
859
|
+
texts.push(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
this.callbacks.onText(texts.join("\n"), frame, attachments.length > 0 ? attachments : void 0);
|
|
864
|
+
});
|
|
865
|
+
client.on("message.voice", (frame) => {
|
|
866
|
+
const content = frame.body?.voice?.content ?? "";
|
|
867
|
+
if (content.trim() !== "") this.callbacks.onText(content, frame);
|
|
868
|
+
});
|
|
698
869
|
client.on("event.enter_chat", (frame) => {
|
|
699
870
|
this.callbacks.onEnter(frame);
|
|
700
871
|
});
|
|
@@ -834,11 +1005,25 @@ async function smartFetch(url, init) {
|
|
|
834
1005
|
json: () => res.json()
|
|
835
1006
|
};
|
|
836
1007
|
}
|
|
1008
|
+
async function smartFetchBinary(url, init) {
|
|
1009
|
+
const urlStr = String(url);
|
|
1010
|
+
const isOverseas = /discord\.com|discordapp\.com|telegram\.org|api\.openai\.com/i.test(urlStr);
|
|
1011
|
+
if (isOverseas) {
|
|
1012
|
+
const dispatcher = await getProxyDispatcher();
|
|
1013
|
+
if (dispatcher) {
|
|
1014
|
+
const res2 = await undiciFetch(urlStr, { ...init, dispatcher });
|
|
1015
|
+
return { status: res2.status, arrayBuffer: () => res2.arrayBuffer() };
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const res = await fetch(url, init);
|
|
1019
|
+
return { status: res.status, arrayBuffer: () => res.arrayBuffer() };
|
|
1020
|
+
}
|
|
837
1021
|
|
|
838
1022
|
// src/host/telegram-bridge.ts
|
|
839
1023
|
var EDIT_INTERVAL_MS = 1200;
|
|
840
1024
|
var MSG_LIMIT = 4096;
|
|
841
1025
|
var POLL_TIMEOUT = 25;
|
|
1026
|
+
var TG_DOWNLOAD_LIMIT = 20 * 1024 * 1024;
|
|
842
1027
|
var TelegramBridge = class {
|
|
843
1028
|
constructor(token, callbacks) {
|
|
844
1029
|
this.token = token;
|
|
@@ -900,7 +1085,7 @@ var TelegramBridge = class {
|
|
|
900
1085
|
const updates = result;
|
|
901
1086
|
for (const update of updates) {
|
|
902
1087
|
this.offset = Math.max(this.offset, update.update_id + 1);
|
|
903
|
-
if (update.message !== void 0) this.handleMessage(update.message);
|
|
1088
|
+
if (update.message !== void 0) void this.handleMessage(update.message);
|
|
904
1089
|
}
|
|
905
1090
|
} else {
|
|
906
1091
|
this.setStatus("error", "poll failed");
|
|
@@ -908,13 +1093,53 @@ var TelegramBridge = class {
|
|
|
908
1093
|
}
|
|
909
1094
|
if (!this.stopped) this.pollTimer = setTimeout(() => void this.poll(), 0);
|
|
910
1095
|
}
|
|
911
|
-
handleMessage(m) {
|
|
1096
|
+
async handleMessage(m) {
|
|
912
1097
|
const from = m.from;
|
|
913
1098
|
if (from?.is_bot === true) return;
|
|
914
|
-
const text = typeof m.text === "string" ? m.text.trim() : "";
|
|
915
|
-
if (text === "") return;
|
|
916
1099
|
const chat = m.chat;
|
|
917
1100
|
if (chat === void 0) return;
|
|
1101
|
+
const caption = typeof m.caption === "string" ? m.caption.trim() : "";
|
|
1102
|
+
let text = typeof m.text === "string" ? m.text.trim() : "";
|
|
1103
|
+
if (text === "") text = caption;
|
|
1104
|
+
const notes = [];
|
|
1105
|
+
const attachments = [];
|
|
1106
|
+
if (Array.isArray(m.photo) && m.photo.length > 0) {
|
|
1107
|
+
const sizes = m.photo;
|
|
1108
|
+
const best = sizes.reduce((a, b) => {
|
|
1109
|
+
const sa = a.file_size ?? (a.width ?? 0) * (a.height ?? 0);
|
|
1110
|
+
const sb = b.file_size ?? (b.width ?? 0) * (b.height ?? 0);
|
|
1111
|
+
return sb > sa ? b : a;
|
|
1112
|
+
});
|
|
1113
|
+
if (best.file_id !== void 0) {
|
|
1114
|
+
const data = await this.downloadTelegramFile(best.file_id);
|
|
1115
|
+
if (data !== null) attachments.push({ kind: "image", data });
|
|
1116
|
+
else notes.push("\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09");
|
|
1117
|
+
}
|
|
1118
|
+
} else {
|
|
1119
|
+
const mediaKeys = ["animation", "document", "video", "video_note", "voice", "audio", "sticker"];
|
|
1120
|
+
for (const key of mediaKeys) {
|
|
1121
|
+
const media = m[key];
|
|
1122
|
+
if (media?.file_id === void 0) continue;
|
|
1123
|
+
const size = media.file_size ?? 0;
|
|
1124
|
+
if (size > TG_DOWNLOAD_LIMIT) {
|
|
1125
|
+
notes.push(`\uFF08${key} \u8D85\u8FC7\u5B98\u65B9 20MB \u4E0B\u8F7D\u4E0A\u9650\uFF0C\u672A\u4E0B\u8F7D\uFF09`);
|
|
1126
|
+
break;
|
|
1127
|
+
}
|
|
1128
|
+
const data = await this.downloadTelegramFile(media.file_id);
|
|
1129
|
+
if (data !== null) {
|
|
1130
|
+
attachments.push({ kind: "file", data, name: media.file_name, mediaType: media.mime_type });
|
|
1131
|
+
} else {
|
|
1132
|
+
notes.push(`\uFF08${key} \u4E0B\u8F7D\u5931\u8D25\uFF09`);
|
|
1133
|
+
}
|
|
1134
|
+
break;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
if (text === "" && attachments.length === 0 && notes.length === 0) {
|
|
1138
|
+
const contentKeys = ["contact", "location", "venue", "poll", "dice", "game", "forward_origin"];
|
|
1139
|
+
if (!contentKeys.some((k) => m[k] !== void 0)) return;
|
|
1140
|
+
text = "\uFF08\u6536\u5230\u8BE5\u7C7B\u578B Telegram \u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09";
|
|
1141
|
+
}
|
|
1142
|
+
if (text === "" && notes.length > 0) text = notes.join("\n");
|
|
918
1143
|
const frame = { chatId: chat.id, messageId: m.message_id ?? 0, chatType: chat.type ?? "private" };
|
|
919
1144
|
const sink = {
|
|
920
1145
|
stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
|
|
@@ -925,8 +1150,26 @@ var TelegramBridge = class {
|
|
|
925
1150
|
sink,
|
|
926
1151
|
chatType: (chat.type ?? "private") === "private" ? "single" : "group"
|
|
927
1152
|
};
|
|
928
|
-
console.log("[dsh-message-gateway] telegram text", { chatId: chat.id, text: text.slice(0, 60) });
|
|
929
|
-
this.callbacks.onText(text, identity);
|
|
1153
|
+
console.log("[dsh-message-gateway] telegram text", { chatId: chat.id, text: text.slice(0, 60), atts: attachments.length });
|
|
1154
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
1155
|
+
}
|
|
1156
|
+
/** 官方文档:getFile(file_id) → file_path → https://api.telegram.org/file/bot<token>/<file_path>。 */
|
|
1157
|
+
async downloadTelegramFile(fileId) {
|
|
1158
|
+
try {
|
|
1159
|
+
const result = await this.api("getFile", { file_id: fileId });
|
|
1160
|
+
const filePath = result?.result?.file_path;
|
|
1161
|
+
if (filePath === void 0 || filePath === "") return null;
|
|
1162
|
+
const dispatcher = await getProxyDispatcher();
|
|
1163
|
+
const response = await fetch(`https://api.telegram.org/file/bot${this.token}/${filePath}`, {
|
|
1164
|
+
signal: AbortSignal.timeout(6e4),
|
|
1165
|
+
...dispatcher ? { dispatcher } : {}
|
|
1166
|
+
});
|
|
1167
|
+
if (!response.ok) return null;
|
|
1168
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
1169
|
+
} catch (error) {
|
|
1170
|
+
console.warn("[dsh-message-gateway] telegram download failed", fileId, String(error));
|
|
1171
|
+
return null;
|
|
1172
|
+
}
|
|
930
1173
|
}
|
|
931
1174
|
/** 流式回复:状态合并 + 单 worker——首次 sendMessage,随后 editMessageText 渐进更新(限频)。 */
|
|
932
1175
|
async streamReply(frame, streamId, content, finish) {
|
|
@@ -1033,6 +1276,7 @@ var REST = "https://discord.com/api/v10";
|
|
|
1033
1276
|
var INTENTS = 1 << 0 | 1 << 9 | 1 << 12 | 1 << 15;
|
|
1034
1277
|
var EDIT_INTERVAL_MS2 = 1200;
|
|
1035
1278
|
var MSG_LIMIT2 = 2e3;
|
|
1279
|
+
var DISCORD_ATTACH_MAX_BYTES = 50 * 1024 * 1024;
|
|
1036
1280
|
var DiscordBridge = class {
|
|
1037
1281
|
constructor(token, callbacks) {
|
|
1038
1282
|
this.token = token;
|
|
@@ -1115,7 +1359,7 @@ var DiscordBridge = class {
|
|
|
1115
1359
|
this.setStatus("connected", name);
|
|
1116
1360
|
console.log("[dsh-message-gateway] discord READY", name);
|
|
1117
1361
|
} else if (payload.t === "MESSAGE_CREATE") {
|
|
1118
|
-
this.handleMessage(payload.d);
|
|
1362
|
+
void this.handleMessage(payload.d);
|
|
1119
1363
|
}
|
|
1120
1364
|
break;
|
|
1121
1365
|
}
|
|
@@ -1166,11 +1410,37 @@ var DiscordBridge = class {
|
|
|
1166
1410
|
clearTimeout(timer);
|
|
1167
1411
|
}
|
|
1168
1412
|
}
|
|
1169
|
-
handleMessage(d) {
|
|
1413
|
+
async handleMessage(d) {
|
|
1170
1414
|
const author = d.author;
|
|
1171
1415
|
if (author?.bot === true) return;
|
|
1172
|
-
|
|
1173
|
-
|
|
1416
|
+
let text = typeof d.content === "string" ? d.content.trim() : "";
|
|
1417
|
+
const notes = [];
|
|
1418
|
+
const attachments = [];
|
|
1419
|
+
const rawAtts = Array.isArray(d.attachments) ? d.attachments : [];
|
|
1420
|
+
for (const a of rawAtts) {
|
|
1421
|
+
const filename = typeof a.filename === "string" ? a.filename : "\u672A\u77E5";
|
|
1422
|
+
const buf = await this.downloadAttachment(a);
|
|
1423
|
+
if (buf === null) {
|
|
1424
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${filename}\u300D\u4E0B\u8F7D\u5931\u8D25\uFF09`);
|
|
1425
|
+
continue;
|
|
1426
|
+
}
|
|
1427
|
+
const contentType = typeof a.content_type === "string" ? a.content_type : "";
|
|
1428
|
+
attachments.push({
|
|
1429
|
+
kind: contentType.startsWith("image/") ? "image" : "file",
|
|
1430
|
+
data: buf,
|
|
1431
|
+
mediaType: contentType === "" ? void 0 : contentType,
|
|
1432
|
+
name: filename
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
const embeds = Array.isArray(d.embeds) ? d.embeds : [];
|
|
1436
|
+
for (const e of embeds) {
|
|
1437
|
+
const title = typeof e.title === "string" ? e.title : "";
|
|
1438
|
+
const url = typeof e.url === "string" ? e.url : "";
|
|
1439
|
+
if (title !== "" || url !== "") notes.push(`\uFF08\u5D4C\u5165\u5185\u5BB9\uFF1A${title} ${url}\uFF09`.replace(/\s+/g, " "));
|
|
1440
|
+
}
|
|
1441
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
1442
|
+
${notes.join("\n")}`;
|
|
1443
|
+
if (text === "" && attachments.length === 0) return;
|
|
1174
1444
|
const channelId = String(d.channel_id ?? "");
|
|
1175
1445
|
if (channelId === "") return;
|
|
1176
1446
|
const guildId = typeof d.guild_id === "string" ? d.guild_id : "";
|
|
@@ -1184,8 +1454,39 @@ var DiscordBridge = class {
|
|
|
1184
1454
|
sink,
|
|
1185
1455
|
chatType: guildId === "" ? "single" : "group"
|
|
1186
1456
|
};
|
|
1187
|
-
console.log("[dsh-message-gateway] discord text", { channelId, text: text.slice(0, 60) });
|
|
1188
|
-
this.callbacks.onText(text, identity);
|
|
1457
|
+
console.log("[dsh-message-gateway] discord text", { channelId, text: text.slice(0, 60), atts: attachments.length });
|
|
1458
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* 下载附件。官方 Reference 明确要求合法的 User-Agent(否则可能被 Cloudflare 拦截);
|
|
1462
|
+
* CDN 是签名 URL,官方未说明是否需要 Bot 鉴权,故先不带鉴权、401/403 时带 token 重试。
|
|
1463
|
+
*/
|
|
1464
|
+
async downloadAttachment(att) {
|
|
1465
|
+
const url = typeof att.url === "string" ? att.url : "";
|
|
1466
|
+
if (url === "") return null;
|
|
1467
|
+
const userAgent = "DiscordBot (https://github.com/a792883583/dsh-message-gateway, 1.0.0)";
|
|
1468
|
+
try {
|
|
1469
|
+
let response = await smartFetchBinary(url, { headers: { "User-Agent": userAgent }, signal: AbortSignal.timeout(6e4) });
|
|
1470
|
+
if (response.status === 401 || response.status === 403) {
|
|
1471
|
+
response = await smartFetchBinary(url, {
|
|
1472
|
+
headers: { "User-Agent": userAgent, authorization: `Bot ${this.token}` },
|
|
1473
|
+
signal: AbortSignal.timeout(6e4)
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
if (response.status !== 200) {
|
|
1477
|
+
console.warn("[dsh-message-gateway] discord attachment http", response.status);
|
|
1478
|
+
return null;
|
|
1479
|
+
}
|
|
1480
|
+
const buf = new Uint8Array(await response.arrayBuffer());
|
|
1481
|
+
if (buf.byteLength > DISCORD_ATTACH_MAX_BYTES) {
|
|
1482
|
+
console.warn("[dsh-message-gateway] discord attachment too large", buf.byteLength);
|
|
1483
|
+
return null;
|
|
1484
|
+
}
|
|
1485
|
+
return buf;
|
|
1486
|
+
} catch (error) {
|
|
1487
|
+
console.warn("[dsh-message-gateway] discord attachment failed", String(error));
|
|
1488
|
+
return null;
|
|
1489
|
+
}
|
|
1189
1490
|
}
|
|
1190
1491
|
/** 流式回复:状态合并 + 单 worker——首次发送消息,随后 PATCH 渐进更新(限频)。 */
|
|
1191
1492
|
async streamReply(frame, streamId, content, finish) {
|
|
@@ -1271,11 +1572,47 @@ var DiscordBridge = class {
|
|
|
1271
1572
|
};
|
|
1272
1573
|
|
|
1273
1574
|
// src/host/qq-bridge.ts
|
|
1575
|
+
init_incoming();
|
|
1274
1576
|
import { createPrivateKey, sign, verify } from "node:crypto";
|
|
1275
1577
|
var TOKEN_URL = "https://api.bot.qq.com/app/getAppAccessToken";
|
|
1276
1578
|
var BASE = "https://api.bot.qq.com";
|
|
1277
1579
|
var INTENTS2 = 1 << 25;
|
|
1278
1580
|
var DEDUP_CAP = 64;
|
|
1581
|
+
var QQ_ATTACH_MAX_BYTES = 200 * 1024 * 1024;
|
|
1582
|
+
async function collectQqAttachments(node) {
|
|
1583
|
+
const attachments = [];
|
|
1584
|
+
const asrTexts = [];
|
|
1585
|
+
const notes = [];
|
|
1586
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1587
|
+
const walk = async (item) => {
|
|
1588
|
+
const list = Array.isArray(item.attachments) ? item.attachments : [];
|
|
1589
|
+
for (const a of list) {
|
|
1590
|
+
const url = typeof a.url === "string" ? a.url : "";
|
|
1591
|
+
const name = typeof a.filename === "string" && a.filename !== "" ? a.filename : "\u672A\u77E5";
|
|
1592
|
+
if (typeof a.asr_refer_text === "string" && a.asr_refer_text.trim() !== "") {
|
|
1593
|
+
asrTexts.push(a.asr_refer_text.trim());
|
|
1594
|
+
}
|
|
1595
|
+
if (url === "" || seen.has(url)) continue;
|
|
1596
|
+
seen.add(url);
|
|
1597
|
+
try {
|
|
1598
|
+
const data = await downloadBytes(url, { maxBytes: QQ_ATTACH_MAX_BYTES });
|
|
1599
|
+
const contentType = typeof a.content_type === "string" ? a.content_type : "";
|
|
1600
|
+
attachments.push({
|
|
1601
|
+
kind: contentType.startsWith("image/") ? "image" : "file",
|
|
1602
|
+
data,
|
|
1603
|
+
mediaType: contentType === "" ? void 0 : contentType,
|
|
1604
|
+
name
|
|
1605
|
+
});
|
|
1606
|
+
} catch (error) {
|
|
1607
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${name}\u300D\u4E0B\u8F7D\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
const elements = Array.isArray(item.msg_elements) ? item.msg_elements : [];
|
|
1611
|
+
for (const el of elements) await walk(el);
|
|
1612
|
+
};
|
|
1613
|
+
await walk(node);
|
|
1614
|
+
return { attachments, asrTexts, notes };
|
|
1615
|
+
}
|
|
1279
1616
|
function qqEd25519Key(secret) {
|
|
1280
1617
|
let seed = secret;
|
|
1281
1618
|
while (Buffer.byteLength(seed) < 32) seed += seed;
|
|
@@ -1517,9 +1854,9 @@ var QQBridge = class {
|
|
|
1517
1854
|
this.setStatus("connected", "qq");
|
|
1518
1855
|
console.log("[dsh-message-gateway] qq READY");
|
|
1519
1856
|
} else if (payload.t === "C2C_MESSAGE_CREATE") {
|
|
1520
|
-
this.handleMessage(payload.d, "c2c");
|
|
1857
|
+
void this.handleMessage(payload.d, "c2c");
|
|
1521
1858
|
} else if (payload.t === "GROUP_AT_MESSAGE_CREATE") {
|
|
1522
|
-
this.handleMessage(payload.d, "group");
|
|
1859
|
+
void this.handleMessage(payload.d, "group");
|
|
1523
1860
|
}
|
|
1524
1861
|
break;
|
|
1525
1862
|
}
|
|
@@ -1587,11 +1924,10 @@ var QQBridge = class {
|
|
|
1587
1924
|
}
|
|
1588
1925
|
}
|
|
1589
1926
|
/** 单聊/群聊消息分发(content 群聊已去 @前缀)。 */
|
|
1590
|
-
handleMessage(d, scene) {
|
|
1927
|
+
async handleMessage(d, scene) {
|
|
1591
1928
|
const author = d.author;
|
|
1592
1929
|
if (author?.bot === true) return;
|
|
1593
|
-
|
|
1594
|
-
if (text === "") return;
|
|
1930
|
+
let text = typeof d.content === "string" ? d.content.trim() : "";
|
|
1595
1931
|
const msgId = String(d.id ?? "");
|
|
1596
1932
|
if (msgId === "") return;
|
|
1597
1933
|
if (this.recentMsgIds.has(msgId)) return;
|
|
@@ -1602,6 +1938,12 @@ var QQBridge = class {
|
|
|
1602
1938
|
}
|
|
1603
1939
|
const openid = scene === "c2c" ? author?.user_openid ?? "" : String(d.group_openid ?? "");
|
|
1604
1940
|
if (openid === "") return;
|
|
1941
|
+
const { attachments, asrTexts, notes } = await collectQqAttachments(d);
|
|
1942
|
+
if (asrTexts.length > 0) text = text === "" ? asrTexts.join("\n") : `${text}
|
|
1943
|
+
${asrTexts.join("\n")}`;
|
|
1944
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
1945
|
+
${notes.join("\n")}`;
|
|
1946
|
+
if (text === "" && attachments.length === 0) return;
|
|
1605
1947
|
const frame = { openid, msgId, scene };
|
|
1606
1948
|
const sink = {
|
|
1607
1949
|
// 单聊:流式(ack 开启,「正在处理…」就地增长);群聊:不支持流式,关闭 ack 只发定稿。
|
|
@@ -1615,8 +1957,8 @@ var QQBridge = class {
|
|
|
1615
1957
|
sink,
|
|
1616
1958
|
chatType: scene === "c2c" ? "single" : "group"
|
|
1617
1959
|
};
|
|
1618
|
-
console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60) });
|
|
1619
|
-
this.callbacks.onText(text, identity);
|
|
1960
|
+
console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60), atts: attachments.length });
|
|
1961
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
1620
1962
|
}
|
|
1621
1963
|
/** 停止网关连接。 */
|
|
1622
1964
|
stop() {
|
|
@@ -1699,8 +2041,17 @@ var QqWebhookBridge = class {
|
|
|
1699
2041
|
sink,
|
|
1700
2042
|
chatType: scene === "c2c" ? "single" : "group"
|
|
1701
2043
|
};
|
|
1702
|
-
|
|
1703
|
-
|
|
2044
|
+
void (async () => {
|
|
2045
|
+
let body = typeof d.content === "string" ? d.content.trim() : "";
|
|
2046
|
+
const { attachments, asrTexts, notes } = await collectQqAttachments(d);
|
|
2047
|
+
if (asrTexts.length > 0) body = body === "" ? asrTexts.join("\n") : `${body}
|
|
2048
|
+
${asrTexts.join("\n")}`;
|
|
2049
|
+
if (notes.length > 0) body = body === "" ? notes.join("\n") : `${body}
|
|
2050
|
+
${notes.join("\n")}`;
|
|
2051
|
+
if (body === "" && attachments.length === 0) return;
|
|
2052
|
+
console.log("[dsh-message-gateway] qq webhook text", { scene, openid, text: body.slice(0, 60), atts: attachments.length });
|
|
2053
|
+
this.callbacks.onText(body, identity, attachments.length > 0 ? attachments : void 0);
|
|
2054
|
+
})();
|
|
1704
2055
|
return true;
|
|
1705
2056
|
}
|
|
1706
2057
|
/** 确保 access_token 未过期(提前 60s 刷新)。 */
|
|
@@ -1756,6 +2107,245 @@ var QqWebhookBridge = class {
|
|
|
1756
2107
|
// src/host/email-bridge.ts
|
|
1757
2108
|
import { connect } from "node:net";
|
|
1758
2109
|
import { connect as tlsConnect } from "node:tls";
|
|
2110
|
+
|
|
2111
|
+
// src/host/email-mime.ts
|
|
2112
|
+
function tokenize(text) {
|
|
2113
|
+
let i = 0;
|
|
2114
|
+
const parseList = () => {
|
|
2115
|
+
if (text[i] !== "(") return null;
|
|
2116
|
+
i += 1;
|
|
2117
|
+
const out = [];
|
|
2118
|
+
while (i < text.length) {
|
|
2119
|
+
const c = text[i];
|
|
2120
|
+
if (c === " " || c === "\r" || c === "\n" || c === " ") {
|
|
2121
|
+
i += 1;
|
|
2122
|
+
continue;
|
|
2123
|
+
}
|
|
2124
|
+
if (c === ")") {
|
|
2125
|
+
i += 1;
|
|
2126
|
+
return out;
|
|
2127
|
+
}
|
|
2128
|
+
if (c === "(") {
|
|
2129
|
+
const inner = parseList();
|
|
2130
|
+
if (inner === null) return null;
|
|
2131
|
+
out.push(inner);
|
|
2132
|
+
continue;
|
|
2133
|
+
}
|
|
2134
|
+
if (c === '"') {
|
|
2135
|
+
i += 1;
|
|
2136
|
+
let s = "";
|
|
2137
|
+
while (i < text.length && text[i] !== '"') {
|
|
2138
|
+
if (text[i] === "\\" && i + 1 < text.length) {
|
|
2139
|
+
i += 1;
|
|
2140
|
+
s += text[i];
|
|
2141
|
+
i += 1;
|
|
2142
|
+
continue;
|
|
2143
|
+
}
|
|
2144
|
+
s += text[i];
|
|
2145
|
+
i += 1;
|
|
2146
|
+
}
|
|
2147
|
+
i += 1;
|
|
2148
|
+
out.push(s);
|
|
2149
|
+
continue;
|
|
2150
|
+
}
|
|
2151
|
+
let atom = "";
|
|
2152
|
+
while (i < text.length && !" ()\r\n ".includes(text[i])) {
|
|
2153
|
+
atom += text[i];
|
|
2154
|
+
i += 1;
|
|
2155
|
+
}
|
|
2156
|
+
out.push(atom.toUpperCase() === "NIL" ? null : atom);
|
|
2157
|
+
}
|
|
2158
|
+
return out;
|
|
2159
|
+
};
|
|
2160
|
+
while (i < text.length && /\s/.test(text[i])) i += 1;
|
|
2161
|
+
return parseList();
|
|
2162
|
+
}
|
|
2163
|
+
function asParams(tok) {
|
|
2164
|
+
const out = {};
|
|
2165
|
+
if (!Array.isArray(tok)) return out;
|
|
2166
|
+
for (let i = 0; i + 1 < tok.length; i += 2) {
|
|
2167
|
+
const k = tok[i];
|
|
2168
|
+
const v = tok[i + 1];
|
|
2169
|
+
if (typeof k === "string" && typeof v === "string") out[k.toLowerCase()] = v;
|
|
2170
|
+
}
|
|
2171
|
+
return out;
|
|
2172
|
+
}
|
|
2173
|
+
function pctToBuffer(s) {
|
|
2174
|
+
const bytes = [];
|
|
2175
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
2176
|
+
if (s[i] === "%" && i + 2 < s.length) {
|
|
2177
|
+
const hex = s.slice(i + 1, i + 3);
|
|
2178
|
+
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
|
2179
|
+
bytes.push(parseInt(hex, 16));
|
|
2180
|
+
i += 2;
|
|
2181
|
+
continue;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
bytes.push(s.charCodeAt(i) & 255);
|
|
2185
|
+
}
|
|
2186
|
+
return Buffer.from(bytes);
|
|
2187
|
+
}
|
|
2188
|
+
function bufferToString(buf, charset) {
|
|
2189
|
+
const cs = charset.trim().toLowerCase();
|
|
2190
|
+
if (cs === "iso-8859-1" || cs === "latin1" || cs === "windows-1252") return buf.toString("latin1");
|
|
2191
|
+
if (cs === "us-ascii" || cs === "ascii") return buf.toString("ascii");
|
|
2192
|
+
return buf.toString("utf8");
|
|
2193
|
+
}
|
|
2194
|
+
function decodeRfc2231(value) {
|
|
2195
|
+
const m = value.match(/^([^']*)'([^']*)'(.*)$/);
|
|
2196
|
+
const charset = m === null ? "utf-8" : m[1];
|
|
2197
|
+
const encoded = m === null ? value : m[3];
|
|
2198
|
+
return bufferToString(pctToBuffer(encoded), charset);
|
|
2199
|
+
}
|
|
2200
|
+
function decodeEncodedWords(value) {
|
|
2201
|
+
return value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g, (_all, charset, enc, text) => {
|
|
2202
|
+
try {
|
|
2203
|
+
if (enc.toUpperCase() === "B") return bufferToString(Buffer.from(text, "base64"), charset);
|
|
2204
|
+
const qp = text.replace(/_/g, " ").replace(/=([0-9A-Fa-f]{2})/g, (_x, h) => String.fromCharCode(parseInt(h, 16)));
|
|
2205
|
+
return bufferToString(Buffer.from(qp, "latin1"), charset);
|
|
2206
|
+
} catch {
|
|
2207
|
+
return text;
|
|
2208
|
+
}
|
|
2209
|
+
});
|
|
2210
|
+
}
|
|
2211
|
+
function paramValue(params, base) {
|
|
2212
|
+
const single = params[`${base}*`];
|
|
2213
|
+
if (single !== void 0) return { value: single, extended: true };
|
|
2214
|
+
const parts = [];
|
|
2215
|
+
const re = new RegExp(`^${base}\\*(\\d+)(\\*)?$`);
|
|
2216
|
+
for (const [k, v] of Object.entries(params)) {
|
|
2217
|
+
const m = k.match(re);
|
|
2218
|
+
if (m !== null) parts.push({ i: Number(m[1]), v, ext: m[2] === "*" });
|
|
2219
|
+
}
|
|
2220
|
+
if (parts.length > 0) {
|
|
2221
|
+
parts.sort((a, b) => a.i - b.i);
|
|
2222
|
+
return { value: parts.map((p) => p.v).join(""), extended: parts[0].ext };
|
|
2223
|
+
}
|
|
2224
|
+
const plain = params[base];
|
|
2225
|
+
return plain === void 0 ? null : { value: plain, extended: false };
|
|
2226
|
+
}
|
|
2227
|
+
function sanitizeFilename(name) {
|
|
2228
|
+
const base = name.split(/[\\/]/).pop() ?? name;
|
|
2229
|
+
const cleaned = base.replace(/[\u0000-\u001f\u007f]/g, "").trim();
|
|
2230
|
+
return cleaned === "" ? "attachment" : cleaned;
|
|
2231
|
+
}
|
|
2232
|
+
function pickFilename(params) {
|
|
2233
|
+
for (const base of ["filename", "name"]) {
|
|
2234
|
+
const hit = paramValue(params, base);
|
|
2235
|
+
if (hit === null) continue;
|
|
2236
|
+
const decoded = hit.extended ? decodeRfc2231(hit.value) : decodeEncodedWords(hit.value);
|
|
2237
|
+
if (decoded.trim() !== "") return sanitizeFilename(decoded);
|
|
2238
|
+
}
|
|
2239
|
+
return "";
|
|
2240
|
+
}
|
|
2241
|
+
function interpret(sexp, prefix) {
|
|
2242
|
+
if (!Array.isArray(sexp) || sexp.length === 0) return null;
|
|
2243
|
+
if (Array.isArray(sexp[0])) {
|
|
2244
|
+
const children = [];
|
|
2245
|
+
let idx = 0;
|
|
2246
|
+
while (idx < sexp.length && Array.isArray(sexp[idx])) {
|
|
2247
|
+
const childPart = prefix === "" ? String(children.length + 1) : `${prefix}.${children.length + 1}`;
|
|
2248
|
+
const child = interpret(sexp[idx], childPart);
|
|
2249
|
+
if (child !== null) children.push(child);
|
|
2250
|
+
idx += 1;
|
|
2251
|
+
}
|
|
2252
|
+
const subtypeRaw = sexp[idx];
|
|
2253
|
+
const subtype2 = typeof subtypeRaw === "string" ? subtypeRaw.toLowerCase() : "mixed";
|
|
2254
|
+
const params2 = asParams(sexp[idx + 1]);
|
|
2255
|
+
return {
|
|
2256
|
+
part: prefix,
|
|
2257
|
+
type: "multipart",
|
|
2258
|
+
subtype: subtype2,
|
|
2259
|
+
params: params2,
|
|
2260
|
+
id: "",
|
|
2261
|
+
encoding: "",
|
|
2262
|
+
octets: 0,
|
|
2263
|
+
disposition: "",
|
|
2264
|
+
filename: "",
|
|
2265
|
+
children
|
|
2266
|
+
};
|
|
2267
|
+
}
|
|
2268
|
+
const type = typeof sexp[0] === "string" ? sexp[0].toLowerCase() : "application";
|
|
2269
|
+
const subtype = typeof sexp[1] === "string" ? sexp[1].toLowerCase() : "octet-stream";
|
|
2270
|
+
const params = asParams(sexp[2]);
|
|
2271
|
+
const id = typeof sexp[3] === "string" ? sexp[3].replace(/^<|>$/g, "") : "";
|
|
2272
|
+
const encoding = typeof sexp[5] === "string" ? sexp[5].toLowerCase() : "7bit";
|
|
2273
|
+
const octets = Number(sexp[6] ?? 0) || 0;
|
|
2274
|
+
let disposition = "";
|
|
2275
|
+
let dispParams = {};
|
|
2276
|
+
for (let i = 7; i < sexp.length; i += 1) {
|
|
2277
|
+
const el = sexp[i];
|
|
2278
|
+
if (Array.isArray(el) && el.length >= 1 && typeof el[0] === "string") {
|
|
2279
|
+
disposition = el[0].toLowerCase();
|
|
2280
|
+
dispParams = asParams(el[1]);
|
|
2281
|
+
break;
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
const merged = { ...params, ...dispParams };
|
|
2285
|
+
return {
|
|
2286
|
+
part: prefix === "" ? "1" : prefix,
|
|
2287
|
+
type,
|
|
2288
|
+
subtype,
|
|
2289
|
+
params: merged,
|
|
2290
|
+
id,
|
|
2291
|
+
encoding,
|
|
2292
|
+
octets,
|
|
2293
|
+
disposition,
|
|
2294
|
+
filename: pickFilename(merged),
|
|
2295
|
+
children: []
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
function parseBodyStructure(sexp) {
|
|
2299
|
+
const tok = tokenize(sexp);
|
|
2300
|
+
if (tok === null) return null;
|
|
2301
|
+
return interpret(tok, "");
|
|
2302
|
+
}
|
|
2303
|
+
function flattenParts(root) {
|
|
2304
|
+
if (root === null) return [];
|
|
2305
|
+
const out = [];
|
|
2306
|
+
const walk = (node) => {
|
|
2307
|
+
if (node.children.length > 0) {
|
|
2308
|
+
for (const c of node.children) walk(c);
|
|
2309
|
+
return;
|
|
2310
|
+
}
|
|
2311
|
+
out.push(node);
|
|
2312
|
+
};
|
|
2313
|
+
walk(root);
|
|
2314
|
+
return out;
|
|
2315
|
+
}
|
|
2316
|
+
function decodeBody(raw, encoding) {
|
|
2317
|
+
const enc = encoding.toLowerCase();
|
|
2318
|
+
if (enc === "base64") {
|
|
2319
|
+
return new Uint8Array(Buffer.from(raw.replace(/[^A-Za-z0-9+/=]/g, ""), "base64"));
|
|
2320
|
+
}
|
|
2321
|
+
if (enc === "quoted-printable") {
|
|
2322
|
+
const bytes = [];
|
|
2323
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
2324
|
+
if (raw[i] === "=") {
|
|
2325
|
+
if (raw[i + 1] === "\r" && raw[i + 2] === "\n") {
|
|
2326
|
+
i += 2;
|
|
2327
|
+
continue;
|
|
2328
|
+
}
|
|
2329
|
+
if (raw[i + 1] === "\n") {
|
|
2330
|
+
i += 1;
|
|
2331
|
+
continue;
|
|
2332
|
+
}
|
|
2333
|
+
const hex = raw.slice(i + 1, i + 3);
|
|
2334
|
+
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
|
2335
|
+
bytes.push(parseInt(hex, 16));
|
|
2336
|
+
i += 2;
|
|
2337
|
+
continue;
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
bytes.push(raw.charCodeAt(i) & 255);
|
|
2341
|
+
}
|
|
2342
|
+
return new Uint8Array(Buffer.from(bytes));
|
|
2343
|
+
}
|
|
2344
|
+
return new Uint8Array(Buffer.from(raw, "latin1"));
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
// src/host/email-bridge.ts
|
|
2348
|
+
var EMAIL_ATTACH_MAX_BYTES = 25 * 1024 * 1024;
|
|
1759
2349
|
var POLL_MS = 3e4;
|
|
1760
2350
|
var RETRY_MS = 5e3;
|
|
1761
2351
|
var MAX_BODY = 12e3;
|
|
@@ -1919,6 +2509,49 @@ var ImapClient = class {
|
|
|
1919
2509
|
const text = literalAt(res, "BODY[TEXT]")?.value ?? "";
|
|
1920
2510
|
return { uid, header, text };
|
|
1921
2511
|
}
|
|
2512
|
+
/**
|
|
2513
|
+
* 取 BODYSTRUCTURE(RFC 3501 §6.4.5):一次拿到整棵 MIME 树,
|
|
2514
|
+
* 含每个 part 的类型/参数/ID/编码/字节数与 Content-Disposition,
|
|
2515
|
+
* 便于在下载正文前判断哪些是附件。BODY.PEEK 不置 \Seen。
|
|
2516
|
+
*/
|
|
2517
|
+
async fetchStructure(id) {
|
|
2518
|
+
let res;
|
|
2519
|
+
try {
|
|
2520
|
+
res = await this.command(`FETCH ${id} (UID BODYSTRUCTURE)`, 3e4);
|
|
2521
|
+
} catch {
|
|
2522
|
+
return null;
|
|
2523
|
+
}
|
|
2524
|
+
const idx = res.indexOf("BODYSTRUCTURE");
|
|
2525
|
+
if (idx === -1) return null;
|
|
2526
|
+
const start = res.indexOf("(", idx);
|
|
2527
|
+
if (start === -1) return null;
|
|
2528
|
+
let depth = 0;
|
|
2529
|
+
for (let i = start; i < res.length; i += 1) {
|
|
2530
|
+
const c = res[i];
|
|
2531
|
+
if (c === '"') {
|
|
2532
|
+
i += 1;
|
|
2533
|
+
while (i < res.length && res[i] !== '"') {
|
|
2534
|
+
if (res[i] === "\\") i += 1;
|
|
2535
|
+
i += 1;
|
|
2536
|
+
}
|
|
2537
|
+
continue;
|
|
2538
|
+
}
|
|
2539
|
+
if (c === "(") depth += 1;
|
|
2540
|
+
else if (c === ")") {
|
|
2541
|
+
depth -= 1;
|
|
2542
|
+
if (depth === 0) return parseBodyStructure(res.slice(start, i + 1));
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
return null;
|
|
2546
|
+
}
|
|
2547
|
+
/**
|
|
2548
|
+
* 拉取指定 part 的正文(原始编码,尚未 base64/QP 解码)。
|
|
2549
|
+
* RFC 3501 §6.4.5:必须用 BODY.PEEK 以免把邮件标记为已读。
|
|
2550
|
+
*/
|
|
2551
|
+
async fetchPart(id, part) {
|
|
2552
|
+
const res = await this.command(`FETCH ${id} (BODY.PEEK[${part}])`, 6e4);
|
|
2553
|
+
return literalAt(res, `BODY[${part}]`)?.value ?? "";
|
|
2554
|
+
}
|
|
1922
2555
|
async markSeen(id) {
|
|
1923
2556
|
await this.command(`STORE ${id} +FLAGS (\\Seen)`);
|
|
1924
2557
|
}
|
|
@@ -2217,10 +2850,52 @@ var EmailBridge = class {
|
|
|
2217
2850
|
const threadKey = references[0] ?? (inReplyTo !== "" ? inReplyTo : messageId);
|
|
2218
2851
|
const from = parseAddress(headerField(fetched.header, "From"));
|
|
2219
2852
|
const subject = headerField(fetched.header, "Subject");
|
|
2220
|
-
const
|
|
2853
|
+
const root = await this.imap.fetchStructure(id);
|
|
2854
|
+
const parts = flattenParts(root);
|
|
2855
|
+
const notes = [];
|
|
2856
|
+
const attachments = [];
|
|
2857
|
+
const textNode = parts.find((p) => p.type === "text" && p.subtype === "plain");
|
|
2858
|
+
let text = "";
|
|
2859
|
+
if (textNode !== void 0) {
|
|
2860
|
+
try {
|
|
2861
|
+
const raw = await this.imap.fetchPart(id, textNode.part);
|
|
2862
|
+
text = cleanBody(Buffer.from(decodeBody(raw, textNode.encoding)).toString("utf8"));
|
|
2863
|
+
} catch {
|
|
2864
|
+
notes.push("\uFF08\u6B63\u6587\u8BFB\u53D6\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u539F\u59CB\u6B63\u6587\uFF09");
|
|
2865
|
+
}
|
|
2866
|
+
}
|
|
2867
|
+
if (text.trim() === "") text = cleanBody(fetched.text);
|
|
2868
|
+
for (const p of parts) {
|
|
2869
|
+
if (p === textNode) continue;
|
|
2870
|
+
const isAttachment = p.disposition === "attachment" || p.disposition === "" && p.filename !== "" || p.disposition !== "inline" && p.filename !== "" && p.disposition !== "attachment";
|
|
2871
|
+
if (!isAttachment) continue;
|
|
2872
|
+
if (p.filename === "") continue;
|
|
2873
|
+
if (p.octets > EMAIL_ATTACH_MAX_BYTES) {
|
|
2874
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u7EA6 ${Math.round(p.octets / 1024 / 1024)}MB\uFF0C\u8D85\u8FC7\u4E0A\u9650\u672A\u4E0B\u8F7D\uFF09`);
|
|
2875
|
+
continue;
|
|
2876
|
+
}
|
|
2877
|
+
try {
|
|
2878
|
+
const raw = await this.imap.fetchPart(id, p.part);
|
|
2879
|
+
const data = decodeBody(raw, p.encoding);
|
|
2880
|
+
if (data.byteLength === 0) {
|
|
2881
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u4E3A\u7A7A\uFF09`);
|
|
2882
|
+
continue;
|
|
2883
|
+
}
|
|
2884
|
+
attachments.push({
|
|
2885
|
+
kind: p.type === "image" ? "image" : "file",
|
|
2886
|
+
data,
|
|
2887
|
+
mediaType: p.type === "image" ? `image/${p.subtype}` : `${p.type}/${p.subtype}`,
|
|
2888
|
+
name: p.filename
|
|
2889
|
+
});
|
|
2890
|
+
} catch (error) {
|
|
2891
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u8BFB\u53D6\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2221
2894
|
void this.imap.markSeen(id).catch(() => {
|
|
2222
2895
|
});
|
|
2223
|
-
if (
|
|
2896
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
2897
|
+
${notes.join("\n")}`;
|
|
2898
|
+
if (from === "" || text.trim() === "" && attachments.length === 0) return;
|
|
2224
2899
|
const frame = { from, subject, threadKey };
|
|
2225
2900
|
const sink = {
|
|
2226
2901
|
ack: false,
|
|
@@ -2236,8 +2911,8 @@ var EmailBridge = class {
|
|
|
2236
2911
|
sink,
|
|
2237
2912
|
chatType: "single"
|
|
2238
2913
|
};
|
|
2239
|
-
console.log("[dsh-message-gateway] email text", { from, subject: subject.slice(0, 40), len: text.length });
|
|
2240
|
-
this.callbacks.onText(text, identity);
|
|
2914
|
+
console.log("[dsh-message-gateway] email text", { from, subject: subject.slice(0, 40), len: text.length, atts: attachments.length });
|
|
2915
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
2241
2916
|
}
|
|
2242
2917
|
async sendReply(frame, content) {
|
|
2243
2918
|
try {
|
|
@@ -2282,7 +2957,9 @@ function sleep(ms) {
|
|
|
2282
2957
|
}
|
|
2283
2958
|
|
|
2284
2959
|
// src/host/feishu-bridge.ts
|
|
2960
|
+
init_incoming();
|
|
2285
2961
|
import * as lark from "@larksuiteoapi/node-sdk";
|
|
2962
|
+
var FEISHU_TEXT_TYPES = /* @__PURE__ */ new Set(["text"]);
|
|
2286
2963
|
var FeishuBridge = class {
|
|
2287
2964
|
constructor(cred, callbacks) {
|
|
2288
2965
|
this.cred = cred;
|
|
@@ -2318,23 +2995,66 @@ var FeishuBridge = class {
|
|
|
2318
2995
|
"im.message.receive_v1": async (data) => {
|
|
2319
2996
|
try {
|
|
2320
2997
|
const msg = data.message;
|
|
2321
|
-
if (!msg
|
|
2322
|
-
const
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2998
|
+
if (!msg) return;
|
|
2999
|
+
const messageId = msg.message_id;
|
|
3000
|
+
const messageType = msg.message_type;
|
|
3001
|
+
let text = "";
|
|
3002
|
+
const attachments = [];
|
|
3003
|
+
if (FEISHU_TEXT_TYPES.has(messageType)) {
|
|
3004
|
+
const parsedContent = JSON.parse(msg.content || "{}");
|
|
3005
|
+
text = parsedContent.text || "";
|
|
3006
|
+
if (msg.chat_type === "group" && Array.isArray(msg.mentions)) {
|
|
3007
|
+
for (const mention of msg.mentions) {
|
|
3008
|
+
if (mention.key) {
|
|
3009
|
+
text = text.replace(new RegExp(mention.key, "g"), "").trim();
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
3013
|
+
} else if (messageType === "image") {
|
|
3014
|
+
const parsed = JSON.parse(msg.content || "{}");
|
|
3015
|
+
if (parsed.image_key !== void 0) {
|
|
3016
|
+
const data2 = await this.downloadMessageResource(messageId, parsed.image_key, "image");
|
|
3017
|
+
if (data2 === null) text = "\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09";
|
|
3018
|
+
else attachments.push({ kind: "image", data: data2, name: `${parsed.image_key}.img` });
|
|
3019
|
+
}
|
|
3020
|
+
} else if (messageType === "file" || messageType === "audio" || messageType === "media") {
|
|
3021
|
+
const parsed = JSON.parse(msg.content || "{}");
|
|
3022
|
+
if (parsed.file_key !== void 0) {
|
|
3023
|
+
const data2 = await this.downloadMessageResource(messageId, parsed.file_key, "file");
|
|
3024
|
+
if (data2 === null) text = "\uFF08\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF09";
|
|
3025
|
+
else attachments.push({ kind: "file", data: data2, name: parsed.file_name ?? `${parsed.file_key}.bin` });
|
|
3026
|
+
}
|
|
3027
|
+
} else if (messageType === "post") {
|
|
3028
|
+
const parsed = JSON.parse(msg.content || "{}");
|
|
3029
|
+
const rows = parsed.content_v2 ?? parsed.content ?? [];
|
|
3030
|
+
const texts = [];
|
|
3031
|
+
for (const row of rows) {
|
|
3032
|
+
for (const node of row) {
|
|
3033
|
+
if (node.tag === "text" && typeof node.text === "string") texts.push(node.text);
|
|
3034
|
+
else if (node.tag === "img" && node.image_key !== void 0) {
|
|
3035
|
+
const data2 = await this.downloadMessageResource(messageId, node.image_key, "image");
|
|
3036
|
+
if (data2 !== null) attachments.push({ kind: "image", data: data2, name: `${node.image_key}.img` });
|
|
3037
|
+
}
|
|
2328
3038
|
}
|
|
2329
3039
|
}
|
|
3040
|
+
text = texts.join("");
|
|
3041
|
+
} else if (messageType === "sticker") {
|
|
3042
|
+
text = "\uFF08\u6536\u5230\u8868\u60C5\u5305\u6D88\u606F\uFF1A\u98DE\u4E66\u4E0D\u652F\u6301\u4E0B\u8F7D\u8868\u60C5\u5305\u8D44\u6E90\uFF0C\u65E0\u6CD5\u5904\u7406\uFF09";
|
|
3043
|
+
} else {
|
|
3044
|
+
text = `\uFF08\u6536\u5230\u98DE\u4E66\u300C${messageType}\u300D\u7C7B\u578B\u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09`;
|
|
2330
3045
|
}
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
3046
|
+
text = text.trim();
|
|
3047
|
+
if (text === "" && attachments.length === 0) return;
|
|
3048
|
+
this.callbacks.onText(
|
|
3049
|
+
text,
|
|
3050
|
+
{
|
|
3051
|
+
chatId: msg.chat_id,
|
|
3052
|
+
messageId,
|
|
3053
|
+
senderId: data.sender?.sender_id?.user_id || data.sender?.sender_id?.open_id || "",
|
|
3054
|
+
chatType: msg.chat_type === "group" ? "group" : "single"
|
|
3055
|
+
},
|
|
3056
|
+
attachments.length > 0 ? attachments : void 0
|
|
3057
|
+
);
|
|
2338
3058
|
} catch (err) {
|
|
2339
3059
|
console.error("[dsh-message-gateway] feishu message parsing error", err);
|
|
2340
3060
|
}
|
|
@@ -2353,6 +3073,31 @@ var FeishuBridge = class {
|
|
|
2353
3073
|
this.setStatus("error", error instanceof Error ? error.message : String(error));
|
|
2354
3074
|
}
|
|
2355
3075
|
}
|
|
3076
|
+
/**
|
|
3077
|
+
* 下载消息中的资源文件。
|
|
3078
|
+
*
|
|
3079
|
+
* 官方文档:必须使用「获取消息中的资源文件」
|
|
3080
|
+
* `GET /open-apis/im/v1/messages/:message_id/resources/:file_key`——
|
|
3081
|
+
* **不能**用 `im/v1/images/:image_key`(后者只能下载机器人自己上传的图片,
|
|
3082
|
+
* 下载用户发来的图会报 234008)。图片把 image_key 的值填到 file_key 位置。
|
|
3083
|
+
*
|
|
3084
|
+
* @param messageId 消息 ID
|
|
3085
|
+
* @param fileKey 图片传 image_key;文件/音频/视频传 file_key
|
|
3086
|
+
* @param type image=图片(含富文本图片);file=文件/音频/视频
|
|
3087
|
+
*/
|
|
3088
|
+
async downloadMessageResource(messageId, fileKey, type) {
|
|
3089
|
+
if (this.client === null) return null;
|
|
3090
|
+
try {
|
|
3091
|
+
const res = await this.client.im.messageResource.get({
|
|
3092
|
+
params: { type },
|
|
3093
|
+
path: { message_id: messageId, file_key: fileKey }
|
|
3094
|
+
});
|
|
3095
|
+
return await collectStream(res.getReadableStream());
|
|
3096
|
+
} catch (error) {
|
|
3097
|
+
console.warn("[dsh-message-gateway] feishu resource download failed", fileKey, String(error));
|
|
3098
|
+
return null;
|
|
3099
|
+
}
|
|
3100
|
+
}
|
|
2356
3101
|
/**
|
|
2357
3102
|
* 回复某条消息(通过 message_id 引用回复)。
|
|
2358
3103
|
*/
|
|
@@ -2406,6 +3151,7 @@ var FeishuBridge = class {
|
|
|
2406
3151
|
};
|
|
2407
3152
|
|
|
2408
3153
|
// src/host/dingtalk-bridge.ts
|
|
3154
|
+
init_incoming();
|
|
2409
3155
|
import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
|
|
2410
3156
|
var DingTalkBridge = class {
|
|
2411
3157
|
constructor(cred, callbacks) {
|
|
@@ -2414,6 +3160,9 @@ var DingTalkBridge = class {
|
|
|
2414
3160
|
}
|
|
2415
3161
|
client = null;
|
|
2416
3162
|
started = false;
|
|
3163
|
+
/** 企业内部应用 accessToken 缓存(下载机器人消息文件需要)。 */
|
|
3164
|
+
accessToken = null;
|
|
3165
|
+
accessTokenExpiresAt = 0;
|
|
2417
3166
|
status = { state: "idle", detail: "", connectedAt: null };
|
|
2418
3167
|
setStatus(state, detail = "") {
|
|
2419
3168
|
this.status = {
|
|
@@ -2444,18 +3193,58 @@ var DingTalkBridge = class {
|
|
|
2444
3193
|
body: JSON.stringify({ status: "SUCCESS" })
|
|
2445
3194
|
}
|
|
2446
3195
|
});
|
|
2447
|
-
const
|
|
2448
|
-
|
|
3196
|
+
const msgtype = raw.msgtype ?? "text";
|
|
3197
|
+
const robotCode = raw.robotCode ?? this.cred.robotCode ?? "";
|
|
3198
|
+
let text = "";
|
|
3199
|
+
const attachments = [];
|
|
3200
|
+
const notes = [];
|
|
3201
|
+
if (msgtype === "text") {
|
|
3202
|
+
text = raw.text?.content?.trim() || "";
|
|
3203
|
+
} else if (msgtype === "picture") {
|
|
3204
|
+
const downloadCode = raw.content?.downloadCode ?? "";
|
|
3205
|
+
const data = await this.downloadRobotFile(downloadCode, robotCode);
|
|
3206
|
+
if (data === null) text = "\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09";
|
|
3207
|
+
else attachments.push({ kind: "image", data, name: `dingtalk-${raw.msgId ?? Date.now()}.jpg` });
|
|
3208
|
+
} else if (msgtype === "richText") {
|
|
3209
|
+
const nodes = raw.content?.richText ?? [];
|
|
3210
|
+
const texts = [];
|
|
3211
|
+
for (const node of nodes) {
|
|
3212
|
+
if (typeof node.text === "string" && node.text !== "") texts.push(node.text);
|
|
3213
|
+
else if (node.type === "picture" && node.downloadCode !== void 0) {
|
|
3214
|
+
const data = await this.downloadRobotFile(node.downloadCode, robotCode);
|
|
3215
|
+
if (data !== null) attachments.push({ kind: "image", data, name: `dingtalk-${Date.now()}.jpg` });
|
|
3216
|
+
else notes.push("\uFF08\u5BCC\u6587\u672C\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09");
|
|
3217
|
+
}
|
|
3218
|
+
}
|
|
3219
|
+
text = texts.join("");
|
|
3220
|
+
} else if (msgtype === "audio") {
|
|
3221
|
+
text = raw.content?.recognition?.trim() || "\uFF08\u6536\u5230\u8BED\u97F3\u6D88\u606F\uFF0C\u4F46\u5E73\u53F0\u672A\u63D0\u4F9B\u8BC6\u522B\u6587\u672C\uFF09";
|
|
3222
|
+
const downloadCode = raw.content?.downloadCode ?? "";
|
|
3223
|
+
if (downloadCode !== "") {
|
|
3224
|
+
const data = await this.downloadRobotFile(downloadCode, robotCode);
|
|
3225
|
+
if (data !== null) attachments.push({ kind: "file", data, name: `voice-${Date.now()}.bin` });
|
|
3226
|
+
}
|
|
3227
|
+
} else if (msgtype === "video" || msgtype === "file") {
|
|
3228
|
+
const downloadCode = raw.content?.downloadCode ?? "";
|
|
3229
|
+
const data = await this.downloadRobotFile(downloadCode, robotCode);
|
|
3230
|
+
if (data === null) notes.push(`\uFF08${msgtype === "video" ? "\u89C6\u9891" : "\u6587\u4EF6"}\u4E0B\u8F7D\u5931\u8D25\uFF0C\u6216\u8BE5\u573A\u666F\u4E0D\u652F\u6301\u63A5\u6536\uFF09`);
|
|
3231
|
+
else attachments.push({ kind: "file", data, name: `dingtalk-${Date.now()}.bin` });
|
|
3232
|
+
} else {
|
|
3233
|
+
text = `\uFF08\u6536\u5230\u9489\u9489\u300C${msgtype}\u300D\u7C7B\u578B\u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09`;
|
|
3234
|
+
}
|
|
3235
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
3236
|
+
${notes.join("\n")}`;
|
|
3237
|
+
if (text.trim() === "" && attachments.length === 0) return;
|
|
2449
3238
|
const isGroup = raw.conversationType === "2";
|
|
2450
3239
|
const sessionWebhook = raw.sessionWebhook || "";
|
|
2451
|
-
this.callbacks.onText(text, {
|
|
3240
|
+
this.callbacks.onText(text.trim(), {
|
|
2452
3241
|
conversationId: raw.conversationId || "",
|
|
2453
3242
|
msgId: raw.msgId || downstream.headers.messageId,
|
|
2454
3243
|
senderNick: raw.senderNick || "",
|
|
2455
3244
|
senderStaffId: raw.senderStaffId || "",
|
|
2456
3245
|
sessionWebhook,
|
|
2457
3246
|
chatType: isGroup ? "group" : "single"
|
|
2458
|
-
});
|
|
3247
|
+
}, attachments.length > 0 ? attachments : void 0);
|
|
2459
3248
|
} catch (err) {
|
|
2460
3249
|
console.error("[dsh-message-gateway] dingtalk message parsing error", err);
|
|
2461
3250
|
}
|
|
@@ -2472,6 +3261,62 @@ var DingTalkBridge = class {
|
|
|
2472
3261
|
this.setStatus("error", error instanceof Error ? error.message : String(error));
|
|
2473
3262
|
}
|
|
2474
3263
|
}
|
|
3264
|
+
/**
|
|
3265
|
+
* 取企业内部应用 accessToken(官方 v1.0 接口,AppKey/AppSecret)。
|
|
3266
|
+
* 带 60 秒提前过期的本地缓存,避免每条附件都换一次令牌。
|
|
3267
|
+
*/
|
|
3268
|
+
async getAccessToken() {
|
|
3269
|
+
if (this.accessToken !== null && Date.now() < this.accessTokenExpiresAt) return this.accessToken;
|
|
3270
|
+
try {
|
|
3271
|
+
const response = await fetch("https://api.dingtalk.com/v1.0/oauth2/accessToken", {
|
|
3272
|
+
method: "POST",
|
|
3273
|
+
headers: { "content-type": "application/json" },
|
|
3274
|
+
body: JSON.stringify({ appKey: this.cred.clientId, appSecret: this.cred.clientSecret })
|
|
3275
|
+
});
|
|
3276
|
+
if (!response.ok) {
|
|
3277
|
+
console.warn("[dsh-message-gateway] dingtalk accessToken http", response.status);
|
|
3278
|
+
return null;
|
|
3279
|
+
}
|
|
3280
|
+
const body = await response.json();
|
|
3281
|
+
if (typeof body.accessToken !== "string" || body.accessToken === "") return null;
|
|
3282
|
+
this.accessToken = body.accessToken;
|
|
3283
|
+
this.accessTokenExpiresAt = Date.now() + Math.max(0, (body.expireIn ?? 7200) - 60) * 1e3;
|
|
3284
|
+
return this.accessToken;
|
|
3285
|
+
} catch (error) {
|
|
3286
|
+
console.warn("[dsh-message-gateway] dingtalk accessToken failed", String(error));
|
|
3287
|
+
return null;
|
|
3288
|
+
}
|
|
3289
|
+
}
|
|
3290
|
+
/**
|
|
3291
|
+
* 下载机器人接收到的消息文件。
|
|
3292
|
+
*
|
|
3293
|
+
* 官方文档两步走:
|
|
3294
|
+
* 1. `POST /v1.0/robot/messageFiles/download`(header `x-acs-dingtalk-access-token`,
|
|
3295
|
+
* body `{ downloadCode, robotCode }`)→ `{ downloadUrl }`
|
|
3296
|
+
* 2. GET 该 downloadUrl 取二进制(返回的文件名无扩展名,官方要求自行判断/替换)
|
|
3297
|
+
*/
|
|
3298
|
+
async downloadRobotFile(downloadCode, robotCode) {
|
|
3299
|
+
if (downloadCode === "") return null;
|
|
3300
|
+
const token = await this.getAccessToken();
|
|
3301
|
+
if (token === null) return null;
|
|
3302
|
+
try {
|
|
3303
|
+
const response = await fetch("https://api.dingtalk.com/v1.0/robot/messageFiles/download", {
|
|
3304
|
+
method: "POST",
|
|
3305
|
+
headers: { "x-acs-dingtalk-access-token": token, "content-type": "application/json" },
|
|
3306
|
+
body: JSON.stringify({ downloadCode, robotCode })
|
|
3307
|
+
});
|
|
3308
|
+
if (!response.ok) {
|
|
3309
|
+
console.warn("[dsh-message-gateway] dingtalk file download http", response.status);
|
|
3310
|
+
return null;
|
|
3311
|
+
}
|
|
3312
|
+
const body = await response.json();
|
|
3313
|
+
if (typeof body.downloadUrl !== "string" || body.downloadUrl === "") return null;
|
|
3314
|
+
return await downloadBytes(body.downloadUrl, { timeoutMs: 6e4 });
|
|
3315
|
+
} catch (error) {
|
|
3316
|
+
console.warn("[dsh-message-gateway] dingtalk file download failed", String(error));
|
|
3317
|
+
return null;
|
|
3318
|
+
}
|
|
3319
|
+
}
|
|
2475
3320
|
/**
|
|
2476
3321
|
* 回复单次消息(通过 sessionWebhook 回复)。
|
|
2477
3322
|
*/
|
|
@@ -2512,6 +3357,11 @@ var DingTalkBridge = class {
|
|
|
2512
3357
|
// src/host/bridge-manager.ts
|
|
2513
3358
|
init_wechat_ilink_bridge();
|
|
2514
3359
|
var DEFAULT_MAX_CHAT_AGENTS = 40;
|
|
3360
|
+
var IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
|
|
3361
|
+
function normalizeImageMediaType(mediaType) {
|
|
3362
|
+
const t = (mediaType ?? "").trim().toLowerCase();
|
|
3363
|
+
return IMAGE_MEDIA_TYPES.includes(t) ? t : null;
|
|
3364
|
+
}
|
|
2515
3365
|
var STREAM_PUSH_INTERVAL = 600;
|
|
2516
3366
|
var ACK_HEARTBEAT_INTERVAL = 4e3;
|
|
2517
3367
|
var BridgeManager = class {
|
|
@@ -2780,11 +3630,61 @@ var BridgeManager = class {
|
|
|
2780
3630
|
finishAllPending() {
|
|
2781
3631
|
for (const key of [...this.pendingMap.keys()]) this.finishPending(key);
|
|
2782
3632
|
}
|
|
3633
|
+
/**
|
|
3634
|
+
* 文本 + 附件 → 内容块。
|
|
3635
|
+
* - 图片:走 ctx.attachments.saveImage → ImageBlock(多模态直接交给模型);
|
|
3636
|
+
* 平台 MIME 不在受支持集合(png/jpeg/webp/gif)时退化为文件块。
|
|
3637
|
+
* - 其它文件:ctx.attachments.saveFile → FileBlock(请求组装时投影为
|
|
3638
|
+
* 「文件名 + 字节数 + 只读路径」句柄文本,Agent 可用文件工具读取处理)。
|
|
3639
|
+
* - 任何保存失败都会产出用户可见的占位文本,绝不静默丢弃。
|
|
3640
|
+
*/
|
|
3641
|
+
async buildContentBlocks(text, attachments) {
|
|
3642
|
+
const blocks = [];
|
|
3643
|
+
if (text.trim() !== "") blocks.push({ type: "text", text });
|
|
3644
|
+
const list = attachments ?? [];
|
|
3645
|
+
if (list.length === 0) return blocks;
|
|
3646
|
+
const store = this.ctx.get?.("attachments");
|
|
3647
|
+
if (store === void 0) {
|
|
3648
|
+
blocks.push({ type: "text", text: "\uFF08\u6536\u5230\u9644\u4EF6\uFF0C\u4F46\u9644\u4EF6\u5B58\u50A8\u670D\u52A1\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5904\u7406\uFF09" });
|
|
3649
|
+
return blocks;
|
|
3650
|
+
}
|
|
3651
|
+
for (const att of list) {
|
|
3652
|
+
try {
|
|
3653
|
+
if (att.kind === "image") {
|
|
3654
|
+
const mediaType = normalizeImageMediaType(att.mediaType);
|
|
3655
|
+
if (mediaType === null) {
|
|
3656
|
+
const ref = await store.saveFile({ data: att.data, name: att.name });
|
|
3657
|
+
blocks.push({ type: "file", attachment: ref });
|
|
3658
|
+
} else {
|
|
3659
|
+
const ref = await store.saveImage({ data: att.data, mediaType, name: att.name });
|
|
3660
|
+
blocks.push({ type: "image", attachment: ref });
|
|
3661
|
+
}
|
|
3662
|
+
} else {
|
|
3663
|
+
const ref = await store.saveFile({ data: att.data, name: att.name });
|
|
3664
|
+
blocks.push({ type: "file", attachment: ref });
|
|
3665
|
+
}
|
|
3666
|
+
} catch (error) {
|
|
3667
|
+
if (att.kind === "image") {
|
|
3668
|
+
try {
|
|
3669
|
+
const ref = await store.saveFile({ data: att.data, name: att.name });
|
|
3670
|
+
blocks.push({ type: "file", attachment: ref });
|
|
3671
|
+
continue;
|
|
3672
|
+
} catch {
|
|
3673
|
+
}
|
|
3674
|
+
}
|
|
3675
|
+
blocks.push({
|
|
3676
|
+
type: "text",
|
|
3677
|
+
text: `\uFF08\u9644\u4EF6\u300C${att.name ?? "\u672A\u77E5"}\u300D\u4FDD\u5B58\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`
|
|
3678
|
+
});
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
return blocks;
|
|
3682
|
+
}
|
|
2783
3683
|
/**
|
|
2784
3684
|
* 外部平台消息统一入口:命令优先,否则注入该聊天独立 agent 会话,
|
|
2785
3685
|
* 回复经 sink 流式回发。所有已打通的平台共用此管线。
|
|
2786
3686
|
*/
|
|
2787
|
-
async handleExternalMessage(id, rawText) {
|
|
3687
|
+
async handleExternalMessage(id, rawText, attachments) {
|
|
2788
3688
|
if (this.disposed) return;
|
|
2789
3689
|
const text = stripMention(rawText);
|
|
2790
3690
|
const reply = (content) => {
|
|
@@ -2803,6 +3703,11 @@ var BridgeManager = class {
|
|
|
2803
3703
|
}
|
|
2804
3704
|
const route = this.matchRoute(id.key, text);
|
|
2805
3705
|
const routedText = route !== null && route.prefix !== "" ? text.slice(route.prefix.length).trim() : text;
|
|
3706
|
+
const content = await this.buildContentBlocks(routedText, attachments);
|
|
3707
|
+
if (content.length === 0) {
|
|
3708
|
+
console.warn("[dsh-message-gateway] no content to send", { key: id.key });
|
|
3709
|
+
return;
|
|
3710
|
+
}
|
|
2806
3711
|
const agent = await this.ensureAgentForKey(id.key, route?.rule);
|
|
2807
3712
|
if (agent === null) {
|
|
2808
3713
|
console.warn("[dsh-message-gateway] no dedicated agent available");
|
|
@@ -2811,7 +3716,7 @@ var BridgeManager = class {
|
|
|
2811
3716
|
const message = {
|
|
2812
3717
|
id: MessageId(`dsh-gateway-${Date.now().toString(36)}`),
|
|
2813
3718
|
role: "user",
|
|
2814
|
-
content
|
|
3719
|
+
content,
|
|
2815
3720
|
source: { kind: "plugin", plugin: "dsh-message-gateway", form: "relay" }
|
|
2816
3721
|
};
|
|
2817
3722
|
const session = agent.session;
|
|
@@ -2925,7 +3830,7 @@ var BridgeManager = class {
|
|
|
2925
3830
|
this.wecom?.stop();
|
|
2926
3831
|
const bridge = new WecomBridge(cred, {
|
|
2927
3832
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
2928
|
-
onText: (rawText, frame) => {
|
|
3833
|
+
onText: (rawText, frame, attachments) => {
|
|
2929
3834
|
const body = frame.body ?? {};
|
|
2930
3835
|
const chattype = body.chattype ?? "single";
|
|
2931
3836
|
const userid = body.from?.userid ?? "";
|
|
@@ -2936,7 +3841,7 @@ var BridgeManager = class {
|
|
|
2936
3841
|
// 企业微信走单一流式消息(ack → 内容 → 定稿同一条消息就地更新);
|
|
2937
3842
|
// 不再叠加 response_url 投递,避免出现重复消息。
|
|
2938
3843
|
};
|
|
2939
|
-
void this.handleExternalMessage({ key, frame, sink, chatType: chattype === "group" ? "group" : "single" }, rawText);
|
|
3844
|
+
void this.handleExternalMessage({ key, frame, sink, chatType: chattype === "group" ? "group" : "single" }, rawText, attachments);
|
|
2940
3845
|
},
|
|
2941
3846
|
onEnter: (frame) => {
|
|
2942
3847
|
if (!this.config.welcomeReply) return;
|
|
@@ -3244,7 +4149,7 @@ ${secret}`;
|
|
|
3244
4149
|
};
|
|
3245
4150
|
const bridge = new WechatIlinkBridge(ilinkCred, {
|
|
3246
4151
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3247
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4152
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3248
4153
|
});
|
|
3249
4154
|
this.wechat = bridge;
|
|
3250
4155
|
bridge.start();
|
|
@@ -3261,7 +4166,7 @@ ${secret}`;
|
|
|
3261
4166
|
{ clientId: cred.clientId ?? "", clientSecret: cred.clientSecret ?? "", robotCode: cred.robotCode },
|
|
3262
4167
|
{
|
|
3263
4168
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3264
|
-
onText: (text, frame) => {
|
|
4169
|
+
onText: (text, frame, attachments) => {
|
|
3265
4170
|
const identity = {
|
|
3266
4171
|
key: `dingtalk:${frame.conversationId}`,
|
|
3267
4172
|
frame,
|
|
@@ -3275,7 +4180,7 @@ ${secret}`;
|
|
|
3275
4180
|
},
|
|
3276
4181
|
chatType: frame.chatType
|
|
3277
4182
|
};
|
|
3278
|
-
void this.handleExternalMessage(identity, text);
|
|
4183
|
+
void this.handleExternalMessage(identity, text, attachments);
|
|
3279
4184
|
}
|
|
3280
4185
|
}
|
|
3281
4186
|
);
|
|
@@ -3294,7 +4199,7 @@ ${secret}`;
|
|
|
3294
4199
|
{ appId: cred.appId ?? "", appSecret: cred.appSecret ?? "" },
|
|
3295
4200
|
{
|
|
3296
4201
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3297
|
-
onText: (text, frame) => {
|
|
4202
|
+
onText: (text, frame, attachments) => {
|
|
3298
4203
|
const identity = {
|
|
3299
4204
|
key: `feishu:${frame.chatId}`,
|
|
3300
4205
|
frame,
|
|
@@ -3308,7 +4213,7 @@ ${secret}`;
|
|
|
3308
4213
|
},
|
|
3309
4214
|
chatType: frame.chatType
|
|
3310
4215
|
};
|
|
3311
|
-
void this.handleExternalMessage(identity, text);
|
|
4216
|
+
void this.handleExternalMessage(identity, text, attachments);
|
|
3312
4217
|
}
|
|
3313
4218
|
}
|
|
3314
4219
|
);
|
|
@@ -3325,7 +4230,7 @@ ${secret}`;
|
|
|
3325
4230
|
this.telegram?.stop();
|
|
3326
4231
|
const bridge = new TelegramBridge(cred.token ?? "", {
|
|
3327
4232
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3328
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4233
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3329
4234
|
});
|
|
3330
4235
|
this.telegram = bridge;
|
|
3331
4236
|
bridge.start();
|
|
@@ -3340,7 +4245,7 @@ ${secret}`;
|
|
|
3340
4245
|
this.discord?.stop();
|
|
3341
4246
|
const bridge = new DiscordBridge(cred.token ?? "", {
|
|
3342
4247
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3343
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4248
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3344
4249
|
});
|
|
3345
4250
|
this.discord = bridge;
|
|
3346
4251
|
bridge.start();
|
|
@@ -3355,7 +4260,7 @@ ${secret}`;
|
|
|
3355
4260
|
this.qq?.stop();
|
|
3356
4261
|
const bridge = new QQBridge(cred.appId ?? "", cred.secret ?? "", {
|
|
3357
4262
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3358
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4263
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3359
4264
|
});
|
|
3360
4265
|
this.qq = bridge;
|
|
3361
4266
|
bridge.start();
|
|
@@ -3380,7 +4285,7 @@ ${secret}`;
|
|
|
3380
4285
|
};
|
|
3381
4286
|
const bridge = new EmailBridge(emailCred, {
|
|
3382
4287
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3383
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4288
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3384
4289
|
});
|
|
3385
4290
|
this.email = bridge;
|
|
3386
4291
|
bridge.start();
|