larkmate 0.1.13 → 0.1.15
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 +14 -5
- package/bin/larkmate.js +51 -2
- package/bin/os-delegate-helper.js +2 -1
- package/docs/agent-broker.md +1 -1
- package/package.json +1 -1
- package/proto/lark.proto +80 -1
- package/skills/larkmate/references/chats.md +10 -0
- package/skills/larkmate/references/writes.md +17 -1
- package/src/agent-broker.js +30 -4
- package/src/agent-files.js +3 -3
- package/src/client.js +94 -0
- package/src/group-management.js +63 -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] 在已扫描的历史消息中按关键词、发送者和时间筛选
|
|
@@ -53,11 +58,15 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
53
58
|
- [x] 给消息添加和取消表情回应
|
|
54
59
|
- [x] 获取消息链接
|
|
55
60
|
- 群聊
|
|
56
|
-
- [x]
|
|
57
|
-
- [x]
|
|
58
|
-
- [x]
|
|
59
|
-
- [x]
|
|
60
|
-
- [
|
|
61
|
+
- [x] 查询群信息、成员、管理员和入退群记录
|
|
62
|
+
- [x] 修改群名称、描述、头像和本人群昵称
|
|
63
|
+
- [x] 邀请、移除成员,退出或解散群聊
|
|
64
|
+
- [x] 管理员设置和群主转让
|
|
65
|
+
- [x] 查询和调整入群审批、发言、邀请及其他群设置
|
|
66
|
+
- [x] 创建群邀请链接,查询和处理入群申请
|
|
67
|
+
- [x] 查询群公告、查询和设置机器人的移除限制
|
|
68
|
+
- [ ] 修改群公告
|
|
69
|
+
- [ ] 管理群机器人及其配置
|
|
61
70
|
- 飞书任务
|
|
62
71
|
- [x] 查询任务中心与任务视图,按关键词搜索任务
|
|
63
72
|
- [x] 新建、编辑、完成、重开和删除任务
|
package/bin/larkmate.js
CHANGED
|
@@ -14,10 +14,11 @@ import { SidebarFilters } from '../src/sidebar-filters.js';
|
|
|
14
14
|
import { FeedGroups } from '../src/feed-groups.js';
|
|
15
15
|
import { Tasks } from '../src/tasks.js';
|
|
16
16
|
import { Calendar } from '../src/calendar.js';
|
|
17
|
+
import { GroupManagement, groupSettingsSchema } from '../src/group-management.js';
|
|
17
18
|
|
|
18
19
|
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
19
20
|
const program = new Command();
|
|
20
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
21
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.15');
|
|
21
22
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
22
23
|
program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
|
|
23
24
|
program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
|
|
@@ -73,6 +74,7 @@ async function sidebar() {
|
|
|
73
74
|
return new SidebarFilters(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) }));
|
|
74
75
|
}
|
|
75
76
|
|
|
77
|
+
async function groups() { const remote = proxy('groups'); return remote || new GroupManagement(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
76
78
|
async function calendar() { const remote = proxy('calendar'); return remote || new Calendar(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
77
79
|
async function feeds() { const remote = proxy('feeds'); return remote || new FeedGroups(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
78
80
|
async function tasks() { const remote = proxy('tasks'); return remote || new Tasks(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
@@ -111,7 +113,7 @@ program.command('broker-serve').description('Start a restricted local agent brok
|
|
|
111
113
|
let promise;
|
|
112
114
|
const getServices = () => promise ||= (async () => {
|
|
113
115
|
const gateway = new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) });
|
|
114
|
-
return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway) };
|
|
116
|
+
return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway), groups: new GroupManagement(gateway) };
|
|
115
117
|
})().catch(error => { promise = undefined; throw error; });
|
|
116
118
|
const broker = await startBroker({ socketPath: o.socket, policy, token, getServices });
|
|
117
119
|
output({ status: 'listening', socket: broker.socketPath });
|
|
@@ -276,6 +278,13 @@ for (const [command, enabled] of [['label-add', true], ['label-remove', false]])
|
|
|
276
278
|
}
|
|
277
279
|
program.command('chat-state').description('Read pin, flag, notification and read state for a conversation.')
|
|
278
280
|
.requiredOption('--chat <id>', 'numeric chat ID').action(async o => output(await (await controls()).state(o.chat)));
|
|
281
|
+
program.command('chat-preferences').description('Read conversation notification and translation preferences.').requiredOption('--chat <id>')
|
|
282
|
+
.action(async o => output(await (await controls()).preferences(o.chat)));
|
|
283
|
+
program.command('chat-preferences-set').description('Update conversation notification and translation preferences.').requiredOption('--chat <id>')
|
|
284
|
+
.option('--mute-at-all <bool>', 'suppress @all notifications: true or false').option('--auto-translate <bool>', 'automatically translate messages: true or false')
|
|
285
|
+
.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) })); });
|
|
286
|
+
program.command('chat-clear-history').description('Clear this conversation history through its current last message.').requiredOption('--chat <id>')
|
|
287
|
+
.action(async o => output(await (await client()).clearChatHistory({ chatId: o.chat })));
|
|
279
288
|
for (const [command, method, enabled, description] of [
|
|
280
289
|
['pin', 'pin', true, 'Pin a conversation.'], ['unpin', 'pin', false, 'Unpin a conversation.'],
|
|
281
290
|
['mark', 'mark', true, 'Flag a conversation.'], ['unmark', 'mark', false, 'Remove a conversation flag.'],
|
|
@@ -429,6 +438,33 @@ program.command('favorites').description('Read the first page of your favorite m
|
|
|
429
438
|
.option('--limit <number>', 'maximum items, 1 to 100', '50')
|
|
430
439
|
.action(async o => output(await (await client()).favorites({ limit: Number(o.limit) })));
|
|
431
440
|
|
|
441
|
+
program.command('group-link').description('Create a group invitation link.').requiredOption('--chat <id>').option('--days <number>','validity days','7').option('--unlimited','no expiration')
|
|
442
|
+
.action(async o=>output(await (await groups()).link({chatId:o.chat,days:Number(o.days),unlimited:!!o.unlimited})));
|
|
443
|
+
program.command('group-requests').description('List pending or processed join applications.').requiredOption('--chat <id>').option('--cursor <cursor>','page cursor','0')
|
|
444
|
+
.action(async o=>output(await (await groups()).requests({chatId:o.chat,cursor:o.cursor})));
|
|
445
|
+
for(const [command,approve] of [['group-request-approve',true],['group-request-reject',false]])program.command(command).description('Review a group join application.').requiredOption('--chat <id>').requiredOption('--user <id>')
|
|
446
|
+
.action(async o=>output(await (await groups()).reviewRequest({chatId:o.chat,userId:o.user,approve})));
|
|
447
|
+
program.command('group-post-users').description('List the group posting whitelist.').requiredOption('--chat <id>').action(async o=>output(await (await groups()).postUsers({chatId:o.chat})));
|
|
448
|
+
program.command('group-settings-schema').description('Show supported group settings and values.').action(()=>output(groupSettingsSchema()));
|
|
449
|
+
program.command('group-settings').description('Read group permissions, owner and announcement.').requiredOption('--chat <id>')
|
|
450
|
+
.action(async o=>output(await (await groups()).info({chatId:o.chat})));
|
|
451
|
+
program.command('group-settings-set').description('Update group permissions and other settings.').requiredOption('--chat <id>').requiredOption('--json <path>','settings JSON or - for stdin')
|
|
452
|
+
.action(async o=>output(await (await groups()).setSettings({chatId:o.chat,settings:await readJson(o.json,{})})));
|
|
453
|
+
program.command('group-admins').description('List group administrators.').requiredOption('--chat <id>').action(async o=>output(await (await groups()).admins({chatId:o.chat})));
|
|
454
|
+
for(const [command,enabled] of [['group-admin-add',true],['group-admin-remove',false]])program.command(command).description('Change group administrators.').requiredOption('--chat <id>')
|
|
455
|
+
.requiredOption('--user <id>','repeatable user ID',collect,[]).action(async o=>output(await (await groups()).setAdmins({chatId:o.chat,userIds:o.user,enabled})));
|
|
456
|
+
program.command('group-remove').description('Remove members from a group.').requiredOption('--chat <id>').requiredOption('--member <id>','repeatable member ID',collect,[])
|
|
457
|
+
.action(async o=>output(await (await groups()).remove({chatId:o.chat,userIds:o.member})));
|
|
458
|
+
program.command('group-leave').description('Leave a group as the current user.').requiredOption('--chat <id>').option('--new-owner <id>','transfer ownership if required')
|
|
459
|
+
.action(async o=>output(await (await groups()).leave({chatId:o.chat,newOwnerId:o.newOwner})));
|
|
460
|
+
program.command('group-owner').description('Transfer ownership of a group.').requiredOption('--chat <id>').requiredOption('--user <id>','new owner user ID')
|
|
461
|
+
.action(async o=>output(await (await groups()).setOwner({chatId:o.chat,userId:o.user})));
|
|
462
|
+
program.command('group-post-set').description('Set who can send messages in a group.').requiredOption('--chat <id>').requiredOption('--mode <mode>','anyone, admin or whitelist')
|
|
463
|
+
.option('--add-user <id>','repeatable user ID',collect,[]).option('--remove-user <id>','repeatable user ID',collect,[])
|
|
464
|
+
.action(async o=>output(await (await groups()).setPost({chatId:o.chat,mode:o.mode,addUsers:o.addUser,removeUsers:o.removeUser})));
|
|
465
|
+
program.command('group-join-history').description('Read group join and leave history.').requiredOption('--chat <id>').option('--cursor <cursor>').option('--limit <number>','page size','20')
|
|
466
|
+
.action(async o=>output(await (await groups()).history({chatId:o.chat,cursor:o.cursor,count:Number(o.limit)})));
|
|
467
|
+
|
|
432
468
|
program.command('group-create').description('Create a group as the user.')
|
|
433
469
|
.requiredOption('--name <name>', 'group name')
|
|
434
470
|
.option('--description <text>', 'group description')
|
|
@@ -447,6 +483,19 @@ program.command('group-update').description('Change a group name or description.
|
|
|
447
483
|
chatId: options.chat, name: options.name, description: options.description,
|
|
448
484
|
})));
|
|
449
485
|
|
|
486
|
+
program.command('contact-alias').description('Read your personal alias for a contact.').requiredOption('--user <id>')
|
|
487
|
+
.action(async o => output(await (await client()).contactAlias({ userId: o.user })));
|
|
488
|
+
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')
|
|
489
|
+
.action(async o => output(await (await client()).setContactAlias({ userId: o.user, alias: o.alias })));
|
|
490
|
+
program.command('contact-note').description('Read your personal note for a contact.').requiredOption('--user <id>')
|
|
491
|
+
.action(async o => output(await (await client()).contactNote({ userId: o.user })));
|
|
492
|
+
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')
|
|
493
|
+
.action(async o => output(await (await client()).setContactNote({ userId: o.user, description: o.description })));
|
|
494
|
+
program.command('group-nickname-set').description('Set your nickname in a group.').requiredOption('--chat <id>').requiredOption('--nickname <text>', 'use an empty string to clear')
|
|
495
|
+
.action(async o => output(await (await client()).setGroupNickname({ chatId: o.chat, nickname: o.nickname })));
|
|
496
|
+
program.command('group-avatar-set').description('Set a group avatar from an image.').requiredOption('--chat <id>').requiredOption('--file <path>')
|
|
497
|
+
.action(async o => output(await (await client()).setGroupAvatar({ chatId: o.chat, path: o.file })));
|
|
498
|
+
|
|
450
499
|
program.command('group-dissolve').description('Dissolve a group as its owner.')
|
|
451
500
|
.requiredOption('--chat <id>', 'numeric group ID')
|
|
452
501
|
.action(async options => output(await (await client()).dissolveGroup(options.chat)));
|
|
@@ -12,6 +12,7 @@ import { SidebarFilters } from '../src/sidebar-filters.js';
|
|
|
12
12
|
import { FeedGroups } from '../src/feed-groups.js';
|
|
13
13
|
import { Tasks } from '../src/tasks.js';
|
|
14
14
|
import { Calendar } from '../src/calendar.js';
|
|
15
|
+
import { GroupManagement, groupSettingsSchema } from '../src/group-management.js';
|
|
15
16
|
|
|
16
17
|
try {
|
|
17
18
|
const caller = process.env.SUDO_UID, owner = process.getuid?.();
|
|
@@ -22,7 +23,7 @@ try {
|
|
|
22
23
|
let services;
|
|
23
24
|
const getServices = () => services ||= (async () => {
|
|
24
25
|
const gateway = new Gateway({ cookie: await loadCookie({ file: config.credentialsFile }) });
|
|
25
|
-
return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway) };
|
|
26
|
+
return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway), groups: new GroupManagement(gateway) };
|
|
26
27
|
})();
|
|
27
28
|
await serveOne({ input: process.stdin, output: process.stdout, uid: caller, profile, getServices });
|
|
28
29
|
} catch (error) {
|
package/docs/agent-broker.md
CHANGED
|
@@ -47,7 +47,7 @@ LarkMate 可以由持有 Cookie 的账户启动本地代理,再让 Agent 使
|
|
|
47
47
|
|
|
48
48
|
运行 `larkmate broker-commands` 可查看代理支持的全部命令、各自所需的授权范围和是否修改数据。
|
|
49
49
|
|
|
50
|
-
按会话限制时,可授权 `chat-info`、`chat-state`、`history`、`messages-export`、`group-members`、`group-
|
|
50
|
+
按会话限制时,可授权 `chat-info`、`chat-state`、`history`、`messages-export`、`group-members`、`group-settings`、`group-admins`、`group-join-history`、`group-requests`、`group-post-users`、`group-update`、`group-dissolve`、`send` 以及会话状态操作:`pin`、`unpin`、`mark`、`unmark`、`mute`、`unmute`、`done`、`inbox`、`box`、`unbox`、`read`、`unread`。其中,`send` 在受限会话配置下仅支持普通文本,不支持 @ 或引用回复。群成员移除、退群、群主转让、管理员设置、入群审批、发言权限、群设置和生成邀请链接也可分别授权,并受 `chatIds` 限制。`group-settings-set` 可改变群的多种权限和公开设置,`group-link` 可生成允许他人入群的链接,应仅按需授权。
|
|
51
51
|
|
|
52
52
|
`minutes-export`、`minutes-access-info` 和 `minutes-request-access` 按 `minuteTokens` 限制;申请权限会向妙记所有者提交请求。`minutes-list` 除须在 `allow` 中授权外,还必须同时开启 `allowGlobal` 和 `allowAllMinutes`。
|
|
53
53
|
|
package/package.json
CHANGED
package/proto/lark.proto
CHANGED
|
@@ -285,15 +285,31 @@ message PullChatsByIdsResponse {
|
|
|
285
285
|
message PatchGroupChatRequest {
|
|
286
286
|
optional int64 chatId = 1;
|
|
287
287
|
optional string name = 2;
|
|
288
|
+
optional string iconData = 3;
|
|
288
289
|
optional string description = 4;
|
|
290
|
+
optional string announcement = 5;
|
|
291
|
+
optional int64 ownerId = 6;
|
|
292
|
+
optional bool offEditInfo = 14;
|
|
293
|
+
optional GroupEntitySetting entitySetting = 16;
|
|
294
|
+
repeated int32 updateEntitySettingFields = 17 [packed=false];
|
|
289
295
|
optional bool isDissolved = 18;
|
|
296
|
+
optional bool isPublicV2 = 19;
|
|
297
|
+
optional GroupGeneralSetting generalSetting = 21;
|
|
298
|
+
repeated int32 updateGeneralSettingFields = 22 [packed=false];
|
|
290
299
|
repeated UpdateFields updateFields = 999;
|
|
291
300
|
|
|
292
301
|
enum UpdateFields {
|
|
293
302
|
UPDATE_FIELDS_UNSPECIFIED = 0;
|
|
294
303
|
NAME = 1;
|
|
304
|
+
ICON_KEY = 2;
|
|
295
305
|
DESCRIPTION = 3;
|
|
306
|
+
ANNOUNCEMENT = 4;
|
|
307
|
+
OWNER_ID = 5;
|
|
308
|
+
OFF_EDIT_INFO = 14;
|
|
309
|
+
ENTITY_SETTING = 15;
|
|
296
310
|
IS_DISSOLVED = 16;
|
|
311
|
+
IS_PUBLIC_V2 = 23;
|
|
312
|
+
GENERAL_CHAT_SETTING = 41;
|
|
297
313
|
}
|
|
298
314
|
}
|
|
299
315
|
|
|
@@ -334,6 +350,7 @@ message Chat {
|
|
|
334
350
|
optional ChatTypeEnum type = 2;
|
|
335
351
|
optional string lastMessageId = 3;
|
|
336
352
|
optional string name = 4;
|
|
353
|
+
optional ChatImage avatar = 5;
|
|
337
354
|
optional string ownerId = 6;
|
|
338
355
|
optional int32 newMessageCount = 7;
|
|
339
356
|
optional int64 updateTime = 9;
|
|
@@ -343,12 +360,20 @@ message Chat {
|
|
|
343
360
|
optional int32 lastMessagePosition = 15;
|
|
344
361
|
optional int32 userCount = 16;
|
|
345
362
|
optional int64 createTime = 18;
|
|
363
|
+
optional int32 role = 20;
|
|
364
|
+
optional bool offEditGroupChatInfo = 23;
|
|
346
365
|
optional string tenantId = 25;
|
|
366
|
+
optional GroupEntitySetting chatEntitySetting = 28;
|
|
347
367
|
optional bool isDissolved = 30;
|
|
348
368
|
optional string lastVisibleMessageId = 32;
|
|
349
369
|
optional int32 readPosition = 48;
|
|
350
370
|
optional int32 lastVisibleMessagePosition = 46;
|
|
351
371
|
optional bool isCrossTenant = 41;
|
|
372
|
+
optional bool isPublicV2 = 109;
|
|
373
|
+
optional int32 postType = 110;
|
|
374
|
+
optional bool allowPost = 111;
|
|
375
|
+
optional bool isAdmin = 126;
|
|
376
|
+
optional GroupGeneralSetting chatGeneralSetting = 136;
|
|
352
377
|
optional Announcement announcement = 24;
|
|
353
378
|
|
|
354
379
|
enum ChatTypeEnum {
|
|
@@ -365,6 +390,7 @@ message Chat {
|
|
|
365
390
|
optional string docUrl = 4;
|
|
366
391
|
}
|
|
367
392
|
}
|
|
393
|
+
message ChatImage { optional string key = 1; }
|
|
368
394
|
|
|
369
395
|
// --- Search (cmd=11021) ---
|
|
370
396
|
|
|
@@ -601,7 +627,20 @@ message PullFeedCardsByIdsRequest { repeated string cardIds = 1; repeated FeedId
|
|
|
601
627
|
message PullFeedCardsByIdsResponse { map<string, InboxCard> cards = 1; }
|
|
602
628
|
message PatchFeedCardUnreadRequest { optional FeedIdentity card = 1; optional bool markAsUnread = 2; optional int64 readPos = 3; }
|
|
603
629
|
message PatchFeedCardUnreadResponse { optional InboxCard card = 1; }
|
|
604
|
-
message ChatSetting {
|
|
630
|
+
message ChatSetting {
|
|
631
|
+
optional bool isRemind = 1;
|
|
632
|
+
optional bool isAutoTranslate = 4;
|
|
633
|
+
optional bool isMuteAtAll = 8;
|
|
634
|
+
}
|
|
635
|
+
message PutGroupNicknameRequest { optional int64 chatId = 1; optional string nickname = 2; }
|
|
636
|
+
message CleanUserChatMessageRequest { optional int64 chatId = 1; optional int32 position = 2; }
|
|
637
|
+
message PutUserAliasRequest { optional int64 targetId = 1; optional string name = 2; }
|
|
638
|
+
message PullContactProfileV2Request { optional int32 scene = 1; optional string userId = 2; optional string chatId = 4; optional bool useNewLayout = 12; }
|
|
639
|
+
message PullContactProfileV2Response { optional ContactProfile profile = 1; optional ContactChatMeta chatChatter = 3; }
|
|
640
|
+
message ContactChatMeta { optional int64 chatId = 1; optional int64 chatterId = 2; optional string groupNickname = 4; }
|
|
641
|
+
message ContactProfile { repeated ContactProfileField fields = 3; }
|
|
642
|
+
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; }
|
|
643
|
+
message PatchUserMemoRequest { optional string targetUserId = 1; optional string memoText = 3; }
|
|
605
644
|
message PullChatSettingsRequest { repeated string chatIds = 1; }
|
|
606
645
|
message PullChatSettingsResponse { map<string, ChatSetting> chatSettings = 1; }
|
|
607
646
|
message PatchChatSettingRequest { optional string chatId = 1; optional ChatSetting chatSetting = 2; repeated int32 updateChatSettingField = 3; }
|
|
@@ -647,3 +686,43 @@ message PullUnreadAtMessageIdsRequest { optional int32 version = 1; repeated int
|
|
|
647
686
|
message PullUnreadAtMessageIdsResponse { repeated string messageIds = 1; map<string, string> messageThreadIds = 2; }
|
|
648
687
|
message PullMessagesByIdsRequest { repeated string messageIds = 1; }
|
|
649
688
|
message PullMessagesByIdsResponse { map<string, MessageEntity> messages = 1; }
|
|
689
|
+
|
|
690
|
+
// Group membership and management over the personal-user gateway.
|
|
691
|
+
message DeleteChatChatterRequest { optional string chatId = 1; repeated string chatterIds = 2; optional string newOwnerId = 3; optional DeleteChatChatterOption option = 4; }
|
|
692
|
+
message DeleteChatChatterOption { optional bool withdraw = 1; }
|
|
693
|
+
message DeleteChatChatterResponse { optional Chat chat = 1; optional int64 chatChatterVersion = 2; optional int64 syncCursor = 3; }
|
|
694
|
+
message GroupAdminUser { optional int64 userId = 1; optional int64 orderWeight = 2; }
|
|
695
|
+
message PullChatAdminUsersRequest { optional string chatId = 1; }
|
|
696
|
+
message PullChatAdminUsersResponse { repeated GroupAdminUser adminUsers = 1; optional int64 updateVersion = 2; }
|
|
697
|
+
message PatchChatAdminUsersRequest { optional string chatId = 1; repeated string toAddUserIds = 2; repeated string toDelUserIds = 3; }
|
|
698
|
+
message PatchChatAdminUsersResponse { repeated GroupAdminUser users = 1; optional int64 updateVersion = 3; }
|
|
699
|
+
message PatchChatPostUserRequest { optional string chatId = 1; optional int32 postType = 2; repeated string toAddUserIds = 3; repeated string toDelUserIds = 4; }
|
|
700
|
+
message PatchChatPostUserResponse {}
|
|
701
|
+
message PullChatJoinLeaveHistoryRequest { optional int64 chatId = 1; optional int64 cursor = 2; optional int32 count = 3; }
|
|
702
|
+
message PullChatJoinLeaveHistoryResponse { repeated GroupMembershipHistory chatterHistory = 1; optional bool hasMore = 2; optional string nextCursor = 3; }
|
|
703
|
+
message GroupMembershipHistory { optional string id = 1; optional int32 action = 2; optional int32 event = 3; optional string chatterId = 4; optional string chatId = 5; optional int64 createTime = 6; optional int32 chatterType = 8; }
|
|
704
|
+
message GroupEntitySetting {
|
|
705
|
+
optional int32 addMemberPermissionSetting = 1; optional int32 atAllPermissionSetting = 2;
|
|
706
|
+
optional int32 joinMessageVisibleSetting = 3; optional int32 quitMessageVisibleSetting = 4;
|
|
707
|
+
optional int32 shareCardPermissionSetting = 5; optional int32 addMemberApplySetting = 6;
|
|
708
|
+
optional int32 threadAnonymousSetting = 7; optional int32 messageVisibilitySetting = 8;
|
|
709
|
+
optional GroupAnonymousSetting anonymousSetting = 9; optional int32 createUrgentSetting = 10;
|
|
710
|
+
optional int32 createVideoConferenceSetting = 11; optional int32 pinPermissionSetting = 12;
|
|
711
|
+
optional int32 topNoticePermissionSetting = 13; optional int32 chatTabPermissionSetting = 14;
|
|
712
|
+
optional int32 chatDisplayModeSetting = 15; optional int32 adminPostSetting = 16;
|
|
713
|
+
optional int32 chatPinPermissionSetting = 17; optional int32 userCountVisibleSetting = 18;
|
|
714
|
+
}
|
|
715
|
+
message GroupAnonymousSetting { optional bool isAllowAnonymous = 1; optional bool isVisible = 2; }
|
|
716
|
+
message GroupGeneralSetting { optional GroupRestrictedMode restrictedModePermissionSetting = 1; optional int32 defDisplaySetting = 2; }
|
|
717
|
+
message GroupRestrictedMode { optional bool status = 1; optional int32 transmitPermissionSetting = 2; optional int32 copyPermissionSetting = 3; optional int32 downloadPermissionSetting = 4; optional int32 screenshotPermissionSetting = 5; optional GroupAutoDelete onTimeDelMsgPermissionSetting = 6; optional GroupWhitelist whiteListSetting = 7; }
|
|
718
|
+
message GroupAutoDelete { optional bool status = 1; optional int64 aliveTime = 2; }
|
|
719
|
+
message GroupWhitelist { optional int32 level = 1; repeated int64 addUserIds = 2 [packed=false]; repeated int64 delUserIds = 3 [packed=false]; repeated int64 userIds = 4 [packed=false]; optional bool hitWhitelist = 5; }
|
|
720
|
+
message PullChatPostUserByChatIDRequest { optional string chatId = 1; }
|
|
721
|
+
message PullChatPostUserByChatIDResponse { repeated string userIds = 1; }
|
|
722
|
+
message PullChatLinkTokenRequest { optional string chatId = 1; optional int32 expiredDay = 2; optional string appName = 3; optional bool isUnlimited = 4; optional int32 targetScene = 5; }
|
|
723
|
+
message PullChatLinkTokenResponse { optional string token = 1; optional int64 expireTime = 2; optional string sharedUrl = 3; optional string kouLing = 4; optional bool isUnlimited = 5; }
|
|
724
|
+
message GroupJoinApplication { optional string reason = 1; optional int32 status = 2; optional int64 time = 3; optional int32 applyWays = 4; optional string inviterId = 5; optional string inviteeId = 6; optional string joinToken = 7; optional int64 teamId = 8; optional string teamName = 9; }
|
|
725
|
+
message PullAddChatChatterApplyRequest { optional string chatId = 1; optional int64 cursor = 2; }
|
|
726
|
+
message PullAddChatChatterApplyResponse { repeated GroupJoinApplication applies = 1; optional int64 nextCursor = 2; }
|
|
727
|
+
message PatchAddChatChatterApplyRequest { optional string chatId = 1; optional bool showBanner = 2; optional string inviteeId = 3; optional int32 status = 4; }
|
|
728
|
+
message PatchAddChatChatterApplyResponse {}
|
|
@@ -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` 查看参数。修改前先查询当前设置。
|
|
@@ -27,12 +27,28 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
|
|
|
27
27
|
|
|
28
28
|
```sh
|
|
29
29
|
larkmate group-members --chat "$CHAT_ID"
|
|
30
|
+
larkmate group-settings --chat "$CHAT_ID"
|
|
31
|
+
larkmate group-settings-schema
|
|
32
|
+
larkmate group-admins --chat "$CHAT_ID"
|
|
33
|
+
larkmate group-join-history --chat "$CHAT_ID"
|
|
34
|
+
larkmate group-requests --chat "$CHAT_ID"
|
|
30
35
|
larkmate group-create --name '群名称' --member "$MEMBER_ID"
|
|
31
36
|
larkmate group-invite --chat "$CHAT_ID" --member "$MEMBER_ID"
|
|
32
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 '群昵称'
|
|
33
41
|
larkmate group-bot-info --chat "$CHAT_ID" --bot "$BOT_ID"
|
|
34
42
|
larkmate group-bot-protection --chat "$CHAT_ID" --bot "$BOT_ID" --allow-member-removal
|
|
35
43
|
larkmate group-dissolve --chat "$CHAT_ID"
|
|
36
44
|
```
|
|
37
45
|
|
|
38
|
-
`--member` 可重复指定。创建或邀请机器人默认限制普通成员移除,`--allow-member-removal`
|
|
46
|
+
`--member` 可重复指定。创建或邀请机器人默认限制普通成员移除,`--allow-member-removal` 可关闭该限制。机器人邀请结果中的 `verified` 表示移除限制已读回。遇到 `GROUP_CREATED_PARTIAL` 或 `INVITE_PARTIAL` 时,先检查已产生的群或成员变化,不要盲目重复操作。
|
|
47
|
+
|
|
48
|
+
群头像支持 PNG、JPEG 和 WebP 格式,文件大小上限为 10 MiB。通过委托或代理调用时,图片由调用方读取,并受目标会话及文件大小授权限制。群昵称传入空字符串可清除。
|
|
49
|
+
|
|
50
|
+
`group-settings` 可读取群主、公告、发言和群权限设置;`group-settings-schema` 列出可修改的字段与值。使用 `group-settings-set --chat "$CHAT_ID" --json <文件>` 修改所需字段,`--json -` 从标准输入读取。它会按字段更新,并可配置入群审批、邀请、@全体、历史消息可见性及受限模式等;修改前先读取当前设置。群公告暂不支持修改。
|
|
51
|
+
|
|
52
|
+
`group-admin-add` 和 `group-admin-remove` 分别设置或撤销管理员;`group-owner` 转让群主,`group-remove` 移除成员,`group-leave` 退出群聊,均需要明确的目标和用户意图。`group-post-set` 配置发言模式,`group-post-users` 查询白名单。`group-requests` 查询入群申请;用 `group-request-approve` 或 `group-request-reject` 处理指定用户的申请。`group-link` 创建可用于入群的邀请链接,应保护链接;默认有效期 7 天。
|
|
53
|
+
|
|
54
|
+
群操作的可用性受当前用户的群角色和飞书权限限制。对于 `submitted_unconfirmed`、`EFFECT_UNKNOWN` 或部分成功,先查询群设置、成员或申请状态,不盲目重试。
|
package/src/agent-broker.js
CHANGED
|
@@ -32,7 +32,17 @@ 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'],
|
|
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'],
|
|
42
|
+
'group-settings': ['groups','info','chatObject'], 'group-settings-set': ['groups','setSettings','chatObject'],
|
|
43
|
+
'group-admins': ['groups','admins','chatObject'], 'group-admin-add': ['groups','setAdmins','chatObject'], 'group-admin-remove': ['groups','setAdmins','chatObject'],
|
|
44
|
+
'group-remove': ['groups','remove','chatObject'], 'group-leave': ['groups','leave','chatObject'], 'group-owner': ['groups','setOwner','chatObject'],
|
|
45
|
+
'group-post-set': ['groups','setPost','chatObject'], 'group-join-history': ['groups','history','chatObject'],
|
|
36
46
|
'group-members': ['client', 'members', 'chatObject'], 'group-bot-info': ['client', 'botProtection', 'chatObject'],
|
|
37
47
|
'group-update': ['client', 'updateGroup', 'chatObject'], 'group-dissolve': ['client', 'dissolveGroup', 'chatArg'],
|
|
38
48
|
'group-create': ['client', 'createGroup', 'allChats'], 'group-invite': ['client', 'invite', 'allChats'],
|
|
@@ -51,11 +61,12 @@ const routes = {
|
|
|
51
61
|
'minutes-list': ['minutes', 'list', 'allMinutes'], 'minutes-export': ['minutes', 'transcript', 'minute'],
|
|
52
62
|
'minutes-access-info': ['minutes', 'accessInfo', 'minute'], 'minutes-request-access': ['minutes', 'requestAccess', 'minute'],
|
|
53
63
|
'send-file': ['files', 'upload', 'file'], 'send-image': ['files', 'upload', 'file'],
|
|
64
|
+
'group-avatar-set': ['files', 'upload', 'file'],
|
|
54
65
|
'download-file': ['files', 'download', 'file'],
|
|
55
66
|
};
|
|
56
|
-
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',
|
|
57
68
|
'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
|
|
58
|
-
'group-update', 'group-dissolve', 'group-bot-protection', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
|
|
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',
|
|
59
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']);
|
|
60
71
|
|
|
61
72
|
export function brokerCommands() {
|
|
@@ -129,6 +140,8 @@ export function authorize(policy, request) {
|
|
|
129
140
|
const chatAllowed = id => numeric(id) && (policy.allowAllChats || policy.chatIds.includes(id));
|
|
130
141
|
if (scope === 'global' && !policy.allowGlobal) denied();
|
|
131
142
|
if (['calendar-subscribe', 'calendar-unsubscribe'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].subscribe !== (request.command === 'calendar-subscribe'))) denied();
|
|
143
|
+
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();
|
|
144
|
+
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();
|
|
132
145
|
if (['task-complete', 'task-reopen'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].completed !== (request.command === 'task-complete'))) denied();
|
|
133
146
|
if (['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) && (!policy.allowGlobal || !policy.allowAllChats)) denied();
|
|
134
147
|
if (scope === 'allMinutes' && (!policy.allowGlobal || !policy.allowAllMinutes)) denied();
|
|
@@ -146,7 +159,20 @@ export function authorize(policy, request) {
|
|
|
146
159
|
const keys = scope === 'send' ? ['chatId', 'text', 'mentions', 'replyTo', 'replyRoot']
|
|
147
160
|
: method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
|
|
148
161
|
: method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
|
|
149
|
-
: method === 'updateGroup' ? ['chatId', 'name', 'description']
|
|
162
|
+
: method === 'updateGroup' ? ['chatId', 'name', 'description']
|
|
163
|
+
: method === 'setPreference' ? ['chatId', 'muteAtAll', 'autoTranslate']
|
|
164
|
+
: method === 'setGroupNickname' ? ['chatId', 'nickname']
|
|
165
|
+
: method === 'info' || method === 'admins' || method === 'postUsers' || method === 'clearChatHistory' ? ['chatId']
|
|
166
|
+
: method === 'link' ? ['chatId','days','unlimited']
|
|
167
|
+
: method === 'requests' ? ['chatId','cursor']
|
|
168
|
+
: method === 'reviewRequest' ? ['chatId','userId','approve']
|
|
169
|
+
: method === 'setSettings' ? ['chatId','settings']
|
|
170
|
+
: method === 'setAdmins' ? ['chatId','userIds','enabled']
|
|
171
|
+
: method === 'remove' ? ['chatId','userIds']
|
|
172
|
+
: method === 'leave' ? ['chatId','newOwnerId']
|
|
173
|
+
: method === 'setOwner' ? ['chatId','userId']
|
|
174
|
+
: method === 'setPost' ? ['chatId','mode','addUsers','removeUsers']
|
|
175
|
+
: method === 'history' ? ['chatId','cursor','count'] : ['chatId', 'botId'];
|
|
150
176
|
if (!only(args[0], keys)) denied();
|
|
151
177
|
// A reply ID may refer to another chat, and mentions can notify additional users.
|
|
152
178
|
if (scope === 'send' && !policy.allowAllChats && (args[0].replyTo || args[0].replyRoot || (args[0].mentions?.length ?? 0) !== 0)) denied();
|
|
@@ -263,7 +289,7 @@ export async function brokerCall(socketPath, request, tokenFile) {
|
|
|
263
289
|
export function brokerProxy(socketPath, service, getCommand, tokenFile) {
|
|
264
290
|
return new Proxy({}, { get(_target, method) {
|
|
265
291
|
if (method === 'then' || typeof method !== 'string') return undefined;
|
|
266
|
-
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);
|
|
267
293
|
if (service === 'client' && method === 'downloadFile') return options => brokerDownload(socketPath, tokenFile, options);
|
|
268
294
|
return (...args) => brokerCall(socketPath, { command: getCommand(), service, method, args }, tokenFile);
|
|
269
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,63 @@
|
|
|
1
|
+
import { FeishuError, requireInt64Id } from './errors.js';
|
|
2
|
+
const obj = x => x && typeof x === 'object' && !Array.isArray(x);
|
|
3
|
+
const fail = message => { throw new FeishuError('INVALID_ARGUMENT', message); };
|
|
4
|
+
const memberIds = (values, empty=false) => { if(!Array.isArray(values)||(!empty&&!values.length)||values.length>100)fail('Provide between 1 and 100 members.');return [...new Set(values.map(x=>requireInt64Id(x,'member ID')))]; };
|
|
5
|
+
const values = (...names) => Object.fromEntries(names.map((name,i)=>[name,i+1]));
|
|
6
|
+
const entityFields = {
|
|
7
|
+
addMemberPermissionSetting:[1,values('ALL_MEMBERS','ONLY_OWNER')], atAllPermissionSetting:[2,values('ALL_MEMBERS','ONLY_OWNER')],
|
|
8
|
+
joinMessageVisibleSetting:[3,values('ONLY_OWNER','ALL_MEMBERS','NOT_ANYONE')], quitMessageVisibleSetting:[4,values('ONLY_OWNER','ALL_MEMBERS','NOT_ANYONE')],
|
|
9
|
+
shareCardPermissionSetting:[5,values('ALLOWED','NOT_ALLOWED')], addMemberApplySetting:[6,values('NO_APPLY','NEED_APPLY')],
|
|
10
|
+
threadAnonymousSetting:[7,values('INVISIBLE','NOT_ALLOWED','ALLOWED')], messageVisibilitySetting:[8,values('ALL_MESSAGES','ONLY_NEW_MESSAGES')],
|
|
11
|
+
anonymousSetting:[9,null], createUrgentSetting:[10,values('ALL_MEMBERS','ONLY_MANAGER')], createVideoConferenceSetting:[11,values('ALL_MEMBERS','ONLY_MANAGER')],
|
|
12
|
+
pinPermissionSetting:[12,values('ALL_MEMBERS','ONLY_MANAGER')], topNoticePermissionSetting:[14,values('ALL_MEMBERS','ONLY_MANAGER')],
|
|
13
|
+
chatTabPermissionSetting:[15,values('ALL_MEMBERS','ONLY_MANAGER')], chatDisplayModeSetting:[16,values('DEFAULT','THREAD')],
|
|
14
|
+
adminPostSetting:[17,values('ALLOW_POST','BANNED_POST')], chatPinPermissionSetting:[18,values('ALL_MEMBERS','ONLY_MANAGER')], userCountVisibleSetting:[19,values('ALL_MEMBERS','ONLY_MANAGER')],
|
|
15
|
+
};
|
|
16
|
+
function enumValue(input,allowed,key) { let v=typeof input==='string'?allowed[input]:input; if(!Number.isInteger(v)||!Object.values(allowed).includes(v))fail(`Invalid value for ${key}.`);return v; }
|
|
17
|
+
function booleanFields(input,allowed,path) {if(!obj(input)||!Object.keys(input).length||Object.keys(input).some(k=>!allowed.includes(k)||typeof input[k]!=='boolean'))fail(`Invalid ${path}.`);return input;}
|
|
18
|
+
export function buildSettings(input) {
|
|
19
|
+
if(!obj(input)||!Object.keys(input).length||Object.keys(input).some(k=>!['entity','general','offEditInfo','isPublicV2'].includes(k)))fail('Settings must contain supported entity, general, offEditInfo or isPublicV2 fields.');
|
|
20
|
+
const patch={},updateFields=[];
|
|
21
|
+
if(input.entity!=null){if(!obj(input.entity)||!Object.keys(input.entity).length)fail('Entity settings must be a non-empty object.');const setting={},fields=[];
|
|
22
|
+
for(const [key,raw]of Object.entries(input.entity)){const entry=entityFields[key];if(!entry)fail(`Unknown entity setting ${key}.`);setting[key]=entry[1]?enumValue(raw,entry[1],key):booleanFields(raw,['isAllowAnonymous','isVisible'],key);fields.push(entry[0]);}
|
|
23
|
+
patch.entitySetting=setting;patch.updateEntitySettingFields=fields;updateFields.push(15);
|
|
24
|
+
}
|
|
25
|
+
if(input.general!=null){if(!obj(input.general)||!Object.keys(input.general).length||Object.keys(input.general).some(k=>!['defDisplaySetting','restrictedModePermissionSetting'].includes(k)))fail('Invalid general settings.');let general={},fields=[];
|
|
26
|
+
if(input.general.defDisplaySetting!=null){general.defDisplaySetting=enumValue(input.general.defDisplaySetting,values('INPUT_BOX','CHAT_MENU'),'defDisplaySetting');fields.push(6)}
|
|
27
|
+
if(input.general.restrictedModePermissionSetting!=null){let raw=input.general.restrictedModePermissionSetting;if(!obj(raw)||!Object.keys(raw).length)fail('Invalid restricted mode settings.');let nested={};
|
|
28
|
+
for(const [key,value] of Object.entries(raw)){if(key==='status'){if(typeof value!=='boolean')fail('Invalid restricted status.');nested.status=value;fields.push(1)}
|
|
29
|
+
else if(['transmitPermissionSetting','copyPermissionSetting','downloadPermissionSetting','screenshotPermissionSetting'].includes(key)){nested[key]=enumValue(value,values('ALL_MEMBERS','NO_MEMBER'),key);fields.push({transmitPermissionSetting:2,copyPermissionSetting:3,downloadPermissionSetting:4,screenshotPermissionSetting:5}[key])}
|
|
30
|
+
else if(key==='onTimeDelMsgPermissionSetting'){if(!obj(value)||!Object.keys(value).length||Object.keys(value).some(k=>!['status','aliveTime'].includes(k)))fail('Invalid auto-delete settings.');let v={};if(value.status!=null){if(typeof value.status!=='boolean')fail('Invalid auto-delete status.');v.status=value.status;fields.push(7)}if(value.aliveTime!=null){let t=String(value.aliveTime);if(!/^\d{1,18}$/.test(t))fail('Invalid auto-delete time.');v.aliveTime=t;fields.push(8)}nested[key]=v}
|
|
31
|
+
else if(key==='whiteListSetting'){if(!obj(value)||!Object.keys(value).length||Object.keys(value).some(k=>!['level','addUserIds','delUserIds'].includes(k)))fail('Invalid restricted-mode whitelist.');let v={};if(value.level!=null){v.level=enumValue(value.level,values('NO_MEMBER','ONLY_ADMIN_AND_OWNER','MEMBER_LIST'),'whitelist level');fields.push(9)}for(const k of ['addUserIds','delUserIds'])if(value[k]!=null){v[k]=memberIds(value[k]);fields.push(10)}nested[key]=v}
|
|
32
|
+
else fail(`Unknown general setting ${key}.`);
|
|
33
|
+
} general.restrictedModePermissionSetting=nested;
|
|
34
|
+
}
|
|
35
|
+
patch.generalSetting=general;patch.updateGeneralSettingFields=[...new Set(fields)];updateFields.push(41);
|
|
36
|
+
}
|
|
37
|
+
for(const [key,field]of [['offEditInfo',14],['isPublicV2',23]])if(input[key]!=null){if(typeof input[key]!=='boolean')fail(`${key} must be boolean.`);patch[key]=input[key];updateFields.push(field)}
|
|
38
|
+
return {...patch,updateFields};
|
|
39
|
+
}
|
|
40
|
+
function matches(expected,actual) {if(!obj(expected))return String(expected)===String(actual);if(!obj(actual))return false;return Object.entries(expected).every(([k,v])=>Array.isArray(v)?false:Object.hasOwn(actual,k)&&matches(v,actual[k]));}
|
|
41
|
+
export function groupSettingsSchema() { return { entity: Object.fromEntries(Object.entries(entityFields).map(([name,[field,choices]])=>[name,{field,values:choices||{isAllowAnonymous:'boolean',isVisible:'boolean'}}])), general: { defDisplaySetting:values('INPUT_BOX','CHAT_MENU'), restrictedModePermissionSetting: { status:'boolean', transmitPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), copyPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), downloadPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), screenshotPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), onTimeDelMsgPermissionSetting:{status:'boolean',aliveTime:'duration value'}, whiteListSetting:{level:values('NO_MEMBER','ONLY_ADMIN_AND_OWNER','MEMBER_LIST'),addUserIds:'user ID array',delUserIds:'user ID array'} } }, offEditInfo:'boolean', isPublicV2:'boolean' }; }
|
|
42
|
+
export class GroupManagement {
|
|
43
|
+
constructor(gateway){this.gateway=gateway;}
|
|
44
|
+
async call(cmd,req,body,res,write=false,operation='group'){let r=await this.gateway.call(cmd,req,body,{mutating:write,operation});try{return {data:this.gateway.decode(res,r.packet.payload||new Uint8Array()),requestId:r.requestId}}catch{throw new FeishuError(write?'EFFECT_UNKNOWN':'INVALID_RESPONSE','Group response was unreadable.',{operation,requestId:r.requestId})}}
|
|
45
|
+
async raw(chatId){requireInt64Id(chatId,'chat ID');const {data}=await this.call(64,'PullChatsByIdsRequest',{chatIds:[chatId]},'PullChatsByIdsResponse');let chat=data.chats?.[chatId];if(!chat||String(chat.id)!==chatId)throw new FeishuError('NOT_FOUND','Group not found or inaccessible.');if(![2,3].includes(chat.type))throw new FeishuError('INVALID_ARGUMENT','The target is not a group.');return chat;}
|
|
46
|
+
async info({chatId}){let c=await this.raw(chatId);return {chatId,name:c.name||'',ownerId:c.ownerId||null,role:Object.hasOwn(c,'role')?c.role:null,isAdmin:Object.hasOwn(c,'isAdmin')?c.isAdmin:null,postType:Object.hasOwn(c,'postType')?c.postType:null,allowPost:Object.hasOwn(c,'allowPost')?c.allowPost:null,announcement:c.announcement||null,entity:c.chatEntitySetting||null,general:c.chatGeneralSetting||null,offEditInfo:Object.hasOwn(c,'offEditGroupChatInfo')?c.offEditGroupChatInfo:null,isPublicV2:Object.hasOwn(c,'isPublicV2')?c.isPublicV2:null};}
|
|
47
|
+
async admins({chatId}){requireInt64Id(chatId,'chat ID');let {data}=await this.call(5902,'PullChatAdminUsersRequest',{chatId},'PullChatAdminUsersResponse');return {chatId,items:data.adminUsers.map(x=>({userId:String(x.userId),orderWeight:Object.hasOwn(x,'orderWeight')?String(x.orderWeight):null})),version:Object.hasOwn(data,'updateVersion')?String(data.updateVersion):null};}
|
|
48
|
+
async setAdmins({chatId,userIds,enabled}){requireInt64Id(chatId,'chat ID');if(typeof enabled!=='boolean')fail('Invalid admin action.');let ids=memberIds(userIds);let {requestId}=await this.call(5900,'PatchChatAdminUsersRequest',{chatId,[enabled?'toAddUserIds':'toDelUserIds']:ids},'PatchChatAdminUsersResponse',true,enabled?'group-admin-add':'group-admin-remove');
|
|
49
|
+
try{let current=await this.admins({chatId}),found=new Set(current.items.map(x=>x.userId));return {chatId,requestId,status:ids.every(id=>found.has(id)===enabled)?'updated':'submitted_unconfirmed',items:current.items}}catch{return {chatId,requestId,status:'submitted_unconfirmed'}}}
|
|
50
|
+
async remove({chatId,userIds}){requireInt64Id(chatId,'chat ID');let ids=memberIds(userIds);let me=await this.gateway.authenticate();if(ids.includes(me.id))fail('Use group-leave to leave a group.');await this.raw(chatId);let {data,requestId}=await this.call(45,'DeleteChatChatterRequest',{chatId,chatterIds:ids},'DeleteChatChatterResponse',true,'group-remove');
|
|
51
|
+
if(data.chat?.id&&String(data.chat.id)!==chatId)throw new FeishuError('EFFECT_UNKNOWN','Unexpected group in response.',{requestId});return {chatId,requestId,status:'submitted_unconfirmed',requested:ids};}
|
|
52
|
+
async leave({chatId,newOwnerId}){requireInt64Id(chatId,'chat ID');if(newOwnerId!=null)requireInt64Id(newOwnerId,'new owner ID');let me=await this.gateway.authenticate();if(newOwnerId===me.id)fail('New owner must be another member.');await this.raw(chatId);let {requestId}=await this.call(45,'DeleteChatChatterRequest',{chatId,chatterIds:[me.id],...(newOwnerId?{newOwnerId}:{})},'DeleteChatChatterResponse',true,'group-leave');return {chatId,requestId,status:'submitted_unconfirmed'};}
|
|
53
|
+
async patch({chatId,body,operation}) {const {data,requestId}=await this.call(72,'PatchGroupChatRequest',{chatId,...body},'PatchGroupChatResponse',true,operation);if(!data.chat?.id||String(data.chat.id)!==chatId)throw new FeishuError('EFFECT_UNKNOWN','Group update was not confirmed.',{requestId});return {data,requestId};}
|
|
54
|
+
async setOwner({chatId,userId}) {requireInt64Id(chatId,'chat ID');requireInt64Id(userId,'owner ID');await this.raw(chatId);let {data,requestId}=await this.patch({chatId,body:{ownerId:userId,updateFields:[5]},operation:'group-owner'});return {chatId,requestId,status:String(data.chat.ownerId||'')===userId?'updated':'submitted_unconfirmed'};}
|
|
55
|
+
|
|
56
|
+
async setSettings({chatId,settings}) {requireInt64Id(chatId,'chat ID');let patch=buildSettings(settings);await this.raw(chatId);let {requestId}=await this.patch({chatId,body:patch,operation:'group-settings-set'});try{let after=await this.info({chatId});let ok=(patch.entitySetting==null||matches(patch.entitySetting,after.entity))&&(patch.generalSetting==null||matches(patch.generalSetting,after.general))&&(patch.offEditInfo==null||patch.offEditInfo===after.offEditInfo)&&(patch.isPublicV2==null||patch.isPublicV2===after.isPublicV2);return {chatId,requestId,status:ok?'updated':'submitted_unconfirmed',settings:after}}catch{return {chatId,requestId,status:'submitted_unconfirmed'}}}
|
|
57
|
+
async setPost({chatId,mode,addUsers=[],removeUsers=[]}) {requireInt64Id(chatId,'chat ID');let mapping={anyone:1,admin:2,whitelist:3},postType=mapping[mode];if(!postType)fail('Mode must be anyone, admin or whitelist.');let add=memberIds(addUsers,true),remove=memberIds(removeUsers,true);if(add.some(x=>remove.includes(x)))fail('A member cannot be added and removed together.');await this.raw(chatId);let {requestId}=await this.call(254,'PatchChatPostUserRequest',{chatId,postType,toAddUserIds:add,toDelUserIds:remove},'PatchChatPostUserResponse',true,'group-post-set');try{let c=await this.info({chatId});return {chatId,requestId,status:c.postType===postType&&!add.length&&!remove.length?'updated':'submitted_unconfirmed',postType:c.postType}}catch{return {chatId,requestId,status:'submitted_unconfirmed'}}}
|
|
58
|
+
async postUsers({chatId}){requireInt64Id(chatId,'chat ID');let {data}=await this.call(253,'PullChatPostUserByChatIDRequest',{chatId},'PullChatPostUserByChatIDResponse');return {chatId,userIds:data.userIds};}
|
|
59
|
+
async link({chatId,days=7,unlimited=false}){requireInt64Id(chatId,'chat ID');if(!Number.isInteger(days)||days<1||days>365||typeof unlimited!=='boolean')fail('Invalid link duration.');await this.raw(chatId);let {data,requestId}=await this.call(5055,'PullChatLinkTokenRequest',{chatId,expiredDay:days,isUnlimited:unlimited},'PullChatLinkTokenResponse',true,'group-link');if(!data.sharedUrl&&!data.token)throw new FeishuError('EFFECT_UNKNOWN','No group invitation link was returned.',{requestId});return {chatId,requestId,url:data.sharedUrl||null,token:data.token||null,expireTime:Object.hasOwn(data,'expireTime')?String(data.expireTime):null,unlimited:Object.hasOwn(data,'isUnlimited')?data.isUnlimited:null};}
|
|
60
|
+
async requests({chatId,cursor='0'}){requireInt64Id(chatId,'chat ID');if(typeof cursor!=='string'||!/^\d{1,19}$/.test(cursor))fail('Invalid request cursor.');let {data}=await this.call(258,'PullAddChatChatterApplyRequest',{chatId,cursor},'PullAddChatChatterApplyResponse');return {chatId,items:data.applies.map(x=>({reason:x.reason||'',status:x.status,time:Object.hasOwn(x,'time')?String(x.time):null,applyWays:x.applyWays,inviterId:x.inviterId||null,inviteeId:x.inviteeId||null,teamName:x.teamName||null})),nextCursor:Object.hasOwn(data,'nextCursor')&&String(data.nextCursor)!=='0'?String(data.nextCursor):null};}
|
|
61
|
+
async reviewRequest({chatId,userId,approve}){requireInt64Id(chatId,'chat ID');requireInt64Id(userId,'user ID');if(typeof approve!=='boolean')fail('Invalid request decision.');await this.raw(chatId);let {requestId}=await this.call(259,'PatchAddChatChatterApplyRequest',{chatId,inviteeId:userId,status:approve?1:2},'PatchAddChatChatterApplyResponse',true,approve?'group-request-approve':'group-request-reject');return {chatId,userId,requestId,status:'submitted_unconfirmed'};}
|
|
62
|
+
async history({chatId,cursor,count=20}) {requireInt64Id(chatId,'chat ID');if(!Number.isInteger(count)||count<1||count>100||(cursor!=null&&!/^\d{1,19}$/.test(String(cursor))))fail('Invalid history pagination.');let {data}=await this.call(5029,'PullChatJoinLeaveHistoryRequest',{chatId,count,...(cursor!=null?{cursor:String(cursor)}:{})},'PullChatJoinLeaveHistoryResponse');if(data.hasMore&&!data.nextCursor)throw new FeishuError('PAGINATION_INCOMPLETE','No continuation cursor was returned.');return {chatId,items:data.chatterHistory,hasMore:data.hasMore,nextCursor:data.hasMore?data.nextCursor:null};}
|
|
63
|
+
}
|
|
@@ -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 };
|