larkmate 0.1.25 → 0.1.27
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 +4 -1
- package/bin/larkmate.js +39 -5
- package/docs/agent-broker.md +2 -0
- package/docs/os-delegation.md +2 -0
- package/package.json +1 -1
- package/proto/lark.proto +62 -1
- package/skills/larkmate/references/chats.md +3 -1
- package/skills/larkmate/references/listen.md +1 -1
- package/skills/larkmate/references/writes.md +21 -1
- package/src/agent-broker.js +15 -6
- package/src/agent-files.js +51 -6
- package/src/client.js +48 -9
- package/src/export-stickers.js +30 -0
- package/src/os-delegate-client.js +11 -2
- package/src/os-delegate.js +16 -12
- package/src/rich-text.js +13 -2
- package/src/stickers.js +80 -0
package/README.md
CHANGED
|
@@ -61,13 +61,16 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
61
61
|
- [x] 按会话、发送者和时间范围分页导出消息到本地文件
|
|
62
62
|
- [x] 读取文本、链接、提及及部分图片和文件元数据
|
|
63
63
|
- [ ] 完整解析富文本中的图片、表情包和互动卡片
|
|
64
|
-
- [x]
|
|
64
|
+
- [x] 发送文本、链接、飞书表情和带标题的消息,引用回复、@ 用户或所有人
|
|
65
65
|
- [x] 发送文件
|
|
66
66
|
- [x] 全局搜索消息(分页)
|
|
67
67
|
- [x] 编辑文本消息或撤回消息
|
|
68
68
|
- [x] 转发或收藏消息
|
|
69
69
|
- [x] 发送图片消息、下载图片或附件
|
|
70
70
|
- [x] 给消息添加和取消表情回应
|
|
71
|
+
- [x] 查询、发送、添加和移除收藏的单个表情
|
|
72
|
+
- [x] 下载单个表情或批量导出原文件
|
|
73
|
+
- [ ] 调整收藏表情的顺序
|
|
71
74
|
- [x] 获取消息链接
|
|
72
75
|
- [x] 全局或按会话监听新消息,支持名称、正则、组合过滤和规则触发脚本
|
|
73
76
|
- [x] 按 API key 限定消息服务的订阅范围
|
package/bin/larkmate.js
CHANGED
|
@@ -10,6 +10,7 @@ import { resolve, join } from 'node:path';
|
|
|
10
10
|
import { homedir } from 'node:os';
|
|
11
11
|
import { FeishuError } from '../src/errors.js';
|
|
12
12
|
import { exportMessages } from '../src/export-messages.js';
|
|
13
|
+
import { exportStickers } from '../src/export-stickers.js';
|
|
13
14
|
import { apiCommands, brokerCall, brokerCommands, brokerProxy, createBrokerToken, loadBrokerToken, loadPolicy, startBroker } from '../src/agent-broker.js';
|
|
14
15
|
import { callOsDelegate, osDelegateProxy } from '../src/os-delegate-client.js';
|
|
15
16
|
import { SidebarFilters } from '../src/sidebar-filters.js';
|
|
@@ -48,13 +49,20 @@ function configuredDelegate() {
|
|
|
48
49
|
if (owner && (configuredBroker() || configuredBrokerToken() || program.opts().credentialsFile)) throw new FeishuError('DELEGATE_CONFIG_INVALID', 'Do not combine OS delegation with broker or credentials options.');
|
|
49
50
|
return owner ? { owner, launcher } : null;
|
|
50
51
|
}
|
|
51
|
-
function proxy(service) {
|
|
52
|
+
function proxy(service, command) {
|
|
52
53
|
const delegate = configuredDelegate();
|
|
53
|
-
if (delegate) return osDelegateProxy(delegate.owner, delegate.launcher, service, () => activeCommand);
|
|
54
|
+
if (delegate) return osDelegateProxy(delegate.owner, delegate.launcher, service, () => command || activeCommand);
|
|
54
55
|
const path = configuredBroker();
|
|
55
56
|
if (!path && configuredBrokerToken()) throw new FeishuError('BROKER_CONFIGURATION_INVALID', 'A broker token file was configured without a broker socket.');
|
|
56
57
|
if (path && program.opts().credentialsFile) throw new FeishuError('INVALID_ARGUMENT', 'A broker client cannot select a credentials file.');
|
|
57
|
-
return path ? brokerProxy(path, service, () => activeCommand, configuredBrokerToken()) : null;
|
|
58
|
+
return path ? brokerProxy(path, service, () => command || activeCommand, configuredBrokerToken()) : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function stickerExportClient() {
|
|
62
|
+
const list = proxy('client', 'stickers-list');
|
|
63
|
+
if (!list) return client();
|
|
64
|
+
const downloads = proxy('client', 'sticker-download');
|
|
65
|
+
return { stickerList: () => list.stickerList(), downloadSticker: options => downloads.downloadSticker(options) };
|
|
58
66
|
}
|
|
59
67
|
|
|
60
68
|
async function controls() {
|
|
@@ -456,6 +464,7 @@ program.command('send').description('Send text once as the user; delivery remain
|
|
|
456
464
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
457
465
|
.requiredOption('--text <text>', 'message text')
|
|
458
466
|
.option('--mention <id:name>', 'mention a numeric user or bot ID, or all for everyone; repeatable', collect, [])
|
|
467
|
+
.option('--emoji <key>', 'turn each :key: marker into a Feishu emoji; repeatable', collect, [])
|
|
459
468
|
.option('--reply-to <id>', 'reply to a numeric message ID')
|
|
460
469
|
.option('--reply-root <id>', 'root ID when replying to an existing reply')
|
|
461
470
|
.action(async options => {
|
|
@@ -464,10 +473,35 @@ program.command('send').description('Send text once as the user; delivery remain
|
|
|
464
473
|
if (colon < 1) throw new FeishuError('INVALID_ARGUMENT', 'A mention must use id:name.');
|
|
465
474
|
return { id: value.slice(0, colon), name: value.slice(colon + 1) };
|
|
466
475
|
});
|
|
467
|
-
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, replyTo: options.replyTo, replyRoot: options.replyRoot }));
|
|
476
|
+
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, emojis: options.emoji, replyTo: options.replyTo, replyRoot: options.replyRoot }));
|
|
468
477
|
});
|
|
469
478
|
|
|
470
|
-
program.command('
|
|
479
|
+
program.command('emoji-list').description('List available Feishu emoji names and keys.')
|
|
480
|
+
.option('--query <text>', 'filter by emoji name or key')
|
|
481
|
+
.action(async options => output(await (await client()).emojiList({ query: options.query })));
|
|
482
|
+
|
|
483
|
+
program.command('stickers-list').description('List the current account’s saved individual stickers.')
|
|
484
|
+
.action(async () => output(await (await client()).stickerList()));
|
|
485
|
+
program.command('sticker-send').description('Send a saved sticker to a chat.')
|
|
486
|
+
.requiredOption('--chat <id>', 'numeric chat ID').requiredOption('--id <id>', 'saved sticker ID or key')
|
|
487
|
+
.action(async options => output(await (await client()).sendSticker({ chatId: options.chat, stickerId: options.id })));
|
|
488
|
+
program.command('sticker-add').description('Save an existing sticker key to the account collection.')
|
|
489
|
+
.requiredOption('--key <key>', 'sticker resource key')
|
|
490
|
+
.action(async options => output(await (await client()).addSticker({ key: options.key })));
|
|
491
|
+
program.command('sticker-add-file').description('Upload an image as a saved individual sticker.')
|
|
492
|
+
.requiredOption('--file <path>', 'local PNG, JPEG, GIF or WebP file')
|
|
493
|
+
.action(async options => output(await (await client()).addStickerFile({ path: options.file })));
|
|
494
|
+
program.command('sticker-remove').description('Remove a saved individual sticker.')
|
|
495
|
+
.requiredOption('--id <id>', 'saved sticker ID or key')
|
|
496
|
+
.action(async options => output(await (await client()).removeSticker({ stickerId: options.id })));
|
|
497
|
+
program.command('sticker-download').description('Download a saved sticker in its original format.')
|
|
498
|
+
.requiredOption('--id <id>', 'saved sticker ID or key').requiredOption('--output <path>', 'new output file')
|
|
499
|
+
.action(async options => output(await (await client()).downloadSticker({ stickerId: options.id, output: options.output })));
|
|
500
|
+
program.command('stickers-export').description('Download saved stickers and a manifest to a new directory.')
|
|
501
|
+
.requiredOption('--output <dir>', 'new output directory').option('--limit <number>', 'maximum number to export')
|
|
502
|
+
.action(async options => output(await exportStickers(await stickerExportClient(), { output: options.output, ...(options.limit != null ? { limit: Number(options.limit) } : {}) })));
|
|
503
|
+
|
|
504
|
+
program.command('send-rich').description('Send structured text, links, mentions and emoji from JSON.')
|
|
471
505
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
472
506
|
.requiredOption('--json <path>', 'JSON file or - for standard input')
|
|
473
507
|
.option('--reply-to <id>', 'reply to a numeric message ID')
|
package/docs/agent-broker.md
CHANGED
|
@@ -55,6 +55,8 @@ LarkMate 可以由持有 Cookie 的账户启动本地代理,再让 Agent 使
|
|
|
55
55
|
|
|
56
56
|
`send-file`、`send-image` 与 `download-file` 均可单独加入 `allow` 列表,并受 `chatIds` 约束。发送时,由 Agent 进程读取本地文件并传输内容;下载时,由 Agent 进程创建输出文件。代理不接受 Agent 指定的代理端本地路径,而是在私有临时目录中处理中转文件,并在正常结束或失败时将其删除。若进程异常终止,可能会遗留临时文件,因此部署方应保护并按需清理代理账户的临时目录。
|
|
57
57
|
|
|
58
|
+
收藏表情属于账号级资源:`stickers-list`、`sticker-add`、`sticker-add-file`、`sticker-remove` 和 `sticker-download` 均需在 `allow` 中分别授权并开启 `allowGlobal`。`sticker-send` 另按 `chatIds` 限制目标会话。批量导出使用 `stickers-list` 和 `sticker-download`;上传和下载由调用方读写自己的文件,代理校验下载的表情属于当前账号的收藏,并应用 `maxFileBytes`。
|
|
59
|
+
|
|
58
60
|
如需限制 Agent 可访问的本地目录,部署方应通过配置 Agent 的系统账户或容器权限来实现。策略文件中的会话与大小限制不会约束 Agent 自身的文件系统,也无法阻止其向代理发送已读取的数据。请仅向 Agent 挂载或开放其业务所需的目录,禁止其读取 Cookie 及其他敏感文件。
|
|
59
61
|
|
|
60
62
|
在受限代理模式下执行下载时,须提供 `history` 返回的消息 `position`、消息 ID 与资源键。代理会重新读取该会话的对应位置,仅在三者完全匹配时才执行下载;若无法核对,则会拒绝请求。普通直连模式不要求提供 `--position`。
|
package/docs/os-delegation.md
CHANGED
|
@@ -20,6 +20,8 @@
|
|
|
20
20
|
|
|
21
21
|
文件、图片发送及附件下载可分别授权;上传文件由 Agent 进程读取,下载文件由 Agent 进程写入。执行器不接受 Agent 提供的所有者本地路径。下载时须提供 `history` 返回的 `--position`,执行器会核验会话、消息和资源键。单个文件受 `maxFileBytes` 限制;执行器在所有者私有临时目录中处理中转数据,正常结束或失败时删除,异常退出可能留下临时文件。部署方应保护、按需清理临时目录,并根据实际需要配置系统资源限制。
|
|
22
22
|
|
|
23
|
+
收藏表情的上传和下载也使用调用方的文件;对应账号级命令须单独授权并开启 `allowGlobal`。执行器会核验下载目标属于当前账号的收藏,批量导出需要分别授权列表和下载命令。
|
|
24
|
+
|
|
23
25
|
## 启动器与 sudoers 示例
|
|
24
26
|
|
|
25
27
|
将 LarkMate 包及依赖安装在 Agent 无法修改的受保护位置,将以下启动器放在同样受保护的位置。示例路径均须替换为实际绝对路径;Node.js 可执行文件和其依赖也不能由 Agent 修改。固定工作目录并清空环境,避免调用者通过环境变量或当前目录影响执行器。
|
package/package.json
CHANGED
package/proto/lark.proto
CHANGED
|
@@ -199,6 +199,7 @@ message RichTextElement {
|
|
|
199
199
|
FIGURE = 4;
|
|
200
200
|
AT = 5;
|
|
201
201
|
A = 6;
|
|
202
|
+
EMOTION = 10;
|
|
202
203
|
}
|
|
203
204
|
}
|
|
204
205
|
|
|
@@ -213,6 +214,65 @@ message AtProperty {
|
|
|
213
214
|
optional string content = 2;
|
|
214
215
|
}
|
|
215
216
|
|
|
217
|
+
message EmotionProperty {
|
|
218
|
+
optional string key = 1;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
message PullEmojiResourcesV2Request {
|
|
222
|
+
map<string, int32> emojiSetId2version = 1;
|
|
223
|
+
optional bool needUserTenantResources = 2;
|
|
224
|
+
optional int32 accessType = 3;
|
|
225
|
+
}
|
|
226
|
+
message EmojiI18nText {
|
|
227
|
+
optional string defaultText = 1;
|
|
228
|
+
map<string, string> i18nTexts = 2;
|
|
229
|
+
}
|
|
230
|
+
message EmojiResource {
|
|
231
|
+
optional string key = 1;
|
|
232
|
+
optional EmojiI18nText i18nText = 2;
|
|
233
|
+
optional bool isDeleted = 4;
|
|
234
|
+
repeated string skinKeys = 5;
|
|
235
|
+
optional string emojiSetId = 7;
|
|
236
|
+
}
|
|
237
|
+
message EmojiResourceSet {
|
|
238
|
+
optional string setId = 1;
|
|
239
|
+
optional int32 setSource = 2;
|
|
240
|
+
repeated EmojiResource emojiResources = 3;
|
|
241
|
+
optional int32 version = 4;
|
|
242
|
+
}
|
|
243
|
+
message PullEmojiResourcesV2Response { repeated EmojiResourceSet emojiResourceSet = 1; }
|
|
244
|
+
|
|
245
|
+
message StickerSummary {
|
|
246
|
+
optional string title = 1;
|
|
247
|
+
optional string description = 2;
|
|
248
|
+
map<string, string> i18nTitles = 3;
|
|
249
|
+
map<string, string> i18nDescriptions = 4;
|
|
250
|
+
}
|
|
251
|
+
message StickerRecord {
|
|
252
|
+
optional string key = 1;
|
|
253
|
+
optional int32 position = 2;
|
|
254
|
+
optional string fsUnit = 3;
|
|
255
|
+
optional ImageSet image = 4;
|
|
256
|
+
optional StickerSummary summary = 5;
|
|
257
|
+
optional int32 mode = 6;
|
|
258
|
+
optional bool hasPaid = 7;
|
|
259
|
+
optional string stickerSetId = 8;
|
|
260
|
+
optional string stickerId = 9;
|
|
261
|
+
}
|
|
262
|
+
message PullStickersRequest { optional int32 position = 1; optional int32 count = 2; }
|
|
263
|
+
message PullStickersResponse { repeated StickerRecord stickers = 1; optional int64 updateTime = 2; }
|
|
264
|
+
message PutStickersRequest { repeated StickerRecord stickers = 1; optional int32 addType = 2; repeated string imageKeys = 3; }
|
|
265
|
+
message StickerDuplicate { optional int32 duplicateType = 1; optional string duplicateKey = 2; }
|
|
266
|
+
message PutStickersResponse { repeated StickerRecord stickers = 1; repeated StickerDuplicate dupStickers = 2; }
|
|
267
|
+
message DeleteStickersRequest { repeated StickerRecord stickers = 1; }
|
|
268
|
+
message DeleteStickersResponse { repeated StickerRecord stickers = 1; }
|
|
269
|
+
message PatchStickersRequest { repeated StickerRecord stickers = 1; }
|
|
270
|
+
message PatchStickersResponse { repeated StickerRecord stickers = 1; }
|
|
271
|
+
message StickerContent {
|
|
272
|
+
optional string key = 4; optional int32 width = 5; optional int32 height = 6;
|
|
273
|
+
optional string fsUnit = 8; optional string stickerSetId = 9; optional string stickerId = 10;
|
|
274
|
+
}
|
|
275
|
+
|
|
216
276
|
// For A (hyperlink) elements.
|
|
217
277
|
message AnchorProperty {
|
|
218
278
|
optional string href = 1;
|
|
@@ -596,7 +656,8 @@ message ImageContent {
|
|
|
596
656
|
optional ImageSet image = 1;
|
|
597
657
|
optional ImageSetV2 imageV2 = 2;
|
|
598
658
|
}
|
|
599
|
-
message
|
|
659
|
+
message ImageDetail { optional string key = 1; optional int32 width = 3; optional int32 height = 4; optional int32 size = 10; optional string fsUnit = 11; }
|
|
660
|
+
message ImageSet { optional string key = 1; optional ImageDetail origin = 2; optional ImageDetail thumbnail = 3; optional string imageKey = 4; optional ImageDetail middle = 5; optional ImageDetail thumbnailWebp = 6; }
|
|
600
661
|
message ImageSetV2 { optional string imageKey = 1; }
|
|
601
662
|
|
|
602
663
|
// Personal message-list controls (web gateway).
|
|
@@ -22,7 +22,9 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
|
|
|
22
22
|
|
|
23
23
|
`chats` 默认读取收件箱的一页,不是全部历史会话。`--type`、`--state` 只过滤当前页,`--scope done` 查询已完成分组;`boxes` 用 `--parent` 单独读取,`nextCursor` 用于翻页。`history` 每页最多 100 个位置,`--pages` 最多 100 页;`--query`、`--sender`、`--after`、`--before` 只过滤已扫描的位置,不是全量搜索。`omittedPositions` 是没有返回的位置数,不是消息数;部分消息类型可能没有可解析正文。
|
|
24
24
|
|
|
25
|
-
历史消息的 `segments`
|
|
25
|
+
历史消息的 `segments` 保留文本、提及、链接和飞书表情代码,`title` 是带标题消息的标题;`textIncomplete` 表示正文未能完整解析,汇总中的 `incompleteText` 是此类消息数。飞书原生表情在纯文本中以 `:代码:` 表示。
|
|
26
|
+
|
|
27
|
+
单个表情消息的 `resource` 包含表情 ID 和资源键,可用于识别或收藏该表情。
|
|
26
28
|
|
|
27
29
|
`search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
|
|
28
30
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
服务订阅支持会话及发送人的 ID、名称和正则,以及消息类型、正文包含/排除、正文正则和排除本人。相同维度的 ID、名称和正则是“或”,不同维度是“且”。大量条件或 `anyOf`、`allOf`、`not` 组合通过 `POST /events` JSON 传入;规则模式支持同样的条件。正则使用 RE2 语法,不支持部分 JavaScript 正则特性。名称解析失败且结果无法确定时会发出 `name_unavailable` 缺口,不猜测匹配;同名对象都会匹配,需要精确区分时使用 ID。
|
|
6
6
|
|
|
7
|
-
消息事件的 `segments`
|
|
7
|
+
消息事件的 `segments` 包含解析出的文本、提及、链接和飞书表情代码;文本过滤也检查带标题消息的标题。`textIncomplete` 表示未能完整解析,无法安全判断的文本规则会产生缺口事件。
|
|
8
8
|
|
|
9
9
|
通过 `listen-service --policy <绝对路径>` 为每个 API key 限定会话、发送人和类型;订阅过滤条件只能缩小授权范围。未配置策略时依靠 socket 文件权限控制访问。授权配置及订阅示例见 [API 服务与授权](https://github.com/NWYLZW/larkmate/blob/main/docs/api-service.md)。限制范围内的 `gap` 会传递;无法定位会话的全局缺口只包含通用原因。
|
|
10
10
|
|
|
@@ -7,6 +7,8 @@ larkmate send --chat "$CHAT_ID" --text '消息内容'
|
|
|
7
7
|
larkmate send --chat "$CHAT_ID" --text '回复内容' --reply-to "$MESSAGE_ID"
|
|
8
8
|
larkmate send --chat "$CHAT_ID" --text '@名称 消息内容' --mention "$MEMBER_ID:名称"
|
|
9
9
|
larkmate send --chat "$CHAT_ID" --text '@所有人 消息内容' --mention 'all:所有人'
|
|
10
|
+
larkmate emoji-list --query '大笑'
|
|
11
|
+
larkmate send --chat "$CHAT_ID" --text '你好 :LAUGH:' --emoji LAUGH
|
|
10
12
|
larkmate send-rich --chat "$CHAT_ID" --json ./message.json
|
|
11
13
|
larkmate send-file --chat "$CHAT_ID" --file ./report.pdf
|
|
12
14
|
larkmate send-image --chat "$CHAT_ID" --file ./image.png
|
|
@@ -21,12 +23,30 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
|
|
|
21
23
|
|
|
22
24
|
同一用户只需提供一次 `--mention`,正文中所有匹配的提及都会生效。
|
|
23
25
|
|
|
24
|
-
`
|
|
26
|
+
使用 `emoji-list` 按名称或代码查询可用的飞书原生表情;`send` 的 `--emoji` 可重复指定,每个 `:代码:` 会转成正文表情。普通 Unicode 表情直接写入文本即可。受限代理和 API key 调用 `emoji-list` 时需要允许该命令和全局访问。
|
|
27
|
+
|
|
28
|
+
个人收藏的单个表情是独立的消息类型,可查询、发送、添加、移除或下载:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
larkmate stickers-list
|
|
32
|
+
larkmate sticker-send --chat "$CHAT_ID" --id "$STICKER_ID"
|
|
33
|
+
larkmate sticker-add --key "$STICKER_KEY"
|
|
34
|
+
larkmate sticker-add-file --file ./sticker.gif
|
|
35
|
+
larkmate sticker-remove --id "$STICKER_ID"
|
|
36
|
+
larkmate sticker-download --id "$STICKER_ID" --output ./sticker.gif
|
|
37
|
+
larkmate stickers-export --output ./my-stickers
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
列表中的 `previewUrl` 可用于识别表情;`history` 的表情消息提供资源键。批量导出要求输出目录不存在,保存原文件并生成带格式和结果的 `manifest.json`;`partial` 表示部分下载失败。受限代理或系统用户委托需要分别授权使用的命令,收藏的查询和管理需要 `allowGlobal`,发送还需要目标会话权限;下载和添加本地文件由调用方读写文件,并受 `maxFileBytes` 限制。批量导出需要同时授权 `stickers-list` 和 `sticker-download`。
|
|
41
|
+
|
|
42
|
+
`send-rich` 的 JSON 使用 `segments` 数组,支持文本、链接、用户提及和表情;可选 `title` 用于发送带标题的消息:
|
|
25
43
|
|
|
26
44
|
```json
|
|
27
45
|
{"title":"标题","segments":[{"type":"text","text":"请查看 "},{"type":"link","text":"参考链接","url":"https://example.com/"},{"type":"text","text":" "},{"type":"mention","text":"@名称","userId":"123"}]}
|
|
28
46
|
```
|
|
29
47
|
|
|
48
|
+
表情片段写作 `{"type":"emoji","key":"LAUGH"}`,代码可从 `emoji-list` 获取。
|
|
49
|
+
|
|
30
50
|
`userId` 使用飞书网页数字 ID;`all` 表示 @所有人,受群权限限制。代理、系统用户委托或 API key 需允许 `send-rich`;在现有策略中,带提及或引用的发送还需要全部会话授权。
|
|
31
51
|
|
|
32
52
|
文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
|
package/src/agent-broker.js
CHANGED
|
@@ -5,12 +5,14 @@ import { chmod, lstat, open, realpath, unlink, writeFile } from 'node:fs/promise
|
|
|
5
5
|
import { dirname, isAbsolute, join } from 'node:path';
|
|
6
6
|
import { FeishuError } from './errors.js';
|
|
7
7
|
import { minuteToken } from './minutes.js';
|
|
8
|
-
import { handleFileRequest, brokerUpload, brokerDownload } from './agent-files.js';
|
|
8
|
+
import { handleFileRequest, brokerUpload, brokerDownload, brokerStickerDownload } from './agent-files.js';
|
|
9
9
|
|
|
10
10
|
// The socket policy is enforced in this process, never by the calling agent.
|
|
11
11
|
// An explicit mapping prevents callers from reaching arbitrary object methods.
|
|
12
12
|
const routes = {
|
|
13
|
-
status: ['client', 'status', 'global'], search: ['client', 'search', 'global'],
|
|
13
|
+
status: ['client', 'status', 'global'], search: ['client', 'search', 'global'], 'emoji-list': ['client', 'emojiList', 'global'],
|
|
14
|
+
'stickers-list': ['client', 'stickerList', 'global'], 'sticker-add': ['client', 'addSticker', 'global'],
|
|
15
|
+
'sticker-remove': ['client', 'removeSticker', 'global'], 'sticker-send': ['client', 'sendSticker', 'chatObject'],
|
|
14
16
|
'calendars': ['calendar','calendars','global'], 'calendar-search': ['calendar','searchCalendars','global'],
|
|
15
17
|
'calendar-busy': ['calendar','busy','global'], 'calendar-suggest': ['calendar','suggest','global'],
|
|
16
18
|
'calendar-events': ['calendar','events','global'], 'event-get': ['calendar','event','global'], 'calendar-rooms': ['calendar','rooms','global'],
|
|
@@ -63,15 +65,16 @@ const routes = {
|
|
|
63
65
|
'send-file': ['files', 'upload', 'file'], 'send-image': ['files', 'upload', 'file'],
|
|
64
66
|
'group-avatar-set': ['files', 'upload', 'file'],
|
|
65
67
|
'download-file': ['files', 'download', 'file'],
|
|
68
|
+
'sticker-add-file': ['files', 'upload', 'globalFile'], 'sticker-download': ['files', 'downloadSticker', 'globalFile'],
|
|
66
69
|
};
|
|
67
|
-
const writes = new Set(['send', 'send-rich', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
|
|
70
|
+
const writes = new Set(['send', 'send-rich', 'sticker-add', 'sticker-add-file', 'sticker-remove', 'sticker-send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
|
|
68
71
|
'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
|
|
69
72
|
'group-update', 'group-dissolve', 'group-bot-protection', 'group-settings-set', 'group-admin-add', 'group-admin-remove', 'group-remove', 'group-leave', 'group-owner', 'group-post-set', 'group-link', 'group-request-approve', 'group-request-reject', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
|
|
70
73
|
'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image', 'sidebar-set', 'task-create', 'task-update', 'task-complete', 'task-reopen', 'task-delete', 'event-create', 'event-update', 'event-delete', 'event-share', 'event-reply', 'calendar-create', 'calendar-update', 'calendar-delete', 'calendar-subscribe', 'calendar-unsubscribe']);
|
|
71
74
|
|
|
72
75
|
export function brokerCommands() {
|
|
73
76
|
return Object.entries(routes).map(([command, [, , scope]]) => ({ command,
|
|
74
|
-
scope:
|
|
77
|
+
scope: ['global', 'globalFile'].includes(scope) ? 'global' : scope === 'allMinutes' ? 'global-and-all-minutes'
|
|
75
78
|
: ['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) ? 'global-and-all-chats'
|
|
76
79
|
: scope === 'minute' ? 'minute' : 'chat', mutating: writes.has(command) }));
|
|
77
80
|
}
|
|
@@ -142,6 +145,10 @@ export function authorize(policy, request) {
|
|
|
142
145
|
const args = request.args;
|
|
143
146
|
const chatAllowed = id => numeric(id) && (policy.allowAllChats || policy.chatIds.includes(id));
|
|
144
147
|
if (scope === 'global' && !policy.allowGlobal) denied();
|
|
148
|
+
if (scope === 'globalFile' && (!policy.allowGlobal || args.length !== 1 || !only(args[0], method === 'upload' ? [] : ['stickerId']) || (method === 'downloadSticker' && (typeof args[0].stickerId !== 'string' || !/^[\w.-]{1,200}$/.test(args[0].stickerId))))) denied();
|
|
149
|
+
if (request.command === 'stickers-list' && args.length !== 0) denied();
|
|
150
|
+
if (request.command === 'sticker-add' && (args.length !== 1 || !only(args[0], ['key']))) denied();
|
|
151
|
+
if (request.command === 'sticker-remove' && (args.length !== 1 || !only(args[0], ['stickerId']))) denied();
|
|
145
152
|
if (['calendar-subscribe', 'calendar-unsubscribe'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].subscribe !== (request.command === 'calendar-subscribe'))) denied();
|
|
146
153
|
if (['group-request-approve', 'group-request-reject'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].approve !== (request.command === 'group-request-approve'))) denied();
|
|
147
154
|
if (['group-admin-add', 'group-admin-remove'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].enabled !== (request.command === 'group-admin-add'))) denied();
|
|
@@ -159,7 +166,8 @@ export function authorize(policy, request) {
|
|
|
159
166
|
}
|
|
160
167
|
if (scope === 'chatObject' || scope === 'send') {
|
|
161
168
|
if (args.length !== 1 || !object(args[0]) || !chatAllowed(args[0].chatId)) denied();
|
|
162
|
-
const keys = scope === 'send' ? (method === 'sendRich' ? ['chatId', 'segments', 'title', 'replyTo', 'replyRoot'] : ['chatId', 'text', 'mentions', 'replyTo', 'replyRoot'])
|
|
169
|
+
const keys = scope === 'send' ? (method === 'sendRich' ? ['chatId', 'segments', 'title', 'replyTo', 'replyRoot'] : ['chatId', 'text', 'mentions', 'emojis', 'replyTo', 'replyRoot'])
|
|
170
|
+
: method === 'sendSticker' ? ['chatId', 'stickerId']
|
|
163
171
|
: method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
|
|
164
172
|
: method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
|
|
165
173
|
: method === 'updateGroup' ? ['chatId', 'name', 'description']
|
|
@@ -293,8 +301,9 @@ export async function brokerCall(socketPath, request, tokenFile) {
|
|
|
293
301
|
export function brokerProxy(socketPath, service, getCommand, tokenFile) {
|
|
294
302
|
return new Proxy({}, { get(_target, method) {
|
|
295
303
|
if (method === 'then' || typeof method !== 'string') return undefined;
|
|
296
|
-
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
|
|
304
|
+
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar', 'addStickerFile'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
|
|
297
305
|
if (service === 'client' && method === 'downloadFile') return options => brokerDownload(socketPath, tokenFile, options);
|
|
306
|
+
if (service === 'client' && method === 'downloadSticker') return options => brokerStickerDownload(socketPath, tokenFile, options);
|
|
298
307
|
return (...args) => brokerCall(socketPath, { command: getCommand(), service, method, args }, tokenFile);
|
|
299
308
|
} });
|
|
300
309
|
}
|
package/src/agent-files.js
CHANGED
|
@@ -24,12 +24,16 @@ export async function handleFileRequest({ req, res, policy, getServices, authori
|
|
|
24
24
|
let meta;
|
|
25
25
|
try { meta = JSON.parse(Buffer.from(req.headers['x-larkmate-file'], 'base64url').toString('utf8')); } catch { bad(); }
|
|
26
26
|
command = meta?.command;
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
const stickerUpload = command === 'sticker-add-file', stickerDownload = command === 'sticker-download';
|
|
28
|
+
const upload = ['send-file', 'send-image', 'group-avatar-set', 'sticker-add-file'].includes(command);
|
|
29
|
+
const keys = stickerUpload ? ['command', 'name', 'size'] : stickerDownload ? ['command', 'stickerId']
|
|
30
|
+
: upload ? ['command', 'chatId', 'name', 'size'] : ['command', 'chatId', 'messageId', 'key', 'position'];
|
|
31
|
+
if (!only(meta, keys) || (!upload && !stickerDownload && command !== 'download-file')) bad();
|
|
32
|
+
authorize(policy, { command, service: 'files', method: upload ? 'upload' : stickerDownload ? 'downloadSticker' : 'download',
|
|
33
|
+
args: [stickerUpload ? {} : stickerDownload ? { stickerId: meta.stickerId } : { chatId: meta.chatId }] });
|
|
34
|
+
if (!stickerUpload && !stickerDownload) requireInt64Id(meta.chatId, 'chat ID');
|
|
31
35
|
if (upload) {
|
|
32
|
-
if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (['send-image', 'group-avatar-set'].includes(command) && meta.size > 10 * 1024 * 1024)) bad();
|
|
36
|
+
if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (['send-image', 'group-avatar-set', 'sticker-add-file'].includes(command) && meta.size > 10 * 1024 * 1024)) bad();
|
|
33
37
|
dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
|
|
34
38
|
const path = join(dir, meta.name);
|
|
35
39
|
const file = await open(path, 'wx', 0o600);
|
|
@@ -45,8 +49,19 @@ export async function handleFileRequest({ req, res, policy, getServices, authori
|
|
|
45
49
|
const { client } = await getServices();
|
|
46
50
|
if (res.destroyed) return;
|
|
47
51
|
dispatched = true;
|
|
48
|
-
const data = await client[command === 'send-file' ? 'sendFile' : command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: meta.chatId, path });
|
|
52
|
+
const data = await client[command === 'send-file' ? 'sendFile' : command === 'send-image' ? 'sendImage' : stickerUpload ? 'addStickerFile' : 'setGroupAvatar'](stickerUpload ? { path } : { chatId: meta.chatId, path });
|
|
49
53
|
answer(200, { ok: true, data });
|
|
54
|
+
} else if (stickerDownload) {
|
|
55
|
+
const { client } = await getServices();
|
|
56
|
+
dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
|
|
57
|
+
const path = join(dir, 'download');
|
|
58
|
+
const result = await client.downloadSticker({ stickerId: meta.stickerId, output: path, maxBytes: policy.maxFileBytes });
|
|
59
|
+
const size = (await stat(path)).size;
|
|
60
|
+
if (size > policy.maxFileBytes || size !== result.bytes) throw new FeishuError('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
|
|
61
|
+
if (res.destroyed) return;
|
|
62
|
+
res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': String(size), 'cache-control': 'no-store', 'connection': 'close',
|
|
63
|
+
'x-larkmate-mime': result.mime, 'x-larkmate-extension': result.extension });
|
|
64
|
+
await pipeline(createReadStream(path), res);
|
|
50
65
|
} else {
|
|
51
66
|
requireInt64Id(meta.messageId, 'message ID');
|
|
52
67
|
if (typeof meta.key !== 'string' || !/^[\w.-]{1,200}$/.test(meta.key) || !Number.isInteger(meta.position) || meta.position < 1 || meta.position > 2147483647) bad();
|
|
@@ -142,3 +157,33 @@ export async function brokerDownload(socketPath, tokenFile, { chatId, messageId,
|
|
|
142
157
|
req.end();
|
|
143
158
|
});
|
|
144
159
|
}
|
|
160
|
+
|
|
161
|
+
export async function brokerStickerDownload(socketPath, tokenFile, { stickerId, output }) {
|
|
162
|
+
if (typeof stickerId !== 'string' || !/^[\w.-]{1,200}$/.test(stickerId)) throw new FeishuError('INVALID_ARGUMENT', 'A valid sticker ID is required.');
|
|
163
|
+
if (typeof output !== 'string' || !output.trim()) throw new FeishuError('INVALID_ARGUMENT', 'An output path is required.');
|
|
164
|
+
const token = await loadBrokerToken(tokenFile);
|
|
165
|
+
const req = fileRequest(socketPath, token, { command: 'sticker-download', stickerId });
|
|
166
|
+
return await new Promise((resolve, reject) => {
|
|
167
|
+
let done = false;
|
|
168
|
+
const finish = (error, data) => { if (done) return; done = true; error ? reject(error) : resolve(data); };
|
|
169
|
+
req.on('response', async res => {
|
|
170
|
+
if (res.statusCode !== 200) { try { return finish(await errorResponse(res)); } catch { return finish(new FeishuError('BROKER_INVALID_RESPONSE', 'Invalid broker response.')); } }
|
|
171
|
+
let file, bytes = 0;
|
|
172
|
+
try {
|
|
173
|
+
const length = Number(res.headers['content-length']);
|
|
174
|
+
if (!Number.isSafeInteger(length) || length < 0 || length > MAX) throw new Error('invalid length');
|
|
175
|
+
try { file = await open(output, 'wx', 0o600); }
|
|
176
|
+
catch (error) { res.destroy(); return finish(new FeishuError('DOWNLOAD_WRITE_FAILED', error.code === 'EEXIST' ? 'Output file already exists; choose a new path.' : 'Could not create the output file.')); }
|
|
177
|
+
for await (const chunk of res) { bytes += chunk.length; if (bytes > length) throw new Error('too large'); await file.writeFile(chunk); }
|
|
178
|
+
if (bytes !== length) throw new Error('incomplete');
|
|
179
|
+
const extension = ['png','jpg','gif','webp','bin'].includes(res.headers['x-larkmate-extension']) ? res.headers['x-larkmate-extension'] : 'bin';
|
|
180
|
+
const mime = ({png:'image/png',jpg:'image/jpeg',gif:'image/gif',webp:'image/webp',bin:'application/octet-stream'})[extension];
|
|
181
|
+
finish(null, { output, bytes, stickerId, mime, extension });
|
|
182
|
+
} catch { finish(new FeishuError('DOWNLOAD_INCOMPLETE', 'The download stopped; the output file is incomplete.', { output, bytes })); }
|
|
183
|
+
finally { await file?.close(); }
|
|
184
|
+
});
|
|
185
|
+
req.on('timeout', () => req.destroy());
|
|
186
|
+
req.on('error', () => finish(new FeishuError('BROKER_UNAVAILABLE', 'Cannot connect to the broker.')));
|
|
187
|
+
req.end();
|
|
188
|
+
});
|
|
189
|
+
}
|
package/src/client.js
CHANGED
|
@@ -4,7 +4,8 @@ import { shortId } from './gateway.js';
|
|
|
4
4
|
import { downloadFile } from './download.js';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
6
|
import { open } from 'node:fs/promises';
|
|
7
|
-
import { buildRichText, readRichText } from './rich-text.js';
|
|
7
|
+
import { buildRichText, readRichText, requireEmojiKey } from './rich-text.js';
|
|
8
|
+
import { Stickers } from './stickers.js';
|
|
8
9
|
|
|
9
10
|
function ids(values, label) {
|
|
10
11
|
if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
|
|
@@ -26,6 +27,33 @@ function decodedPayload(gateway, response, type, operation) {
|
|
|
26
27
|
export class LarkMateClient {
|
|
27
28
|
constructor(gateway) { this.gateway = gateway; }
|
|
28
29
|
|
|
30
|
+
async stickerList() { return new Stickers(this.gateway).list(); }
|
|
31
|
+
async sendSticker(options) { return new Stickers(this.gateway).send(options); }
|
|
32
|
+
async addSticker(options) { return new Stickers(this.gateway).add(options); }
|
|
33
|
+
async addStickerFile(options) { return new Stickers(this.gateway).addFile(options); }
|
|
34
|
+
async removeSticker(options) { return new Stickers(this.gateway).remove(options); }
|
|
35
|
+
async downloadSticker(options) { return new Stickers(this.gateway).download(options); }
|
|
36
|
+
|
|
37
|
+
async emojiList({ query } = {}) {
|
|
38
|
+
if (query != null && (typeof query !== 'string' || query.length > 200)) throw new FeishuError('INVALID_ARGUMENT', 'emoji query must be at most 200 characters.');
|
|
39
|
+
const response = await this.gateway.call(142, 'PullEmojiResourcesV2Request', { needUserTenantResources: true, accessType: 1 },
|
|
40
|
+
{ version: '8.5.0', operation: 'emoji-list' });
|
|
41
|
+
if (!response.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No emoji resources were returned.');
|
|
42
|
+
let data; try { data = this.gateway.decode('PullEmojiResourcesV2Response', response.packet.payload); }
|
|
43
|
+
catch { throw new FeishuError('INVALID_RESPONSE', 'The emoji resource list was unreadable.'); }
|
|
44
|
+
const needle = (query || '').trim().toLocaleLowerCase();
|
|
45
|
+
const items = [];
|
|
46
|
+
for (const set of data.emojiResourceSet || []) for (const emoji of set.emojiResources || []) {
|
|
47
|
+
if (!emoji.key || emoji.isDeleted) continue;
|
|
48
|
+
const names = emoji.i18nText?.i18nTexts || {};
|
|
49
|
+
const name = names['zh-CN'] || emoji.i18nText?.defaultText || emoji.key;
|
|
50
|
+
const englishName = names['en-US'] || emoji.i18nText?.defaultText || null;
|
|
51
|
+
if (needle && ![emoji.key, name, englishName, ...Object.values(names)].some(value => typeof value === 'string' && value.toLocaleLowerCase().includes(needle))) continue;
|
|
52
|
+
items.push({ key: emoji.key, name, englishName, source: ({ 1: 'default', 2: 'tenant', 3: 'other_tenant' })[set.setSource] || 'unknown', skinKeys: emoji.skinKeys || [] });
|
|
53
|
+
}
|
|
54
|
+
return { items };
|
|
55
|
+
}
|
|
56
|
+
|
|
29
57
|
async contactAlias({ userId }) {
|
|
30
58
|
requireInt64Id(userId, 'user ID');
|
|
31
59
|
const r = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId, useNewLayout: true }, { operation: 'contact-alias' });
|
|
@@ -318,6 +346,13 @@ export class LarkMateClient {
|
|
|
318
346
|
: { key: content.imageV2?.imageKey || content.image?.imageKey || content.image?.key || null };
|
|
319
347
|
} catch { /* Leave unknown resources unparsed. */ }
|
|
320
348
|
}
|
|
349
|
+
if (message.content?.length && message.type === 10) {
|
|
350
|
+
try {
|
|
351
|
+
const content = this.gateway.decode('StickerContent', message.content);
|
|
352
|
+
resource = { key: content.key || null, stickerId: content.stickerId || null, stickerSetId: content.stickerSetId || null,
|
|
353
|
+
width: content.width || null, height: content.height || null };
|
|
354
|
+
} catch { /* Leave unknown sticker resources unparsed. */ }
|
|
355
|
+
}
|
|
321
356
|
return { id: String(message.id || ''), position: Number(position), rootId: message.rootId || null, parentId: message.parentId || null,
|
|
322
357
|
senderId: message.fromId || '', type: message.type, title, text, segments, textIncomplete,
|
|
323
358
|
createTime: Object.hasOwn(message, 'createTime') ? String(message.createTime) : null, resource };
|
|
@@ -508,13 +543,14 @@ export class LarkMateClient {
|
|
|
508
543
|
return { items, hasMore: !!result.hasMore };
|
|
509
544
|
}
|
|
510
545
|
|
|
511
|
-
async send({ chatId, text, mentions = [], replyTo, replyRoot }) {
|
|
546
|
+
async send({ chatId, text, mentions = [], emojis = [], replyTo, replyRoot }) {
|
|
512
547
|
requireNumericId(chatId, 'chat ID');
|
|
513
548
|
requireText(text, 'text');
|
|
514
549
|
if (replyTo) requireNumericId(replyTo, 'reply message ID');
|
|
515
550
|
if (replyRoot) requireNumericId(replyRoot, 'reply root ID');
|
|
516
551
|
if (replyRoot && !replyTo) throw new FeishuError('INVALID_ARGUMENT', 'reply-root requires reply-to.');
|
|
517
552
|
if (!Array.isArray(mentions)) throw new FeishuError('INVALID_ARGUMENT', 'mentions must be a list.');
|
|
553
|
+
if (!Array.isArray(emojis)) throw new FeishuError('INVALID_ARGUMENT', 'emojis must be a list.');
|
|
518
554
|
await this.gateway.authenticate();
|
|
519
555
|
const elementIds = [];
|
|
520
556
|
const atIds = [];
|
|
@@ -523,9 +559,10 @@ export class LarkMateClient {
|
|
|
523
559
|
for (const mention of mentions) {
|
|
524
560
|
if (mention.id !== 'all') requireNumericId(mention.id, 'mention ID');
|
|
525
561
|
const marker = `@${requireText(mention.name, 'mention name')}`;
|
|
526
|
-
if (markers.has(marker) && markers.get(marker) !== mention.id) throw new FeishuError('INVALID_ARGUMENT', 'A mention name cannot identify multiple users.');
|
|
527
|
-
markers.set(marker, mention.id);
|
|
562
|
+
if (markers.has(marker) && markers.get(marker).userId !== mention.id) throw new FeishuError('INVALID_ARGUMENT', 'A mention name cannot identify multiple users.');
|
|
563
|
+
markers.set(marker, { type: 'mention', userId: mention.id });
|
|
528
564
|
}
|
|
565
|
+
for (const key of emojis) markers.set(`:${requireEmojiKey(key)}:`, { type: 'emoji', key });
|
|
529
566
|
const found = new Set();
|
|
530
567
|
const addText = part => {
|
|
531
568
|
if (!part) return;
|
|
@@ -536,20 +573,22 @@ export class LarkMateClient {
|
|
|
536
573
|
let position = 0;
|
|
537
574
|
while (position < text.length) {
|
|
538
575
|
let next = null;
|
|
539
|
-
for (const [marker,
|
|
576
|
+
for (const [marker, value] of markers) {
|
|
540
577
|
const index = text.indexOf(marker, position);
|
|
541
|
-
if (index >= 0 && (!next || index < next.index || index === next.index && marker.length > next.marker.length)) next = { marker,
|
|
578
|
+
if (index >= 0 && (!next || index < next.index || index === next.index && marker.length > next.marker.length)) next = { marker, value, index };
|
|
542
579
|
}
|
|
543
580
|
if (!next) break;
|
|
544
581
|
addText(text.slice(position, next.index));
|
|
545
582
|
const id = shortId();
|
|
546
583
|
elementIds.push(id);
|
|
547
|
-
|
|
548
|
-
|
|
584
|
+
if (next.value.type === 'mention') {
|
|
585
|
+
atIds.push(id);
|
|
586
|
+
dictionary[id] = { tag: 5, property: this.gateway.encode('AtProperty', { userId: next.value.userId, content: next.marker }) };
|
|
587
|
+
} else dictionary[id] = { tag: 10, property: this.gateway.encode('EmotionProperty', { key: next.value.key }) };
|
|
549
588
|
found.add(next.marker);
|
|
550
589
|
position = next.index + next.marker.length;
|
|
551
590
|
}
|
|
552
|
-
if (found.size !== markers.size) throw new FeishuError('INVALID_ARGUMENT', '
|
|
591
|
+
if (found.size !== markers.size) throw new FeishuError('INVALID_ARGUMENT', 'A mention or emoji marker is absent from the text.');
|
|
553
592
|
addText(text.slice(position));
|
|
554
593
|
const cid = shortId();
|
|
555
594
|
const response = await this.gateway.call(5, 'PutMessageRequest', {
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { mkdir, writeFile, link, unlink } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { FeishuError } from './errors.js';
|
|
4
|
+
|
|
5
|
+
// All file paths remain in the caller process, including for delegated clients.
|
|
6
|
+
export async function exportStickers(client, { output, limit } = {}) {
|
|
7
|
+
if (typeof output !== 'string' || !output.trim()) throw new FeishuError('INVALID_ARGUMENT', 'An output directory is required.');
|
|
8
|
+
if (limit != null && (!Number.isSafeInteger(limit) || limit < 1)) throw new FeishuError('INVALID_ARGUMENT', 'limit must be a positive integer.');
|
|
9
|
+
const collection=await client.stickerList();
|
|
10
|
+
const items=limit == null ? collection.items : collection.items.slice(0,limit);
|
|
11
|
+
try { await mkdir(output,{mode:0o700}); }
|
|
12
|
+
catch(error) { throw new FeishuError('EXPORT_WRITE_FAILED',error.code==='EEXIST'?'Output directory already exists; choose a new path.':'Could not create the output directory.'); }
|
|
13
|
+
const results=new Array(items.length); let next=0;
|
|
14
|
+
const worker=async()=>{while(next<items.length){const index=next++,item=items[index],id=item.id || item.key;
|
|
15
|
+
const name=String(index+1).padStart(4,'0')+'-'+(typeof id==='string'&&/^[\w.-]{1,200}$/.test(id)?id:'unknown');
|
|
16
|
+
const partial=join(output,`${name}.partial`);
|
|
17
|
+
try{const result=await client.downloadSticker({stickerId:id,output:partial});
|
|
18
|
+
const extension=['png','jpg','gif','webp','bin'].includes(result.extension)?result.extension:'bin';
|
|
19
|
+
const filename=`${name}.${extension}`;await link(partial,join(output,filename));await unlink(partial);
|
|
20
|
+
results[index]={...item,status:'saved',file:filename,bytes:result.bytes,mime:result.mime};
|
|
21
|
+
}catch(error){results[index]={...item,status:'failed',error:error.code||'DOWNLOAD_FAILED'};}
|
|
22
|
+
}};
|
|
23
|
+
try {
|
|
24
|
+
await Promise.all(Array.from({length:Math.min(3,items.length)},worker));
|
|
25
|
+
const failed=results.filter(x=>x.status==='failed').length;
|
|
26
|
+
const manifest={version:1,collectionSize:collection.items.length,requested:items.length,saved:items.length-failed,failed,updateTime:collection.updateTime,items:results};
|
|
27
|
+
await writeFile(join(output,'manifest.json'),JSON.stringify(manifest,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
28
|
+
return {status:failed?'partial':'exported',output,collectionSize:collection.items.length,requested:items.length,saved:items.length-failed,failed,manifest:join(output,'manifest.json')};
|
|
29
|
+
} catch(error) { throw new FeishuError('EXPORT_INCOMPLETE','Sticker export did not finish; inspect the output directory.',{output,cause:error.code||'WRITE_FAILED'}); }
|
|
30
|
+
}
|
|
@@ -63,6 +63,11 @@ export async function callOsDelegate({ owner, launcher, request, inputPath, outp
|
|
|
63
63
|
if (spawnError || !parsed) throw unavailable();
|
|
64
64
|
if (outputPath != null) {
|
|
65
65
|
if (bytes !== parsed.size) fail('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
|
|
66
|
+
if (request.command === 'sticker-download') {
|
|
67
|
+
const extension = ['png','jpg','gif','webp','bin'].includes(parsed.extension) ? parsed.extension : 'bin';
|
|
68
|
+
const mime = ({png:'image/png',jpg:'image/jpeg',gif:'image/gif',webp:'image/webp',bin:'application/octet-stream'})[extension];
|
|
69
|
+
return { output: outputPath, bytes, stickerId: request.args[0].stickerId, mime, extension };
|
|
70
|
+
}
|
|
66
71
|
return { output: outputPath, bytes, messageId: request.args[0].messageId };
|
|
67
72
|
}
|
|
68
73
|
return parsed.data;
|
|
@@ -79,9 +84,13 @@ export function osDelegateProxy(owner, launcher, service, getCommand) {
|
|
|
79
84
|
if (method === 'then' || typeof method !== 'string') return undefined;
|
|
80
85
|
return (...args) => {
|
|
81
86
|
const command = getCommand();
|
|
82
|
-
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) {
|
|
87
|
+
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar', 'addStickerFile'].includes(method)) {
|
|
83
88
|
const { chatId, path } = args[0];
|
|
84
|
-
return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'upload', args: [{ chatId }] }, inputPath: path });
|
|
89
|
+
return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'upload', args: [method === 'addStickerFile' ? {} : { chatId }] }, inputPath: path });
|
|
90
|
+
}
|
|
91
|
+
if (service === 'client' && method === 'downloadSticker') {
|
|
92
|
+
const { stickerId, output } = args[0];
|
|
93
|
+
return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'downloadSticker', args: [{ stickerId }] }, outputPath: output });
|
|
85
94
|
}
|
|
86
95
|
if (service === 'client' && method === 'downloadFile') {
|
|
87
96
|
const { chatId, messageId, key, position, output } = args[0];
|
package/src/os-delegate.js
CHANGED
|
@@ -79,14 +79,14 @@ export async function checkDelegation({ profile, uid, request, file }) {
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
export async function invokeDelegated({ profile, uid, request, getServices, filePath }) {
|
|
82
|
-
const fileOp = ['send-file', 'send-image', 'group-avatar-set', 'download-file'].includes(request?.command);
|
|
82
|
+
const fileOp = ['send-file', 'send-image', 'group-avatar-set', 'download-file', 'sticker-add-file', 'sticker-download'].includes(request?.command);
|
|
83
83
|
if (fileOp && request.service !== 'files') noAccess();
|
|
84
84
|
if (!fileOp && request.service === 'files') noAccess();
|
|
85
85
|
let file;
|
|
86
|
-
if (['send-file', 'send-image', 'group-avatar-set'].includes(request.command)) {
|
|
86
|
+
if (['send-file', 'send-image', 'group-avatar-set', 'sticker-add-file'].includes(request.command)) {
|
|
87
87
|
if (!filePath || !nameOk(request.fileName)) fail('INVALID_REQUEST', 'Invalid file transfer.');
|
|
88
88
|
const info = await stat(filePath);
|
|
89
|
-
if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (['send-image', 'group-avatar-set'].includes(request.command) && info.size > 10 * 1024 * 1024)) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
|
|
89
|
+
if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (['send-image', 'group-avatar-set', 'sticker-add-file'].includes(request.command) && info.size > 10 * 1024 * 1024)) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
|
|
90
90
|
const hash = createHash('sha256'); for await (const chunk of createReadStream(filePath)) hash.update(chunk);
|
|
91
91
|
file = { name: request.fileName, size: info.size, sha256: hash.digest('hex') };
|
|
92
92
|
}
|
|
@@ -108,10 +108,10 @@ export async function invokeDelegated({ profile, uid, request, getServices, file
|
|
|
108
108
|
}
|
|
109
109
|
const client = services.client, o = args[0];
|
|
110
110
|
if (method === 'upload') {
|
|
111
|
-
try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : rpc.command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: o.chatId, path: filePath }) }; }
|
|
111
|
+
try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : rpc.command === 'send-image' ? 'sendImage' : rpc.command === 'sticker-add-file' ? 'addStickerFile' : 'setGroupAvatar'](rpc.command === 'sticker-add-file' ? { path: filePath } : { chatId: o.chatId, path: filePath }) }; }
|
|
112
112
|
catch (error) { if (!(error instanceof FeishuError)) fail('EFFECT_UNKNOWN', 'The delegated write could not be confirmed; inspect before retrying.'); throw error; }
|
|
113
113
|
}
|
|
114
|
-
return { download: true, client, options: o };
|
|
114
|
+
return { download: true, client, options: o, command: rpc.command };
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
// The privileged helper parses one framed request and terminates; it never opens a listening socket.
|
|
@@ -128,7 +128,7 @@ export async function serveOne({ input, output, uid, profile, getServices }) {
|
|
|
128
128
|
try { request = JSON.parse(header.subarray(0, end).toString('utf8')); } catch { fail('INVALID_REQUEST', 'Invalid request.'); }
|
|
129
129
|
data = header.subarray(end + 1); header = null;
|
|
130
130
|
if (!only(request, ['command', 'service', 'method', 'args', 'fileName', 'size'])) fail('INVALID_REQUEST', 'Invalid request.');
|
|
131
|
-
const upload = ['send-file', 'send-image', 'group-avatar-set'].includes(request.command);
|
|
131
|
+
const upload = ['send-file', 'send-image', 'group-avatar-set', 'sticker-add-file'].includes(request.command);
|
|
132
132
|
if (upload) {
|
|
133
133
|
if (!nameOk(request.fileName) || !Number.isSafeInteger(request.size) || request.size < 1 || request.size > profile.policy.maxFileBytes || request.size > MAX_FILE) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
|
|
134
134
|
const { size, fileName, ...rpc } = request;
|
|
@@ -153,15 +153,19 @@ export async function serveOne({ input, output, uid, profile, getServices }) {
|
|
|
153
153
|
outcome = await invokeDelegated({ profile, uid, request: rpc, getServices, filePath: path });
|
|
154
154
|
if (!outcome.download) { output.write(JSON.stringify({ ok: true, data: outcome.data }) + '\n'); return; }
|
|
155
155
|
const o = outcome.options;
|
|
156
|
-
if (
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
156
|
+
if (outcome.command !== 'sticker-download') {
|
|
157
|
+
if (!only(o, ['chatId', 'messageId', 'key', 'position']) || !Number.isInteger(o.position) || o.position < 1 || o.position > 2147483647 || typeof o.messageId !== 'string' || typeof o.key !== 'string') fail('INVALID_REQUEST', 'A valid message position and resource are required.');
|
|
158
|
+
const page = await outcome.client.history({ chatId: o.chatId, start: o.position, limit: 1 });
|
|
159
|
+
const item = page.items?.[0];
|
|
160
|
+
if (!item || item.position !== o.position || item.id !== o.messageId || item.resource?.key !== o.key) noAccess();
|
|
161
|
+
}
|
|
160
162
|
temp = await mkdtemp(join(tmpdir(), 'larkmate-os-transfer-')); path = join(temp, 'download');
|
|
161
|
-
const result =
|
|
163
|
+
const result = outcome.command === 'sticker-download'
|
|
164
|
+
? await outcome.client.downloadSticker({ stickerId: o.stickerId, output: path, maxBytes: profile.policy.maxFileBytes })
|
|
165
|
+
: await outcome.client.downloadFile({ chatId: o.chatId, messageId: o.messageId, key: o.key, output: path, maxBytes: profile.policy.maxFileBytes });
|
|
162
166
|
const info = await stat(path);
|
|
163
167
|
if (info.size !== result.bytes || info.size > profile.policy.maxFileBytes) fail('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
|
|
164
|
-
output.write(JSON.stringify({ ok: true, size: info.size }) + '\n');
|
|
168
|
+
output.write(JSON.stringify({ ok: true, size: info.size, ...(outcome.command === 'sticker-download' ? { extension: result.extension } : {}) }) + '\n');
|
|
165
169
|
started = true;
|
|
166
170
|
for await (const chunk of createReadStream(path)) if (!output.write(chunk)) await new Promise(resolve => output.once('drain', resolve));
|
|
167
171
|
} catch (error) {
|
package/src/rich-text.js
CHANGED
|
@@ -4,6 +4,11 @@ import { shortId } from './gateway.js';
|
|
|
4
4
|
const ownKeys = (value, allowed) => value && typeof value === 'object' && !Array.isArray(value)
|
|
5
5
|
&& Object.keys(value).every(key => allowed.includes(key));
|
|
6
6
|
|
|
7
|
+
export function requireEmojiKey(key) {
|
|
8
|
+
if (typeof key !== 'string' || !/^[A-Za-z0-9_+.-]{1,128}$/.test(key)) throw new FeishuError('INVALID_ARGUMENT', 'emoji key must be a Feishu emoji name.');
|
|
9
|
+
return key;
|
|
10
|
+
}
|
|
11
|
+
|
|
7
12
|
// RichText can contain nested paragraphs, and innerText can be empty even when
|
|
8
13
|
// the element dictionary contains readable text, mentions, or links.
|
|
9
14
|
export function readRichText(gateway, richText, fallback = null) {
|
|
@@ -22,6 +27,10 @@ export function readRichText(gateway, richText, fallback = null) {
|
|
|
22
27
|
const start = segments.length;
|
|
23
28
|
for (const child of element.childIds || []) visit(child);
|
|
24
29
|
if (segments.length > start && !segments.at(-1).text?.endsWith('\n')) segments.push({ type: 'text', text: '\n' });
|
|
30
|
+
} else if (element.tag === 10) {
|
|
31
|
+
const property = gateway.decode('EmotionProperty', element.property || new Uint8Array());
|
|
32
|
+
if (!Object.hasOwn(property, 'key') || !property.key) { incomplete = true; return; }
|
|
33
|
+
segments.push({ type: 'emoji', key: property.key, text: `:${property.key}:` });
|
|
25
34
|
} else if ([1, 5, 6].includes(element.tag)) {
|
|
26
35
|
const type = element.tag === 1 ? 'TextProperty' : element.tag === 5 ? 'AtProperty' : 'AnchorProperty';
|
|
27
36
|
const property = gateway.decode(type, element.property || new Uint8Array());
|
|
@@ -54,8 +63,8 @@ export function buildRichText(gateway, parts) {
|
|
|
54
63
|
if (!Array.isArray(parts) || parts.length === 0 || parts.length > 1000) throw new FeishuError('INVALID_ARGUMENT', 'segments must contain 1 to 1000 items.');
|
|
55
64
|
const elementIds = [], atIds = [], anchorIds = [], dictionary = {}, texts = [];
|
|
56
65
|
for (const part of parts) {
|
|
57
|
-
if (!ownKeys(part, ['type', 'text', 'userId', 'url'])) throw new FeishuError('INVALID_ARGUMENT', 'Invalid rich text segment.');
|
|
58
|
-
const text = part.text;
|
|
66
|
+
if (!ownKeys(part, ['type', 'text', 'userId', 'url', 'key'])) throw new FeishuError('INVALID_ARGUMENT', 'Invalid rich text segment.');
|
|
67
|
+
const text = part.type === 'emoji' ? `:${requireEmojiKey(part.key)}:` : part.text;
|
|
59
68
|
if (typeof text !== 'string' || text.length === 0) throw new FeishuError('INVALID_ARGUMENT', 'segment text must not be empty.');
|
|
60
69
|
const id = shortId();
|
|
61
70
|
let tag, property;
|
|
@@ -70,6 +79,8 @@ export function buildRichText(gateway, parts) {
|
|
|
70
79
|
let url; try { url = new URL(part.url); } catch { throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL.'); }
|
|
71
80
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL without credentials.');
|
|
72
81
|
tag = 6; property = gateway.encode('AnchorProperty', { href: part.url, content: text, textContent: text }); anchorIds.push(id);
|
|
82
|
+
} else if (part.type === 'emoji' && ownKeys(part, ['type', 'key'])) {
|
|
83
|
+
tag = 10; property = gateway.encode('EmotionProperty', { key: part.key });
|
|
73
84
|
} else throw new FeishuError('INVALID_ARGUMENT', 'Unsupported rich text segment.');
|
|
74
85
|
elementIds.push(id); dictionary[id] = { tag, property }; texts.push(text);
|
|
75
86
|
}
|
package/src/stickers.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises';
|
|
2
|
+
import { FeishuError, requireInt64Id } from './errors.js';
|
|
3
|
+
import { uploadFile } from './upload.js';
|
|
4
|
+
import { shortId } from './gateway.js';
|
|
5
|
+
|
|
6
|
+
const VERSION = '8.5.0';
|
|
7
|
+
const validKey = key => typeof key === 'string' && /^[\w.-]{1,200}$/.test(key);
|
|
8
|
+
function invalid() { throw new FeishuError('INVALID_ARGUMENT', 'A valid sticker ID or key is required.'); }
|
|
9
|
+
function mimeInfo(head) {
|
|
10
|
+
if (head.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex'))) return { mime:'image/png', extension:'png' };
|
|
11
|
+
if (head.length>=3 && head[0]===0xff && head[1]===0xd8 && head[2]===0xff) return { mime:'image/jpeg', extension:'jpg' };
|
|
12
|
+
if (head.length>=6 && ['GIF87a','GIF89a'].includes(head.subarray(0,6).toString('ascii'))) return { mime:'image/gif', extension:'gif' };
|
|
13
|
+
if (head.length>=12 && head.subarray(0,4).toString('ascii')==='RIFF' && head.subarray(8,12).toString('ascii')==='WEBP') return { mime:'image/webp', extension:'webp' };
|
|
14
|
+
return { mime:'application/octet-stream', extension:'bin' };
|
|
15
|
+
}
|
|
16
|
+
export class Stickers {
|
|
17
|
+
constructor(gateway) { this.gateway=gateway; }
|
|
18
|
+
async rawList() {
|
|
19
|
+
const response=await this.gateway.call(103,'PullStickersRequest',{position:0,count:50},{version:VERSION,operation:'stickers-list'});
|
|
20
|
+
if (!Object.hasOwn(response.packet, 'payload') || response.packet.payload == null) throw new FeishuError('INVALID_RESPONSE','No sticker collection was returned.');
|
|
21
|
+
try { const data=this.gateway.decode('PullStickersResponse',response.packet.payload); return { stickers:data.stickers || [],updateTime:Object.hasOwn(data,'updateTime')?String(data.updateTime):null }; }
|
|
22
|
+
catch { throw new FeishuError('INVALID_RESPONSE','The sticker collection was unreadable.'); }
|
|
23
|
+
}
|
|
24
|
+
async list() {
|
|
25
|
+
const result=await this.rawList();
|
|
26
|
+
return {items:result.stickers.map((s,index)=>({index:index+1,id:s.stickerId || null,key:s.key || null,position:Object.hasOwn(s,'position')?s.position:null,
|
|
27
|
+
mode:s.mode || null,name:s.summary?.i18nTitles?.['zh-CN'] || s.summary?.title || null,width:s.image?.origin?.width || null,height:s.image?.origin?.height || null,
|
|
28
|
+
previewUrl:validKey(s.key)?`https://s3-imfile.feishucdn.com/static-resource/v1/${encodeURIComponent(s.key)}~?image_size=default-small&format=default-small&sticker_format=.webp`:null})),updateTime:result.updateTime};
|
|
29
|
+
}
|
|
30
|
+
async find(id) {
|
|
31
|
+
if (!validKey(id)) invalid();
|
|
32
|
+
const {stickers}=await this.rawList(); const matches=stickers.filter(s=>s.stickerId===id || s.key===id);
|
|
33
|
+
if (matches.length!==1) throw new FeishuError(matches.length?'AMBIGUOUS':'NOT_FOUND',matches.length?'Multiple stickers matched; use their IDs.':'Sticker not found in the current account collection.');
|
|
34
|
+
if (!validKey(matches[0].key)) throw new FeishuError('INVALID_RESPONSE','Sticker resource key was unavailable.');
|
|
35
|
+
return matches[0];
|
|
36
|
+
}
|
|
37
|
+
async send({chatId,stickerId}) {
|
|
38
|
+
requireInt64Id(chatId,'chat ID'); const s=await this.find(stickerId); const cid=shortId();
|
|
39
|
+
const response=await this.gateway.call(5,'PutMessageRequest',{type:10,chatId,cid,isNotified:true,version:1,content:{fileKey:s.key,...(s.stickerId?{stickerId:s.stickerId}:{}),...(s.stickerSetId?{stickerSetId:s.stickerSetId}:{})}},
|
|
40
|
+
{version:VERSION,mutating:true,operation:'sticker-send'});
|
|
41
|
+
let messageId=null;try{if(response.packet.payload?.length){const m=this.gateway.decode('PutMessageResponse',response.packet.payload).message;if(m?.id&&!String(m.id).startsWith('-')&&(!m.chatId||m.chatId===chatId))messageId=String(m.id)}}catch{}
|
|
42
|
+
return {status:messageId?'accepted':'submitted_unconfirmed',chatId,stickerId:s.stickerId||null,messageId,cid,requestId:response.requestId};
|
|
43
|
+
}
|
|
44
|
+
async add({key}) {
|
|
45
|
+
if(!validKey(key)) invalid(); return this.addRequest({stickers:[{key}],addType:1});
|
|
46
|
+
}
|
|
47
|
+
async addFile({path}) {
|
|
48
|
+
const image=await uploadFile(this.gateway,path,{image:true});
|
|
49
|
+
return this.addRequest({imageKeys:[image.key],addType:2});
|
|
50
|
+
}
|
|
51
|
+
async addRequest(body) {
|
|
52
|
+
const response=await this.gateway.call(100,'PutStickersRequest',body,{version:VERSION,mutating:true,operation:'sticker-add'});
|
|
53
|
+
if(!response.packet.payload?.length)return {status:'submitted_unconfirmed',requestId:response.requestId};
|
|
54
|
+
let data;try{data=this.gateway.decode('PutStickersResponse',response.packet.payload)}catch{return {status:'submitted_unconfirmed',requestId:response.requestId}}
|
|
55
|
+
if(data.dupStickers?.length)return {status:'duplicate',requestId:response.requestId};
|
|
56
|
+
const added=data.stickers?.[0];
|
|
57
|
+
return {status:added?.stickerId?'accepted':'submitted_unconfirmed',stickerId:added?.stickerId || null,requestId:response.requestId};
|
|
58
|
+
}
|
|
59
|
+
async remove({stickerId}) {
|
|
60
|
+
const s=await this.find(stickerId);
|
|
61
|
+
const response=await this.gateway.call(101,'DeleteStickersRequest',{stickers:[s]},{version:VERSION,mutating:true,operation:'sticker-remove'});
|
|
62
|
+
try {const after=await this.rawList();if(!after.stickers.some(x=>x.stickerId===s.stickerId && x.key===s.key))return {status:'removed',stickerId:s.stickerId||null,requestId:response.requestId};}catch{}
|
|
63
|
+
return {status:'submitted_unconfirmed',stickerId:s.stickerId||null,requestId:response.requestId};
|
|
64
|
+
}
|
|
65
|
+
async download({stickerId,output,maxBytes=100*1024*1024}) {
|
|
66
|
+
if(typeof output!=='string'||!output.trim())throw new FeishuError('INVALID_ARGUMENT','An output path is required.');
|
|
67
|
+
if(!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>100*1024*1024)throw new FeishuError('INVALID_ARGUMENT','Invalid download size limit.');
|
|
68
|
+
const s=await this.find(stickerId);
|
|
69
|
+
const url=`https://s3-imfile.feishucdn.com/static-resource/v1/${encodeURIComponent(s.key)}~`;
|
|
70
|
+
let response;try{response=await this.gateway.fetchImpl(url,{redirect:'manual',headers:{accept:'*/*'},signal:AbortSignal.timeout(this.gateway.timeoutMs)});}catch{throw new FeishuError('DOWNLOAD_FAILED','Could not retrieve the sticker.');}
|
|
71
|
+
if(response.status!==200||!response.body){try{await response.body?.cancel()}catch{}throw new FeishuError('DOWNLOAD_FAILED','Feishu did not return the sticker.',{httpStatus:response.status});}
|
|
72
|
+
let handle;try{handle=await open(output,'wx',0o600)}catch(e){try{await response.body.cancel()}catch{}throw new FeishuError('DOWNLOAD_WRITE_FAILED',e.code==='EEXIST'?'Output file already exists; choose a new path.':'Could not create the output file.')}
|
|
73
|
+
let bytes=0,head=Buffer.alloc(0);
|
|
74
|
+
try {for await(const chunk of response.body){bytes+=chunk.length;if(bytes>maxBytes)throw new FeishuError('FILE_TOO_LARGE','The download exceeds the configured file limit.');if(head.length<12)head=Buffer.concat([head,Buffer.from(chunk).subarray(0,12-head.length)]);await handle.writeFile(chunk)}
|
|
75
|
+
const length=response.headers.get('content-length'),encoding=response.headers.get('content-encoding');
|
|
76
|
+
if(!bytes || (length&&(!encoding||encoding==='identity')&&/^\d+$/.test(length)&&BigInt(bytes)!==BigInt(length)))throw Error('incomplete');
|
|
77
|
+
return {output,bytes,stickerId:s.stickerId||null,...mimeInfo(head)};
|
|
78
|
+
}catch(error){if(error instanceof FeishuError)throw error;throw new FeishuError('DOWNLOAD_INCOMPLETE','Sticker download is incomplete.',{output,bytes})}finally{await handle.close()}
|
|
79
|
+
}
|
|
80
|
+
}
|