larkmate 0.0.0-stage → 0.1.1
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/INSTALL.md +52 -0
- package/README.md +122 -2
- package/bin/larkmate.js +224 -0
- package/package.json +36 -4
- package/proto/lark.proto +547 -0
- package/skills/larkmate/SKILL.md +18 -0
- package/skills/larkmate/references/chats.md +30 -0
- package/skills/larkmate/references/minutes.md +14 -0
- package/skills/larkmate/references/writes.md +23 -0
- package/src/client.js +445 -0
- package/src/credentials.js +23 -0
- package/src/errors.js +22 -0
- package/src/gateway.js +184 -0
- package/src/minutes.js +129 -0
- package/src/session-controls.js +266 -0
- package/src/upload.js +61 -0
- package/third_party/NOTICE.md +6 -0
- package/third_party/feishu-user-plugin-LICENSE +21 -0
package/src/gateway.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import protobuf from 'protobufjs';
|
|
4
|
+
import { FeishuError } from './errors.js';
|
|
5
|
+
|
|
6
|
+
const protoFile = fileURLToPath(new URL('../proto/lark.proto', import.meta.url));
|
|
7
|
+
const defaults = {
|
|
8
|
+
csrf: 'https://internal-api-lark-api.feishu.cn/accounts/csrf',
|
|
9
|
+
user: 'https://internal-api-lark-api.feishu.cn/accounts/web/user',
|
|
10
|
+
gateway: 'https://internal-api-lark-api.feishu.cn/im/gateway/',
|
|
11
|
+
botApi: 'https://open.feishu.cn/open-apis/chatbot/api/',
|
|
12
|
+
file: 'https://internal-api-lark-file.feishu.cn',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const shortId = () => randomBytes(8).toString('hex').slice(0, 10);
|
|
16
|
+
|
|
17
|
+
function parseCookies(value) {
|
|
18
|
+
const jar = new Map();
|
|
19
|
+
for (const item of value.split(';')) {
|
|
20
|
+
const i = item.indexOf('=');
|
|
21
|
+
if (i > 0) jar.set(item.slice(0, i).trim(), item.slice(i + 1).trim());
|
|
22
|
+
}
|
|
23
|
+
return jar;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class Gateway {
|
|
27
|
+
constructor({ cookie, fetchImpl = fetch, endpoints = defaults, timeoutMs = 15000 } = {}) {
|
|
28
|
+
this.jar = parseCookies(cookie);
|
|
29
|
+
this.fetchImpl = fetchImpl;
|
|
30
|
+
this.endpoints = endpoints;
|
|
31
|
+
this.timeoutMs = timeoutMs;
|
|
32
|
+
this.proto = null;
|
|
33
|
+
this.user = null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
baseHeaders() {
|
|
37
|
+
return {
|
|
38
|
+
cookie: [...this.jar].map(([key, value]) => `${key}=${value}`).join('; '),
|
|
39
|
+
origin: 'https://www.feishu.cn',
|
|
40
|
+
referer: 'https://www.feishu.cn/',
|
|
41
|
+
'accept-language': 'zh-CN,zh;q=0.9',
|
|
42
|
+
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
jsonHeaders() {
|
|
47
|
+
return {
|
|
48
|
+
...this.baseHeaders(),
|
|
49
|
+
accept: 'application/json, text/plain, */*',
|
|
50
|
+
'x-app-id': '12',
|
|
51
|
+
'x-api-version': '2',
|
|
52
|
+
'x-device-info': 'platform=websdk',
|
|
53
|
+
'x-lgw-os-type': '1',
|
|
54
|
+
'x-lgw-terminal-type': '2',
|
|
55
|
+
'x-terminal-type': '2',
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
absorbCookies(headers) {
|
|
60
|
+
for (const row of headers.getSetCookie?.() || []) {
|
|
61
|
+
const first = row.split(';', 1)[0];
|
|
62
|
+
const separator = first.indexOf('=');
|
|
63
|
+
if (separator > 0) this.jar.set(first.slice(0, separator), first.slice(separator + 1));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async request(url, options, { operation, mutating = false } = {}) {
|
|
68
|
+
let response;
|
|
69
|
+
try {
|
|
70
|
+
response = await this.fetchImpl(url, { ...options, signal: AbortSignal.timeout(this.timeoutMs) });
|
|
71
|
+
} catch {
|
|
72
|
+
throw new FeishuError(mutating ? 'EFFECT_UNKNOWN' : 'REQUEST_FAILED',
|
|
73
|
+
mutating ? 'Request outcome is unknown; inspect the chat before retrying.' : 'The Feishu request failed.',
|
|
74
|
+
{ operation });
|
|
75
|
+
}
|
|
76
|
+
if (!response.ok) {
|
|
77
|
+
throw new FeishuError(mutating ? 'EFFECT_UNKNOWN' : 'REQUEST_FAILED',
|
|
78
|
+
mutating ? 'Request outcome is unknown; inspect the chat before retrying.' : 'The Feishu request was rejected.',
|
|
79
|
+
{ operation, httpStatus: response.status });
|
|
80
|
+
}
|
|
81
|
+
return response;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async authenticate() {
|
|
85
|
+
if (this.user) return this.user;
|
|
86
|
+
this.proto ||= await protobuf.load(protoFile);
|
|
87
|
+
const csrf = await this.request(this.endpoints.csrf, {
|
|
88
|
+
method: 'POST', headers: { ...this.jsonHeaders(), 'x-request-id': randomUUID() },
|
|
89
|
+
}, { operation: 'authenticate' });
|
|
90
|
+
this.absorbCookies(csrf.headers);
|
|
91
|
+
const response = await this.request(`${this.endpoints.user}?app_id=12&_t=${Date.now()}`, {
|
|
92
|
+
headers: {
|
|
93
|
+
...this.jsonHeaders(),
|
|
94
|
+
'x-csrf-token': this.jar.get('swp_csrf_token') || '',
|
|
95
|
+
'x-request-id': randomUUID(),
|
|
96
|
+
},
|
|
97
|
+
}, { operation: 'authenticate' });
|
|
98
|
+
let body;
|
|
99
|
+
try { body = await response.json(); } catch { /* classified below */ }
|
|
100
|
+
const user = body?.data?.user;
|
|
101
|
+
if (!user?.id) throw new FeishuError('AUTH_FAILED', 'The user Cookie is invalid or expired.');
|
|
102
|
+
this.user = { id: String(user.id), name: user.name || null };
|
|
103
|
+
return this.user;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
encode(name, data) {
|
|
107
|
+
const type = this.proto.lookupType(name);
|
|
108
|
+
const message = type.fromObject(data);
|
|
109
|
+
const error = type.verify(message);
|
|
110
|
+
if (error) throw new FeishuError('PROTOCOL_INPUT_INVALID', `Invalid ${name} payload.`);
|
|
111
|
+
return type.encode(message).finish();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
decode(name, bytes) {
|
|
115
|
+
return this.proto.lookupType(name).decode(bytes);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async uploadRequest(path, body, contentType) {
|
|
119
|
+
const response = await this.request(this.endpoints.file + path, {
|
|
120
|
+
method: 'POST', redirect: 'manual', headers: { ...this.baseHeaders(), 'content-type': contentType }, body,
|
|
121
|
+
}, { operation: 'upload-file', mutating: true });
|
|
122
|
+
try { return new Uint8Array(await response.arrayBuffer()); }
|
|
123
|
+
catch { throw new FeishuError('UPLOAD_FAILED', 'File upload response was unreadable.'); }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async botApi(action, body, { mutating = false, operation } = {}) {
|
|
127
|
+
if (!['SetBotAddConf', 'UpdateAppBotInfo', 'fetch_bot_conf_resource'].includes(action)) {
|
|
128
|
+
throw new FeishuError('INVALID_ARGUMENT', 'Unsupported bot operation.');
|
|
129
|
+
}
|
|
130
|
+
await this.authenticate();
|
|
131
|
+
const requestId = randomUUID();
|
|
132
|
+
const response = await this.request(`${this.endpoints.botApi}${action}`, {
|
|
133
|
+
method: 'POST', redirect: 'manual',
|
|
134
|
+
headers: {
|
|
135
|
+
...this.baseHeaders(), 'content-type': 'text/plain;charset=UTF-8',
|
|
136
|
+
'x-csrf-token': this.jar.get('swp_csrf_token') || '', 'x-request-id': requestId,
|
|
137
|
+
},
|
|
138
|
+
body: JSON.stringify({ ...body, i18n: 'zh-CN' }),
|
|
139
|
+
}, { mutating, operation });
|
|
140
|
+
let data;
|
|
141
|
+
try { data = await response.json(); } catch { /* classified below */ }
|
|
142
|
+
if (!data || typeof data.code !== 'number') {
|
|
143
|
+
throw new FeishuError(mutating ? 'EFFECT_UNKNOWN' : 'INVALID_RESPONSE',
|
|
144
|
+
mutating ? 'The response was unreadable; inspect the group before retrying.' : 'The bot response was unreadable.',
|
|
145
|
+
{ operation, requestId });
|
|
146
|
+
}
|
|
147
|
+
if (data.code !== 0) {
|
|
148
|
+
throw new FeishuError('BOT_API_REJECTED', 'Feishu rejected the bot operation.',
|
|
149
|
+
{ operation, status: data.code, requestId });
|
|
150
|
+
}
|
|
151
|
+
return { data, requestId };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async call(command, requestType, body, { version = '2.7.0', mutating = false, operation } = {}) {
|
|
155
|
+
await this.authenticate();
|
|
156
|
+
const requestId = randomUUID();
|
|
157
|
+
const packet = this.encode('Packet', {
|
|
158
|
+
payloadType: 1, cmd: command, cid: requestId,
|
|
159
|
+
payload: this.encode(requestType, body),
|
|
160
|
+
});
|
|
161
|
+
const response = await this.request(this.endpoints.gateway, {
|
|
162
|
+
method: 'POST',
|
|
163
|
+
headers: {
|
|
164
|
+
...this.baseHeaders(), accept: '*/*', 'content-type': 'application/x-protobuf',
|
|
165
|
+
locale: 'zh_CN', 'x-appid': '161471', 'x-command': String(command),
|
|
166
|
+
'x-command-version': version, 'x-lgw-os-type': '1', 'x-lgw-terminal-type': '2',
|
|
167
|
+
'x-request-id': requestId, 'x-source': 'web', 'x-web-version': '3.9.32',
|
|
168
|
+
},
|
|
169
|
+
body: packet,
|
|
170
|
+
}, { mutating, operation });
|
|
171
|
+
let decoded;
|
|
172
|
+
try { decoded = this.decode('Packet', new Uint8Array(await response.arrayBuffer())); }
|
|
173
|
+
catch {
|
|
174
|
+
throw new FeishuError(mutating ? 'EFFECT_UNKNOWN' : 'INVALID_RESPONSE',
|
|
175
|
+
mutating ? 'The response was unreadable; inspect the chat before retrying.' : 'The gateway response was unreadable.',
|
|
176
|
+
{ operation, requestId });
|
|
177
|
+
}
|
|
178
|
+
if (Object.hasOwn(decoded, 'status') && decoded.status != null && decoded.status !== 0) {
|
|
179
|
+
throw new FeishuError('GATEWAY_REJECTED', 'The gateway rejected the request.',
|
|
180
|
+
{ operation, status: decoded.status, requestId });
|
|
181
|
+
}
|
|
182
|
+
return { packet: decoded, requestId };
|
|
183
|
+
}
|
|
184
|
+
}
|
package/src/minutes.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { FeishuError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
const BASE = 'https://meetings.feishu.cn/minutes/api/';
|
|
4
|
+
|
|
5
|
+
export function minuteToken(value) {
|
|
6
|
+
let token = value;
|
|
7
|
+
if (typeof value === 'string' && /^https?:\/\//i.test(value)) {
|
|
8
|
+
let url;
|
|
9
|
+
try { url = new URL(value); } catch { /* handled below */ }
|
|
10
|
+
const parts = url?.pathname.split('/').filter(Boolean) || [];
|
|
11
|
+
token = parts[0] === 'minutes' ? parts[1] : '';
|
|
12
|
+
}
|
|
13
|
+
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{10,128}$/.test(token)) {
|
|
14
|
+
throw new FeishuError('INVALID_ARGUMENT', 'Use a recording minutes token or URL.');
|
|
15
|
+
}
|
|
16
|
+
return token;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function clock(value) {
|
|
20
|
+
const n = Number(value);
|
|
21
|
+
if (!Number.isFinite(n) || n < 0) return null;
|
|
22
|
+
const seconds = Math.floor(n / 1000);
|
|
23
|
+
const h = Math.floor(seconds / 3600), m = Math.floor(seconds / 60) % 60, s = seconds % 60;
|
|
24
|
+
return (h ? `${String(h).padStart(2, '0')}:` : '') + `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class Minutes {
|
|
28
|
+
constructor(gateway) { this.gateway = gateway; }
|
|
29
|
+
|
|
30
|
+
async get(path, params = {}) {
|
|
31
|
+
const url = new URL(path, BASE);
|
|
32
|
+
for (const [key, value] of Object.entries(params)) if (value != null) url.searchParams.set(key, String(value));
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await this.gateway.fetchImpl(url, { headers: this.gateway.baseHeaders(), redirect: 'manual', signal: AbortSignal.timeout(this.gateway.timeoutMs) });
|
|
36
|
+
} catch { throw new FeishuError('REQUEST_FAILED', 'Could not reach Feishu minutes.'); }
|
|
37
|
+
if (response.status >= 300 && response.status < 400 || response.status === 401) throw new FeishuError('AUTH_FAILED', 'The Cookie is invalid or expired for Feishu minutes.');
|
|
38
|
+
if (response.status === 403) throw new FeishuError('MINUTES_ACCESS_DENIED', 'The current user cannot access this recording.');
|
|
39
|
+
if (!response.ok) throw new FeishuError('MINUTES_REQUEST_FAILED', 'Feishu rejected the minutes request.', { httpStatus: response.status });
|
|
40
|
+
let payload;
|
|
41
|
+
try { payload = await response.json(); } catch { throw new FeishuError('AUTH_FAILED', 'Feishu minutes returned an invalid response; check the Cookie.'); }
|
|
42
|
+
if (payload?.code !== 0) throw new FeishuError('MINUTES_REQUEST_FAILED', 'Feishu could not return the recording data.', { upstreamCode: payload?.code });
|
|
43
|
+
return payload.data;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async list({ limit = 20, cursor } = {}) {
|
|
47
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new FeishuError('INVALID_ARGUMENT', 'Limit must be between 1 and 100.');
|
|
48
|
+
if (cursor != null && !/^\d{1,20}$/.test(cursor)) throw new FeishuError('INVALID_ARGUMENT', 'Invalid minutes cursor.');
|
|
49
|
+
const page = await this.get('space/list', { size: limit, space_name: '', timestamp: cursor });
|
|
50
|
+
if (!Array.isArray(page?.list)) throw new FeishuError('MINUTES_RESPONSE_INVALID', 'The minutes list response was incomplete.');
|
|
51
|
+
const nextCursor = page.has_more ? String(page.list.at(-1)?.share_time ?? '') : null;
|
|
52
|
+
if (page.has_more && (!/^\d{1,20}$/.test(nextCursor) || nextCursor === cursor)) throw new FeishuError('MINUTES_RESPONSE_INVALID', 'The minutes list did not provide a usable next cursor.');
|
|
53
|
+
return { items: page.list, hasMore: !!page.has_more, nextCursor };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async accessInfo(value) {
|
|
57
|
+
const result = await this.get('permission/apply/info', { object_token: minuteToken(value), language: 'zh_cn' });
|
|
58
|
+
if (typeof result?.allow_apply !== 'boolean') throw new FeishuError('MINUTES_RESPONSE_INVALID', 'The permission information was incomplete.');
|
|
59
|
+
return { ownerId: result.owner_user_id || null, ownerName: result.owner_name || null, allowApply: result.allow_apply, notAllowedTips: result.not_allowed_tips || null };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async requestAccess(value, { reason = '' } = {}) {
|
|
63
|
+
const token = minuteToken(value);
|
|
64
|
+
if (typeof reason !== 'string' || [...reason].length > 600) throw new FeishuError('INVALID_ARGUMENT', 'The request reason must be at most 600 characters.');
|
|
65
|
+
const info = await this.accessInfo(token);
|
|
66
|
+
if (!info.allowApply) throw new FeishuError('MINUTES_APPLY_NOT_ALLOWED', 'The owner does not allow access requests for this recording.', { ownerName: info.ownerName, notAllowedTips: info.notAllowedTips });
|
|
67
|
+
|
|
68
|
+
// The minutes page sets the CSRF cookie used by the web client's write requests.
|
|
69
|
+
const pageUrl = `https://meetings.feishu.cn/minutes/${token}`;
|
|
70
|
+
let page;
|
|
71
|
+
try {
|
|
72
|
+
page = await this.gateway.fetchImpl(pageUrl, { headers: this.gateway.baseHeaders(), redirect: 'manual', signal: AbortSignal.timeout(this.gateway.timeoutMs) });
|
|
73
|
+
} catch { throw new FeishuError('REQUEST_FAILED', 'Could not prepare the Feishu minutes session; no request was sent.'); }
|
|
74
|
+
if (![200, 301, 302, 303, 307, 308].includes(page.status)) throw new FeishuError('REQUEST_FAILED', 'Could not prepare the Feishu minutes session; no request was sent.', { httpStatus: page.status });
|
|
75
|
+
this.gateway.absorbCookies(page.headers);
|
|
76
|
+
const csrf = this.gateway.jar.get('bv_csrf_token');
|
|
77
|
+
if (!csrf) throw new FeishuError('MINUTES_CSRF_UNAVAILABLE', 'Feishu did not provide a CSRF token; no request was sent.');
|
|
78
|
+
|
|
79
|
+
let response;
|
|
80
|
+
try {
|
|
81
|
+
response = await this.gateway.fetchImpl(new URL('permission/apply/action', BASE), {
|
|
82
|
+
method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(this.gateway.timeoutMs),
|
|
83
|
+
headers: { ...this.gateway.baseHeaders(), origin: 'https://meetings.feishu.cn', referer: pageUrl,
|
|
84
|
+
'content-type': 'application/x-www-form-urlencoded', 'bv-csrf-token': csrf, platform: 'web' },
|
|
85
|
+
body: new URLSearchParams({ remark: reason, object_token: token, language: 'zh_cn' }),
|
|
86
|
+
});
|
|
87
|
+
} catch { throw new FeishuError('EFFECT_UNKNOWN', 'The access request may have been submitted; check with the owner before retrying.'); }
|
|
88
|
+
if (response.status >= 500 || response.status === 408 || response.status === 429 || response.status >= 300 && response.status < 400) {
|
|
89
|
+
throw new FeishuError('EFFECT_UNKNOWN', 'The access request may have been submitted; check with the owner before retrying.', { httpStatus: response.status });
|
|
90
|
+
}
|
|
91
|
+
if (!response.ok) throw new FeishuError('MINUTES_APPLY_REJECTED', 'Feishu rejected the access request.', { httpStatus: response.status });
|
|
92
|
+
let payload;
|
|
93
|
+
try { payload = await response.json(); } catch { throw new FeishuError('EFFECT_UNKNOWN', 'The access request may have been submitted; check with the owner before retrying.'); }
|
|
94
|
+
if (typeof payload?.code !== 'number') throw new FeishuError('EFFECT_UNKNOWN', 'The access request may have been submitted; check with the owner before retrying.');
|
|
95
|
+
if (payload.code !== 0) throw new FeishuError('MINUTES_APPLY_REJECTED', 'Feishu rejected the access request.', { upstreamCode: payload.code });
|
|
96
|
+
return { status: 'submitted', ownerName: info.ownerName, message: 'Request submitted; access still requires the owner to approve it.' };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async transcript(value) {
|
|
100
|
+
const token = minuteToken(value), query = { object_token: token, language: 'zh_cn' };
|
|
101
|
+
const ids = await this.get('subtitles/paragraph-ids', { page_size: 10000, page_num: 0, ...query });
|
|
102
|
+
if (!Array.isArray(ids?.list) || !Number.isInteger(Number(ids.total)) || Number(ids.total) < 0) throw new FeishuError('MINUTES_RESPONSE_INVALID', 'The transcript index response was incomplete.');
|
|
103
|
+
const total = Number(ids.total);
|
|
104
|
+
if (!total) throw new FeishuError('TRANSCRIPT_UNAVAILABLE', 'This recording has no available transcript.');
|
|
105
|
+
if (ids.has_more || ids.list.length < total || total > 10000 || !ids.list[0]?.pid) throw new FeishuError('TRANSCRIPT_INCOMPLETE', 'The transcript index is incomplete; no export was written.');
|
|
106
|
+
const [subtitles, speakers] = await Promise.all([
|
|
107
|
+
this.get('subtitles_v2', { paragraph_id: ids.list[0].pid, size: total, translate_lang: 'default', is_fluent: false, filter_speaker: true, ...query }),
|
|
108
|
+
this.get('speakers', { size: 10000, translate_lang: 'default', ...query }),
|
|
109
|
+
]);
|
|
110
|
+
if (!Array.isArray(subtitles?.paragraphs) || subtitles.has_more || subtitles.paragraphs.length !== total) throw new FeishuError('TRANSCRIPT_INCOMPLETE', 'Feishu returned an incomplete transcript; no export was written.');
|
|
111
|
+
if (!speakers?.paragraph_to_speaker || !speakers?.speaker_info_map) throw new FeishuError('MINUTES_RESPONSE_INVALID', 'Speaker information was incomplete; no export was written.');
|
|
112
|
+
const entries = subtitles.paragraphs.map((p, index) => {
|
|
113
|
+
if (!Array.isArray(p.sentences)) throw new FeishuError('TRANSCRIPT_INCOMPLETE', 'A transcript paragraph was incomplete; no export was written.');
|
|
114
|
+
if (p.pid !== ids.list[index]?.pid || p.sentences.some(s => !Array.isArray(s.contents))) throw new FeishuError('TRANSCRIPT_INCOMPLETE', 'A transcript paragraph was missing or out of order; no export was written.');
|
|
115
|
+
const first = p.sentences[0];
|
|
116
|
+
const speakerId = speakers.paragraph_to_speaker[first?.sid];
|
|
117
|
+
return { speaker: speakers.speaker_info_map[speakerId]?.user_name || null, timestamp: clock(first?.start_time ?? p.start_time), text: p.sentences.map(s => (s.contents || []).map(c => c.content || '').join('')).join('').trim() };
|
|
118
|
+
});
|
|
119
|
+
return { token, entries, total };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function formatTranscript(entries, { speakers = true, timestamps = true, format = 'txt' } = {}) {
|
|
124
|
+
if (!['txt', 'markdown'].includes(format)) throw new FeishuError('INVALID_ARGUMENT', 'Format must be txt or markdown.');
|
|
125
|
+
return entries.filter(e => e.text).map(e => {
|
|
126
|
+
const header = [timestamps && e.timestamp ? `[${e.timestamp}]` : '', speakers ? (e.speaker || '未知发言人') : ''].filter(Boolean).join(' ');
|
|
127
|
+
return header ? `${format === 'markdown' ? `**${header}**` : header}\n${e.text}` : e.text;
|
|
128
|
+
}).join('\n\n') + '\n';
|
|
129
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { FeishuError, requireNumericId, requireText } from './errors.js';
|
|
2
|
+
import { LarkMateClient } from './client.js';
|
|
3
|
+
|
|
4
|
+
const VERSION = '5.7.0';
|
|
5
|
+
const own = (value, field) => value != null && Object.hasOwn(value, field);
|
|
6
|
+
const str = value => value == null ? null : String(value);
|
|
7
|
+
function numeric(value, label) {
|
|
8
|
+
requireNumericId(value, label);
|
|
9
|
+
if (BigInt(value) < 1n || BigInt(value) > 9223372036854775807n) throw new FeishuError('INVALID_ARGUMENT', `${label} is outside the supported range.`);
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class SessionControls {
|
|
14
|
+
constructor(gateway) { this.gateway = gateway; }
|
|
15
|
+
|
|
16
|
+
async read(cmd, req, body, response) {
|
|
17
|
+
const result = await this.gateway.call(cmd, req, body, { version: VERSION, operation: req });
|
|
18
|
+
if (!own(result.packet, 'payload') || !result.packet.payload) throw new FeishuError('INVALID_RESPONSE', `${req} returned no readable page.`);
|
|
19
|
+
try { return this.gateway.decode(response, result.packet.payload); }
|
|
20
|
+
catch { throw new FeishuError('INVALID_RESPONSE', `${req} returned an unreadable page.`); }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async write(cmd, req, body) {
|
|
24
|
+
return this.gateway.call(cmd, req, body, { version: VERSION, mutating: true, operation: req });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async verified(write, verify) {
|
|
28
|
+
const result = await write();
|
|
29
|
+
try {
|
|
30
|
+
return { status: await verify() ? 'verified' : 'submitted_unconfirmed', requestId: result.requestId };
|
|
31
|
+
} catch (error) {
|
|
32
|
+
return { status: 'submitted_unconfirmed', requestId: result.requestId, verificationError: error.code || 'READBACK_FAILED' };
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async describe(items) {
|
|
37
|
+
const types = { 1: 'p2p', 2: 'group', 3: 'topic_group' };
|
|
38
|
+
const result = [];
|
|
39
|
+
for (let i = 0; i < items.length; i += 20) {
|
|
40
|
+
const batch = items.slice(i, i + 20);
|
|
41
|
+
let chats = {};
|
|
42
|
+
try { chats = (await this.read(64, 'PullChatsByIdsRequest', { chatIds: batch.map(x => x.id) }, 'PullChatsByIdsResponse')).chats; }
|
|
43
|
+
catch { /* The list remains useful when chat metadata is unavailable. */ }
|
|
44
|
+
result.push(...batch.map(item => ({ ...item, name: chats[item.id]?.name || null,
|
|
45
|
+
chatType: types[chats[item.id]?.type] || 'unknown' })));
|
|
46
|
+
}
|
|
47
|
+
const missing = result.filter(x => x.chatType === 'p2p' && !x.name);
|
|
48
|
+
if (missing.length) {
|
|
49
|
+
try {
|
|
50
|
+
const self = await this.gateway.authenticate();
|
|
51
|
+
const client = new LarkMateClient(this.gateway);
|
|
52
|
+
for (const item of missing) {
|
|
53
|
+
try {
|
|
54
|
+
const members = (await client.members({ chatId: item.id, limit: 20 })).items;
|
|
55
|
+
const other = members.find(member => member.id !== self.id && member.name);
|
|
56
|
+
item.name = other?.name || (members.length === 1 && members[0].id === self.id ? self.name : null) || null;
|
|
57
|
+
} catch { /* Metadata is optional; the conversation ID remains available. */ }
|
|
58
|
+
}
|
|
59
|
+
} catch { /* Leave unknown names empty. */ }
|
|
60
|
+
}
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async pinned({ details = true } = {}) {
|
|
65
|
+
const items = [], seen = new Set(); let position = 0;
|
|
66
|
+
for (let i = 0; i < 100; i++) {
|
|
67
|
+
const p = await this.read(1103, 'PullShortcutsRequest', { position, count: 50 }, 'PullShortcutsResponse');
|
|
68
|
+
items.push(...p.shortcuts.map(x => ({ id: x.id, type: x.type, position: x.position })));
|
|
69
|
+
if (!p.hasMore) { const chats = items.filter(x => x.type === 1); return { items: details ? await this.describe(chats) : chats }; }
|
|
70
|
+
const next = Math.max(position, ...p.shortcuts.map(x => x.position));
|
|
71
|
+
if (next <= position || seen.has(next)) break;
|
|
72
|
+
seen.add(next); position = next;
|
|
73
|
+
}
|
|
74
|
+
throw new FeishuError('PAGINATION_INCOMPLETE', 'Unable to read the entire pinned list.');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async pin(chatId, enabled) {
|
|
78
|
+
numeric(chatId, 'chat ID'); const before = (await this.pinned({ details: false })).items; const item = before.find(x => x.id === chatId);
|
|
79
|
+
if (!!item === enabled) return { status: 'already_set', chatId, pinned: enabled };
|
|
80
|
+
const position = enabled ? Math.max(0, ...before.map(x => x.position)) + 1 : item.position;
|
|
81
|
+
if (position > 2147483647) throw new FeishuError('INVALID_RESPONSE', 'The pinned list position is invalid.');
|
|
82
|
+
const result = await this.verified(
|
|
83
|
+
() => this.write(enabled ? 1100 : 1101, enabled ? 'PutShortcutsRequest' : 'DeleteShortcutsRequest', { shortcuts: [{ id: chatId, type: 1, position }] }),
|
|
84
|
+
async () => (await this.pinned({ details: false })).items.some(x => x.id === chatId) === enabled,
|
|
85
|
+
);
|
|
86
|
+
return { ...result, chatId, pinned: enabled };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async marked({ details = true } = {}) {
|
|
90
|
+
const items = [], seen = new Set(); let cursor = '';
|
|
91
|
+
for (let i = 0; i < 100; i++) {
|
|
92
|
+
const p = await this.read(1028, 'PullFlagsRequest', { cursor, count: 50 }, 'PullFlagsResponse');
|
|
93
|
+
items.push(...p.items.filter(x => x.flagType === 1 && x.itemType === 1).map(x => ({ id: str(x.itemId), type: 'chat' })));
|
|
94
|
+
if (!p.hasMore) return { items: details ? await this.describe(items) : items };
|
|
95
|
+
if (!p.nextCursor || seen.has(p.nextCursor)) break;
|
|
96
|
+
seen.add(p.nextCursor); cursor = p.nextCursor;
|
|
97
|
+
}
|
|
98
|
+
throw new FeishuError('PAGINATION_INCOMPLETE', 'Unable to read the entire marked list.');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async mark(chatId, enabled) {
|
|
102
|
+
numeric(chatId, 'chat ID'); const before = (await this.marked({ details: false })).items.some(x => x.id === chatId);
|
|
103
|
+
if (before === enabled) return { status: 'already_set', chatId, marked: enabled };
|
|
104
|
+
const body = { [enabled ? 'items' : 'deletedItems']: [{ itemId: chatId, itemType: 1, flagType: 1 }] };
|
|
105
|
+
const result = await this.verified(() => this.write(1027, 'UpdateFlagsRequest', body),
|
|
106
|
+
async () => (await this.marked({ details: false })).items.some(x => x.id === chatId) === enabled);
|
|
107
|
+
return { ...result, chatId, marked: enabled };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async labels() {
|
|
111
|
+
const items = [], seen = new Set(); let cursor = '';
|
|
112
|
+
for (let i = 0; i < 100; i++) {
|
|
113
|
+
const p = await this.read(1020, 'PullFeedGroupsRequest', { cursor, count: 20, isRebuilding: false, version: 1 }, 'PullFeedGroupsResponse');
|
|
114
|
+
if (p.needRebuilding) throw new FeishuError('LABELS_REBUILDING', 'Labels are being rebuilt; retry the read later.');
|
|
115
|
+
items.push(...p.feedGroups.map(x => ({ id: str(x.id), name: x.name, type: x.type, isDefault: x.isDefault })));
|
|
116
|
+
if (!p.hasMore) return { items };
|
|
117
|
+
if (!p.nextCursor || seen.has(p.nextCursor)) break;
|
|
118
|
+
seen.add(p.nextCursor); cursor = p.nextCursor;
|
|
119
|
+
}
|
|
120
|
+
throw new FeishuError('PAGINATION_INCOMPLETE', 'Unable to read all labels.');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async label(labelId) {
|
|
124
|
+
numeric(labelId, 'label ID'); const label = (await this.labels()).items.find(x => x.id === labelId);
|
|
125
|
+
if (!label) throw new FeishuError('NOT_FOUND', 'The label was not found.');
|
|
126
|
+
return label;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async labelChats(labelId, { details = true } = {}) {
|
|
130
|
+
numeric(labelId, 'label ID'); const items = [], seen = new Set(); let cursor = '';
|
|
131
|
+
for (let i = 0; i < 100; i++) {
|
|
132
|
+
const p = await this.read(1022, 'PullFeedGroupItemsRequest', { args: [{ key: labelId, value: { cursor, count: 20, isRebuilding: false } }] }, 'PullFeedGroupItemsResponse');
|
|
133
|
+
const page = p.data.find(x => str(x.key) === labelId)?.value;
|
|
134
|
+
if (!page) throw new FeishuError('INVALID_RESPONSE', 'The requested label page was absent.');
|
|
135
|
+
if (page.needRebuilding) throw new FeishuError('LABELS_REBUILDING', 'Label members are being rebuilt; retry the read later.');
|
|
136
|
+
items.push(...page.items.filter(x => x.feedCardType === 1 && !x.exclude).map(x => ({ id: str(x.feedCardId), type: 'chat' })));
|
|
137
|
+
if (!page.hasMore) return { labelId, items: details ? await this.describe(items) : items };
|
|
138
|
+
if (!page.nextCursor || seen.has(page.nextCursor)) break;
|
|
139
|
+
seen.add(page.nextCursor); cursor = page.nextCursor;
|
|
140
|
+
}
|
|
141
|
+
throw new FeishuError('PAGINATION_INCOMPLETE', 'Unable to read all label members.');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async createLabel(name) {
|
|
145
|
+
requireText(name, 'label name');
|
|
146
|
+
const result = await this.write(1018, 'CreateFeedGroupRequest', { feedGroup: { type: 1, name } });
|
|
147
|
+
let labelId = null;
|
|
148
|
+
try { labelId = str(this.gateway.decode('CreateFeedGroupResponse', result.packet.payload).feedGroup?.id); } catch { /* preserve unknown result */ }
|
|
149
|
+
if (!labelId || labelId === '0') return { status: 'submitted_unconfirmed', requestId: result.requestId };
|
|
150
|
+
try {
|
|
151
|
+
const label = (await this.labels()).items.find(x => x.id === labelId && x.name === name);
|
|
152
|
+
return { status: label ? 'verified' : 'submitted_unconfirmed', labelId, requestId: result.requestId };
|
|
153
|
+
} catch (error) { return { status: 'submitted_unconfirmed', labelId, requestId: result.requestId, verificationError: error.code || 'READBACK_FAILED' }; }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async renameLabel(labelId, name) {
|
|
157
|
+
requireText(name, 'label name'); const before = await this.label(labelId);
|
|
158
|
+
if (before.name === name) return { status: 'already_set', labelId, name };
|
|
159
|
+
const result = await this.verified(() => this.write(1023, 'UpdateFeedGroupsRequest', {
|
|
160
|
+
feedGroups: [{ id: labelId, type: before.type, name }], feedGroupsUpdateFields: [{ key: labelId, value: { fields: [1] } }],
|
|
161
|
+
}), async () => (await this.labels()).items.some(x => x.id === labelId && x.name === name));
|
|
162
|
+
return { ...result, labelId, name };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async deleteLabel(labelId) {
|
|
166
|
+
const label = await this.label(labelId);
|
|
167
|
+
const result = await this.verified(() => this.write(1023, 'UpdateFeedGroupsRequest', { deletedGroups: [{ id: labelId, type: label.type, name: label.name }] }),
|
|
168
|
+
async () => !(await this.labels()).items.some(x => x.id === labelId));
|
|
169
|
+
return { ...result, labelId };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async labelChat(labelId, chatId, enabled) {
|
|
173
|
+
numeric(chatId, 'chat ID'); const label = await this.label(labelId);
|
|
174
|
+
if (label.type !== 1) throw new FeishuError('UNSUPPORTED_LABEL_TYPE', 'Only manually managed labels are supported.');
|
|
175
|
+
const before = (await this.labelChats(labelId, { details: false })).items.some(x => x.id === chatId);
|
|
176
|
+
if (before === enabled) return { status: 'already_set', labelId, chatId, included: enabled };
|
|
177
|
+
const key = enabled ? 'feedGroupItems' : 'deletedFeedGroupItems';
|
|
178
|
+
const result = await this.verified(() => this.write(1023, 'UpdateFeedGroupsRequest', { [key]: [{ feedCardId: chatId, feedCardType: 1, groupId: labelId }] }),
|
|
179
|
+
async () => (await this.labelChats(labelId, { details: false })).items.some(x => x.id === chatId) === enabled);
|
|
180
|
+
return { ...result, labelId, chatId, included: enabled };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async card(chatId) {
|
|
184
|
+
numeric(chatId, 'chat ID'); const p = await this.read(1009, 'PullFeedCardsByIdsRequest', { feedCardIdentities: [{ id: chatId, type: 1 }] }, 'PullFeedCardsByIdsResponse');
|
|
185
|
+
const card = p.cards[chatId]; if (!card) throw new FeishuError('NOT_FOUND', 'The conversation card was not found.');
|
|
186
|
+
return card;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async chat(chatId) {
|
|
190
|
+
numeric(chatId, 'chat ID'); const p = await this.read(64, 'PullChatsByIdsRequest', { chatIds: [chatId] }, 'PullChatsByIdsResponse');
|
|
191
|
+
const chat = p.chats[chatId]; if (!chat) throw new FeishuError('NOT_FOUND', 'The conversation was not found.');
|
|
192
|
+
return chat;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async muted(chatId) {
|
|
196
|
+
numeric(chatId, 'chat ID'); const p = await this.read(62, 'PullChatSettingsRequest', { chatIds: [chatId] }, 'PullChatSettingsResponse');
|
|
197
|
+
const x = p.chatSettings[chatId]; if (!own(x, 'isRemind')) throw new FeishuError('STATE_UNAVAILABLE', 'Notification settings were not returned.');
|
|
198
|
+
return !x.isRemind;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async setMute(chatId, enabled) {
|
|
202
|
+
const before = await this.muted(chatId);
|
|
203
|
+
if (before === enabled) return { status: 'already_set', chatId, muted: enabled };
|
|
204
|
+
const result = await this.verified(() => this.write(60, 'PatchChatSettingRequest', {
|
|
205
|
+
chatId, chatSetting: { isRemind: !enabled }, updateChatSettingField: [1],
|
|
206
|
+
}), async () => await this.muted(chatId) === enabled);
|
|
207
|
+
return { ...result, chatId, muted: enabled };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async setUnread(chatId) {
|
|
211
|
+
const card = await this.card(chatId);
|
|
212
|
+
if (card.feedCardField?.markAsUnread?.unread === true) return { status: 'already_set', chatId, manualUnread: true };
|
|
213
|
+
const result = await this.verified(() => this.write(1045, 'PatchFeedCardUnreadRequest', { card: { id: chatId, type: 1 }, markAsUnread: true }),
|
|
214
|
+
async () => (await this.card(chatId)).feedCardField?.markAsUnread?.unread === true);
|
|
215
|
+
return { ...result, chatId, manualUnread: true };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async setRead(chatId) {
|
|
219
|
+
const [chat, card] = await Promise.all([this.chat(chatId), this.card(chatId)]);
|
|
220
|
+
const maxPosition = own(chat, 'lastVisibleMessagePosition') ? chat.lastVisibleMessagePosition : chat.lastMessagePosition;
|
|
221
|
+
if (!Number.isInteger(maxPosition) || maxPosition < 0) throw new FeishuError('POSITION_UNAVAILABLE', 'The latest message position was not returned.');
|
|
222
|
+
const marked = card.feedCardField?.markAsUnread?.unread === true;
|
|
223
|
+
if (own(chat, 'readPosition') && chat.readPosition >= maxPosition && !marked) return { status: 'already_set', chatId, readThrough: maxPosition };
|
|
224
|
+
const result = await this.write(40, 'PutReadMessagesRequest', { chatId, maxPosition });
|
|
225
|
+
if (marked) {
|
|
226
|
+
try { await this.write(1045, 'PatchFeedCardUnreadRequest', { card: { id: chatId, type: 1 }, markAsUnread: false }); }
|
|
227
|
+
catch (error) { throw new FeishuError('PARTIAL_EFFECT', 'Read position was submitted but the manual unread marker could not be cleared.', { chatId, requestId: result.requestId, causeCode: error.code || 'UNKNOWN' }); }
|
|
228
|
+
}
|
|
229
|
+
try {
|
|
230
|
+
const [after, feed] = await Promise.all([this.chat(chatId), this.card(chatId)]);
|
|
231
|
+
const verified = own(after, 'readPosition') && after.readPosition >= maxPosition && feed.feedCardField?.markAsUnread?.unread !== true;
|
|
232
|
+
return { status: verified ? 'verified' : 'submitted_unconfirmed', chatId, readThrough: maxPosition, requestId: result.requestId };
|
|
233
|
+
} catch (error) { return { status: 'submitted_unconfirmed', chatId, readThrough: maxPosition, requestId: result.requestId, verificationError: error.code || 'READBACK_FAILED' }; }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async setDone(chatId, enabled) {
|
|
237
|
+
const card = await this.card(chatId); const target = enabled ? 2 : 1;
|
|
238
|
+
if (card.feedType === target) return { status: 'already_set', chatId, done: enabled };
|
|
239
|
+
const result = await this.verified(() => this.write(1001, 'PatchFeedCardsRequest', { type: target, ids: [chatId] }),
|
|
240
|
+
async () => (await this.card(chatId)).feedType === target);
|
|
241
|
+
return { ...result, chatId, done: enabled };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async setBox(chatId, enabled) {
|
|
245
|
+
const card = await this.card(chatId);
|
|
246
|
+
if (!own(card, 'parentCardId')) throw new FeishuError('STATE_UNAVAILABLE', 'The conversation box state was not returned.');
|
|
247
|
+
const boxed = String(card.parentCardId) !== '0';
|
|
248
|
+
if (boxed === enabled) return { status: 'already_set', chatId, boxed: enabled };
|
|
249
|
+
const result = await this.verified(() => this.write(enabled ? 1006 : 1007, 'BoxCardsRequest', { feedCards: { [chatId]: 1 } }),
|
|
250
|
+
async () => { const after = await this.card(chatId); return own(after, 'parentCardId') && (String(after.parentCardId) !== '0') === enabled; });
|
|
251
|
+
return { ...result, chatId, boxed: enabled };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async state(chatId) {
|
|
255
|
+
const [card, chat, muted, pinned, marked] = await Promise.all([this.card(chatId), this.chat(chatId), this.muted(chatId), this.pinned({ details: false }), this.marked({ details: false })]);
|
|
256
|
+
const manualUnread = card.feedCardField ? (card.feedCardField.markAsUnread?.unread ?? false) : null;
|
|
257
|
+
const unreadCount = own(chat, 'newMessageCount') ? chat.newMessageCount : null;
|
|
258
|
+
const unread = unreadCount > 0 || manualUnread === true ? true : unreadCount === 0 && manualUnread === false ? false : null;
|
|
259
|
+
return { chatId, pinned: pinned.items.some(x => x.id === chatId), marked: marked.items.some(x => x.id === chatId), muted,
|
|
260
|
+
manualUnread, unread, unreadCount,
|
|
261
|
+
readPosition: own(chat, 'readPosition') ? chat.readPosition : null,
|
|
262
|
+
lastPosition: own(chat, 'lastMessagePosition') ? chat.lastMessagePosition : null,
|
|
263
|
+
feedType: own(card, 'feedType') ? card.feedType : null,
|
|
264
|
+
boxId: own(card, 'parentCardId') ? str(card.parentCardId) : null };
|
|
265
|
+
}
|
|
266
|
+
}
|
package/src/upload.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises';
|
|
2
|
+
import { basename } from 'node:path';
|
|
3
|
+
import { FeishuError } from './errors.js';
|
|
4
|
+
|
|
5
|
+
const CHUNK = 4 * 1024 * 1024;
|
|
6
|
+
const MAX_BYTES = 100 * 1024 * 1024;
|
|
7
|
+
const table = Uint32Array.from({ length: 256 }, (_, n) => {
|
|
8
|
+
for (let i = 0; i < 8; i++) n = (n >>> 1) ^ ((n & 1) ? 0xedb88320 : 0);
|
|
9
|
+
return n >>> 0;
|
|
10
|
+
});
|
|
11
|
+
export function crc32(bytes) {
|
|
12
|
+
let crc = 0xffffffff;
|
|
13
|
+
for (const b of bytes) crc = table[(crc ^ b) & 255] ^ (crc >>> 8);
|
|
14
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function uploadFile(gateway, path) {
|
|
18
|
+
let handle;
|
|
19
|
+
try { handle = await open(path, 'r'); }
|
|
20
|
+
catch { throw new FeishuError('FILE_UNAVAILABLE', 'Cannot open the file.'); }
|
|
21
|
+
try {
|
|
22
|
+
const stat = await handle.stat();
|
|
23
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > MAX_BYTES) {
|
|
24
|
+
throw new FeishuError('FILE_INVALID', 'Use a regular, non-empty file up to 100 MiB.');
|
|
25
|
+
}
|
|
26
|
+
const name = basename(path);
|
|
27
|
+
await gateway.authenticate();
|
|
28
|
+
const created = gateway.decode('CreateFileUploadResponse', await gateway.uploadRequest('/upload/create',
|
|
29
|
+
gateway.encode('CreateFileUploadRequest', { fileType: 1, fileName: name, fileSize: stat.size }), 'application/x-protobuf'));
|
|
30
|
+
const key = created.uploadId;
|
|
31
|
+
if (typeof key !== 'string' || !/^[\w.-]{1,200}$/.test(key)) {
|
|
32
|
+
throw new FeishuError('UPLOAD_FAILED', 'File upload could not be initialized.');
|
|
33
|
+
}
|
|
34
|
+
const checksums = {};
|
|
35
|
+
let offset = 0;
|
|
36
|
+
let partId = 0;
|
|
37
|
+
while (offset < stat.size) {
|
|
38
|
+
const buffer = Buffer.allocUnsafe(Math.min(CHUNK, stat.size - offset));
|
|
39
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
|
|
40
|
+
if (bytesRead !== buffer.length) throw new FeishuError('FILE_CHANGED', 'File changed during upload.');
|
|
41
|
+
partId++;
|
|
42
|
+
const expected = crc32(buffer);
|
|
43
|
+
const part = gateway.decode('UploadFilePartResponse', await gateway.uploadRequest(
|
|
44
|
+
`/upload/part?upload_id=${encodeURIComponent(key)}&part_id=${partId}`, buffer, 'application/octet-stream'));
|
|
45
|
+
if (!Object.hasOwn(part, 'partId') || !Object.hasOwn(part, 'crc32') || part.partId !== partId || part.crc32 !== expected) {
|
|
46
|
+
throw new FeishuError('UPLOAD_FAILED', 'File part checksum did not match.');
|
|
47
|
+
}
|
|
48
|
+
checksums[partId] = expected;
|
|
49
|
+
offset += bytesRead;
|
|
50
|
+
}
|
|
51
|
+
const finalStat = await handle.stat();
|
|
52
|
+
if (finalStat.size !== stat.size || finalStat.mtimeMs !== stat.mtimeMs) {
|
|
53
|
+
throw new FeishuError('FILE_CHANGED', 'File changed during upload.');
|
|
54
|
+
}
|
|
55
|
+
const completed = gateway.decode('CompleteFileUploadResponse', await gateway.uploadRequest('/upload/complete',
|
|
56
|
+
gateway.encode('CompleteFileUploadRequest', { uploadId: key, fileType: 1, partToCrc32: checksums, fileName: name }),
|
|
57
|
+
'application/x-protobuf'));
|
|
58
|
+
if (completed.code !== 0) throw new FeishuError('UPLOAD_FAILED', 'File upload completion was rejected.');
|
|
59
|
+
return { key, name, size: stat.size };
|
|
60
|
+
} finally { await handle.close(); }
|
|
61
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
The initial `proto/lark.proto` is adapted from `feishu-user-plugin` 1.4.1,
|
|
2
|
+
Copyright (c) 2026 EthanQC, distributed under the MIT license reproduced in
|
|
3
|
+
`feishu-user-plugin-LICENSE`. Its public repository is
|
|
4
|
+
https://github.com/EthanQC/feishu-user-plugin.
|
|
5
|
+
|
|
6
|
+
The protocol messages are a deliberately small subset of the web gateway.
|