@kadaliao/dsh-bots 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -9
- package/README.zh-CN.md +71 -7
- package/client.js +330 -42
- package/index.js +65 -11
- package/lib/apps.mjs +85 -4
- package/lib/channels/feishu.mjs +1249 -0
- package/lib/channels/slack.mjs +906 -0
- package/lib/channels.mjs +7 -3
- package/lib/logos.mjs +2 -0
- package/lib/skills.mjs +198 -5
- package/lib/store.mjs +22 -3
- package/package.json +1 -1
|
@@ -0,0 +1,1249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feishu / Lark transport for chat channels: events over Feishu's long
|
|
3
|
+
* connection (the WebSocket protocol the official SDK's WSClient speaks), and
|
|
4
|
+
* the Open API with a tenant_access_token for replies and lookups.
|
|
5
|
+
*
|
|
6
|
+
* Transport only: it knows nothing about bots, pairing or the store
|
|
7
|
+
* (lib/channels.mjs decides what a message means).
|
|
8
|
+
*
|
|
9
|
+
* - Long connection: POST {base}/callback/ws/endpoint with the App ID and App
|
|
10
|
+
* Secret answers a wss URL and a ClientConfig (ping interval). Frames are
|
|
11
|
+
* protobuf `pbbp2.Frame`, encoded by hand below: method 0 is control
|
|
12
|
+
* (ping / pong), method 1 is data (an event as JSON, possibly split over
|
|
13
|
+
* several frames by the `sum` / `seq` headers). A complete event is acked at
|
|
14
|
+
* once with a response frame (`{"code":200}`); Feishu pushes again what is
|
|
15
|
+
* not acked within 3 s. No public URL is needed, and events arrive as plain
|
|
16
|
+
* JSON (the channel itself is encrypted).
|
|
17
|
+
* - Feishu (open.feishu.cn) and Lark (open.larksuite.com) apps have the same
|
|
18
|
+
* App ID format. The App ID is first looked up on Feishu with a dummy secret;
|
|
19
|
+
* when Feishu does not know it the app is a Lark app, so a Lark app's secret
|
|
20
|
+
* is only ever sent to Lark. Messages from Lark carry `source: 'Lark'`.
|
|
21
|
+
* - Replies are `post` messages holding one `md` element (CommonMark + GFM),
|
|
22
|
+
* hence `MARKDOWN`; in a group the first part answers the person's message.
|
|
23
|
+
* - Feishu delivers a message twice now and then; duplicates are dropped by
|
|
24
|
+
* message_id, and `order` (the message's create_time in ms, rising within a
|
|
25
|
+
* chat) feeds the hub's replay guard across restarts.
|
|
26
|
+
* - Feishu has no typing indicator for bots: a "Typing" reaction on the
|
|
27
|
+
* person's message stands in while the bot works and goes away when the
|
|
28
|
+
* reply is sent or the work stops.
|
|
29
|
+
* - The App Secret, tenant tokens and the connection URL (it carries a ticket)
|
|
30
|
+
* never appear in log lines, errors or statuses.
|
|
31
|
+
*
|
|
32
|
+
* `apiBase` defaults to `BOTS_FEISHU_API` or https://open.feishu.cn, and
|
|
33
|
+
* `larkApiBase` to `BOTS_LARK_API` or https://open.larksuite.com; with a custom
|
|
34
|
+
* Feishu base and no Lark base there is no Lark fallback, so test credentials
|
|
35
|
+
* never reach a real server.
|
|
36
|
+
*
|
|
37
|
+
* @module @kadaliao/dsh-bots/lib/channels/feishu
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import { randomUUID } from 'node:crypto';
|
|
41
|
+
import { redact, splitText, toPlainText } from '../channels.mjs';
|
|
42
|
+
|
|
43
|
+
export const kind = 'feishu';
|
|
44
|
+
export const TEXT_LIMIT = 4000;
|
|
45
|
+
export const MARKDOWN = true;
|
|
46
|
+
|
|
47
|
+
const FEISHU_API = 'https://open.feishu.cn';
|
|
48
|
+
const LARK_API = 'https://open.larksuite.com';
|
|
49
|
+
/** Post messages may be 30 KB; leave room for Feishu's own accounting. */
|
|
50
|
+
const MAX_BODY_BYTES = 28_000;
|
|
51
|
+
const MIN_BACKOFF = 1000;
|
|
52
|
+
const MAX_BACKOFF = 60_000;
|
|
53
|
+
/** How often to look again whether the bot capability is live. */
|
|
54
|
+
const BOT_RETRY_MS = 15_000;
|
|
55
|
+
const CONN_LIMIT_RETRY_MS = 60_000;
|
|
56
|
+
const DEFAULT_PING_MS = 120_000;
|
|
57
|
+
const PONG_TIMEOUT_MS = 30_000;
|
|
58
|
+
const OPEN_TIMEOUT_MS = 20_000;
|
|
59
|
+
/** Fragments of an event that never completes are dropped after this long. */
|
|
60
|
+
const FRAGMENT_TTL_MS = 10_000;
|
|
61
|
+
/** A name lookup must not hold a message up for long. */
|
|
62
|
+
const LOOKUP_TIMEOUT_MS = 4000;
|
|
63
|
+
const NAME_TTL_MS = 6 * 3600_000;
|
|
64
|
+
const LOOKUP_RETRY_MS = 10 * 60_000;
|
|
65
|
+
const LOOKUP_OFF_MS = 30 * 60_000;
|
|
66
|
+
/** The hub asks for "typing" every ~5 s while a bot works; silence this long means it stopped. */
|
|
67
|
+
const TYPING_IDLE_MS = 15_000;
|
|
68
|
+
/** Only a person's recent message gets the "Typing" reaction. */
|
|
69
|
+
const TYPING_FRESH_MS = 2 * 60_000;
|
|
70
|
+
/** Sent in place of the App Secret to learn whether Feishu knows the App ID. */
|
|
71
|
+
const PROBE_SECRET = 'dsh-bots-domain-probe';
|
|
72
|
+
|
|
73
|
+
const TOKEN_CODES = new Set([99991661, 99991663, 99991664, 99991665, 99991671]);
|
|
74
|
+
const RATE_CODES = new Set([99991400, 230020]);
|
|
75
|
+
const SCOPE_CODES = new Set([99991672, 99991679, 230027]);
|
|
76
|
+
/** The message being answered is gone: post to the chat instead. */
|
|
77
|
+
const REPLY_GONE = new Set([230011, 230019, 230110, 231003]);
|
|
78
|
+
/** Feishu would not take the reply as Markdown: send it as plain text instead. */
|
|
79
|
+
const POST_REJECTED = new Set([230001, 230025]);
|
|
80
|
+
|
|
81
|
+
/** App IDs that turned out to be Lark apps, for `links`. */
|
|
82
|
+
const larkApps = new Set();
|
|
83
|
+
|
|
84
|
+
const enc = new TextEncoder();
|
|
85
|
+
const dec = new TextDecoder();
|
|
86
|
+
const trimSlash = (s) => String(s).replace(/\/+$/, '');
|
|
87
|
+
const secs = (ms) => Math.max(1, Math.round(ms / 1000));
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Reconnect delay for the n-th consecutive failure (0-based): doubles from 1 s,
|
|
91
|
+
* capped at 60 s, ±20 % jitter.
|
|
92
|
+
*/
|
|
93
|
+
export function backoffDelay(attempt, random = Math.random) {
|
|
94
|
+
const base = Math.min(MAX_BACKOFF, MIN_BACKOFF * 2 ** Math.max(0, attempt));
|
|
95
|
+
return Math.round(Math.min(MAX_BACKOFF, Math.max(MIN_BACKOFF, base * (0.8 + 0.4 * random()))));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// --- pbbp2.Frame ------------------------------------------------------------------------
|
|
99
|
+
//
|
|
100
|
+
// message Header { required string key = 1; required string value = 2; }
|
|
101
|
+
// message Frame {
|
|
102
|
+
// required uint64 SeqID = 1; required uint64 LogID = 2;
|
|
103
|
+
// required int32 service = 3; required int32 method = 4;
|
|
104
|
+
// repeated Header headers = 5;
|
|
105
|
+
// optional string payloadEncoding = 6; optional string payloadType = 7;
|
|
106
|
+
// optional bytes payload = 8; optional string LogIDNew = 9;
|
|
107
|
+
// }
|
|
108
|
+
|
|
109
|
+
class Writer {
|
|
110
|
+
constructor() {
|
|
111
|
+
this.chunks = [];
|
|
112
|
+
this.size = 0;
|
|
113
|
+
}
|
|
114
|
+
raw(bytes) {
|
|
115
|
+
this.chunks.push(bytes);
|
|
116
|
+
this.size += bytes.length;
|
|
117
|
+
}
|
|
118
|
+
varint(value) {
|
|
119
|
+
let n = BigInt.asUintN(64, BigInt(value));
|
|
120
|
+
const out = [];
|
|
121
|
+
while (n > 0x7fn) {
|
|
122
|
+
out.push(Number(n & 0x7fn) | 0x80);
|
|
123
|
+
n >>= 7n;
|
|
124
|
+
}
|
|
125
|
+
out.push(Number(n));
|
|
126
|
+
this.raw(Uint8Array.from(out));
|
|
127
|
+
}
|
|
128
|
+
tag(field, wire) {
|
|
129
|
+
this.varint((field << 3) | wire);
|
|
130
|
+
}
|
|
131
|
+
bytes(field, bytes) {
|
|
132
|
+
this.tag(field, 2);
|
|
133
|
+
this.varint(bytes.length);
|
|
134
|
+
this.raw(bytes);
|
|
135
|
+
}
|
|
136
|
+
string(field, s) {
|
|
137
|
+
this.bytes(field, enc.encode(String(s)));
|
|
138
|
+
}
|
|
139
|
+
finish() {
|
|
140
|
+
const out = new Uint8Array(this.size);
|
|
141
|
+
let at = 0;
|
|
142
|
+
for (const c of this.chunks) {
|
|
143
|
+
out.set(c, at);
|
|
144
|
+
at += c.length;
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function reader(buf) {
|
|
151
|
+
let pos = 0;
|
|
152
|
+
const need = (n) => {
|
|
153
|
+
if (pos + n > buf.length) throw new Error('truncated frame');
|
|
154
|
+
};
|
|
155
|
+
const varint = () => {
|
|
156
|
+
let result = 0n;
|
|
157
|
+
for (let shift = 0n; shift < 70n; shift += 7n) {
|
|
158
|
+
need(1);
|
|
159
|
+
const b = buf[pos++];
|
|
160
|
+
result |= BigInt(b & 0x7f) << shift;
|
|
161
|
+
if (!(b & 0x80)) return BigInt.asUintN(64, result);
|
|
162
|
+
}
|
|
163
|
+
throw new Error('malformed varint');
|
|
164
|
+
};
|
|
165
|
+
const bytes = () => {
|
|
166
|
+
const n = Number(varint());
|
|
167
|
+
need(n);
|
|
168
|
+
const out = buf.slice(pos, pos + n);
|
|
169
|
+
pos += n;
|
|
170
|
+
return out;
|
|
171
|
+
};
|
|
172
|
+
const skip = (wire) => {
|
|
173
|
+
if (wire === 0) varint();
|
|
174
|
+
else if (wire === 1) (need(8), (pos += 8));
|
|
175
|
+
else if (wire === 2) bytes();
|
|
176
|
+
else if (wire === 5) (need(4), (pos += 4));
|
|
177
|
+
else throw new Error(`unknown wire type ${wire}`);
|
|
178
|
+
};
|
|
179
|
+
return { varint, bytes, skip, done: () => pos >= buf.length };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A frame object as protobuf bytes. */
|
|
183
|
+
export function encodeFrame(f) {
|
|
184
|
+
const w = new Writer();
|
|
185
|
+
w.tag(1, 0);
|
|
186
|
+
w.varint(f.SeqID ?? 0);
|
|
187
|
+
w.tag(2, 0);
|
|
188
|
+
w.varint(f.LogID ?? 0);
|
|
189
|
+
w.tag(3, 0);
|
|
190
|
+
w.varint(f.service ?? 0);
|
|
191
|
+
w.tag(4, 0);
|
|
192
|
+
w.varint(f.method ?? 0);
|
|
193
|
+
for (const h of f.headers ?? []) {
|
|
194
|
+
const hw = new Writer();
|
|
195
|
+
hw.string(1, h.key);
|
|
196
|
+
hw.string(2, h.value);
|
|
197
|
+
w.bytes(5, hw.finish());
|
|
198
|
+
}
|
|
199
|
+
if (f.payloadEncoding != null) w.string(6, f.payloadEncoding);
|
|
200
|
+
if (f.payloadType != null) w.string(7, f.payloadType);
|
|
201
|
+
if (f.payload != null) w.bytes(8, f.payload instanceof Uint8Array ? f.payload : enc.encode(String(f.payload)));
|
|
202
|
+
if (f.LogIDNew != null) w.string(9, f.LogIDNew);
|
|
203
|
+
return w.finish();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Protobuf bytes as a frame object: SeqID / LogID as BigInt (echoed back exactly in acks). */
|
|
207
|
+
export function decodeFrame(input) {
|
|
208
|
+
const buf = input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
209
|
+
const r = reader(buf);
|
|
210
|
+
const f = { SeqID: 0n, LogID: 0n, service: 0, method: 0, headers: [] };
|
|
211
|
+
while (!r.done()) {
|
|
212
|
+
const tag = Number(r.varint());
|
|
213
|
+
const field = tag >>> 3;
|
|
214
|
+
const wire = tag & 7;
|
|
215
|
+
if (field === 1 && wire === 0) f.SeqID = r.varint();
|
|
216
|
+
else if (field === 2 && wire === 0) f.LogID = r.varint();
|
|
217
|
+
else if (field === 3 && wire === 0) f.service = Number(BigInt.asIntN(32, r.varint()));
|
|
218
|
+
else if (field === 4 && wire === 0) f.method = Number(BigInt.asIntN(32, r.varint()));
|
|
219
|
+
else if (field === 5 && wire === 2) {
|
|
220
|
+
const hr = reader(r.bytes());
|
|
221
|
+
const h = { key: '', value: '' };
|
|
222
|
+
while (!hr.done()) {
|
|
223
|
+
const t = Number(hr.varint());
|
|
224
|
+
if (t >>> 3 === 1 && (t & 7) === 2) h.key = dec.decode(hr.bytes());
|
|
225
|
+
else if (t >>> 3 === 2 && (t & 7) === 2) h.value = dec.decode(hr.bytes());
|
|
226
|
+
else hr.skip(t & 7);
|
|
227
|
+
}
|
|
228
|
+
f.headers.push(h);
|
|
229
|
+
} else if (field === 6 && wire === 2) f.payloadEncoding = dec.decode(r.bytes());
|
|
230
|
+
else if (field === 7 && wire === 2) f.payloadType = dec.decode(r.bytes());
|
|
231
|
+
else if (field === 8 && wire === 2) f.payload = r.bytes();
|
|
232
|
+
else if (field === 9 && wire === 2) f.LogIDNew = dec.decode(r.bytes());
|
|
233
|
+
else r.skip(wire);
|
|
234
|
+
}
|
|
235
|
+
return f;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const headersOf = (frame) => Object.fromEntries((frame?.headers ?? []).map((h) => [h.key, h.value]));
|
|
239
|
+
|
|
240
|
+
// --- messages ---------------------------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
const REMOVED = '\u0000';
|
|
243
|
+
|
|
244
|
+
/** Text with the removed mentions closed up: "hey @bot, plan it" → "hey, plan it". */
|
|
245
|
+
function closeUp(s) {
|
|
246
|
+
return s
|
|
247
|
+
.replace(/(^|\n)[ \t]*\u0000[ \t]*[,,::]?[ \t]*/g, '$1')
|
|
248
|
+
.replace(/[ \t]*\u0000[ \t]*([,,::]?)[ \t]*/g, (_, p) => (p ? `${p} ` : ' '))
|
|
249
|
+
.replace(/\u0000/g, '')
|
|
250
|
+
.replace(/^[\s,,::]+/, '')
|
|
251
|
+
.replace(/[ \t]+$/gm, '')
|
|
252
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
253
|
+
.trim();
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The readable text of a received `post` (either shape: `{title, content}` or one per locale). */
|
|
257
|
+
function postText(c, at) {
|
|
258
|
+
const body = c && typeof c === 'object' && !Array.isArray(c.content) ? (c.zh_cn ?? c.en_us ?? c.ja_jp ?? Object.values(c).find((v) => v && Array.isArray(v.content))) : c;
|
|
259
|
+
const lines = [];
|
|
260
|
+
if (typeof body?.title === 'string' && body.title.trim()) lines.push(body.title.trim());
|
|
261
|
+
for (const para of Array.isArray(body?.content) ? body.content : []) {
|
|
262
|
+
let line = '';
|
|
263
|
+
for (const el of Array.isArray(para) ? para : []) {
|
|
264
|
+
const text = typeof el?.text === 'string' ? el.text : '';
|
|
265
|
+
switch (el?.tag) {
|
|
266
|
+
case 'text':
|
|
267
|
+
case 'md':
|
|
268
|
+
line += text;
|
|
269
|
+
break;
|
|
270
|
+
case 'a': {
|
|
271
|
+
const href = typeof el.href === 'string' ? el.href : '';
|
|
272
|
+
line += !href || text === href ? text || href : text ? `${text} (${href})` : href;
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
case 'at':
|
|
276
|
+
line += at(String(el.user_id ?? ''), el.user_name);
|
|
277
|
+
break;
|
|
278
|
+
case 'code_block':
|
|
279
|
+
line += `\n\`\`\`${String(el.language ?? '').toLowerCase()}\n${text}\n\`\`\`\n`;
|
|
280
|
+
break;
|
|
281
|
+
case 'emotion':
|
|
282
|
+
line += el.emoji_type ? `[${el.emoji_type}]` : '';
|
|
283
|
+
break;
|
|
284
|
+
case 'hr':
|
|
285
|
+
line += '\n---\n';
|
|
286
|
+
break;
|
|
287
|
+
default:
|
|
288
|
+
break; // images and video: nothing to read
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
lines.push(line);
|
|
292
|
+
}
|
|
293
|
+
return lines.join('\n');
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* An `im.message.receive_v1` event as a channel message (without `userName`,
|
|
298
|
+
* which takes a lookup), or null when it is not a person's text or post.
|
|
299
|
+
* In a group, `mentioned` means the bot's own open_id is among the mentions
|
|
300
|
+
* (with no open_id known yet: any bot mention), or the message replies to one
|
|
301
|
+
* the bot sent. The bot's `@_user_N` placeholder is removed, other people's
|
|
302
|
+
* become `@Name`.
|
|
303
|
+
* @param {object} event the event body (`sender`, `message`)
|
|
304
|
+
* @param {{botOpenId?: string, sentIds?: {has(id: string): boolean}}} [me]
|
|
305
|
+
*/
|
|
306
|
+
export function normalizeEvent(event, { botOpenId = '', sentIds } = {}) {
|
|
307
|
+
const m = event?.message;
|
|
308
|
+
const s = event?.sender;
|
|
309
|
+
if (!m || !s || s.sender_type !== 'user') return null;
|
|
310
|
+
const userId = String(s.sender_id?.open_id ?? '');
|
|
311
|
+
if (!userId || userId === botOpenId || !m.chat_id || !m.message_id) return null;
|
|
312
|
+
let content;
|
|
313
|
+
try {
|
|
314
|
+
content = typeof m.content === 'string' ? JSON.parse(m.content) : m.content;
|
|
315
|
+
} catch {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
const mentions = new Map((Array.isArray(m.mentions) ? m.mentions : []).map((x) => [String(x?.key ?? ''), x]));
|
|
319
|
+
const isBot = (x) => (botOpenId ? String(x?.id?.open_id ?? '') === botOpenId : x?.mentioned_type === 'bot');
|
|
320
|
+
let mentioned = false;
|
|
321
|
+
const at = (key, fallbackName) => {
|
|
322
|
+
const x = mentions.get(key);
|
|
323
|
+
if (x && isBot(x)) {
|
|
324
|
+
mentioned = true;
|
|
325
|
+
return REMOVED;
|
|
326
|
+
}
|
|
327
|
+
if (key === '@_all' || key === 'all') return '@all';
|
|
328
|
+
const name = String(x?.name ?? fallbackName ?? '').trim();
|
|
329
|
+
return name ? `@${name}` : REMOVED;
|
|
330
|
+
};
|
|
331
|
+
let raw;
|
|
332
|
+
if (m.message_type === 'text') raw = String(content?.text ?? '').replace(/@_user_\d+|@_all/g, (key) => at(key));
|
|
333
|
+
else if (m.message_type === 'post') raw = postText(content, at);
|
|
334
|
+
else return null;
|
|
335
|
+
const text = closeUp(raw);
|
|
336
|
+
if (!text) return null;
|
|
337
|
+
const isDirect = m.chat_type === 'p2p';
|
|
338
|
+
if (!isDirect && m.parent_id && sentIds?.has(String(m.parent_id))) mentioned = true;
|
|
339
|
+
const created = String(m.create_time ?? '');
|
|
340
|
+
return {
|
|
341
|
+
chatId: String(m.chat_id),
|
|
342
|
+
messageId: String(m.message_id),
|
|
343
|
+
...(/^\d{1,30}$/.test(created) ? { order: created } : {}),
|
|
344
|
+
userId,
|
|
345
|
+
text,
|
|
346
|
+
isDirect,
|
|
347
|
+
mentioned: isDirect || mentioned,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Model Markdown made safe for a Feishu `md` element: no mentions (least of all @all), remote images as links. */
|
|
352
|
+
function safeMarkdown(md) {
|
|
353
|
+
return String(md)
|
|
354
|
+
.replace(/<(\/?)at\b/gi, '<$1at')
|
|
355
|
+
.replace(/!\[([^\]\n]*)\]\((https?:\/\/[^)\s]+)\)/g, (_, alt, url) => `[${alt || url}](${url})`);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const postBody = (md) => ({ msg_type: 'post', content: JSON.stringify({ zh_cn: { content: [[{ tag: 'md', text: safeMarkdown(md) }]] } }) });
|
|
359
|
+
|
|
360
|
+
/** Reply parts of at most TEXT_LIMIT characters whose request body stays under the 30 KB post limit. */
|
|
361
|
+
function partsOf(text) {
|
|
362
|
+
const out = [];
|
|
363
|
+
const queue = splitText(text, TEXT_LIMIT);
|
|
364
|
+
while (queue.length) {
|
|
365
|
+
const part = queue.shift();
|
|
366
|
+
if (part.length < 400 || Buffer.byteLength(JSON.stringify(postBody(part))) <= MAX_BODY_BYTES) out.push(part);
|
|
367
|
+
else queue.unshift(...splitText(part, Math.floor(part.length / 2)));
|
|
368
|
+
}
|
|
369
|
+
return out;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Remember `id` in an insertion-ordered set of at most `max` entries. */
|
|
373
|
+
function remember(set, id, max) {
|
|
374
|
+
set.delete(id);
|
|
375
|
+
set.add(id);
|
|
376
|
+
if (set.size > max) set.delete(set.values().next().value);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// --- panel links ------------------------------------------------------------------------
|
|
380
|
+
|
|
381
|
+
/** "Open in Feishu": the AppLink that opens a chat with the bot. */
|
|
382
|
+
export function links({ values } = {}) {
|
|
383
|
+
const appId = String(values?.appId ?? '').trim();
|
|
384
|
+
if (!/^cli_[A-Za-z0-9]+$/.test(appId)) return {};
|
|
385
|
+
const host = larkApps.has(appId) ? 'applink.larksuite.com' : 'applink.feishu.cn';
|
|
386
|
+
return { link: `https://${host}/client/bot/open?appId=${appId}` };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// --- the connector ----------------------------------------------------------------------
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* @param {{
|
|
393
|
+
* token?: string, // the App Secret (the app's first secret field)
|
|
394
|
+
* values?: {appId?: string, appSecret?: string},
|
|
395
|
+
* onMessage: (msg: object) => void,
|
|
396
|
+
* onStatus?: (s: {state: 'connecting'|'connected'|'error'|'stopped', detail?: string, fatal?: boolean, hint?: string}) => void,
|
|
397
|
+
* log?: (line: string) => void,
|
|
398
|
+
* fetchImpl?: typeof fetch,
|
|
399
|
+
* WebSocketImpl?: typeof WebSocket,
|
|
400
|
+
* apiBase?: string,
|
|
401
|
+
* larkApiBase?: string,
|
|
402
|
+
* setTimeoutImpl?: typeof setTimeout, // for tests
|
|
403
|
+
* clearTimeoutImpl?: typeof clearTimeout, // for tests
|
|
404
|
+
* random?: () => number, // for tests (backoff jitter)
|
|
405
|
+
* now?: () => number, // for tests
|
|
406
|
+
* }} opts
|
|
407
|
+
*/
|
|
408
|
+
export function createConnector(opts = {}) {
|
|
409
|
+
const appId = String(opts.values?.appId ?? '').trim();
|
|
410
|
+
const secret = String(opts.values?.appSecret ?? opts.token ?? '').trim();
|
|
411
|
+
const onMessage = typeof opts.onMessage === 'function' ? opts.onMessage : () => {};
|
|
412
|
+
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
|
|
413
|
+
const WebSocketImpl = opts.WebSocketImpl ?? globalThis.WebSocket;
|
|
414
|
+
const setTimeoutImpl = opts.setTimeoutImpl ?? setTimeout;
|
|
415
|
+
const clearTimeoutImpl = opts.clearTimeoutImpl ?? clearTimeout;
|
|
416
|
+
const random = opts.random ?? Math.random;
|
|
417
|
+
const now = opts.now ?? Date.now;
|
|
418
|
+
const customBase = opts.apiBase || process.env.BOTS_FEISHU_API;
|
|
419
|
+
const feishuBase = trimSlash(customBase || FEISHU_API);
|
|
420
|
+
const larkSetting = opts.larkApiBase || process.env.BOTS_LARK_API;
|
|
421
|
+
const larkBase = larkSetting ? trimSlash(larkSetting) : customBase ? '' : LARK_API;
|
|
422
|
+
|
|
423
|
+
/** Everything that must never leave this module: the secret, tokens, connection URLs. */
|
|
424
|
+
const hidden = new Set([secret]);
|
|
425
|
+
const clean = (s) => redact(String(s ?? ''), [...hidden]).replace(/(wss?:\/\/[^\s?"']+)\?[^\s"']*/g, '$1?…');
|
|
426
|
+
const log = (line) => {
|
|
427
|
+
try {
|
|
428
|
+
opts.log?.(clean(line));
|
|
429
|
+
} catch {
|
|
430
|
+
// Logging is a convenience.
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
const status = (state, detail = '', { fatal = false, hint = '' } = {}) => {
|
|
434
|
+
try {
|
|
435
|
+
opts.onStatus?.({ state, ...(detail ? { detail: clean(detail) } : {}), ...(fatal ? { fatal: true } : {}), ...(hint ? { hint } : {}) });
|
|
436
|
+
} catch {
|
|
437
|
+
// The listener's problem.
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
const guard =
|
|
441
|
+
(fn) =>
|
|
442
|
+
(...args) => {
|
|
443
|
+
try {
|
|
444
|
+
const r = fn(...args);
|
|
445
|
+
if (r && typeof r.catch === 'function') r.catch((e) => log(`feishu: ${e?.message ?? e}`));
|
|
446
|
+
} catch (e) {
|
|
447
|
+
log(`feishu: ${e?.message ?? e}`);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
let stopped = false;
|
|
452
|
+
let dead = false;
|
|
453
|
+
let fatalError = null;
|
|
454
|
+
let started = false;
|
|
455
|
+
let startPromise = null;
|
|
456
|
+
let stopping = null;
|
|
457
|
+
/** {base, lark} once the App ID is known on one of them. */
|
|
458
|
+
let domain = null;
|
|
459
|
+
/** {openId, name} of the bot, from bot/v3/info. */
|
|
460
|
+
let me = null;
|
|
461
|
+
let tokenCache = null;
|
|
462
|
+
let tokenFlight = null;
|
|
463
|
+
const halt = new AbortController();
|
|
464
|
+
const halted = () => stopped || dead;
|
|
465
|
+
const label = () => (domain?.lark ? 'Lark' : 'Feishu');
|
|
466
|
+
const stoppedError = () => fatalError ?? new Error('the Feishu connector was stopped');
|
|
467
|
+
|
|
468
|
+
// Waits that stop() and fail() cut short.
|
|
469
|
+
const sleepers = new Set();
|
|
470
|
+
const sleep = (ms) =>
|
|
471
|
+
new Promise((resolve) => {
|
|
472
|
+
if (halted()) return resolve();
|
|
473
|
+
const s = { resolve };
|
|
474
|
+
s.timer = setTimeoutImpl(() => {
|
|
475
|
+
sleepers.delete(s);
|
|
476
|
+
resolve();
|
|
477
|
+
}, ms);
|
|
478
|
+
sleepers.add(s);
|
|
479
|
+
});
|
|
480
|
+
const wakeAll = () => {
|
|
481
|
+
for (const s of sleepers) {
|
|
482
|
+
clearTimeoutImpl(s.timer);
|
|
483
|
+
s.resolve();
|
|
484
|
+
}
|
|
485
|
+
sleepers.clear();
|
|
486
|
+
};
|
|
487
|
+
const cancel = (...timers) => {
|
|
488
|
+
for (const t of timers) if (t != null) clearTimeoutImpl(t);
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
// --- HTTP -----------------------------------------------------------------------------
|
|
492
|
+
|
|
493
|
+
async function http(method, url, { body, token, timeoutMs = 20_000, afterStop = false } = {}) {
|
|
494
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
495
|
+
const signal = afterStop ? timeout : AbortSignal.any([halt.signal, timeout]);
|
|
496
|
+
const headers = { 'content-type': 'application/json; charset=utf-8' };
|
|
497
|
+
if (token) headers.authorization = `Bearer ${token}`;
|
|
498
|
+
const where = new URL(url).pathname;
|
|
499
|
+
let res;
|
|
500
|
+
try {
|
|
501
|
+
res = await fetchImpl(url, { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal });
|
|
502
|
+
} catch (error) {
|
|
503
|
+
const why = error?.name === 'TimeoutError' || timeout.aborted ? 'timed out' : error?.cause?.code ?? error?.cause?.message ?? error?.message ?? 'network error';
|
|
504
|
+
throw Object.assign(new Error(clean(`could not reach ${label()} (${where}: ${why})`)), { network: true });
|
|
505
|
+
}
|
|
506
|
+
let json = null;
|
|
507
|
+
try {
|
|
508
|
+
const text = await res.text();
|
|
509
|
+
json = text ? JSON.parse(text) : null;
|
|
510
|
+
} catch {
|
|
511
|
+
json = null;
|
|
512
|
+
}
|
|
513
|
+
return { status: res.status, json, headers: res.headers };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function apiError(what, r) {
|
|
517
|
+
const code = Number(r.json?.code) || 0;
|
|
518
|
+
const msg = String(r.json?.msg ?? r.json?.message ?? `HTTP ${r.status}`);
|
|
519
|
+
return Object.assign(new Error(clean(`${label()} ${what}: ${msg}${code ? ` (code ${code})` : ''}`)), { code, httpStatus: r.status, msg: clean(msg) });
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Why a token request failed, classified: unknown App ID, wrong secret, disabled app, or try again. */
|
|
523
|
+
function credentialError(r, lark) {
|
|
524
|
+
const where = lark ? 'Lark' : 'Feishu';
|
|
525
|
+
const code = Number(r.json?.code) || 0;
|
|
526
|
+
const msg = clean(String(r.json?.msg ?? `HTTP ${r.status}`));
|
|
527
|
+
const e = (message, extra) => Object.assign(new Error(message), { code, msg, ...extra });
|
|
528
|
+
if (code === 10014 && /not\s*exist/i.test(msg)) return e(`${where} does not know this App ID (${msg}).`, { notFound: true, fatal: true, hint: 'appId' });
|
|
529
|
+
if (code === 10015) return e(`${where} rejected the App Secret (${msg}). Copy it again from the developer console: your app → Credentials & Basic Info.`, { fatal: true, hint: 'secret' });
|
|
530
|
+
if (code === 10003) return e(`${where} says the App ID or App Secret is malformed (${msg}). Copy both again from the developer console: your app → Credentials & Basic Info.`, { fatal: true, hint: 'appId' });
|
|
531
|
+
if (code === 10014 || code === 99991662 || code === 99991673)
|
|
532
|
+
return e(`${where} will not sign this app in (${msg}, code ${code}). Check in the developer console that the app is enabled.`, { fatal: true, hint: 'disabled' });
|
|
533
|
+
return e(`${where} sign-in failed: ${msg}${code ? ` (code ${code})` : ''}`, {});
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function requestToken(base, appSecret, lark) {
|
|
537
|
+
const r = await http('POST', `${base}/open-apis/auth/v3/tenant_access_token/internal`, { body: { app_id: appId, app_secret: appSecret }, timeoutMs: 15_000 });
|
|
538
|
+
if (Number(r.json?.code) === 0 && typeof r.json?.tenant_access_token === 'string' && r.json.tenant_access_token) {
|
|
539
|
+
const value = r.json.tenant_access_token;
|
|
540
|
+
hidden.add(value);
|
|
541
|
+
const life = Math.max(60, Number(r.json.expire) || 7200) * 1000;
|
|
542
|
+
// Feishu hands out a fresh token once less than 30 minutes remain; renew 20 minutes before expiry.
|
|
543
|
+
return { value, refreshAt: now() + Math.max(life / 2, life - 20 * 60_000) };
|
|
544
|
+
}
|
|
545
|
+
throw credentialError(r, lark);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** The cached tenant_access_token, renewed before it expires (one request at a time). */
|
|
549
|
+
async function tenantToken() {
|
|
550
|
+
if (tokenCache && tokenCache.refreshAt > now()) return tokenCache.value;
|
|
551
|
+
if (!tokenFlight) {
|
|
552
|
+
tokenFlight = requestToken(domain.base, secret, domain.lark)
|
|
553
|
+
.then((t) => {
|
|
554
|
+
tokenCache = t;
|
|
555
|
+
return t.value;
|
|
556
|
+
})
|
|
557
|
+
.catch((e) => {
|
|
558
|
+
// The secret was changed or the app disabled while connected: nothing to retry.
|
|
559
|
+
if (e.fatal) fail(e.message, e.hint);
|
|
560
|
+
throw e;
|
|
561
|
+
})
|
|
562
|
+
.finally(() => {
|
|
563
|
+
tokenFlight = null;
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
return tokenFlight;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** One Open API call with the tenant token: renews a rejected token once, waits out rate limits, retries network errors. */
|
|
570
|
+
async function api(method, path, body, { retries = 2, what = path } = {}) {
|
|
571
|
+
let renewed = false;
|
|
572
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
573
|
+
if (halted()) throw stoppedError();
|
|
574
|
+
const token = await tenantToken();
|
|
575
|
+
let r;
|
|
576
|
+
try {
|
|
577
|
+
r = await http(method, `${domain.base}${path}`, { body, token });
|
|
578
|
+
} catch (e) {
|
|
579
|
+
if (e.network && attempt < retries && !halted()) {
|
|
580
|
+
await sleep(backoffDelay(attempt, random));
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
throw e;
|
|
584
|
+
}
|
|
585
|
+
const code = Number(r.json?.code);
|
|
586
|
+
if (code === 0) return r.json;
|
|
587
|
+
if (TOKEN_CODES.has(code) && !renewed) {
|
|
588
|
+
renewed = true;
|
|
589
|
+
tokenCache = null;
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
if ((RATE_CODES.has(code) || r.status === 429) && attempt < retries + 1) {
|
|
593
|
+
const reset = Number(r.headers?.get?.('x-ogw-ratelimit-reset'));
|
|
594
|
+
await sleep(Number.isFinite(reset) && reset > 0 ? Math.min(30, reset) * 1000 : backoffDelay(attempt, random));
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
if (r.status >= 500 && attempt < retries) {
|
|
598
|
+
await sleep(backoffDelay(attempt, random));
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
throw apiError(what, r);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// --- sign-in --------------------------------------------------------------------------
|
|
606
|
+
|
|
607
|
+
/** Find the platform that knows the App ID and get a token there. */
|
|
608
|
+
async function chooseDomain() {
|
|
609
|
+
const feishu = { base: feishuBase, lark: false };
|
|
610
|
+
const lark = larkBase ? { base: larkBase, lark: true } : null;
|
|
611
|
+
let order = [feishu];
|
|
612
|
+
if (lark) {
|
|
613
|
+
let unknown = false;
|
|
614
|
+
try {
|
|
615
|
+
await requestToken(feishu.base, PROBE_SECRET, false);
|
|
616
|
+
} catch (e) {
|
|
617
|
+
if (e.network) throw e;
|
|
618
|
+
unknown = e.notFound === true;
|
|
619
|
+
}
|
|
620
|
+
order = unknown ? [lark] : [feishu, lark];
|
|
621
|
+
}
|
|
622
|
+
for (const d of order) {
|
|
623
|
+
try {
|
|
624
|
+
tokenCache = await requestToken(d.base, secret, d.lark);
|
|
625
|
+
domain = d;
|
|
626
|
+
return;
|
|
627
|
+
} catch (e) {
|
|
628
|
+
if (e.notFound && d !== order.at(-1)) continue;
|
|
629
|
+
if (e.notFound) {
|
|
630
|
+
throw Object.assign(
|
|
631
|
+
new Error(`${lark ? 'Neither Feishu nor Lark knows' : 'Feishu does not know'} this App ID. Copy it again from the developer console: your app → Credentials & Basic Info (it starts with cli_).`),
|
|
632
|
+
{ fatal: true, hint: 'appId' },
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
throw e;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
async function signIn() {
|
|
641
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
642
|
+
try {
|
|
643
|
+
await chooseDomain();
|
|
644
|
+
return;
|
|
645
|
+
} catch (e) {
|
|
646
|
+
if (halted()) throw stoppedError();
|
|
647
|
+
if (e.fatal) throw e;
|
|
648
|
+
const ms = backoffDelay(attempt, random);
|
|
649
|
+
status('error', `${e.message}; retrying in ${secs(ms)} s`);
|
|
650
|
+
log(`feishu: ${e.message}`);
|
|
651
|
+
await sleep(ms);
|
|
652
|
+
if (halted()) throw stoppedError();
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** The bot's open_id and name. Until the bot capability is live, says so and looks again every 15 s. */
|
|
658
|
+
async function loadBot() {
|
|
659
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
660
|
+
if (halted()) throw stoppedError();
|
|
661
|
+
try {
|
|
662
|
+
const r = await api('GET', '/open-apis/bot/v3/info', undefined, { retries: 0, what: 'bot info' });
|
|
663
|
+
const b = r?.bot ?? r?.data?.bot ?? {};
|
|
664
|
+
if (b.open_id) {
|
|
665
|
+
me = { openId: String(b.open_id), name: String(b.app_name ?? '').trim() };
|
|
666
|
+
if (b.activate_status !== undefined && b.activate_status !== 2) log(`feishu: the bot's activate_status is ${b.activate_status} (2 = enabled); publish a version if messages do not arrive`);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
throw Object.assign(new Error(`${label()} bot info: this app has no bot`), { code: -1 });
|
|
670
|
+
} catch (e) {
|
|
671
|
+
if (halted()) throw stoppedError();
|
|
672
|
+
if (e.fatal) throw e;
|
|
673
|
+
if (e.network || e.httpStatus >= 500 || RATE_CODES.has(e.code)) {
|
|
674
|
+
const ms = backoffDelay(attempt, random);
|
|
675
|
+
status('error', `${e.message}; retrying in ${secs(ms)} s`);
|
|
676
|
+
await sleep(ms);
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
status(
|
|
680
|
+
'error',
|
|
681
|
+
`${e.message}. Turn on the bot: developer console → your app → Add features → Bot, then publish a version (Version Management & Release). The channel connects by itself once that is live.`,
|
|
682
|
+
{ hint: 'bot' },
|
|
683
|
+
);
|
|
684
|
+
log(`feishu: ${e.message}; waiting for the bot capability`);
|
|
685
|
+
await sleep(BOT_RETRY_MS);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// --- long connection ------------------------------------------------------------------
|
|
691
|
+
|
|
692
|
+
let ws = null;
|
|
693
|
+
let wsOpen = false;
|
|
694
|
+
let healthy = false;
|
|
695
|
+
let attempts = 0;
|
|
696
|
+
let serviceId = 0;
|
|
697
|
+
let pingMs = DEFAULT_PING_MS;
|
|
698
|
+
let pingTimer = null;
|
|
699
|
+
let pongTimer = null;
|
|
700
|
+
let openTimer = null;
|
|
701
|
+
let reconnectTimer = null;
|
|
702
|
+
let waitOpen = null;
|
|
703
|
+
/** message_id → {parts, got, at}: an event split over several frames */
|
|
704
|
+
const fragments = new Map();
|
|
705
|
+
|
|
706
|
+
function applyConfig(cfg) {
|
|
707
|
+
const ping = Number(cfg?.PingInterval);
|
|
708
|
+
if (Number.isFinite(ping) && ping > 0) pingMs = Math.min(600_000, Math.max(10_000, ping * 1000));
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** The wss URL of a new connection. Errors carry `fatal` (credentials) or `retryMs`. */
|
|
712
|
+
async function endpoint() {
|
|
713
|
+
const r = await http('POST', `${domain.base}/callback/ws/endpoint`, { body: { AppID: appId, AppSecret: secret }, timeoutMs: 15_000 });
|
|
714
|
+
const code = Number(r.json?.code);
|
|
715
|
+
const url = r.json?.data?.URL;
|
|
716
|
+
if (code === 0 && typeof url === 'string' && /^wss?:\/\//.test(url)) {
|
|
717
|
+
hidden.add(url);
|
|
718
|
+
try {
|
|
719
|
+
serviceId = Number(new URL(url).searchParams.get('service_id')) || 0;
|
|
720
|
+
} catch {
|
|
721
|
+
serviceId = 0;
|
|
722
|
+
}
|
|
723
|
+
applyConfig(r.json.data.ClientConfig);
|
|
724
|
+
return url;
|
|
725
|
+
}
|
|
726
|
+
const msg = clean(String(r.json?.msg ?? `HTTP ${r.status}`));
|
|
727
|
+
if (code === 1000040345 || code === 514) {
|
|
728
|
+
throw Object.assign(new Error(`${label()} rejected the App ID or App Secret for the long connection (${msg}). Copy both again from the developer console: your app → Credentials & Basic Info.`), { fatal: true, hint: 'secret' });
|
|
729
|
+
}
|
|
730
|
+
if (code === 1000040350) {
|
|
731
|
+
throw Object.assign(new Error(`${label()} refused another long connection for this app (${msg}): it allows 50. Stop other programs that use this App ID.`), { retryMs: CONN_LIMIT_RETRY_MS, hint: 'connlimit' });
|
|
732
|
+
}
|
|
733
|
+
throw Object.assign(new Error(`${label()} long connection: ${msg}${code ? ` (code ${code})` : ''}`), code === 403 ? { retryMs: CONN_LIMIT_RETRY_MS } : {});
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function detach() {
|
|
737
|
+
const sock = ws;
|
|
738
|
+
ws = null;
|
|
739
|
+
wsOpen = false;
|
|
740
|
+
cancel(pingTimer, pongTimer, openTimer);
|
|
741
|
+
pingTimer = pongTimer = openTimer = null;
|
|
742
|
+
if (sock) {
|
|
743
|
+
try {
|
|
744
|
+
sock.close(1000);
|
|
745
|
+
} catch {
|
|
746
|
+
// Already closed.
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/** Something failed: reconnect with backoff. The first drop after a good connection reads as `connecting`, repeats as `error`. */
|
|
752
|
+
function retry(why, minDelay = 0, hint = '') {
|
|
753
|
+
detach();
|
|
754
|
+
if (halted()) return;
|
|
755
|
+
const delay = Math.max(minDelay, backoffDelay(attempts, random));
|
|
756
|
+
attempts += 1;
|
|
757
|
+
const detail = `${why}; reconnecting in ${secs(delay)} s`;
|
|
758
|
+
log(`feishu: ${detail}`);
|
|
759
|
+
status(healthy ? 'connecting' : 'error', detail, { hint });
|
|
760
|
+
healthy = false;
|
|
761
|
+
cancel(reconnectTimer);
|
|
762
|
+
reconnectTimer = setTimeoutImpl(
|
|
763
|
+
guard(() => {
|
|
764
|
+
reconnectTimer = null;
|
|
765
|
+
openSocket();
|
|
766
|
+
}),
|
|
767
|
+
delay,
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** Unrecoverable: no reconnects. Rejects a pending start. */
|
|
772
|
+
function fail(detail, hint = '') {
|
|
773
|
+
if (halted()) return;
|
|
774
|
+
dead = true;
|
|
775
|
+
fatalError = Object.assign(new Error(clean(detail)), { fatal: true, ...(hint ? { hint } : {}) });
|
|
776
|
+
cancel(reconnectTimer);
|
|
777
|
+
reconnectTimer = null;
|
|
778
|
+
detach();
|
|
779
|
+
wakeAll();
|
|
780
|
+
log(`feishu: ${detail}`);
|
|
781
|
+
status('error', detail, { fatal: true, hint });
|
|
782
|
+
if (waitOpen) {
|
|
783
|
+
waitOpen.reject(fatalError);
|
|
784
|
+
waitOpen = null;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
async function openSocket() {
|
|
789
|
+
if (halted()) return;
|
|
790
|
+
let url;
|
|
791
|
+
try {
|
|
792
|
+
url = await endpoint();
|
|
793
|
+
} catch (e) {
|
|
794
|
+
if (halted()) return;
|
|
795
|
+
if (e.fatal) return fail(e.message, e.hint);
|
|
796
|
+
return retry(e.message, e.retryMs ?? 0, e.hint ?? '');
|
|
797
|
+
}
|
|
798
|
+
if (halted()) return;
|
|
799
|
+
let sock;
|
|
800
|
+
try {
|
|
801
|
+
sock = new WebSocketImpl(url);
|
|
802
|
+
} catch (e) {
|
|
803
|
+
return retry(`could not open the ${label()} connection: ${e?.message ?? e}`);
|
|
804
|
+
}
|
|
805
|
+
try {
|
|
806
|
+
sock.binaryType = 'arraybuffer';
|
|
807
|
+
} catch {
|
|
808
|
+
// Not every implementation lets it be set.
|
|
809
|
+
}
|
|
810
|
+
ws = sock;
|
|
811
|
+
openTimer = setTimeoutImpl(
|
|
812
|
+
guard(() => {
|
|
813
|
+
if (sock === ws && !wsOpen) retry(`the ${label()} connection did not open within ${secs(OPEN_TIMEOUT_MS)} s`);
|
|
814
|
+
}),
|
|
815
|
+
OPEN_TIMEOUT_MS,
|
|
816
|
+
);
|
|
817
|
+
sock.addEventListener('open', guard(() => onOpen(sock)));
|
|
818
|
+
sock.addEventListener('message', guard((ev) => onData(sock, ev?.data)));
|
|
819
|
+
sock.addEventListener('close', guard((ev) => onClose(sock, ev)));
|
|
820
|
+
sock.addEventListener('error', guard(() => {
|
|
821
|
+
if (sock === ws) log('feishu: connection error');
|
|
822
|
+
}));
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
function onOpen(sock) {
|
|
826
|
+
if (sock !== ws) return;
|
|
827
|
+
cancel(openTimer);
|
|
828
|
+
openTimer = null;
|
|
829
|
+
wsOpen = true;
|
|
830
|
+
attempts = 0;
|
|
831
|
+
healthy = true;
|
|
832
|
+
if (started) status('connected');
|
|
833
|
+
if (waitOpen) {
|
|
834
|
+
waitOpen.resolve();
|
|
835
|
+
waitOpen = null;
|
|
836
|
+
}
|
|
837
|
+
ping(sock);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function sendFrame(sock, frame) {
|
|
841
|
+
try {
|
|
842
|
+
sock.send(encodeFrame(frame));
|
|
843
|
+
} catch (e) {
|
|
844
|
+
log(`feishu: could not send a frame: ${e?.message ?? e}`);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
function ping(sock) {
|
|
849
|
+
if (sock !== ws || !wsOpen) return;
|
|
850
|
+
sendFrame(sock, { SeqID: 0, LogID: 0, service: serviceId, method: 0, headers: [{ key: 'type', value: 'ping' }] });
|
|
851
|
+
// Armed by the first unanswered ping and cleared by any frame; a later ping does not push it back.
|
|
852
|
+
pongTimer ??= setTimeoutImpl(
|
|
853
|
+
guard(() => {
|
|
854
|
+
pongTimer = null;
|
|
855
|
+
if (sock === ws) retry(`${label()} did not answer a ping within ${secs(PONG_TIMEOUT_MS)} s`);
|
|
856
|
+
}),
|
|
857
|
+
PONG_TIMEOUT_MS,
|
|
858
|
+
);
|
|
859
|
+
cancel(pingTimer);
|
|
860
|
+
pingTimer = setTimeoutImpl(guard(() => ping(sock)), pingMs);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
function onClose(sock, ev) {
|
|
864
|
+
if (sock !== ws) return;
|
|
865
|
+
ws = null;
|
|
866
|
+
wsOpen = false;
|
|
867
|
+
cancel(pingTimer, pongTimer, openTimer);
|
|
868
|
+
pingTimer = pongTimer = openTimer = null;
|
|
869
|
+
if (halted()) return;
|
|
870
|
+
const code = ev?.code;
|
|
871
|
+
retry(`${label()} closed the connection (${code ?? 'no code'}${ev?.reason ? `: ${clean(ev.reason)}` : ''})`);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
async function onData(sock, data) {
|
|
875
|
+
if (sock !== ws) return;
|
|
876
|
+
let bytes;
|
|
877
|
+
if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);
|
|
878
|
+
else if (ArrayBuffer.isView(data)) bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
879
|
+
else if (data && typeof data.arrayBuffer === 'function') bytes = new Uint8Array(await data.arrayBuffer());
|
|
880
|
+
else return;
|
|
881
|
+
if (sock !== ws) return;
|
|
882
|
+
// Any frame proves the connection is alive.
|
|
883
|
+
cancel(pongTimer);
|
|
884
|
+
pongTimer = null;
|
|
885
|
+
let frame;
|
|
886
|
+
try {
|
|
887
|
+
frame = decodeFrame(bytes);
|
|
888
|
+
} catch (e) {
|
|
889
|
+
return log(`feishu: ignored an unreadable frame (${e.message})`);
|
|
890
|
+
}
|
|
891
|
+
const h = headersOf(frame);
|
|
892
|
+
if (frame.method === 0) {
|
|
893
|
+
if (h.type === 'pong' && frame.payload?.length) {
|
|
894
|
+
try {
|
|
895
|
+
applyConfig(JSON.parse(dec.decode(frame.payload)));
|
|
896
|
+
} catch {
|
|
897
|
+
// A pong without settings.
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
if (frame.method !== 1) return;
|
|
903
|
+
const whole = assemble(h, frame.payload ?? new Uint8Array(0));
|
|
904
|
+
if (!whole) return;
|
|
905
|
+
const began = now();
|
|
906
|
+
let event = null;
|
|
907
|
+
try {
|
|
908
|
+
event = JSON.parse(dec.decode(whole));
|
|
909
|
+
} catch {
|
|
910
|
+
log(`feishu: ignored an unreadable event (${h.type ?? 'no type'})`);
|
|
911
|
+
}
|
|
912
|
+
// Acked at once, whatever happens next: Feishu pushes again what is not acked within 3 s.
|
|
913
|
+
sendFrame(sock, { ...frame, headers: [...frame.headers, { key: 'biz_rt', value: String(Math.max(0, now() - began)) }], payload: enc.encode(JSON.stringify({ code: 200 })) });
|
|
914
|
+
if (event && h.type === 'event') handleEvent(event);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** The whole payload of a data frame, or null while parts are missing. */
|
|
918
|
+
function assemble(h, payload) {
|
|
919
|
+
const sum = Number(h.sum ?? 1);
|
|
920
|
+
const seq = Number(h.seq ?? 0);
|
|
921
|
+
if (!h.sum || sum === 1) return payload;
|
|
922
|
+
if (!Number.isInteger(sum) || sum < 1 || sum > 1000 || !Number.isInteger(seq) || seq < 0 || seq >= sum) {
|
|
923
|
+
log(`feishu: ignored an event part with bad numbering (sum ${h.sum}, seq ${h.seq})`);
|
|
924
|
+
return null;
|
|
925
|
+
}
|
|
926
|
+
const t = now();
|
|
927
|
+
for (const [id, f] of fragments) if (t - f.at > FRAGMENT_TTL_MS) fragments.delete(id);
|
|
928
|
+
const id = String(h.message_id ?? '');
|
|
929
|
+
let f = fragments.get(id);
|
|
930
|
+
if (!f || f.parts.length !== sum) {
|
|
931
|
+
f = { parts: new Array(sum).fill(null), got: 0, at: t };
|
|
932
|
+
fragments.set(id, f);
|
|
933
|
+
}
|
|
934
|
+
if (!f.parts[seq]) f.got += 1;
|
|
935
|
+
f.parts[seq] = payload;
|
|
936
|
+
if (f.got < sum) return null;
|
|
937
|
+
fragments.delete(id);
|
|
938
|
+
const out = new Uint8Array(f.parts.reduce((n, p) => n + p.length, 0));
|
|
939
|
+
let at = 0;
|
|
940
|
+
for (const p of f.parts) {
|
|
941
|
+
out.set(p, at);
|
|
942
|
+
at += p.length;
|
|
943
|
+
}
|
|
944
|
+
return out;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// --- inbound messages -----------------------------------------------------------------
|
|
948
|
+
|
|
949
|
+
/** message ids seen lately (Feishu may push one twice) */
|
|
950
|
+
const seenIds = new Set();
|
|
951
|
+
/** message ids the bot sent (a reply to one of them addresses the bot) */
|
|
952
|
+
const sentIds = new Set();
|
|
953
|
+
/** chatId → the latest person's message there, for the "Typing" reaction */
|
|
954
|
+
const lastInbound = new Map();
|
|
955
|
+
let inbound = Promise.resolve();
|
|
956
|
+
let warnedEncrypted = false;
|
|
957
|
+
|
|
958
|
+
function handleEvent(data) {
|
|
959
|
+
if (data?.encrypt) {
|
|
960
|
+
if (!warnedEncrypted) log('feishu: an encrypted event arrived; long-connection events should be plain. Ignored.');
|
|
961
|
+
warnedEncrypted = true;
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
const type = data?.header?.event_type ?? data?.event?.type;
|
|
965
|
+
if (type !== 'im.message.receive_v1') return;
|
|
966
|
+
const event = data.event;
|
|
967
|
+
// One at a time, in arrival order: a name lookup must not let a later message overtake.
|
|
968
|
+
inbound = inbound.then(() => deliver(event)).catch((e) => log(`feishu: a message was not handled: ${e?.message ?? e}`));
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
async function deliver(event) {
|
|
972
|
+
const msg = normalizeEvent(event, { botOpenId: me?.openId ?? '', sentIds });
|
|
973
|
+
if (!msg || seenIds.has(msg.messageId)) return;
|
|
974
|
+
remember(seenIds, msg.messageId, 2000);
|
|
975
|
+
msg.userName = await nameOf(msg.userId);
|
|
976
|
+
if (!msg.isDirect) {
|
|
977
|
+
const title = await titleOf(msg.chatId);
|
|
978
|
+
if (title) msg.chatTitle = title;
|
|
979
|
+
}
|
|
980
|
+
if (domain?.lark) msg.source = 'Lark';
|
|
981
|
+
lastInbound.delete(msg.chatId);
|
|
982
|
+
lastInbound.set(msg.chatId, { messageId: msg.messageId, at: now(), used: false });
|
|
983
|
+
if (lastInbound.size > 500) lastInbound.delete(lastInbound.keys().next().value);
|
|
984
|
+
if (halted()) return;
|
|
985
|
+
try {
|
|
986
|
+
const r = onMessage(msg);
|
|
987
|
+
if (r && typeof r.catch === 'function') r.catch((e) => log(`feishu: a message handler failed: ${e?.message ?? e}`));
|
|
988
|
+
} catch (e) {
|
|
989
|
+
log(`feishu: a message handler failed: ${e?.message ?? e}`);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
/**
|
|
994
|
+
* A cached lookup with an off switch: a missing permission stops asking for a
|
|
995
|
+
* while (logged once). An answer slower than LOOKUP_TIMEOUT_MS does not hold
|
|
996
|
+
* the message up; it lands in the cache for the next one.
|
|
997
|
+
*/
|
|
998
|
+
function lookup({ what, fetchOne, advice }) {
|
|
999
|
+
const cache = new Map();
|
|
1000
|
+
const flights = new Map();
|
|
1001
|
+
let offUntil = 0;
|
|
1002
|
+
let warned = false;
|
|
1003
|
+
const warn = (why) => {
|
|
1004
|
+
if (!warned) log(`feishu: ${why}; ${advice}`);
|
|
1005
|
+
warned = true;
|
|
1006
|
+
};
|
|
1007
|
+
const fetchAndCache = (id, previous) =>
|
|
1008
|
+
Promise.resolve()
|
|
1009
|
+
.then(() => fetchOne(id))
|
|
1010
|
+
.then((v) => {
|
|
1011
|
+
const value = String(v ?? '').trim();
|
|
1012
|
+
cache.set(id, { value, until: now() + (value ? NAME_TTL_MS : LOOKUP_RETRY_MS) });
|
|
1013
|
+
if (cache.size > 2000) cache.delete(cache.keys().next().value);
|
|
1014
|
+
if (!value) warn(`${what} came back empty`);
|
|
1015
|
+
return value;
|
|
1016
|
+
})
|
|
1017
|
+
.catch((e) => {
|
|
1018
|
+
if (SCOPE_CODES.has(e.code)) offUntil = now() + LOOKUP_OFF_MS;
|
|
1019
|
+
if (SCOPE_CODES.has(e.code) || e.code === 41050) warn(`no ${what} (${e.message})`);
|
|
1020
|
+
cache.set(id, { value: previous, until: now() + LOOKUP_RETRY_MS });
|
|
1021
|
+
return previous;
|
|
1022
|
+
})
|
|
1023
|
+
.finally(() => flights.delete(id));
|
|
1024
|
+
return async (id) => {
|
|
1025
|
+
const hit = cache.get(id);
|
|
1026
|
+
if (hit && hit.until > now()) return hit.value;
|
|
1027
|
+
const previous = hit?.value ?? '';
|
|
1028
|
+
if (offUntil > now() || halted()) return previous;
|
|
1029
|
+
let flight = flights.get(id);
|
|
1030
|
+
if (flight?.late) return previous; // already too slow once: the next messages do not wait for it again
|
|
1031
|
+
if (!flight) {
|
|
1032
|
+
flight = { promise: fetchAndCache(id, previous), late: false };
|
|
1033
|
+
flights.set(id, flight);
|
|
1034
|
+
}
|
|
1035
|
+
let timer;
|
|
1036
|
+
const late = new Promise((resolve) => {
|
|
1037
|
+
timer = setTimeoutImpl(() => {
|
|
1038
|
+
flight.late = true;
|
|
1039
|
+
resolve(previous);
|
|
1040
|
+
}, LOOKUP_TIMEOUT_MS);
|
|
1041
|
+
});
|
|
1042
|
+
return Promise.race([flight.promise, late]).finally(() => clearTimeoutImpl(timer));
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
const userName = lookup({
|
|
1047
|
+
what: 'sender names',
|
|
1048
|
+
advice: 'add the permissions contact:contact.base:readonly and contact:user.base:readonly, and check Permissions & Scopes → Data permissions → contact range covers these people',
|
|
1049
|
+
fetchOne: async (openId) => {
|
|
1050
|
+
const r = await api('GET', `/open-apis/contact/v3/users/${encodeURIComponent(openId)}?user_id_type=open_id`, undefined, { retries: 0, what: 'user lookup' });
|
|
1051
|
+
const u = r?.data?.user ?? {};
|
|
1052
|
+
return u.name || u.en_name || u.nickname || '';
|
|
1053
|
+
},
|
|
1054
|
+
});
|
|
1055
|
+
const nameOf = async (openId) => (await userName(openId)) || `user ${openId.slice(-6)}`;
|
|
1056
|
+
|
|
1057
|
+
const titleOf = lookup({
|
|
1058
|
+
what: 'group names',
|
|
1059
|
+
advice: 'add the permission im:chat:readonly to show them',
|
|
1060
|
+
fetchOne: async (chatId) => {
|
|
1061
|
+
const r = await api('GET', `/open-apis/im/v1/chats/${encodeURIComponent(chatId)}`, undefined, { retries: 0, what: 'group lookup' });
|
|
1062
|
+
return r?.data?.name ?? '';
|
|
1063
|
+
},
|
|
1064
|
+
});
|
|
1065
|
+
|
|
1066
|
+
// --- typing: a "Typing" reaction -------------------------------------------------------
|
|
1067
|
+
|
|
1068
|
+
/** chatId → {messageId, reactionId, timer, adding} */
|
|
1069
|
+
const marks = new Map();
|
|
1070
|
+
let reactionsOff = false;
|
|
1071
|
+
|
|
1072
|
+
function removeMark(chatId, { afterStop = false } = {}) {
|
|
1073
|
+
const mark = marks.get(chatId);
|
|
1074
|
+
if (!mark) return Promise.resolve();
|
|
1075
|
+
marks.delete(chatId);
|
|
1076
|
+
cancel(mark.timer);
|
|
1077
|
+
return Promise.resolve(mark.adding)
|
|
1078
|
+
.then(async () => {
|
|
1079
|
+
if (!mark.reactionId) return;
|
|
1080
|
+
const path = `/open-apis/im/v1/messages/${encodeURIComponent(mark.messageId)}/reactions/${encodeURIComponent(mark.reactionId)}`;
|
|
1081
|
+
if (afterStop) {
|
|
1082
|
+
if (tokenCache?.value) await http('DELETE', `${domain.base}${path}`, { token: tokenCache.value, timeoutMs: 3000, afterStop: true });
|
|
1083
|
+
} else await api('DELETE', path, undefined, { retries: 1, what: 'typing reaction' });
|
|
1084
|
+
})
|
|
1085
|
+
.catch((e) => log(`feishu: could not remove the typing reaction: ${e?.message ?? e}`));
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
async function typing(chatId) {
|
|
1089
|
+
chatId = String(chatId);
|
|
1090
|
+
if (halted() || !domain) return;
|
|
1091
|
+
const mark = marks.get(chatId);
|
|
1092
|
+
if (mark) {
|
|
1093
|
+
cancel(mark.timer);
|
|
1094
|
+
mark.timer = setTimeoutImpl(guard(() => removeMark(chatId)), TYPING_IDLE_MS);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
const last = lastInbound.get(chatId);
|
|
1098
|
+
if (reactionsOff || !last || last.used || now() - last.at > TYPING_FRESH_MS) return;
|
|
1099
|
+
last.used = true;
|
|
1100
|
+
const m = { messageId: last.messageId, reactionId: '', timer: null, adding: null };
|
|
1101
|
+
m.timer = setTimeoutImpl(guard(() => removeMark(chatId)), TYPING_IDLE_MS);
|
|
1102
|
+
marks.set(chatId, m);
|
|
1103
|
+
m.adding = api('POST', `/open-apis/im/v1/messages/${encodeURIComponent(m.messageId)}/reactions`, { reaction_type: { emoji_type: 'Typing' } }, { retries: 0, what: 'typing reaction' })
|
|
1104
|
+
.then((r) => {
|
|
1105
|
+
m.reactionId = String(r?.data?.reaction_id ?? '');
|
|
1106
|
+
})
|
|
1107
|
+
.catch((e) => {
|
|
1108
|
+
if (SCOPE_CODES.has(e.code)) {
|
|
1109
|
+
reactionsOff = true;
|
|
1110
|
+
log(`feishu: no typing reaction (${e.message}); add the permission im:message.reactions:write_only to show one`);
|
|
1111
|
+
} else log(`feishu: typing reaction: ${e?.message ?? e}`);
|
|
1112
|
+
});
|
|
1113
|
+
await m.adding;
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
// --- sending --------------------------------------------------------------------------
|
|
1117
|
+
|
|
1118
|
+
let sendTrouble = false;
|
|
1119
|
+
|
|
1120
|
+
async function deliverBody(chatId, body, replyTo) {
|
|
1121
|
+
let r = null;
|
|
1122
|
+
if (replyTo) {
|
|
1123
|
+
try {
|
|
1124
|
+
r = await api('POST', `/open-apis/im/v1/messages/${encodeURIComponent(replyTo)}/reply`, { ...body, uuid: randomUUID() }, { what: 'reply' });
|
|
1125
|
+
} catch (e) {
|
|
1126
|
+
if (!REPLY_GONE.has(e.code)) throw e;
|
|
1127
|
+
r = null;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
if (!r) r = await api('POST', '/open-apis/im/v1/messages?receive_id_type=chat_id', { receive_id: chatId, ...body, uuid: randomUUID() }, { what: 'send' });
|
|
1131
|
+
const id = r?.data?.message_id;
|
|
1132
|
+
if (id) remember(sentIds, String(id), 500);
|
|
1133
|
+
return r;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
async function sendPart(chatId, md, replyTo) {
|
|
1137
|
+
try {
|
|
1138
|
+
return await deliverBody(chatId, postBody(md), replyTo);
|
|
1139
|
+
} catch (e) {
|
|
1140
|
+
if (!POST_REJECTED.has(e.code)) throw e;
|
|
1141
|
+
log(`feishu: ${label()} did not take a reply as Markdown (${e.message}); sending it as plain text`);
|
|
1142
|
+
return deliverBody(chatId, { msg_type: 'text', content: JSON.stringify({ text: toPlainText(md) }) }, replyTo);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/** A send that failed on the app's own setup reads in the panel until a later send works. */
|
|
1147
|
+
function noteSendTrouble(e) {
|
|
1148
|
+
if (SCOPE_CODES.has(e?.code)) {
|
|
1149
|
+
sendTrouble = true;
|
|
1150
|
+
status('error', `${label()} would not let the app send messages (${e.msg ?? e.message}). Add the permission im:message:send_as_bot (Permissions & Scopes), then publish a version.`, { hint: 'scopes' });
|
|
1151
|
+
} else if (e?.code === 230006) {
|
|
1152
|
+
sendTrouble = true;
|
|
1153
|
+
status('error', `${label()} says the bot capability is off (${e.msg ?? e.message}). Turn it on (Add features → Bot) and publish a version.`, { hint: 'bot' });
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// --- public ---------------------------------------------------------------------------
|
|
1158
|
+
|
|
1159
|
+
async function run() {
|
|
1160
|
+
if (!appId || !secret) throw failStart('Fill in the App ID and the App Secret from the developer console: your app → Credentials & Basic Info.', 'appId');
|
|
1161
|
+
if (!/^cli_[A-Za-z0-9]{6,64}$/.test(appId)) throw failStart('That is not a Feishu / Lark App ID: it starts with cli_. Copy it from the developer console: your app → Credentials & Basic Info.', 'appId');
|
|
1162
|
+
if (typeof WebSocketImpl !== 'function') throw failStart('This runtime has no WebSocket.');
|
|
1163
|
+
if (typeof fetchImpl !== 'function') throw failStart('This runtime has no fetch.');
|
|
1164
|
+
status('connecting');
|
|
1165
|
+
try {
|
|
1166
|
+
await signIn();
|
|
1167
|
+
} catch (e) {
|
|
1168
|
+
if (e.fatal) fail(e.message, e.hint);
|
|
1169
|
+
throw stoppedError();
|
|
1170
|
+
}
|
|
1171
|
+
if (domain.lark) larkApps.add(appId);
|
|
1172
|
+
else larkApps.delete(appId);
|
|
1173
|
+
log(`feishu: signed in to ${label()}; opening the long connection`);
|
|
1174
|
+
await new Promise((resolve, reject) => {
|
|
1175
|
+
waitOpen = { resolve, reject };
|
|
1176
|
+
void openSocket();
|
|
1177
|
+
});
|
|
1178
|
+
await loadBot();
|
|
1179
|
+
if (halted()) throw stoppedError();
|
|
1180
|
+
started = true;
|
|
1181
|
+
if (wsOpen) status('connected');
|
|
1182
|
+
return { id: appId, username: me.name, name: me.name };
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
function failStart(detail, hint = '') {
|
|
1186
|
+
fail(detail, hint);
|
|
1187
|
+
return fatalError;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
return {
|
|
1191
|
+
/**
|
|
1192
|
+
* Sign in, open the long connection, then learn the bot's identity.
|
|
1193
|
+
* Resolves with {id: App ID, username: bot name, name}; network trouble
|
|
1194
|
+
* keeps retrying, bad credentials reject (fatal).
|
|
1195
|
+
*/
|
|
1196
|
+
start() {
|
|
1197
|
+
if (stopped) return Promise.reject(new Error('the Feishu connector was stopped'));
|
|
1198
|
+
if (!startPromise) {
|
|
1199
|
+
startPromise = run();
|
|
1200
|
+
startPromise.catch(() => {});
|
|
1201
|
+
}
|
|
1202
|
+
return startPromise;
|
|
1203
|
+
},
|
|
1204
|
+
|
|
1205
|
+
/** Close the connection for good; a "Typing" reaction still showing is removed (best effort). */
|
|
1206
|
+
stop() {
|
|
1207
|
+
if (stopping) return stopping;
|
|
1208
|
+
stopped = true;
|
|
1209
|
+
halt.abort();
|
|
1210
|
+
cancel(reconnectTimer);
|
|
1211
|
+
reconnectTimer = null;
|
|
1212
|
+
detach();
|
|
1213
|
+
wakeAll();
|
|
1214
|
+
if (waitOpen) {
|
|
1215
|
+
waitOpen.reject(new Error('the Feishu connector was stopped'));
|
|
1216
|
+
waitOpen = null;
|
|
1217
|
+
}
|
|
1218
|
+
const chats = [...marks.keys()];
|
|
1219
|
+
stopping = Promise.allSettled(chats.map((c) => removeMark(c, { afterStop: true }))).then(() => status('stopped'));
|
|
1220
|
+
return stopping;
|
|
1221
|
+
},
|
|
1222
|
+
|
|
1223
|
+
/** Send Markdown as `post` messages of at most TEXT_LIMIT; the first part answers `replyTo`. */
|
|
1224
|
+
async send(chatId, text, sendOpts = {}) {
|
|
1225
|
+
if (halted()) throw new Error(`the ${label()} connector is stopped`);
|
|
1226
|
+
if (!domain) throw new Error(`the ${label()} connector is not signed in yet`);
|
|
1227
|
+
chatId = String(chatId);
|
|
1228
|
+
let first = true;
|
|
1229
|
+
try {
|
|
1230
|
+
for (const part of partsOf(text)) {
|
|
1231
|
+
await sendPart(chatId, part, first && sendOpts?.replyTo ? String(sendOpts.replyTo) : '');
|
|
1232
|
+
first = false;
|
|
1233
|
+
}
|
|
1234
|
+
if (sendTrouble) {
|
|
1235
|
+
sendTrouble = false;
|
|
1236
|
+
if (wsOpen && started) status('connected');
|
|
1237
|
+
}
|
|
1238
|
+
} catch (e) {
|
|
1239
|
+
noteSendTrouble(e);
|
|
1240
|
+
throw e;
|
|
1241
|
+
} finally {
|
|
1242
|
+
void removeMark(chatId);
|
|
1243
|
+
}
|
|
1244
|
+
},
|
|
1245
|
+
|
|
1246
|
+
/** Called every ~5 s while a bot works: a "Typing" reaction on the person's message, removed when the work stops. */
|
|
1247
|
+
typing,
|
|
1248
|
+
};
|
|
1249
|
+
}
|