larkmate 0.1.14 → 0.1.16
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 +8 -0
- package/bin/larkmate.js +51 -1
- package/docs/message-listening.md +60 -0
- package/package.json +1 -1
- package/proto/lark.proto +22 -1
- package/skills/larkmate/SKILL.md +2 -1
- package/skills/larkmate/references/chats.md +10 -0
- package/skills/larkmate/references/listen.md +7 -0
- package/skills/larkmate/references/writes.md +6 -1
- package/src/agent-broker.js +11 -3
- package/src/agent-files.js +3 -3
- package/src/client.js +94 -0
- package/src/listen-modes.js +94 -0
- package/src/listen.js +179 -0
- package/src/os-delegate-client.js +1 -1
- package/src/os-delegate.js +5 -5
- package/src/session-controls.js +24 -0
package/README.md
CHANGED
|
@@ -35,11 +35,16 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
35
35
|
- [x] 查询、置顶和取消置顶会话
|
|
36
36
|
- [x] 查询、标记和取消标记会话
|
|
37
37
|
- [x] 标记已读或未读、设置免打扰
|
|
38
|
+
- [x] 设置 @所有人提醒和消息自动翻译
|
|
39
|
+
- [x] 查询和修改联系人备注名及纯文本备注描述
|
|
38
40
|
- [x] 移入或移出已完成、会话收纳
|
|
39
41
|
- [x] 按未读、免打扰、@我、单聊、群组等分组查询
|
|
40
42
|
- [x] 配置侧边栏分组的显示、隐藏、顺序和展示规则
|
|
41
43
|
- [x] 创建、重命名和删除标签,管理手动标签下的会话
|
|
42
44
|
- [ ] 修改自动规则标签的会话成员
|
|
45
|
+
- [ ] 配置会话菜单和翻译助手的完整选项
|
|
46
|
+
- [x] 清空聊天记录
|
|
47
|
+
- [ ] 管理联系人备注图片及富文本
|
|
43
48
|
- 消息
|
|
44
49
|
- [x] 分页读取指定会话的历史消息
|
|
45
50
|
- [x] 在已扫描的历史消息中按关键词、发送者和时间筛选
|
|
@@ -52,14 +57,17 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
52
57
|
- [x] 发送图片消息、下载图片或附件
|
|
53
58
|
- [x] 给消息添加和取消表情回应
|
|
54
59
|
- [x] 获取消息链接
|
|
60
|
+
- [x] 监听指定会话的新消息,支持本地服务和规则触发脚本
|
|
55
61
|
- 群聊
|
|
56
62
|
- [x] 查询群信息、成员、管理员和入退群记录
|
|
63
|
+
- [x] 修改群名称、描述、头像和本人群昵称
|
|
57
64
|
- [x] 邀请、移除成员,退出或解散群聊
|
|
58
65
|
- [x] 管理员设置和群主转让
|
|
59
66
|
- [x] 查询和调整入群审批、发言、邀请及其他群设置
|
|
60
67
|
- [x] 创建群邀请链接,查询和处理入群申请
|
|
61
68
|
- [x] 查询群公告、查询和设置机器人的移除限制
|
|
62
69
|
- [ ] 修改群公告
|
|
70
|
+
- [ ] 管理群机器人及其配置
|
|
63
71
|
- 飞书任务
|
|
64
72
|
- [x] 查询任务中心与任务视图,按关键词搜索任务
|
|
65
73
|
- [x] 新建、编辑、完成、重开和删除任务
|
package/bin/larkmate.js
CHANGED
|
@@ -15,10 +15,12 @@ import { FeedGroups } from '../src/feed-groups.js';
|
|
|
15
15
|
import { Tasks } from '../src/tasks.js';
|
|
16
16
|
import { Calendar } from '../src/calendar.js';
|
|
17
17
|
import { GroupManagement, groupSettingsSchema } from '../src/group-management.js';
|
|
18
|
+
import { listen } from '../src/listen.js';
|
|
19
|
+
import { createRuleOutput, loadListenRules, startListenService } from '../src/listen-modes.js';
|
|
18
20
|
|
|
19
21
|
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
20
22
|
const program = new Command();
|
|
21
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
23
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.16');
|
|
22
24
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
23
25
|
program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
|
|
24
26
|
program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
|
|
@@ -137,6 +139,34 @@ program.command('status').description('Check the current user login.')
|
|
|
137
139
|
program.command('search').description('Search users, bots and groups.')
|
|
138
140
|
.requiredOption('--query <text>', 'search text')
|
|
139
141
|
.action(async options => output(await (await client()).search(options.query)));
|
|
142
|
+
program.command('listen').description('Stream new messages from selected chats as JSON lines.')
|
|
143
|
+
.requiredOption('--chat <id>', 'numeric chat ID; repeatable', collect, [])
|
|
144
|
+
.action(async o => {
|
|
145
|
+
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
146
|
+
const controller = new AbortController(), stop = () => controller.abort();
|
|
147
|
+
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
148
|
+
try { await listen({ gateway: new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) }), chatIds: o.chat, signal: controller.signal }); }
|
|
149
|
+
finally { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); }
|
|
150
|
+
});
|
|
151
|
+
program.command('listen-service').description('Serve selected chat messages on a private Unix socket.')
|
|
152
|
+
.requiredOption('--chat <id>', 'numeric chat ID; repeatable', collect, []).requiredOption('--socket <path>', 'absolute Unix socket path')
|
|
153
|
+
.action(async o => {
|
|
154
|
+
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
155
|
+
const service = await startListenService(o.socket), controller = new AbortController(), stop = () => controller.abort();
|
|
156
|
+
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
157
|
+
try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await listen({ gateway:new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}),chatIds:o.chat,output:service.output,signal:controller.signal }); }
|
|
158
|
+
finally { await service.close(); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
|
|
159
|
+
});
|
|
160
|
+
program.command('listen-run').description('Run configured scripts for matching new messages.')
|
|
161
|
+
.requiredOption('--rules <path>', 'protected JSON rules file')
|
|
162
|
+
.action(async o => {
|
|
163
|
+
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
164
|
+
const config=await loadListenRules(o.rules), gateway=new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}), self=await gateway.authenticate();
|
|
165
|
+
const sink=createRuleOutput({...config,selfId:self.id}), controller=new AbortController(), stop=()=>controller.abort();
|
|
166
|
+
process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
167
|
+
try { await listen({ gateway,chatIds:config.chatIds,output:sink,signal:controller.signal }); }
|
|
168
|
+
finally { await new Promise(resolve=>sink.end(resolve)); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
|
|
169
|
+
});
|
|
140
170
|
program.command('search-messages').description('Search accessible messages across conversations.')
|
|
141
171
|
.requiredOption('--query <text>', 'search text')
|
|
142
172
|
.option('--limit <number>', 'results per page, 1 to 100', '20')
|
|
@@ -278,6 +308,13 @@ for (const [command, enabled] of [['label-add', true], ['label-remove', false]])
|
|
|
278
308
|
}
|
|
279
309
|
program.command('chat-state').description('Read pin, flag, notification and read state for a conversation.')
|
|
280
310
|
.requiredOption('--chat <id>', 'numeric chat ID').action(async o => output(await (await controls()).state(o.chat)));
|
|
311
|
+
program.command('chat-preferences').description('Read conversation notification and translation preferences.').requiredOption('--chat <id>')
|
|
312
|
+
.action(async o => output(await (await controls()).preferences(o.chat)));
|
|
313
|
+
program.command('chat-preferences-set').description('Update conversation notification and translation preferences.').requiredOption('--chat <id>')
|
|
314
|
+
.option('--mute-at-all <bool>', 'suppress @all notifications: true or false').option('--auto-translate <bool>', 'automatically translate messages: true or false')
|
|
315
|
+
.action(async o => { const parse = value => { if (value === undefined) return undefined; if (!['true','false'].includes(value)) throw new FeishuError('INVALID_ARGUMENT', 'Use true or false.'); return value === 'true'; }; output(await (await controls()).setPreference({ chatId:o.chat, muteAtAll:parse(o.muteAtAll), autoTranslate:parse(o.autoTranslate) })); });
|
|
316
|
+
program.command('chat-clear-history').description('Clear this conversation history through its current last message.').requiredOption('--chat <id>')
|
|
317
|
+
.action(async o => output(await (await client()).clearChatHistory({ chatId: o.chat })));
|
|
281
318
|
for (const [command, method, enabled, description] of [
|
|
282
319
|
['pin', 'pin', true, 'Pin a conversation.'], ['unpin', 'pin', false, 'Unpin a conversation.'],
|
|
283
320
|
['mark', 'mark', true, 'Flag a conversation.'], ['unmark', 'mark', false, 'Remove a conversation flag.'],
|
|
@@ -476,6 +513,19 @@ program.command('group-update').description('Change a group name or description.
|
|
|
476
513
|
chatId: options.chat, name: options.name, description: options.description,
|
|
477
514
|
})));
|
|
478
515
|
|
|
516
|
+
program.command('contact-alias').description('Read your personal alias for a contact.').requiredOption('--user <id>')
|
|
517
|
+
.action(async o => output(await (await client()).contactAlias({ userId: o.user })));
|
|
518
|
+
program.command('contact-alias-set').description('Set or clear your personal alias for a contact.').requiredOption('--user <id>').requiredOption('--alias <text>', 'use an empty string to clear')
|
|
519
|
+
.action(async o => output(await (await client()).setContactAlias({ userId: o.user, alias: o.alias })));
|
|
520
|
+
program.command('contact-note').description('Read your personal note for a contact.').requiredOption('--user <id>')
|
|
521
|
+
.action(async o => output(await (await client()).contactNote({ userId: o.user })));
|
|
522
|
+
program.command('contact-note-set').description('Set or clear the plain-text note for a contact.').requiredOption('--user <id>').requiredOption('--description <text>', 'use an empty string to clear')
|
|
523
|
+
.action(async o => output(await (await client()).setContactNote({ userId: o.user, description: o.description })));
|
|
524
|
+
program.command('group-nickname-set').description('Set your nickname in a group.').requiredOption('--chat <id>').requiredOption('--nickname <text>', 'use an empty string to clear')
|
|
525
|
+
.action(async o => output(await (await client()).setGroupNickname({ chatId: o.chat, nickname: o.nickname })));
|
|
526
|
+
program.command('group-avatar-set').description('Set a group avatar from an image.').requiredOption('--chat <id>').requiredOption('--file <path>')
|
|
527
|
+
.action(async o => output(await (await client()).setGroupAvatar({ chatId: o.chat, path: o.file })));
|
|
528
|
+
|
|
479
529
|
program.command('group-dissolve').description('Dissolve a group as its owner.')
|
|
480
530
|
.requiredOption('--chat <id>', 'numeric group ID')
|
|
481
531
|
.action(async options => output(await (await client()).dissolveGroup(options.chat)));
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# 监听飞书消息
|
|
2
|
+
|
|
3
|
+
LarkMate 使用当前用户的飞书 Cookie 监听指定会话。先通过 `search` 或 `chats` 确认会话 ID,监听不会主动标记消息为已读。监听进程需要持续运行;退出后不会在后台继续收取消息。
|
|
4
|
+
|
|
5
|
+
## 本地事件服务
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
mkdir -p "$HOME/.larkmate/events"
|
|
9
|
+
chmod 700 "$HOME/.larkmate/events"
|
|
10
|
+
larkmate listen-service --socket "$HOME/.larkmate/events/messages.sock" --chat "$CHAT_ID"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
可重复传入 `--chat`。其他本机程序通过 Unix socket 订阅 JSON Lines:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
curl -N --unix-socket "$HOME/.larkmate/events/messages.sock" http://localhost/events
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
socket 为 `0600`,父目录必须归当前用户所有且不能被其他用户写入。所有连接者接收启动时指定的全部会话;订阅者不在线时不保存事件。也可用 `larkmate listen --chat "$CHAT_ID"` 直接向标准输出流式输出,不启动服务。
|
|
20
|
+
|
|
21
|
+
## 规则与脚本
|
|
22
|
+
|
|
23
|
+
创建私有 JSON 文件,例如:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"version": 1,
|
|
28
|
+
"rules": [
|
|
29
|
+
{
|
|
30
|
+
"name": "process-request",
|
|
31
|
+
"chatIds": ["123456789"],
|
|
32
|
+
"senderIds": ["987654321"],
|
|
33
|
+
"types": [4],
|
|
34
|
+
"contains": "需要处理",
|
|
35
|
+
"excludeContains": "无需处理",
|
|
36
|
+
"excludeSelf": true,
|
|
37
|
+
"filter": { "path": "/absolute/path/filter", "args": [], "timeoutSeconds": 10 },
|
|
38
|
+
"run": { "path": "/absolute/path/handler", "args": [], "timeoutSeconds": 30 }
|
|
39
|
+
}
|
|
40
|
+
]
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
执行 `chmod 600 rules.json`,将示例 ID 和脚本路径改为实际值,然后运行:
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
larkmate listen-run --rules ./rules.json
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`chatIds` 和 `run` 必填;每条规则至少指定一个会话。其他筛选项可省略,填写的条件同时生效。`types` 使用消息类型数字,`4` 表示文本;`contains` 和 `excludeContains` 区分大小写。`excludeSelf` 为 `true` 时跳过当前账号发送的消息。
|
|
51
|
+
|
|
52
|
+
过滤器和目标脚本均为固定的绝对可执行文件路径,`args` 为固定参数;消息不会经由 shell 解析。每次调用时,通过标准输入传入一行消息 JSON。过滤器退出码 `0` 表示匹配,`1` 表示不匹配,其余退出码或超时均视为错误;仅在匹配成功时执行 `run`。过滤器和脚本的标准输出与标准错误不会被转发,失败信息写入监听进程的标准错误。脚本默认超时时间为 30 秒,可配置为 1–600 秒。规则按顺序执行,脚本执行失败不会自动重试。
|
|
53
|
+
|
|
54
|
+
规则文件必须由当前用户或 root 拥有,不能对组或其他用户开放写权限。脚本以启动监听进程的系统用户身份运行;部署方应保护规则文件、脚本及其目录。监听服务和规则模式目前使用持有 Cookie 的账号直接运行,不能通过受限 broker 或系统用户委托调用。
|
|
55
|
+
|
|
56
|
+
## 事件与恢复
|
|
57
|
+
|
|
58
|
+
`message` 事件包含 `id`、`chatId`、`senderId`、`position`、`type`、`text`、`createTime` 等字段。文本无法完整解析时 `textIncomplete` 为 `true`;其他消息类型的 `text` 可能为 `null`。规则模式仅对 `message` 执行脚本,`gap` 事件写到标准错误。
|
|
59
|
+
|
|
60
|
+
连接中断后会自动重连,并在进程保持运行期间按会话位置尽力补拉消息;补拉的消息带有 `backfill: true` 标记。若出现补拉失败、位置不可读或超出补拉上限等情况,会输出 `gap`,调用方应检查并按需通过 `history` 补查。去重状态与会话位置均保存在内存中,进程重启后不会恢复;不保证事件不丢失,也不保证脚本恰好执行一次。
|
package/package.json
CHANGED
package/proto/lark.proto
CHANGED
|
@@ -26,6 +26,7 @@ message Packet {
|
|
|
26
26
|
optional uint32 status = 4;
|
|
27
27
|
optional bytes payload = 5;
|
|
28
28
|
optional string cid = 6;
|
|
29
|
+
repeated int64 compactedSids = 13 [packed=false];
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
enum PayloadType {
|
|
@@ -94,6 +95,9 @@ message PushMessagesRequest {
|
|
|
94
95
|
map<string, bool> forcePush = 8;
|
|
95
96
|
map<string, bool> messagesAtMe = 9;
|
|
96
97
|
}
|
|
98
|
+
message PullPacketsBySidsRequest { repeated string sids = 1; }
|
|
99
|
+
message PullPacketsBySidsResponse { map<string, Packet> packets = 1; }
|
|
100
|
+
message PushBatchCopyMessages { repeated int64 messageIds = 1 [packed=false]; optional MessageEntity lastMessage = 3; }
|
|
97
101
|
|
|
98
102
|
message MessageEntity {
|
|
99
103
|
optional string id = 1;
|
|
@@ -285,6 +289,7 @@ message PullChatsByIdsResponse {
|
|
|
285
289
|
message PatchGroupChatRequest {
|
|
286
290
|
optional int64 chatId = 1;
|
|
287
291
|
optional string name = 2;
|
|
292
|
+
optional string iconData = 3;
|
|
288
293
|
optional string description = 4;
|
|
289
294
|
optional string announcement = 5;
|
|
290
295
|
optional int64 ownerId = 6;
|
|
@@ -300,6 +305,7 @@ message PatchGroupChatRequest {
|
|
|
300
305
|
enum UpdateFields {
|
|
301
306
|
UPDATE_FIELDS_UNSPECIFIED = 0;
|
|
302
307
|
NAME = 1;
|
|
308
|
+
ICON_KEY = 2;
|
|
303
309
|
DESCRIPTION = 3;
|
|
304
310
|
ANNOUNCEMENT = 4;
|
|
305
311
|
OWNER_ID = 5;
|
|
@@ -348,6 +354,7 @@ message Chat {
|
|
|
348
354
|
optional ChatTypeEnum type = 2;
|
|
349
355
|
optional string lastMessageId = 3;
|
|
350
356
|
optional string name = 4;
|
|
357
|
+
optional ChatImage avatar = 5;
|
|
351
358
|
optional string ownerId = 6;
|
|
352
359
|
optional int32 newMessageCount = 7;
|
|
353
360
|
optional int64 updateTime = 9;
|
|
@@ -387,6 +394,7 @@ message Chat {
|
|
|
387
394
|
optional string docUrl = 4;
|
|
388
395
|
}
|
|
389
396
|
}
|
|
397
|
+
message ChatImage { optional string key = 1; }
|
|
390
398
|
|
|
391
399
|
// --- Search (cmd=11021) ---
|
|
392
400
|
|
|
@@ -623,7 +631,20 @@ message PullFeedCardsByIdsRequest { repeated string cardIds = 1; repeated FeedId
|
|
|
623
631
|
message PullFeedCardsByIdsResponse { map<string, InboxCard> cards = 1; }
|
|
624
632
|
message PatchFeedCardUnreadRequest { optional FeedIdentity card = 1; optional bool markAsUnread = 2; optional int64 readPos = 3; }
|
|
625
633
|
message PatchFeedCardUnreadResponse { optional InboxCard card = 1; }
|
|
626
|
-
message ChatSetting {
|
|
634
|
+
message ChatSetting {
|
|
635
|
+
optional bool isRemind = 1;
|
|
636
|
+
optional bool isAutoTranslate = 4;
|
|
637
|
+
optional bool isMuteAtAll = 8;
|
|
638
|
+
}
|
|
639
|
+
message PutGroupNicknameRequest { optional int64 chatId = 1; optional string nickname = 2; }
|
|
640
|
+
message CleanUserChatMessageRequest { optional int64 chatId = 1; optional int32 position = 2; }
|
|
641
|
+
message PutUserAliasRequest { optional int64 targetId = 1; optional string name = 2; }
|
|
642
|
+
message PullContactProfileV2Request { optional int32 scene = 1; optional string userId = 2; optional string chatId = 4; optional bool useNewLayout = 12; }
|
|
643
|
+
message PullContactProfileV2Response { optional ContactProfile profile = 1; optional ContactChatMeta chatChatter = 3; }
|
|
644
|
+
message ContactChatMeta { optional int64 chatId = 1; optional int64 chatterId = 2; optional string groupNickname = 4; }
|
|
645
|
+
message ContactProfile { repeated ContactProfileField fields = 3; }
|
|
646
|
+
message ContactProfileField { optional string key = 1; optional bool visible = 3; optional int32 fieldValueType = 5; optional bytes fieldVal = 6; optional string strFieldVal = 7; optional bool editable = 8; }
|
|
647
|
+
message PatchUserMemoRequest { optional string targetUserId = 1; optional string memoText = 3; }
|
|
627
648
|
message PullChatSettingsRequest { repeated string chatIds = 1; }
|
|
628
649
|
message PullChatSettingsResponse { map<string, ChatSetting> chatSettings = 1; }
|
|
629
650
|
message PatchChatSettingRequest { optional string chatId = 1; optional ChatSetting chatSetting = 2; repeated int32 updateChatSettingField = 3; }
|
package/skills/larkmate/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: larkmate
|
|
3
|
-
description: 使用 LarkMate
|
|
3
|
+
description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、搜索、监听与操作消息、收发文件及图片、管理群组、飞书任务和日历,以及查询录制妙记、申请访问权限和导出文字记录。当用户要求使用 LarkMate 或需要执行上述个人飞书操作时使用;不负责飞书文档。
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# LarkMate
|
|
@@ -14,6 +14,7 @@ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、
|
|
|
14
14
|
根据任务读取所需参考:
|
|
15
15
|
|
|
16
16
|
- 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
|
|
17
|
+
- 监听指定会话、本地事件服务及脚本触发规则: [消息监听](references/listen.md)。
|
|
17
18
|
- 发送与管理消息、文件、图片、表情和收藏,管理群组及成员: [发送与群组](references/writes.md)。
|
|
18
19
|
- 查询和管理飞书任务、任务视图及成员: [飞书任务](references/tasks.md)。
|
|
19
20
|
- 查询和管理日历、日程及邀请: [日历与日程](references/calendar.md)。
|
|
@@ -34,6 +34,12 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
|
|
|
34
34
|
larkmate pinned
|
|
35
35
|
larkmate marked
|
|
36
36
|
larkmate chat-state --chat "$CHAT_ID"
|
|
37
|
+
larkmate chat-preferences --chat "$CHAT_ID"
|
|
38
|
+
larkmate chat-preferences-set --chat "$CHAT_ID" --mute-at-all true --auto-translate false
|
|
39
|
+
larkmate contact-alias --user "$USER_ID"
|
|
40
|
+
larkmate contact-alias-set --user "$USER_ID" --alias '备注名'
|
|
41
|
+
larkmate contact-note --user "$USER_ID"
|
|
42
|
+
larkmate contact-note-set --user "$USER_ID" --description '备注描述'
|
|
37
43
|
larkmate pin --chat "$CHAT_ID" # 取消置顶:unpin
|
|
38
44
|
larkmate mark --chat "$CHAT_ID" # 取消旗帜标记:unmark
|
|
39
45
|
larkmate unread --chat "$CHAT_ID" # 标为已读:read
|
|
@@ -48,6 +54,10 @@ larkmate label-remove --label "$LABEL_ID" --chat "$CHAT_ID"
|
|
|
48
54
|
|
|
49
55
|
`mark` 对应聊天右键菜单的旗帜“标记”。`read` 会推进到调用时最新可见位置并清除手动未读标记;`unread` 可能把已完成会话放回收件箱。标签创建、重命名和删除分别使用 `label-create`、`label-rename`、`label-delete`,会话成员调整仅支持手动标签。删除标签会删除整个个人标签。
|
|
50
56
|
|
|
57
|
+
`chat-clear-history --chat "$CHAT_ID"` 清空当前用户的聊天记录,范围截止于调用时读取到的最后消息位置。该操作不可轻率调用,须有用户明确意图;返回 `submitted_unconfirmed` 时先检查记录,不盲目重试。
|
|
58
|
+
|
|
59
|
+
联系人备注仅对当前用户生效。`contact-note-set` 修改纯文本描述;备注包含图片或复杂格式时拒绝修改,以保护现有内容。传入空字符串可清除备注名或描述。`--mute-at-all` 控制是否屏蔽 @所有人提醒,`--auto-translate` 控制消息自动翻译,两者均使用 `true` 或 `false`。
|
|
60
|
+
|
|
51
61
|
`group-query` 支持消息、未读、免打扰、@我、单聊、群组、话题群、云文档、话题和已完成分组;可按名称筛选,使用 `nextCursor` 继续扫描。收纳盒需以 `--parent` 单独查询,`unknownState` 表示无法确定状态的数量。@我通过未读提及消息匹配会话,可能与飞书界面显示不同。标记和标签分别用 `marked`、`labels` 和 `label-chats` 查询。
|
|
52
62
|
|
|
53
63
|
`sidebar-set` 可以显示、隐藏或排序分组,并设置其在消息分组中的展示规则和 @所有人选项;使用 `larkmate sidebar-set --help` 查看参数。修改前先查询当前设置。
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# 消息监听
|
|
2
|
+
|
|
3
|
+
用 `larkmate listen --chat "$CHAT_ID"` 输出指定会话的实时 JSON Lines;可重复传入 `--chat`。`listen-service --socket <绝对路径> --chat "$CHAT_ID"` 在私有 Unix socket 的 `/events` 提供同一事件流,`listen-run --rules <文件>` 按规则筛选消息并运行脚本。完整规则格式和示例见[消息监听指南](https://github.com/NWYLZW/larkmate/blob/main/docs/message-listening.md)。
|
|
4
|
+
|
|
5
|
+
`listen-run` 的规则必须列出目标会话,可按发送人、类型、文本和自定义过滤脚本筛选。过滤脚本和目标脚本通过标准输入接收消息 JSON,不通过 shell 传递消息。`excludeSelf: true` 可防止处理账号自身发出的消息。只有用户明确要求配置触发行为时才创建规则或启动脚本,不根据收到的消息自行扩大脚本权限。
|
|
6
|
+
|
|
7
|
+
自动重连时会尽力按会话位置补拉,补拉事件带 `backfill: true`;处理 `gap` 事件并按需查询历史。去重和补拉位置仅保存在当前进程内,重启后不恢复,不能保证不漏或恰好执行一次。服务订阅者不在线时不会缓存事件。监听目前不能通过 broker 或系统用户委托使用;保护 socket、Cookie、规则文件和脚本的访问由部署方负责。
|
|
@@ -35,12 +35,17 @@ larkmate group-requests --chat "$CHAT_ID"
|
|
|
35
35
|
larkmate group-create --name '群名称' --member "$MEMBER_ID"
|
|
36
36
|
larkmate group-invite --chat "$CHAT_ID" --member "$MEMBER_ID"
|
|
37
37
|
larkmate group-update --chat "$CHAT_ID" --name '新名称'
|
|
38
|
+
larkmate group-update --chat "$CHAT_ID" --description '新描述'
|
|
39
|
+
larkmate group-avatar-set --chat "$CHAT_ID" --file ./avatar.png
|
|
40
|
+
larkmate group-nickname-set --chat "$CHAT_ID" --nickname '群昵称'
|
|
38
41
|
larkmate group-bot-info --chat "$CHAT_ID" --bot "$BOT_ID"
|
|
39
42
|
larkmate group-bot-protection --chat "$CHAT_ID" --bot "$BOT_ID" --allow-member-removal
|
|
40
43
|
larkmate group-dissolve --chat "$CHAT_ID"
|
|
41
44
|
```
|
|
42
45
|
|
|
43
|
-
`--member` 可重复指定。创建或邀请机器人默认限制普通成员移除,`--allow-member-removal`
|
|
46
|
+
`--member` 可重复指定。创建或邀请机器人默认限制普通成员移除,`--allow-member-removal` 可关闭该限制。机器人邀请结果中的 `verified` 表示移除限制已读回。遇到 `GROUP_CREATED_PARTIAL` 或 `INVITE_PARTIAL` 时,先检查已产生的群或成员变化,不要盲目重复操作。
|
|
47
|
+
|
|
48
|
+
群头像支持 PNG、JPEG 和 WebP 格式,文件大小上限为 10 MiB。通过委托或代理调用时,图片由调用方读取,并受目标会话及文件大小授权限制。群昵称传入空字符串可清除。
|
|
44
49
|
|
|
45
50
|
`group-settings` 可读取群主、公告、发言和群权限设置;`group-settings-schema` 列出可修改的字段与值。使用 `group-settings-set --chat "$CHAT_ID" --json <文件>` 修改所需字段,`--json -` 从标准输入读取。它会按字段更新,并可配置入群审批、邀请、@全体、历史消息可见性及受限模式等;修改前先读取当前设置。群公告暂不支持修改。
|
|
46
51
|
|
package/src/agent-broker.js
CHANGED
|
@@ -32,6 +32,11 @@ const routes = {
|
|
|
32
32
|
favorites: ['client', 'favorites', 'allChats'],
|
|
33
33
|
'chat-open': ['client', 'openChat', 'allChats'],
|
|
34
34
|
'chat-info': ['client', 'chatInfo', 'chatArg'], 'chat-state': ['controls', 'state', 'chatArg'],
|
|
35
|
+
'chat-preferences': ['controls', 'preferences', 'chatArg'], 'chat-preferences-set': ['controls', 'setPreference', 'chatObject'],
|
|
36
|
+
'chat-clear-history': ['client', 'clearChatHistory', 'chatObject'],
|
|
37
|
+
'contact-alias': ['client', 'contactAlias', 'global'], 'contact-alias-set': ['client', 'setContactAlias', 'global'],
|
|
38
|
+
'contact-note': ['client', 'contactNote', 'global'], 'contact-note-set': ['client', 'setContactNote', 'global'],
|
|
39
|
+
'group-nickname-set': ['client', 'setGroupNickname', 'chatObject'],
|
|
35
40
|
history: ['client', 'historyPages', 'chatObject'], 'messages-export': ['client', 'historyPages', 'chatObject'],
|
|
36
41
|
'group-link': ['groups','link','chatObject'], 'group-requests': ['groups','requests','chatObject'], 'group-request-approve': ['groups','reviewRequest','chatObject'], 'group-request-reject': ['groups','reviewRequest','chatObject'], 'group-post-users': ['groups','postUsers','chatObject'],
|
|
37
42
|
'group-settings': ['groups','info','chatObject'], 'group-settings-set': ['groups','setSettings','chatObject'],
|
|
@@ -56,9 +61,10 @@ const routes = {
|
|
|
56
61
|
'minutes-list': ['minutes', 'list', 'allMinutes'], 'minutes-export': ['minutes', 'transcript', 'minute'],
|
|
57
62
|
'minutes-access-info': ['minutes', 'accessInfo', 'minute'], 'minutes-request-access': ['minutes', 'requestAccess', 'minute'],
|
|
58
63
|
'send-file': ['files', 'upload', 'file'], 'send-image': ['files', 'upload', 'file'],
|
|
64
|
+
'group-avatar-set': ['files', 'upload', 'file'],
|
|
59
65
|
'download-file': ['files', 'download', 'file'],
|
|
60
66
|
};
|
|
61
|
-
const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread',
|
|
67
|
+
const writes = new Set(['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',
|
|
62
68
|
'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
|
|
63
69
|
'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',
|
|
64
70
|
'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']);
|
|
@@ -154,7 +160,9 @@ export function authorize(policy, request) {
|
|
|
154
160
|
: method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
|
|
155
161
|
: method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
|
|
156
162
|
: method === 'updateGroup' ? ['chatId', 'name', 'description']
|
|
157
|
-
: method === '
|
|
163
|
+
: method === 'setPreference' ? ['chatId', 'muteAtAll', 'autoTranslate']
|
|
164
|
+
: method === 'setGroupNickname' ? ['chatId', 'nickname']
|
|
165
|
+
: method === 'info' || method === 'admins' || method === 'postUsers' || method === 'clearChatHistory' ? ['chatId']
|
|
158
166
|
: method === 'link' ? ['chatId','days','unlimited']
|
|
159
167
|
: method === 'requests' ? ['chatId','cursor']
|
|
160
168
|
: method === 'reviewRequest' ? ['chatId','userId','approve']
|
|
@@ -281,7 +289,7 @@ export async function brokerCall(socketPath, request, tokenFile) {
|
|
|
281
289
|
export function brokerProxy(socketPath, service, getCommand, tokenFile) {
|
|
282
290
|
return new Proxy({}, { get(_target, method) {
|
|
283
291
|
if (method === 'then' || typeof method !== 'string') return undefined;
|
|
284
|
-
if (service === 'client' && ['sendFile', 'sendImage'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
|
|
292
|
+
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
|
|
285
293
|
if (service === 'client' && method === 'downloadFile') return options => brokerDownload(socketPath, tokenFile, options);
|
|
286
294
|
return (...args) => brokerCall(socketPath, { command: getCommand(), service, method, args }, tokenFile);
|
|
287
295
|
} });
|
package/src/agent-files.js
CHANGED
|
@@ -24,12 +24,12 @@ 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 upload =
|
|
27
|
+
const upload = ['send-file', 'send-image', 'group-avatar-set'].includes(command);
|
|
28
28
|
if (!only(meta, upload ? ['command', 'chatId', 'name', 'size'] : ['command', 'chatId', 'messageId', 'key', 'position']) || (!upload && command !== 'download-file')) bad();
|
|
29
29
|
authorize(policy, { command, service: 'files', method: upload ? 'upload' : 'download', args: [{ chatId: meta.chatId }] });
|
|
30
30
|
requireInt64Id(meta.chatId, 'chat ID');
|
|
31
31
|
if (upload) {
|
|
32
|
-
if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (
|
|
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();
|
|
33
33
|
dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
|
|
34
34
|
const path = join(dir, meta.name);
|
|
35
35
|
const file = await open(path, 'wx', 0o600);
|
|
@@ -45,7 +45,7 @@ export async function handleFileRequest({ req, res, policy, getServices, authori
|
|
|
45
45
|
const { client } = await getServices();
|
|
46
46
|
if (res.destroyed) return;
|
|
47
47
|
dispatched = true;
|
|
48
|
-
const data = await client[command === 'send-file' ? 'sendFile' : 'sendImage']({ chatId: meta.chatId, path });
|
|
48
|
+
const data = await client[command === 'send-file' ? 'sendFile' : command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: meta.chatId, path });
|
|
49
49
|
answer(200, { ok: true, data });
|
|
50
50
|
} else {
|
|
51
51
|
requireInt64Id(meta.messageId, 'message ID');
|
package/src/client.js
CHANGED
|
@@ -3,6 +3,7 @@ import { FeishuError, requireNumericId, requireInt64Id, requireText } from './er
|
|
|
3
3
|
import { shortId } from './gateway.js';
|
|
4
4
|
import { downloadFile } from './download.js';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { open } from 'node:fs/promises';
|
|
6
7
|
|
|
7
8
|
function ids(values, label) {
|
|
8
9
|
if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
|
|
@@ -24,6 +25,99 @@ function decodedPayload(gateway, response, type, operation) {
|
|
|
24
25
|
export class LarkMateClient {
|
|
25
26
|
constructor(gateway) { this.gateway = gateway; }
|
|
26
27
|
|
|
28
|
+
async contactAlias({ userId }) {
|
|
29
|
+
requireInt64Id(userId, 'user ID');
|
|
30
|
+
const r = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId, useNewLayout: true }, { operation: 'contact-alias' });
|
|
31
|
+
const p = this.gateway.decode('PullContactProfileV2Response', r.packet.payload);
|
|
32
|
+
if (!p.profile || !Array.isArray(p.profile.fields)) throw new FeishuError('STATE_UNAVAILABLE', 'Contact profile was not returned.');
|
|
33
|
+
const field = p.profile.fields.find(x => x.fieldValueType === 50 && x.key === 'B-ALIAS');
|
|
34
|
+
if (!field) return { userId, alias: '' };
|
|
35
|
+
try { const alias = JSON.parse(field.strFieldVal).text.default_val; if (typeof alias !== 'string') throw new Error(); return { userId, alias }; }
|
|
36
|
+
catch { throw new FeishuError('INVALID_RESPONSE', 'Contact alias was unreadable.'); }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async contactNote({ userId }) {
|
|
40
|
+
requireInt64Id(userId, 'user ID');
|
|
41
|
+
const r = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId, useNewLayout: true }, { operation: 'contact-note' });
|
|
42
|
+
const p = this.gateway.decode('PullContactProfileV2Response', r.packet.payload);
|
|
43
|
+
if (!p.profile || !Array.isArray(p.profile.fields)) throw new FeishuError('STATE_UNAVAILABLE', 'Contact profile was not returned.');
|
|
44
|
+
const field = p.profile.fields.find(x => x.fieldValueType === 105 && x.key === 'B-MEMO-DESCRIPTION');
|
|
45
|
+
if (!field) return { userId, description: '', hasImages: false, hasRichText: false };
|
|
46
|
+
try {
|
|
47
|
+
const note = JSON.parse(field.strFieldVal);
|
|
48
|
+
const elements = Object.values(note.memo_text_v2?.elements?.dictionary || {});
|
|
49
|
+
return { userId, description: note.memo_text ?? note.memo_text_v2?.inner_text ?? '',
|
|
50
|
+
hasImages: !!note.memo_picture || !!note.memo_picture_v2?.length,
|
|
51
|
+
hasRichText: elements.some(x => x.tag !== 1) };
|
|
52
|
+
} catch { throw new FeishuError('INVALID_RESPONSE', 'Contact note was unreadable.'); }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async setContactNote({ userId, description }) {
|
|
56
|
+
requireInt64Id(userId, 'user ID');
|
|
57
|
+
if (typeof description !== 'string' || Buffer.byteLength(description) > 65536) throw new FeishuError('INVALID_ARGUMENT', 'Description must be a string up to 64 KiB.');
|
|
58
|
+
const before = await this.contactNote({ userId });
|
|
59
|
+
if (before.hasImages || before.hasRichText) throw new FeishuError('UNSUPPORTED_NOTE_CONTENT', 'The note contains images or rich text; use Feishu to preserve them.');
|
|
60
|
+
if (before.description === description) return { status: 'already_set', userId, description };
|
|
61
|
+
const r = await this.gateway.call(5036, 'PatchUserMemoRequest', { targetUserId: userId, memoText: description }, { mutating: true, operation: 'contact-note-set' });
|
|
62
|
+
try { const after = await this.contactNote({ userId }); return { status: after.description === description ? 'verified' : 'submitted_unconfirmed', userId, requestId: r.requestId }; }
|
|
63
|
+
catch { return { status: 'submitted_unconfirmed', userId, requestId: r.requestId }; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async setContactAlias({ userId, alias }) {
|
|
67
|
+
requireInt64Id(userId, 'user ID');
|
|
68
|
+
if (typeof alias !== 'string' || Buffer.byteLength(alias) > 1024) throw new FeishuError('INVALID_ARGUMENT', 'Alias must be a string up to 1024 bytes.');
|
|
69
|
+
const before = await this.contactAlias({ userId });
|
|
70
|
+
if (before.alias === alias) return { status: 'already_set', userId, alias };
|
|
71
|
+
const r = await this.gateway.call(5400, 'PutUserAliasRequest', { targetId: userId, name: alias }, { mutating: true, operation: 'contact-alias-set' });
|
|
72
|
+
try { const after = await this.contactAlias({ userId }); return { status: after.alias === alias ? 'verified' : 'submitted_unconfirmed', userId, requestId: r.requestId }; }
|
|
73
|
+
catch { return { status: 'submitted_unconfirmed', userId, requestId: r.requestId }; }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async setGroupNickname({ chatId, nickname }) {
|
|
77
|
+
requireInt64Id(chatId, 'chat ID');
|
|
78
|
+
if (typeof nickname !== 'string' || Buffer.byteLength(nickname) > 1024) throw new FeishuError('INVALID_ARGUMENT', 'Nickname must be a string up to 1024 bytes.');
|
|
79
|
+
const r = await this.gateway.call(5401, 'PutGroupNicknameRequest', { chatId, nickname }, { mutating: true, operation: 'group-nickname-set' });
|
|
80
|
+
try {
|
|
81
|
+
const me = await this.gateway.authenticate();
|
|
82
|
+
const p = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId: me.id, chatId, useNewLayout: true }, { operation: 'group-nickname-read' });
|
|
83
|
+
const meta = this.gateway.decode('PullContactProfileV2Response', p.packet.payload).chatChatter;
|
|
84
|
+
return { status: String(meta?.chatId) === chatId && meta.groupNickname === nickname ? 'verified' : 'submitted_unconfirmed', chatId, requestId: r.requestId };
|
|
85
|
+
} catch { return { status: 'submitted_unconfirmed', chatId, requestId: r.requestId }; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async clearChatHistory({ chatId }) {
|
|
89
|
+
requireInt64Id(chatId, 'chat ID');
|
|
90
|
+
const info = await this.chatInfo(chatId);
|
|
91
|
+
if (!Number.isInteger(info.lastMessagePosition) || info.lastMessagePosition < 0) throw new FeishuError('POSITION_UNAVAILABLE', 'The last message position is unavailable.');
|
|
92
|
+
if (!info.lastMessagePosition) return { status: 'already_empty', chatId };
|
|
93
|
+
const r = await this.gateway.call(900011, 'CleanUserChatMessageRequest', { chatId, position: info.lastMessagePosition }, { mutating: true, operation: 'chat-clear-history' });
|
|
94
|
+
return { status: 'submitted_unconfirmed', chatId, throughPosition: info.lastMessagePosition, requestId: r.requestId };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async setGroupAvatar({ chatId, path }) {
|
|
98
|
+
requireInt64Id(chatId, 'chat ID');
|
|
99
|
+
let file, dispatched = false;
|
|
100
|
+
try {
|
|
101
|
+
file = await open(path, 'r'); const stat = await file.stat();
|
|
102
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > 10 * 1024 * 1024) throw new FeishuError('FILE_INVALID', 'Use an image up to 10 MiB.');
|
|
103
|
+
const b = await file.readFile();
|
|
104
|
+
let mime;
|
|
105
|
+
if (b.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex'))) mime = 'image/png';
|
|
106
|
+
else if (b.length >= 3 && b[0] === 255 && b[1] === 216 && b[2] === 255) mime = 'image/jpeg';
|
|
107
|
+
else if (b.subarray(0,4).toString() === 'RIFF' && b.subarray(8,12).toString() === 'WEBP') mime = 'image/webp';
|
|
108
|
+
else throw new FeishuError('FILE_INVALID', 'Use a PNG, JPEG or WebP image.');
|
|
109
|
+
const getAvatar = async () => { const x = await this.gateway.call(64, 'PullChatsByIdsRequest', { chatIds: [chatId] }, { operation: 'group-avatar-read' }); const chat = this.gateway.decode('PullChatsByIdsResponse', x.packet.payload).chats?.[chatId]; if (!chat || ![2, 3].includes(chat.type)) throw new FeishuError('NOT_FOUND', 'Group was not found.'); return chat.avatar?.key || null; };
|
|
110
|
+
const before = await getAvatar();
|
|
111
|
+
dispatched = true;
|
|
112
|
+
const r = await this.gateway.call(72, 'PatchGroupChatRequest', { chatId, iconData: `data:${mime};base64,${b.toString('base64')}`, updateFields: [2] }, { mutating: true, operation: 'group-avatar-set' });
|
|
113
|
+
const result = decodedPayload(this.gateway, r, 'PatchGroupChatResponse', 'group-avatar-set');
|
|
114
|
+
if (!result.chat?.id || String(result.chat.id) !== chatId) throw new FeishuError('EFFECT_UNKNOWN', 'Group avatar update was not confirmed.', { requestId: r.requestId });
|
|
115
|
+
try { const after = await getAvatar(); return { status: after && after !== before ? 'verified' : 'submitted_unconfirmed', chatId, requestId: r.requestId }; }
|
|
116
|
+
catch { return { status: 'submitted_unconfirmed', chatId, requestId: r.requestId }; }
|
|
117
|
+
} catch (e) { if (e instanceof FeishuError) throw e; throw new FeishuError(dispatched ? 'EFFECT_UNKNOWN' : 'FILE_UNAVAILABLE', dispatched ? 'The avatar update could not be confirmed; inspect before retrying.' : 'Cannot read the image or group.'); }
|
|
118
|
+
finally { await file?.close(); }
|
|
119
|
+
}
|
|
120
|
+
|
|
27
121
|
async status() {
|
|
28
122
|
return { status: 'ready', identity: 'user', user: await this.gateway.authenticate() };
|
|
29
123
|
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { Writable } from 'node:stream';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { open, lstat, realpath, chmod, unlink } from 'node:fs/promises';
|
|
6
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
7
|
+
import { FeishuError, requireInt64Id } from './errors.js';
|
|
8
|
+
|
|
9
|
+
const obj = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
10
|
+
const only = (x, fields) => obj(x) && Object.keys(x).every(k => fields.includes(k));
|
|
11
|
+
const invalid = message => { throw new FeishuError('LISTEN_CONFIG_INVALID', message); };
|
|
12
|
+
function stringArray(value, label, max = 100) {
|
|
13
|
+
if (!Array.isArray(value) || value.length > max || value.some(x => typeof x !== 'string' || Buffer.byteLength(x)>4096)) invalid(`Invalid ${label}.`);
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function script(value, label) {
|
|
17
|
+
if (!only(value,['path','args','timeoutSeconds']) || typeof value.path !== 'string' || !isAbsolute(value.path) || value.path.includes('\0')) invalid(`Invalid ${label}.`);
|
|
18
|
+
const args = value.args === undefined ? [] : stringArray(value.args, `${label} arguments`, 32);
|
|
19
|
+
const timeoutSeconds = value.timeoutSeconds ?? 30;
|
|
20
|
+
if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 600) invalid(`Invalid ${label} timeout.`);
|
|
21
|
+
return {path:value.path,args,timeoutSeconds};
|
|
22
|
+
}
|
|
23
|
+
export function parseListenRules(raw) {
|
|
24
|
+
if (!only(raw,['version','rules']) || raw.version!==1 || !Array.isArray(raw.rules) || !raw.rules.length || raw.rules.length>100) invalid('Use version 1 and 1 to 100 rules.');
|
|
25
|
+
const names=new Set(), chats=new Set();
|
|
26
|
+
const rules=raw.rules.map(r=>{
|
|
27
|
+
if (!only(r,['name','chatIds','senderIds','types','contains','excludeContains','excludeSelf','filter','run']) || typeof r.name!=='string' || !r.name.trim() || r.name.length>100 || names.has(r.name)) invalid('Invalid or duplicate rule name.');
|
|
28
|
+
names.add(r.name);
|
|
29
|
+
const chatIds=stringArray(r.chatIds,'chat IDs'); if (!chatIds.length) invalid('Every rule needs at least one chat ID.');
|
|
30
|
+
for(const id of chatIds){requireInt64Id(id,'chat ID');chats.add(id);}
|
|
31
|
+
const senderIds=r.senderIds===undefined?null:stringArray(r.senderIds,'sender IDs'); if(senderIds)for(const id of senderIds)requireInt64Id(id,'sender ID');
|
|
32
|
+
const types=r.types===undefined?null:r.types;
|
|
33
|
+
if(types!==null&&(!Array.isArray(types)||types.length>100||types.some(x=>!Number.isInteger(x)||x<0)))invalid('Invalid message types.');
|
|
34
|
+
for(const k of ['contains','excludeContains'])if(r[k]!==undefined&&(typeof r[k]!=='string'||!r[k]||Buffer.byteLength(r[k])>4096))invalid(`Invalid ${k}.`);
|
|
35
|
+
if(r.excludeSelf!==undefined&&typeof r.excludeSelf!=='boolean')invalid('Invalid excludeSelf.');
|
|
36
|
+
return {name:r.name,chatIds,senderIds,types,contains:r.contains,excludeContains:r.excludeContains,excludeSelf:r.excludeSelf===true,filter:r.filter===undefined?null:script(r.filter,'filter'),run:script(r.run,'run')};
|
|
37
|
+
});
|
|
38
|
+
if(chats.size>100)invalid('At most 100 distinct chats are allowed.');
|
|
39
|
+
return {rules,chatIds:[...chats]};
|
|
40
|
+
}
|
|
41
|
+
export async function loadListenRules(path) {
|
|
42
|
+
let f;
|
|
43
|
+
try { f=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW); const st=await f.stat();
|
|
44
|
+
if(!st.isFile()||st.size>65536||![0,process.getuid?.()].includes(st.uid)||(st.mode&0o022)) throw new Error();
|
|
45
|
+
const input=await f.readFile('utf8');return parseListenRules(JSON.parse(input));
|
|
46
|
+
} catch(e) { if(e instanceof FeishuError)throw e;throw new FeishuError('LISTEN_CONFIG_INVALID','Cannot read a protected rules file.'); }
|
|
47
|
+
finally { await f?.close(); }
|
|
48
|
+
}
|
|
49
|
+
function matches(rule,event,selfId) {
|
|
50
|
+
return event.kind==='message'&&rule.chatIds.includes(event.chatId)&&(!rule.senderIds||rule.senderIds.includes(event.senderId))&&(!rule.types||rule.types.includes(event.type))
|
|
51
|
+
&&(!rule.excludeSelf||(selfId&&event.senderId!==selfId))&&(rule.contains===undefined||(event.text||'').includes(rule.contains))&&(rule.excludeContains===undefined||!(event.text||'').includes(rule.excludeContains));
|
|
52
|
+
}
|
|
53
|
+
function runScript(config,event) {
|
|
54
|
+
return new Promise(resolve=>{
|
|
55
|
+
let child, settled=false, timer;
|
|
56
|
+
const done=(result)=>{if(settled)return;settled=true;clearTimeout(timer);resolve(result)};
|
|
57
|
+
try { child=spawn(config.path,config.args,{shell:false,stdio:['pipe','ignore','ignore'],env:{PATH:process.env.PATH||'/usr/bin:/bin',HOME:process.env.HOME||'',LANG:process.env.LANG||'C.UTF-8'}}); }
|
|
58
|
+
catch {return done({ok:false,reason:'spawn_failed'});}
|
|
59
|
+
timer=setTimeout(()=>{child.kill('SIGKILL');done({ok:false,reason:'timeout'})},config.timeoutSeconds*1000);
|
|
60
|
+
child.on('error',()=>done({ok:false,reason:'spawn_failed'}));
|
|
61
|
+
child.on('close',code=>done({ok:code===0,code}));
|
|
62
|
+
child.stdin.on('error',()=>{});child.stdin.end(`${JSON.stringify(event)}\n`);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export function createRuleOutput({rules,selfId,log=process.stderr}) {
|
|
66
|
+
return new Writable({write(chunk,_encoding,callback){(async()=>{
|
|
67
|
+
const event=JSON.parse(chunk.toString());
|
|
68
|
+
if(event.kind!=='message'){log.write(`${JSON.stringify(event)}\n`);return;}
|
|
69
|
+
for(const rule of rules){if(!matches(rule,event,selfId))continue;
|
|
70
|
+
if(rule.filter){const result=await runScript(rule.filter,event);if(!result.ok){if(result.code!==1)log.write(`${JSON.stringify({kind:'filter_error',rule:rule.name,reason:result.reason||'exit',code:result.code})}\n`);continue;}}
|
|
71
|
+
const result=await runScript(rule.run,event);if(!result.ok)log.write(`${JSON.stringify({kind:'script_error',rule:rule.name,reason:result.reason||'exit',code:result.code})}\n`);
|
|
72
|
+
}
|
|
73
|
+
})().then(()=>callback(),callback)}});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Exposes only the preselected chat stream, protected by the socket and parent directory permissions.
|
|
77
|
+
export async function startListenService(socketPath) {
|
|
78
|
+
if(typeof socketPath!=='string'||!isAbsolute(socketPath)||socketPath.endsWith('/'))throw new FeishuError('INVALID_ARGUMENT','Use an absolute socket path.');
|
|
79
|
+
let parent;try{parent=await realpath(dirname(socketPath));}catch{throw new FeishuError('LISTEN_SOCKET_INVALID','The socket directory must exist.');}
|
|
80
|
+
const st=await lstat(parent);if(!st.isDirectory()||st.uid!==process.getuid?.()||(st.mode&0o022))throw new FeishuError('LISTEN_SOCKET_INVALID','The socket directory must be owned by the user and not writable by others.');
|
|
81
|
+
const path=join(parent,socketPath.slice(socketPath.lastIndexOf('/')+1));
|
|
82
|
+
try{await lstat(path);throw new FeishuError('LISTEN_SOCKET_EXISTS','The socket path already exists.');}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
83
|
+
const clients=new Set();
|
|
84
|
+
const server=http.createServer((req,res)=>{
|
|
85
|
+
if(req.method!=='GET'||req.url!=='/events'){res.writeHead(404);res.end();return;}
|
|
86
|
+
if(clients.size>=20){res.writeHead(503);res.end();return;}
|
|
87
|
+
res.writeHead(200,{'content-type':'application/x-ndjson','cache-control':'no-store','x-content-type-options':'nosniff'});res.flushHeaders();clients.add(res);res.on('close',()=>clients.delete(res));
|
|
88
|
+
});
|
|
89
|
+
const oldMask=process.umask(0o077);
|
|
90
|
+
try { await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve)}); } finally { process.umask(oldMask); }
|
|
91
|
+
await chmod(path,0o600);const inode=(await lstat(path)).ino;
|
|
92
|
+
const output=new Writable({write(chunk,_encoding,callback){for(const client of clients){if(client.writableLength>1024*1024){client.destroy();continue;}client.write(chunk);}callback();}});
|
|
93
|
+
return {path,output,async close(){for(const c of clients)c.destroy();await new Promise(resolve=>server.close(resolve));try{const now=await lstat(path);if(now.ino===inode&&now.isSocket())await unlink(path);}catch(e){if(e.code!=='ENOENT')throw e;}}};
|
|
94
|
+
}
|
package/src/listen.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { gunzipSync, inflateSync } from 'node:zlib';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import { FeishuError, requireInt64Id } from './errors.js';
|
|
6
|
+
import { LarkMateClient } from './client.js';
|
|
7
|
+
|
|
8
|
+
const MAX_FRAME = 8 * 1024 * 1024;
|
|
9
|
+
const asString = x => x == null ? null : String(x);
|
|
10
|
+
|
|
11
|
+
// Only use tenant domains supplied by Feishu, constrained to its known domains.
|
|
12
|
+
function tenantHosts(tenant) {
|
|
13
|
+
const name = tenant?.tenant_domain;
|
|
14
|
+
const hosts = [];
|
|
15
|
+
if (typeof name === 'string' && /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(name)) hosts.push(`${name}.larkoffice.com`);
|
|
16
|
+
const full = tenant?.tenant_full_domain;
|
|
17
|
+
if (typeof full === 'string' && /^(?:[a-z0-9-]+\.)+(?:feishu\.cn|larkoffice\.com|larksuite\.com)$/i.test(full)) hosts.push(full);
|
|
18
|
+
return [...new Set(hosts)];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function connectionUrl(gateway) {
|
|
22
|
+
await gateway.authenticate();
|
|
23
|
+
const userResponse = await gateway.request(`${gateway.endpoints.user}?app_id=12&_t=${Date.now()}`, {
|
|
24
|
+
headers: { ...gateway.jsonHeaders(), 'x-csrf-token': gateway.jar.get('swp_csrf_token') || '' },
|
|
25
|
+
}, { operation: 'listen-profile' });
|
|
26
|
+
let profile; try { profile = await userResponse.json(); } catch { throw new FeishuError('INVALID_RESPONSE', 'Cannot read account information.'); }
|
|
27
|
+
let appKey;
|
|
28
|
+
for (const host of tenantHosts(profile?.data?.user?.tenant)) {
|
|
29
|
+
try {
|
|
30
|
+
const response = await gateway.request(`https://${host}/next/messenger/`, { headers: gateway.baseHeaders(), redirect: 'error' }, { operation: 'listen-config' });
|
|
31
|
+
const page = await response.text();
|
|
32
|
+
appKey = page.match(/appKey\s*:\s*["']([^"']+)["']/)?.[1];
|
|
33
|
+
if (appKey) break;
|
|
34
|
+
} catch { /* Try the next Feishu tenant host. */ }
|
|
35
|
+
}
|
|
36
|
+
if (!appKey) throw new FeishuError('LISTEN_CONFIG_UNAVAILABLE', 'Cannot obtain the Feishu connection configuration.');
|
|
37
|
+
const localDevice = gateway.jar.get('passport_web_did') || '';
|
|
38
|
+
const response = await gateway.request(`https://login.feishu.cn/suite/passport/frontier_ticket/?local_device_id=${encodeURIComponent(localDevice)}`, { headers: gateway.baseHeaders(), redirect: 'error' }, { operation: 'listen-ticket' });
|
|
39
|
+
let ticket; try { ticket = await response.json(); } catch { throw new FeishuError('INVALID_RESPONSE', 'Cannot read the connection ticket.'); }
|
|
40
|
+
if (typeof ticket.ticket !== 'string' || !ticket.ticket || !/^\d{1,30}$/.test(String(ticket.device_id || ''))) throw new FeishuError('AUTH_FAILED', 'Cannot obtain a connection ticket.');
|
|
41
|
+
const device = String(ticket.device_id);
|
|
42
|
+
const params = new URLSearchParams({ accept_encoding:'gzip', sdk_version:'7.72.8', version_code:'7.72.8', type:'sdk_main', platform:'', terminal_type:'2', device_model:'', lark_version:'7.72.0', net_status:'5', lark_env:'online', request_id:randomBytes(5).toString('hex'), aid:'1', fpid:'2', device_id:device,
|
|
43
|
+
access_key:createHash('md5').update(`2${appKey}${device}f8a69f1719916z`).digest('hex'), ticket:ticket.ticket });
|
|
44
|
+
return `wss://msg-frontier.feishu.cn/ws/v2?${params}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function frame(gateway, packet) {
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
return gateway.encode('Frame', { seqid:String(Math.floor(now/1000)), logid:String(Math.floor(now/1000)), service:1, method:1,
|
|
50
|
+
headers:[{key:'x-request-time',value:String(now)}], payloadType:'pb', payload:gateway.encode('Packet',packet) });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function decodePush(gateway, bytes) {
|
|
54
|
+
if (bytes.byteLength > MAX_FRAME) throw new FeishuError('LISTEN_FRAME_INVALID', 'The event frame is too large.');
|
|
55
|
+
const envelope = gateway.decode('Frame', bytes);
|
|
56
|
+
const encoding = (envelope.payloadEncoding || '').toLowerCase(), raw = envelope.payload;
|
|
57
|
+
if (encoding === 'json') return { packet: null, messages: [] };
|
|
58
|
+
if (!['','gzip','deflate','zlib','identity','pb'].includes(encoding)) throw new FeishuError('LISTEN_FRAME_INVALID', 'Unknown event encoding.');
|
|
59
|
+
const payload = encoding === 'gzip' || (!encoding && raw?.[0] === 0x1f && raw?.[1] === 0x8b)
|
|
60
|
+
? gunzipSync(raw, { maxOutputLength: MAX_FRAME })
|
|
61
|
+
: ['deflate','zlib'].includes(encoding) ? inflateSync(raw, { maxOutputLength: MAX_FRAME }) : raw;
|
|
62
|
+
const packet = gateway.decode('Packet', payload);
|
|
63
|
+
const messages = packet.cmd === 6 ? Object.values(gateway.decode('PushMessagesRequest', packet.payload).messages || {}) : [];
|
|
64
|
+
return { packet, messages };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function formatMessage(gateway, m) {
|
|
68
|
+
let text = null, textIncomplete = false;
|
|
69
|
+
if (m.content?.length && [2, 4].includes(m.type)) {
|
|
70
|
+
try {
|
|
71
|
+
const c = gateway.decode(m.type === 4 ? 'TextContent' : 'PostContent', m.content);
|
|
72
|
+
text = c.richText?.innerText || c.text || null;
|
|
73
|
+
if (!text && c.richText?.elementIds?.length) {
|
|
74
|
+
let pieces = [];
|
|
75
|
+
for (const id of c.richText.elementIds) {
|
|
76
|
+
const element = c.richText.elements?.dictionary?.[id];
|
|
77
|
+
if (element && [1,5].includes(element.tag)) {
|
|
78
|
+
const property = gateway.decode(element.tag === 1 ? 'TextProperty' : 'AtProperty', element.property);
|
|
79
|
+
if (typeof property.content === 'string') pieces.push(property.content); else textIncomplete = true;
|
|
80
|
+
} else textIncomplete = true;
|
|
81
|
+
}
|
|
82
|
+
text = pieces.join('') || null;
|
|
83
|
+
}
|
|
84
|
+
} catch { textIncomplete = true; }
|
|
85
|
+
}
|
|
86
|
+
return { kind:'message', id:asString(m.id), chatId:asString(m.chatId), senderId:asString(m.fromId), position:Number.isInteger(m.position)?m.position:null,
|
|
87
|
+
type:m.type, text, textIncomplete, createTime:asString(m.createTime), rootId:asString(m.rootId), parentId:asString(m.parentId) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function listen({ gateway, chatIds, output = process.stdout, log = process.stderr, signal, WebSocketImpl = WebSocket }) {
|
|
91
|
+
if (!Array.isArray(chatIds) || !chatIds.length || chatIds.length > 100) throw new FeishuError('INVALID_ARGUMENT', 'Specify 1 to 100 chat IDs.');
|
|
92
|
+
const selected = new Set(chatIds.map(id => requireInt64Id(id, 'chat ID')));
|
|
93
|
+
const client = new LarkMateClient(gateway), seen = new Set(), seenOrder = [], positions = new Map();
|
|
94
|
+
const emit = async value => { if (!output.write(`${JSON.stringify(value)}\n`)) await once(output, 'drain'); };
|
|
95
|
+
const remember = id => { if (!id || seen.has(id)) return false; seen.add(id); seenOrder.push(id); if (seenOrder.length > 10000) seen.delete(seenOrder.shift()); return true; };
|
|
96
|
+
const writeMessage = async message => { if (!selected.has(message.chatId) || !remember(message.id)) return;
|
|
97
|
+
if (Number.isInteger(message.position)) positions.set(message.chatId, Math.max(positions.get(message.chatId) ?? 0, message.position)); await emit(message); };
|
|
98
|
+
for (const chatId of selected) { const info = await client.chatInfo(chatId); if (!Number.isInteger(info.lastMessagePosition)) throw new FeishuError('POSITION_UNAVAILABLE', 'Cannot read the initial message position.'); positions.set(chatId, info.lastMessagePosition); }
|
|
99
|
+
const backfill = async () => { for (const chatId of selected) {
|
|
100
|
+
const latest = (await client.chatInfo(chatId)).lastMessagePosition, from = positions.get(chatId) + 1;
|
|
101
|
+
if (!Number.isInteger(latest)) { await emit({ kind:'gap', chatId, reason:'position_unavailable' }); continue; }
|
|
102
|
+
if (latest - from >= 10000) { await emit({ kind:'gap', chatId, reason:'backfill_limit', fromPosition:from, throughPosition:latest }); positions.set(chatId,latest); continue; }
|
|
103
|
+
for (let start=from; start<=latest; start+=100) {
|
|
104
|
+
const page = await client.history({chatId,start,limit:Math.min(100,latest-start+1)});
|
|
105
|
+
for (const m of page.items) await writeMessage({kind:'message',chatId,...m,backfill:true});
|
|
106
|
+
if (page.omittedPositions) await emit({kind:'gap',chatId,reason:'positions_unavailable',start,count:page.omittedPositions});
|
|
107
|
+
}
|
|
108
|
+
positions.set(chatId, Math.max(positions.get(chatId), latest));
|
|
109
|
+
} };
|
|
110
|
+
let attempt = 0;
|
|
111
|
+
while (!signal?.aborted) {
|
|
112
|
+
let socket, heartbeat, pending = Promise.resolve(), connected = false, failure = null, reported = false;
|
|
113
|
+
try {
|
|
114
|
+
const url = await connectionUrl(gateway);
|
|
115
|
+
socket = new WebSocketImpl(url); socket.binaryType = 'arraybuffer';
|
|
116
|
+
await new Promise((resolve,reject) => {
|
|
117
|
+
const cleanup = () => { clearTimeout(timeout); signal?.removeEventListener('abort',abort); };
|
|
118
|
+
const abort = () => { cleanup(); socket.close(); reject(new FeishuError('LISTEN_STOPPED','Listener stopped.')); };
|
|
119
|
+
const timeout = setTimeout(() => { cleanup(); socket.close(); reject(new FeishuError('LISTEN_CONNECT_FAILED','Connection timed out.')); },15000);
|
|
120
|
+
socket.addEventListener('open',()=>{cleanup();resolve();},{once:true});
|
|
121
|
+
socket.addEventListener('error',()=>{cleanup();reject(new FeishuError('LISTEN_CONNECT_FAILED','Feishu rejected the message connection.'));},{once:true});
|
|
122
|
+
socket.addEventListener('close',()=>{cleanup();reject(new FeishuError('LISTEN_CONNECT_FAILED','Feishu closed the message connection.'));},{once:true});
|
|
123
|
+
signal?.addEventListener('abort',abort,{once:true});
|
|
124
|
+
});
|
|
125
|
+
connected = true; attempt = 0;
|
|
126
|
+
const closed = new Promise(resolve => socket.addEventListener('close',resolve,{once:true}));
|
|
127
|
+
const stop = () => socket.close(); signal?.addEventListener('abort',stop,{once:true});
|
|
128
|
+
const initialBackfill = backfill();
|
|
129
|
+
pending = initialBackfill;
|
|
130
|
+
let queued = 0, queuedBytes = 0;
|
|
131
|
+
socket.addEventListener('message', event => {
|
|
132
|
+
const size = event.data?.byteLength;
|
|
133
|
+
if (!Number.isSafeInteger(size) || size > MAX_FRAME || ++queued > 500 || (queuedBytes += size) > 16 * 1024 * 1024) { failure = new FeishuError('LISTEN_BACKPRESSURE', 'The event queue is full or a frame is invalid.'); socket.close(); return; }
|
|
134
|
+
pending = pending.then(async () => {
|
|
135
|
+
const {packet,messages} = decodePush(gateway,new Uint8Array(event.data));
|
|
136
|
+
if (!packet) return;
|
|
137
|
+
if (packet.sid) socket.send(frame(gateway,{cmd:1,payloadType:1,sid:packet.sid,payload:Uint8Array.of(8,0)}));
|
|
138
|
+
if (packet.cmd === 6000) {
|
|
139
|
+
const sids = [...new Set([packet.sid, ...(packet.compactedSids || []).map(String)].filter(Boolean))];
|
|
140
|
+
if (!sids.length) { await emit({kind:'gap',reason:'missing_push_identifiers'}); return; }
|
|
141
|
+
try {
|
|
142
|
+
const result = await gateway.call(12001,'PullPacketsBySidsRequest',{sids},{version:'5.7.0',operation:'listen-pull-packets'});
|
|
143
|
+
const packets = gateway.decode('PullPacketsBySidsResponse',result.packet.payload).packets || {};
|
|
144
|
+
for (const p of Object.values(packets)) if (p.cmd === 6) for (const m of Object.values(gateway.decode('PushMessagesRequest',p.payload).messages || {})) await writeMessage(formatMessage(gateway,m));
|
|
145
|
+
if (sids.some(sid => !Object.hasOwn(packets,sid))) await emit({kind:'gap',reason:'missing_push_packets'});
|
|
146
|
+
} catch { await emit({kind:'gap',reason:'push_pull_failed'}); }
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (packet.cmd === 134) {
|
|
150
|
+
try {
|
|
151
|
+
const batch = gateway.decode('PushBatchCopyMessages',packet.payload);
|
|
152
|
+
if (batch.lastMessage?.id) await writeMessage(formatMessage(gateway,batch.lastMessage));
|
|
153
|
+
const ids = [...new Set((batch.messageIds || []).map(String))].filter(id=>id!==String(batch.lastMessage?.id || ''));
|
|
154
|
+
if (ids.length) {
|
|
155
|
+
const result = await gateway.call(8,'PullMessagesByIdsRequest',{messageIds:ids},{version:'5.7.0',operation:'listen-pull-messages'});
|
|
156
|
+
const found = gateway.decode('PullMessagesByIdsResponse',result.packet.payload).messages || {};
|
|
157
|
+
for (const m of Object.values(found)) await writeMessage(formatMessage(gateway,m));
|
|
158
|
+
if (ids.some(id => !Object.hasOwn(found,id))) await emit({kind:'gap',reason:'missing_forwarded_messages'});
|
|
159
|
+
}
|
|
160
|
+
} catch { await emit({kind:'gap',reason:'forwarded_messages_pull_failed'}); }
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
for (const m of messages) await writeMessage(formatMessage(gateway,m));
|
|
164
|
+
}).catch(error => { failure = error; socket.close(); }).finally(() => { queued--; queuedBytes -= size; });
|
|
165
|
+
});
|
|
166
|
+
heartbeat = setInterval(()=>{ try { if(socket.readyState === 1) socket.send(frame(gateway,{cmd:4,payloadType:1})); } catch { socket.close(); } },30000);
|
|
167
|
+
log.write('LarkMate: message listener connected.\n');
|
|
168
|
+
await initialBackfill; await closed; await pending; signal?.removeEventListener('abort',stop);
|
|
169
|
+
if (failure) throw failure;
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (signal?.aborted) break;
|
|
172
|
+
await emit({kind:'gap',reason:connected?'connection_interrupted':'connection_failed',code:error.code || 'LISTEN_FAILED'});
|
|
173
|
+
reported = true;
|
|
174
|
+
} finally { clearInterval(heartbeat); if (socket && socket.readyState < 2) socket.close(); }
|
|
175
|
+
if (signal?.aborted) break;
|
|
176
|
+
if (connected && !reported) await emit({kind:'gap',reason:'connection_interrupted'});
|
|
177
|
+
try { await delay(Math.min(30000,1000 * 2**Math.min(attempt++,5)), undefined, { signal }); } catch (error) { if (!signal?.aborted) throw error; }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -79,7 +79,7 @@ export function osDelegateProxy(owner, launcher, service, getCommand) {
|
|
|
79
79
|
if (method === 'then' || typeof method !== 'string') return undefined;
|
|
80
80
|
return (...args) => {
|
|
81
81
|
const command = getCommand();
|
|
82
|
-
if (service === 'client' && ['sendFile', 'sendImage'].includes(method)) {
|
|
82
|
+
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) {
|
|
83
83
|
const { chatId, path } = args[0];
|
|
84
84
|
return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'upload', args: [{ chatId }] }, inputPath: path });
|
|
85
85
|
}
|
package/src/os-delegate.js
CHANGED
|
@@ -77,14 +77,14 @@ export async function checkDelegation({ profile, uid, request, file }) {
|
|
|
77
77
|
}
|
|
78
78
|
|
|
79
79
|
export async function invokeDelegated({ profile, uid, request, getServices, filePath }) {
|
|
80
|
-
const fileOp = ['send-file', 'send-image', 'download-file'].includes(request?.command);
|
|
80
|
+
const fileOp = ['send-file', 'send-image', 'group-avatar-set', 'download-file'].includes(request?.command);
|
|
81
81
|
if (fileOp && request.service !== 'files') noAccess();
|
|
82
82
|
if (!fileOp && request.service === 'files') noAccess();
|
|
83
83
|
let file;
|
|
84
|
-
if (
|
|
84
|
+
if (['send-file', 'send-image', 'group-avatar-set'].includes(request.command)) {
|
|
85
85
|
if (!filePath || !nameOk(request.fileName)) fail('INVALID_REQUEST', 'Invalid file transfer.');
|
|
86
86
|
const info = await stat(filePath);
|
|
87
|
-
if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (
|
|
87
|
+
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.');
|
|
88
88
|
const hash = createHash('sha256'); for await (const chunk of createReadStream(filePath)) hash.update(chunk);
|
|
89
89
|
file = { name: request.fileName, size: info.size, sha256: hash.digest('hex') };
|
|
90
90
|
}
|
|
@@ -106,7 +106,7 @@ export async function invokeDelegated({ profile, uid, request, getServices, file
|
|
|
106
106
|
}
|
|
107
107
|
const client = services.client, o = args[0];
|
|
108
108
|
if (method === 'upload') {
|
|
109
|
-
try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : 'sendImage']({ chatId: o.chatId, path: filePath }) }; }
|
|
109
|
+
try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : rpc.command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: o.chatId, path: filePath }) }; }
|
|
110
110
|
catch (error) { if (!(error instanceof FeishuError)) fail('EFFECT_UNKNOWN', 'The delegated write could not be confirmed; inspect before retrying.'); throw error; }
|
|
111
111
|
}
|
|
112
112
|
return { download: true, client, options: o };
|
|
@@ -126,7 +126,7 @@ export async function serveOne({ input, output, uid, profile, getServices }) {
|
|
|
126
126
|
try { request = JSON.parse(header.subarray(0, end).toString('utf8')); } catch { fail('INVALID_REQUEST', 'Invalid request.'); }
|
|
127
127
|
data = header.subarray(end + 1); header = null;
|
|
128
128
|
if (!only(request, ['command', 'service', 'method', 'args', 'fileName', 'size'])) fail('INVALID_REQUEST', 'Invalid request.');
|
|
129
|
-
const upload =
|
|
129
|
+
const upload = ['send-file', 'send-image', 'group-avatar-set'].includes(request.command);
|
|
130
130
|
if (upload) {
|
|
131
131
|
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.');
|
|
132
132
|
const { size, fileName, ...rpc } = request;
|
package/src/session-controls.js
CHANGED
|
@@ -198,6 +198,30 @@ export class SessionControls {
|
|
|
198
198
|
return !x.isRemind;
|
|
199
199
|
}
|
|
200
200
|
|
|
201
|
+
async preferences(chatId) {
|
|
202
|
+
numeric(chatId, 'chat ID');
|
|
203
|
+
const p = await this.read(62, 'PullChatSettingsRequest', { chatIds: [chatId] }, 'PullChatSettingsResponse');
|
|
204
|
+
const x = p.chatSettings?.[chatId];
|
|
205
|
+
if (!x) throw new FeishuError('STATE_UNAVAILABLE', 'Conversation settings were not returned.');
|
|
206
|
+
return { chatId, muteAtAll: own(x, 'isMuteAtAll') ? x.isMuteAtAll : null,
|
|
207
|
+
autoTranslate: own(x, 'isAutoTranslate') ? x.isAutoTranslate : null };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async setPreference({ chatId, muteAtAll, autoTranslate }) {
|
|
211
|
+
numeric(chatId, 'chat ID');
|
|
212
|
+
const settings = {}, fields = [];
|
|
213
|
+
for (const [name, value, field, id] of [['muteAtAll', muteAtAll, 'isMuteAtAll', 6], ['autoTranslate', autoTranslate, 'isAutoTranslate', 4]]) {
|
|
214
|
+
if (value !== undefined) {
|
|
215
|
+
if (typeof value !== 'boolean') throw new FeishuError('INVALID_ARGUMENT', `${name} must be a boolean.`);
|
|
216
|
+
settings[field] = value; fields.push(id);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (!fields.length) throw new FeishuError('INVALID_ARGUMENT', 'Specify at least one preference.');
|
|
220
|
+
const result = await this.verified(() => this.write(60, 'PatchChatSettingRequest', { chatId, chatSetting: settings, updateChatSettingField: fields }),
|
|
221
|
+
async () => { const after = await this.preferences(chatId); return (muteAtAll === undefined || after.muteAtAll === muteAtAll) && (autoTranslate === undefined || after.autoTranslate === autoTranslate); });
|
|
222
|
+
return { ...result, chatId };
|
|
223
|
+
}
|
|
224
|
+
|
|
201
225
|
async setMute(chatId, enabled) {
|
|
202
226
|
const before = await this.muted(chatId);
|
|
203
227
|
if (before === enabled) return { status: 'already_set', chatId, muted: enabled };
|