diff --git a/packages/onebot/tests/actions-group-admin.test.ts b/packages/onebot/tests/actions-group-admin.test.ts new file mode 100644 index 00000000..9e5d618c --- /dev/null +++ b/packages/onebot/tests/actions-group-admin.test.ts @@ -0,0 +1,1153 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiActionContext } from '../src/api-handler'; +import { actions } from '../src/actions/group-admin'; + +function requireAction(name: string) { + const action = actions.find((entry) => entry.names[0] === name); + if (!action) throw new Error(`${name} action missing`); + return action; +} + +function adminCtx(groupAdmin: Record>): { + ctx: ApiActionContext; + groupAdmin: typeof groupAdmin; +} { + return { + groupAdmin, + ctx: { bridge: { apis: { groupAdmin } } } as unknown as ApiActionContext, + }; +} + +function portraitCtx(setGroupAvatar = vi.fn(async () => {})): { + ctx: ApiActionContext; + setGroupAvatar: ReturnType; +} { + return { + setGroupAvatar, + ctx: { + bridge: { apis: { profile: { setGroupAvatar } } }, + } as unknown as ApiActionContext, + }; +} + +const setGroupKick = requireAction('set_group_kick'); +const setGroupKickMembers = requireAction('set_group_kick_members'); +const setGroupBan = requireAction('set_group_ban'); +const setGroupWholeBan = requireAction('set_group_whole_ban'); +const setGroupAddOption = requireAction('set_group_add_option'); +const setGroupSearch = requireAction('set_group_search'); +const setGroupMemberInvitePolicy = requireAction('set_group_member_invite_policy'); +const setGroupNewMemberHistoryVisibility = requireAction('set_group_new_member_history_visibility'); +const setGroupMemberPermissions = requireAction('set_group_member_permissions'); +const setGroupAdmin = requireAction('set_group_admin'); +const setGroupCard = requireAction('set_group_card'); +const setGroupName = requireAction('set_group_name'); +const setGroupLeave = requireAction('set_group_leave'); +const setGroupSpecialTitle = requireAction('set_group_special_title'); +const setGroupAnonymous = requireAction('set_group_anonymous'); +const setGroupAnonymousBan = requireAction('set_group_anonymous_ban'); +const setGroupPortrait = requireAction('set_group_portrait'); + +describe('group admin actions catalog', () => { + it('exports the public group-admin actions in source order', () => { + expect(actions.map((action) => [...action.names])).toEqual([ + ['set_group_kick'], + ['set_group_kick_members'], + ['set_group_ban'], + ['set_group_whole_ban'], + ['set_group_add_option'], + ['set_group_search'], + ['set_group_member_invite_policy'], + ['set_group_new_member_history_visibility'], + ['set_group_member_permissions'], + ['set_group_admin'], + ['set_group_card'], + ['set_group_name'], + ['set_group_leave'], + ['set_group_special_title'], + ['set_group_anonymous'], + ['set_group_anonymous_ban'], + ['set_group_portrait'], + ]); + expect(actions.map((action) => action.kind)).toEqual([ + 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', + 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', + 'normal', 'normal', 'normal', + ]); + }); +}); + +describe('set_group_kick parse', () => { + it('requires group_id and user_id and defaults reject_add_request to false', () => { + expect(setGroupKick.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, reject_add_request: false }, + }); + }); + + it('coerces numeric-string ids and an explicit reject flag', () => { + expect(setGroupKick.parse({ + group_id: '80001', + user_id: '24680', + reject_add_request: 'yes', + })).toEqual({ + ok: true, + value: { group_id: 80001, user_id: 24680, reject_add_request: true }, + }); + }); + + it('rejects a missing group_id', () => { + expect(setGroupKick.parse({ user_id: 271828 })).toEqual({ + ok: false, + field: 'group_id', + reason: 'is required', + }); + }); + + it('rejects group_id 0 and user_id 0', () => { + expect(setGroupKick.parse({ group_id: 0, user_id: 271828 })).toEqual({ + ok: false, + field: 'group_id', + reason: 'must be >= 1', + }); + expect(setGroupKick.parse({ group_id: 314159, user_id: 0 })).toEqual({ + ok: false, + field: 'user_id', + reason: 'must be >= 1', + }); + }); + + it('rejects an unrecognised reject_add_request synonym', () => { + expect(setGroupKick.parse({ + group_id: 314159, + user_id: 271828, + reject_add_request: 'maybe', + })).toEqual({ + ok: false, + field: 'reject_add_request', + reason: 'expected a boolean', + }); + }); +}); + +describe('set_group_kick toHandler', () => { + it('forwards the default reject flag and returns an empty ok payload', async () => { + const kickMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMember }); + + await expect(setGroupKick.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMember.mock.calls).toEqual([[314159, 271828, false]]); + }); + + it('forwards an explicit reject_add_request', async () => { + const kickMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMember }); + + await expect(setGroupKick.toHandler(ctx)({ + group_id: 80002, + user_id: 30003, + reject_add_request: 1, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMember.mock.calls).toEqual([[80002, 30003, true]]); + }); + + it('returns BAD_REQUEST for a missing user_id without kicking', async () => { + const kickMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMember }); + + await expect(setGroupKick.toHandler(ctx)({ group_id: 314159 })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'user_id: is required', + }); + expect(kickMember).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_kick_members parse', () => { + it('requires a non-empty member-id array and defaults reject_add_request', () => { + expect(setGroupKickMembers.parse({ + group_id: 888001, + user_id: [271828, '13579'], + })).toEqual({ + ok: true, + value: { group_id: 888001, user_id: [271828, 13579], reject_add_request: false }, + }); + }); + + it('keeps an explicit reject_add_request of false', () => { + expect(setGroupKickMembers.parse({ + group_id: 888001, + user_id: [24680], + reject_add_request: false, + })).toEqual({ + ok: true, + value: { group_id: 888001, user_id: [24680], reject_add_request: false }, + }); + }); + + it('rejects a missing or non-array user_id', () => { + expect(setGroupKickMembers.parse({ group_id: 888001 })).toEqual({ + ok: false, + field: 'user_id', + reason: 'is required', + }); + expect(setGroupKickMembers.parse({ group_id: 888001, user_id: 271828 })).toEqual({ + ok: false, + field: 'user_id', + reason: 'expected an array', + }); + }); + + it('rejects an empty member list and names a bad element index', () => { + expect(setGroupKickMembers.parse({ group_id: 888001, user_id: [] })).toEqual({ + ok: false, + field: 'user_id', + reason: 'must not be empty', + }); + expect(setGroupKickMembers.parse({ group_id: 888001, user_id: [271828, 0] })).toEqual({ + ok: false, + field: 'user_id[1]', + reason: 'must be >= 1', + }); + }); +}); + +describe('set_group_kick_members toHandler', () => { + it('forwards the member list and default reject flag', async () => { + const kickMembers = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMembers }); + + await expect(setGroupKickMembers.toHandler(ctx)({ + group_id: 888001, + user_id: [271828, 13579], + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMembers.mock.calls).toEqual([[888001, [271828, 13579], false]]); + }); + + it('forwards reject_add_request when kicking several members', async () => { + const kickMembers = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMembers }); + + await expect(setGroupKickMembers.toHandler(ctx)({ + group_id: '70001', + user_id: ['24681'], + reject_add_request: 'on', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMembers.mock.calls).toEqual([[70001, [24681], true]]); + }); + + it('returns BAD_REQUEST for an empty member list without kicking', async () => { + const kickMembers = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMembers }); + + await expect(setGroupKickMembers.toHandler(ctx)({ + group_id: 888001, + user_id: [], + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'user_id: must not be empty', + }); + expect(kickMembers).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_ban parse', () => { + it('defaults duration to 1800 and keeps a present 0 as unmute', () => { + expect(setGroupBan.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, duration: 1800 }, + }); + expect(setGroupBan.parse({ group_id: 314159, user_id: 271828, duration: 0 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, duration: 0 }, + }); + }); + + it('truncates a numeric-string duration', () => { + expect(setGroupBan.parse({ + group_id: 314159, + user_id: 271828, + duration: '600.9', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, duration: 600 }, + }); + }); + + it('rejects a negative duration', () => { + expect(setGroupBan.parse({ + group_id: 314159, + user_id: 271828, + duration: -1, + })).toEqual({ + ok: false, + field: 'duration', + reason: 'must be >= 0', + }); + }); +}); + +describe('set_group_ban toHandler', () => { + it('mutes with the default duration', async () => { + const muteMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteMember }); + + await expect(setGroupBan.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteMember.mock.calls).toEqual([[314159, 271828, 1800]]); + }); + + it('forwards duration 0 as unmute', async () => { + const muteMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteMember }); + + await expect(setGroupBan.toHandler(ctx)({ + group_id: 80003, + user_id: 30004, + duration: 0, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteMember.mock.calls).toEqual([[80003, 30004, 0]]); + }); + + it('returns BAD_REQUEST for a negative duration without muting', async () => { + const muteMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteMember }); + + await expect(setGroupBan.toHandler(ctx)({ + group_id: 314159, + user_id: 271828, + duration: -3, + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'duration: must be >= 0', + }); + expect(muteMember).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_ban describe', () => { + it('documents the group-user preset and the unmute-capable duration', () => { + const doc = setGroupBan.describe(); + + expect(doc.name).toBe('set_group_ban'); + expect(doc.aliases).toEqual([]); + expect(doc.summary).toBe('禁言群成员(duration=0 解除)'); + expect(doc.readOnly).toBe(false); + expect(doc.returns).toBeUndefined(); + expect(doc.returnsSchema).toBeUndefined(); + expect(doc.stream).toBeUndefined(); + expect(doc.invariants).toEqual([]); + expect(doc.params).toEqual([ + { + name: 'group_id', + type: 'uint', + required: true, + desc: '群号', + role: 'group_id', + schema: { type: 'integer', minimum: 1 }, + }, + { + name: 'user_id', + type: 'uint', + required: true, + desc: 'QQ 号', + role: 'member_id', + schema: { type: 'integer', minimum: 1 }, + }, + { + name: 'duration', + type: 'int', + required: false, + default: 1800, + role: 'duration', + schema: { type: 'integer', minimum: 0 }, + }, + ]); + expect(doc.inputSchema).toEqual({ + type: 'object', + additionalProperties: true, + required: ['group_id', 'user_id'], + properties: { + group_id: { + type: 'integer', + minimum: 1, + description: '群号', + 'x-role': 'group_id', + }, + user_id: { + type: 'integer', + minimum: 1, + description: 'QQ 号', + 'x-role': 'member_id', + }, + duration: { + type: 'integer', + minimum: 0, + default: 1800, + 'x-role': 'duration', + }, + }, + }); + }); +}); + +describe('set_group_whole_ban parse', () => { + it('defaults enable to true', () => { + expect(setGroupWholeBan.parse({ group_id: 941657197 })).toEqual({ + ok: true, + value: { group_id: 941657197, enable: true }, + }); + }); + + it('coerces enable false synonyms', () => { + expect(setGroupWholeBan.parse({ group_id: 941657197, enable: 0 })).toEqual({ + ok: true, + value: { group_id: 941657197, enable: false }, + }); + expect(setGroupWholeBan.parse({ group_id: 941657197, enable: 'OFF' })).toEqual({ + ok: true, + value: { group_id: 941657197, enable: false }, + }); + }); +}); + +describe('set_group_whole_ban toHandler', () => { + it('enables whole-group mute by default', async () => { + const muteAll = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteAll }); + + await expect(setGroupWholeBan.toHandler(ctx)({ group_id: 941657197 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteAll.mock.calls).toEqual([[941657197, true]]); + }); + + it('forwards an explicit disable', async () => { + const muteAll = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteAll }); + + await expect(setGroupWholeBan.toHandler(ctx)({ + group_id: 12345, + enable: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteAll.mock.calls).toEqual([[12345, false]]); + }); +}); + +describe('set_group_add_option parse', () => { + it('defaults add_type to 0 and keeps a present 0', () => { + expect(setGroupAddOption.parse({ group_id: 12345 })).toEqual({ + ok: true, + value: { group_id: 12345, add_type: 0 }, + }); + expect(setGroupAddOption.parse({ group_id: 12345, add_type: 0 })).toEqual({ + ok: true, + value: { group_id: 12345, add_type: 0 }, + }); + }); + + it('accepts a positive add_type and rejects a negative one', () => { + expect(setGroupAddOption.parse({ group_id: 12345, add_type: '2' })).toEqual({ + ok: true, + value: { group_id: 12345, add_type: 2 }, + }); + expect(setGroupAddOption.parse({ group_id: 12345, add_type: -1 })).toEqual({ + ok: false, + field: 'add_type', + reason: 'must be >= 0', + }); + }); +}); + +describe('set_group_add_option toHandler', () => { + it('forwards the default add_type of 0', async () => { + const setAddOption = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAddOption }); + + await expect(setGroupAddOption.toHandler(ctx)({ group_id: 12345 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAddOption.mock.calls).toEqual([[12345, 0]]); + }); + + it('forwards an explicit add_type', async () => { + const setAddOption = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAddOption }); + + await expect(setGroupAddOption.toHandler(ctx)({ + group_id: 941657197, + add_type: 3, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAddOption.mock.calls).toEqual([[941657197, 3]]); + }); +}); + +describe('set_group_search parse', () => { + it('leaves both search switches undefined when omitted', () => { + expect(setGroupSearch.parse({ group_id: 70001 })).toEqual({ + ok: true, + value: { + group_id: 70001, + no_finger_open: undefined, + no_code_finger_open: undefined, + }, + }); + }); + + it('keeps a present 0 instead of treating it as missing', () => { + expect(setGroupSearch.parse({ + group_id: 70001, + no_finger_open: 0, + no_code_finger_open: '1', + })).toEqual({ + ok: true, + value: { + group_id: 70001, + no_finger_open: 0, + no_code_finger_open: 1, + }, + }); + }); + + it('rejects a negative search switch', () => { + expect(setGroupSearch.parse({ group_id: 70001, no_finger_open: -1 })).toEqual({ + ok: false, + field: 'no_finger_open', + reason: 'must be >= 0', + }); + expect(setGroupSearch.parse({ group_id: 70001, no_code_finger_open: -2 })).toEqual({ + ok: false, + field: 'no_code_finger_open', + reason: 'must be >= 0', + }); + }); +}); + +describe('set_group_search toHandler', () => { + it('forwards omitted switches as undefined', async () => { + const setSearch = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSearch }); + + await expect(setGroupSearch.toHandler(ctx)({ group_id: 70001 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSearch.mock.calls).toEqual([[70001, undefined, undefined]]); + }); + + it('forwards both supplied switches', async () => { + const setSearch = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSearch }); + + await expect(setGroupSearch.toHandler(ctx)({ + group_id: 70002, + no_finger_open: 1, + no_code_finger_open: 0, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSearch.mock.calls).toEqual([[70002, 1, 0]]); + }); +}); + +describe('set_group_member_invite_policy parse', () => { + it.each([ + 'disabled', + 'require_approval', + 'no_approval', + 'no_approval_under_100', + ] as const)('accepts policy %s', (policy) => { + expect(setGroupMemberInvitePolicy.parse({ group_id: 12345, policy })).toEqual({ + ok: true, + value: { group_id: 12345, policy }, + }); + }); + + it('requires policy and rejects an unknown value', () => { + expect(setGroupMemberInvitePolicy.parse({ group_id: 12345 })).toEqual({ + ok: false, + field: 'policy', + reason: 'is required', + }); + expect(setGroupMemberInvitePolicy.parse({ + group_id: 12345, + policy: 'anything', + })).toEqual({ + ok: false, + field: 'policy', + reason: 'expected one of: disabled, require_approval, no_approval, no_approval_under_100', + }); + }); +}); + +describe('set_group_member_invite_policy toHandler', () => { + it('forwards the validated policy', async () => { + const setMemberInvitePolicy = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberInvitePolicy }); + + await expect(setGroupMemberInvitePolicy.toHandler(ctx)({ + group_id: '12345', + policy: 'no_approval_under_100', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setMemberInvitePolicy.mock.calls).toEqual([[12345, 'no_approval_under_100']]); + }); + + it('returns BAD_REQUEST for an unknown policy without calling the API', async () => { + const setMemberInvitePolicy = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberInvitePolicy }); + + await expect(setGroupMemberInvitePolicy.toHandler(ctx)({ + group_id: 12345, + policy: 'open', + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'policy: expected one of: disabled, require_approval, no_approval, no_approval_under_100', + }); + expect(setMemberInvitePolicy).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_new_member_history_visibility parse', () => { + it('requires visible and coerces boolean synonyms', () => { + expect(setGroupNewMemberHistoryVisibility.parse({ + group_id: 12345, + visible: 'false', + })).toEqual({ + ok: true, + value: { group_id: 12345, visible: false }, + }); + expect(setGroupNewMemberHistoryVisibility.parse({ group_id: 12345 })).toEqual({ + ok: false, + field: 'visible', + reason: 'is required', + }); + }); +}); + +describe('set_group_new_member_history_visibility toHandler', () => { + it('forwards the normalized group id and visibility', async () => { + const setNewMemberHistoryVisibility = vi.fn(async () => {}); + const { ctx } = adminCtx({ setNewMemberHistoryVisibility }); + + await expect(setGroupNewMemberHistoryVisibility.toHandler(ctx)({ + group_id: '12345', + visible: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setNewMemberHistoryVisibility.mock.calls).toEqual([[12345, false]]); + }); + + it('returns BAD_REQUEST when visible is missing', async () => { + const setNewMemberHistoryVisibility = vi.fn(async () => {}); + const { ctx } = adminCtx({ setNewMemberHistoryVisibility }); + + await expect(setGroupNewMemberHistoryVisibility.toHandler(ctx)({ group_id: 12345 })) + .resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'visible: is required', + }); + expect(setNewMemberHistoryVisibility).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_member_permissions parse', () => { + it('accepts a single capability switch and leaves the others undefined', () => { + expect(setGroupMemberPermissions.parse({ + group_id: 12345, + allow_member_upload_album: false, + })).toEqual({ + ok: true, + value: { + group_id: 12345, + allow_member_upload_album: false, + allow_member_temporary_session: undefined, + allow_member_create_group: undefined, + }, + }); + }); + + it('coerces every supplied capability switch', () => { + expect(setGroupMemberPermissions.parse({ + group_id: '12345', + allow_member_upload_album: 'true', + allow_member_temporary_session: false, + allow_member_create_group: 1, + })).toEqual({ + ok: true, + value: { + group_id: 12345, + allow_member_upload_album: true, + allow_member_temporary_session: false, + allow_member_create_group: true, + }, + }); + }); + + it('rejects an empty update after optional fields resolve to undefined', () => { + expect(setGroupMemberPermissions.parse({ group_id: 12345 })).toEqual({ + ok: false, + field: '', + reason: 'at least one of: allow_member_upload_album, allow_member_temporary_session, allow_member_create_group', + }); + }); +}); + +describe('set_group_member_permissions toHandler', () => { + it('remaps all supplied switches into the group-admin payload', async () => { + const setMemberPermissions = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberPermissions }); + + await expect(setGroupMemberPermissions.toHandler(ctx)({ + group_id: '12345', + allow_member_upload_album: 'true', + allow_member_temporary_session: false, + allow_member_create_group: 1, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setMemberPermissions.mock.calls).toEqual([[12345, { + allowMemberUploadAlbum: true, + allowMemberTemporarySession: false, + allowMemberCreateGroup: true, + }]]); + }); + + it('forwards a single supplied switch with the others undefined', async () => { + const setMemberPermissions = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberPermissions }); + + await expect(setGroupMemberPermissions.toHandler(ctx)({ + group_id: 12345, + allow_member_temporary_session: true, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setMemberPermissions.mock.calls).toEqual([[12345, { + allowMemberUploadAlbum: undefined, + allowMemberTemporarySession: true, + allowMemberCreateGroup: undefined, + }]]); + }); + + it('returns BAD_REQUEST for an empty update without calling the API', async () => { + const setMemberPermissions = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberPermissions }); + + await expect(setGroupMemberPermissions.toHandler(ctx)({ group_id: 12345 })) + .resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'at least one of: allow_member_upload_album, allow_member_temporary_session, allow_member_create_group', + }); + expect(setMemberPermissions).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_member_permissions describe', () => { + it('documents the at-least-one capability invariant', () => { + const doc = setGroupMemberPermissions.describe(); + + expect(doc.name).toBe('set_group_member_permissions'); + expect(doc.summary).toBe('设置群成员权限'); + expect(doc.invariants).toEqual([ + 'at least one of: allow_member_upload_album, allow_member_temporary_session, allow_member_create_group', + ]); + expect(doc.inputSchema).toEqual({ + type: 'object', + additionalProperties: true, + required: ['group_id'], + properties: { + group_id: { + type: 'integer', + minimum: 1, + description: '群号', + 'x-role': 'group_id', + }, + allow_member_upload_album: { type: 'boolean' }, + allow_member_temporary_session: { type: 'boolean' }, + allow_member_create_group: { type: 'boolean' }, + }, + }); + }); +}); + +describe('set_group_admin parse', () => { + it('defaults enable to true', () => { + expect(setGroupAdmin.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, enable: true }, + }); + }); + + it('accepts an explicit disable', () => { + expect(setGroupAdmin.parse({ + group_id: 314159, + user_id: 271828, + enable: 'no', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, enable: false }, + }); + }); +}); + +describe('set_group_admin toHandler', () => { + it('promotes a member with the default enable flag', async () => { + const setAdmin = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAdmin }); + + await expect(setGroupAdmin.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAdmin.mock.calls).toEqual([[314159, 271828, true]]); + }); + + it('forwards an explicit demotion', async () => { + const setAdmin = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAdmin }); + + await expect(setGroupAdmin.toHandler(ctx)({ + group_id: 80004, + user_id: 30005, + enable: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAdmin.mock.calls).toEqual([[80004, 30005, false]]); + }); +}); + +describe('set_group_card parse', () => { + it('defaults card to an empty string and keeps an explicit empty clear', () => { + expect(setGroupCard.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, card: '' }, + }); + expect(setGroupCard.parse({ + group_id: 314159, + user_id: 271828, + card: '', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, card: '' }, + }); + }); + + it('stringifies a numeric card and rejects a non-stringifiable value', () => { + expect(setGroupCard.parse({ + group_id: 314159, + user_id: 271828, + card: 404, + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, card: '404' }, + }); + expect(setGroupCard.parse({ + group_id: 314159, + user_id: 271828, + card: { text: 'nick' }, + })).toEqual({ + ok: false, + field: 'card', + reason: 'expected a string', + }); + }); +}); + +describe('set_group_card toHandler', () => { + it('forwards the default empty card as a clear', async () => { + const setCard = vi.fn(async () => {}); + const { ctx } = adminCtx({ setCard }); + + await expect(setGroupCard.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setCard.mock.calls).toEqual([[314159, 271828, '']]); + }); + + it('forwards an explicit card string', async () => { + const setCard = vi.fn(async () => {}); + const { ctx } = adminCtx({ setCard }); + + await expect(setGroupCard.toHandler(ctx)({ + group_id: 80005, + user_id: 30006, + card: '值班号', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setCard.mock.calls).toEqual([[80005, 30006, '值班号']]); + }); +}); + +describe('set_group_name parse', () => { + it('defaults group_name to an empty string', () => { + expect(setGroupName.parse({ group_id: 314159 })).toEqual({ + ok: true, + value: { group_id: 314159, group_name: '' }, + }); + }); + + it('stringifies a boolean group_name', () => { + expect(setGroupName.parse({ group_id: 314159, group_name: true })).toEqual({ + ok: true, + value: { group_id: 314159, group_name: 'true' }, + }); + }); +}); + +describe('set_group_name toHandler', () => { + it('forwards the default empty name', async () => { + const setName = vi.fn(async () => {}); + const { ctx } = adminCtx({ setName }); + + await expect(setGroupName.toHandler(ctx)({ group_id: 314159 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setName.mock.calls).toEqual([[314159, '']]); + }); + + it('forwards an explicit group name', async () => { + const setName = vi.fn(async () => {}); + const { ctx } = adminCtx({ setName }); + + await expect(setGroupName.toHandler(ctx)({ + group_id: 941657197, + group_name: 'Muted Group', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setName.mock.calls).toEqual([[941657197, 'Muted Group']]); + }); +}); + +describe('set_group_leave parse', () => { + it('requires only group_id and drops undeclared keys', () => { + expect(setGroupLeave.parse({ group_id: 314159, extra: true })).toEqual({ + ok: true, + value: { group_id: 314159 }, + }); + }); + + it('rejects a missing group_id', () => { + expect(setGroupLeave.parse({})).toEqual({ + ok: false, + field: 'group_id', + reason: 'is required', + }); + }); +}); + +describe('set_group_leave toHandler', () => { + it('forwards the group id to leave', async () => { + const leave = vi.fn(async () => {}); + const { ctx } = adminCtx({ leave }); + + await expect(setGroupLeave.toHandler(ctx)({ group_id: 314159 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(leave.mock.calls).toEqual([[314159]]); + }); + + it('returns BAD_REQUEST for group_id 0 without leaving', async () => { + const leave = vi.fn(async () => {}); + const { ctx } = adminCtx({ leave }); + + await expect(setGroupLeave.toHandler(ctx)({ group_id: 0 })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'group_id: must be >= 1', + }); + expect(leave).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_special_title parse', () => { + it('defaults special_title to an empty string', () => { + expect(setGroupSpecialTitle.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, special_title: '' }, + }); + }); + + it('keeps an explicit empty title', () => { + expect(setGroupSpecialTitle.parse({ + group_id: 314159, + user_id: 271828, + special_title: '', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, special_title: '' }, + }); + }); +}); + +describe('set_group_special_title toHandler', () => { + it('forwards the default empty title', async () => { + const setSpecialTitle = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSpecialTitle }); + + await expect(setGroupSpecialTitle.toHandler(ctx)({ + group_id: 314159, + user_id: 271828, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSpecialTitle.mock.calls).toEqual([[314159, 271828, '']]); + }); + + it('forwards an explicit title', async () => { + const setSpecialTitle = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSpecialTitle }); + + await expect(setGroupSpecialTitle.toHandler(ctx)({ + group_id: 80006, + user_id: 30007, + special_title: '龙王', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSpecialTitle.mock.calls).toEqual([[80006, 30007, '龙王']]); + }); +}); + +describe('set_group_anonymous parse', () => { + it('accepts any params and returns an empty object', () => { + expect(setGroupAnonymous.parse({})).toEqual({ ok: true, value: {} }); + expect(setGroupAnonymous.parse({ group_id: 314159, enable: true })).toEqual({ + ok: true, + value: {}, + }); + }); +}); + +describe('set_group_anonymous toHandler', () => { + it('returns ok without touching the bridge', async () => { + await expect(setGroupAnonymous.toHandler({} as ApiActionContext)({ + group_id: 314159, + enable: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + }); +}); + +describe('set_group_anonymous describe', () => { + it('documents the unimplemented anonymous switch', () => { + const doc = setGroupAnonymous.describe(); + + expect(doc.name).toBe('set_group_anonymous'); + expect(doc.summary).toBe('匿名开关(未实现,返回 ok)'); + expect(doc.readOnly).toBe(false); + expect(doc.params).toEqual([]); + expect(doc.invariants).toEqual([]); + expect(doc.inputSchema).toEqual({ + type: 'object', + properties: {}, + additionalProperties: true, + }); + }); +}); + +describe('set_group_anonymous_ban parse', () => { + it('accepts any params and returns an empty object', () => { + expect(setGroupAnonymousBan.parse({ + group_id: 314159, + anonymous_flag: 'x', + duration: 60, + })).toEqual({ ok: true, value: {} }); + }); +}); + +describe('set_group_anonymous_ban toHandler', () => { + it('returns ok without touching the bridge', async () => { + await expect(setGroupAnonymousBan.toHandler({} as ApiActionContext)({ + flag: 'anon', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + }); +}); + +describe('set_group_anonymous_ban describe', () => { + it('documents the unimplemented anonymous mute', () => { + expect(setGroupAnonymousBan.describe().summary).toBe('匿名禁言(未实现,返回 ok)'); + }); +}); + +describe('set_group_portrait parse', () => { + it('requires a non-empty image source and stringifies primitives', () => { + expect(setGroupPortrait.parse({ + group_id: 314159, + file: 'https://example.invalid/avatar.png', + })).toEqual({ + ok: true, + value: { group_id: 314159, file: 'https://example.invalid/avatar.png' }, + }); + expect(setGroupPortrait.parse({ group_id: 314159, file: 10001 })).toEqual({ + ok: true, + value: { group_id: 314159, file: '10001' }, + }); + }); + + it('rejects a missing or empty file', () => { + expect(setGroupPortrait.parse({ group_id: 314159 })).toEqual({ + ok: false, + field: 'file', + reason: 'is required', + }); + expect(setGroupPortrait.parse({ group_id: 314159, file: '' })).toEqual({ + ok: false, + field: 'file', + reason: 'must not be empty', + }); + }); + + it('rejects a non-stringifiable file', () => { + expect(setGroupPortrait.parse({ + group_id: 314159, + file: { url: 'https://example.invalid/avatar.png' }, + })).toEqual({ + ok: false, + field: 'file', + reason: 'expected a string', + }); + }); +}); + +describe('set_group_portrait toHandler', () => { + it('forwards the image source to profile.setGroupAvatar', async () => { + const { ctx, setGroupAvatar } = portraitCtx(); + + await expect(setGroupPortrait.toHandler(ctx)({ + group_id: 314159, + file: 'base64://abc', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setGroupAvatar.mock.calls).toEqual([[314159, 'base64://abc']]); + }); + + it('returns BAD_REQUEST for an empty file without setting the avatar', async () => { + const { ctx, setGroupAvatar } = portraitCtx(); + + await expect(setGroupPortrait.toHandler(ctx)({ + group_id: 314159, + file: '', + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'file: must not be empty', + }); + expect(setGroupAvatar).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/actions-message.test.ts b/packages/onebot/tests/actions-message.test.ts new file mode 100644 index 00000000..35d55765 --- /dev/null +++ b/packages/onebot/tests/actions-message.test.ts @@ -0,0 +1,570 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiActionContext } from '../src/api-handler'; +import { actions } from '../src/actions/message'; +import type { JsonObject, MessageMeta } from '../src/types'; + +function requireAction(name: string) { + const action = actions.find((entry) => entry.names[0] === name); + if (!action) throw new Error(`${name} action missing`); + return action; +} + +function asCtx(partial: Partial): ApiActionContext { + return partial as ApiActionContext; +} + +const sendMsg = requireAction('send_msg'); +const sendPrivateMsg = requireAction('send_private_msg'); +const sendGroupMsg = requireAction('send_group_msg'); +const getMsg = requireAction('get_msg'); +const deleteMsg = requireAction('delete_msg'); + +describe('message actions catalog', () => { + it('exports the five public message actions in source order', () => { + expect(actions.map((entry) => entry.names[0])).toEqual([ + 'send_msg', + 'send_private_msg', + 'send_group_msg', + 'get_msg', + 'delete_msg', + ]); + }); + + it('marks only get_msg as read-only', () => { + expect(sendMsg.describe().readOnly).toBe(false); + expect(sendPrivateMsg.describe().readOnly).toBe(false); + expect(sendGroupMsg.describe().readOnly).toBe(false); + expect(getMsg.describe().readOnly).toBe(true); + expect(deleteMsg.describe().readOnly).toBe(false); + }); +}); + +describe('send_msg parse', () => { + it('defaults auto_escape to false and leaves optional ids unset', () => { + expect(sendMsg.parse({ message: 'hello route' })).toEqual({ + ok: true, + value: { + message: 'hello route', + message_type: undefined, + group_id: undefined, + user_id: undefined, + auto_escape: false, + }, + }); + }); + + it('parses a JSON-array message string and numeric ids', () => { + expect(sendMsg.parse({ + message: '[{"type":"text","data":{"text":"hi"}}]', + message_type: 'group', + group_id: '314159', + user_id: '271828', + auto_escape: 'on', + })).toEqual({ + ok: true, + value: { + message: [{ type: 'text', data: { text: 'hi' } }], + message_type: 'group', + group_id: 314159, + user_id: 271828, + auto_escape: true, + }, + }); + }); + + it('requires message and rejects group_id 0', () => { + expect(sendMsg.parse({})).toEqual({ + ok: false, + field: 'message', + reason: 'is required', + }); + expect(sendMsg.parse({ message: 'x', group_id: 0 })).toEqual({ + ok: false, + field: 'group_id', + reason: 'must be >= 1', + }); + }); +}); + +describe('send_msg run', () => { + it('sends a group message when message_type is group', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9001 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'group', + group_id: 314159, + message: 'group hello', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9001 } }); + expect(sendGroupMessage.mock.calls).toEqual([[314159, 'group hello', false]]); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('sends a group message when only group_id is present', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9002 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + group_id: 80001, + user_id: 271828, + message: [{ type: 'text', data: { text: 'by group_id' } }], + auto_escape: true, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9002 } }); + expect(sendGroupMessage.mock.calls).toEqual([[ + 80001, + [{ type: 'text', data: { text: 'by group_id' } }], + true, + ]]); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('sends a private message when only user_id is present', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9003 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + user_id: 271828, + message: 'private hello', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9003 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[271828, 'private hello', false, undefined]]); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('routes private + both ids into a temp-session reply', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9004 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'private', + user_id: 13579, + group_id: 70001, + message: 'temp hi', + auto_escape: false, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9004 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[13579, 'temp hi', false, 70001]]); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('still sends a group message when message_type is group and user_id is also set', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9005 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'group', + group_id: 80002, + user_id: 30003, + message: 'not temp', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9005 } }); + expect(sendGroupMessage.mock.calls).toEqual([[80002, 'not temp', false]]); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('returns BAD_REQUEST when message_type is group without group_id', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'group', + message: 'missing group', + }); + + expect(response).toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'group_id is required', + }); + expect(sendGroupMessage).not.toHaveBeenCalled(); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('returns BAD_REQUEST when neither a group route nor user_id is present', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'private', + message: 'missing user', + }); + + expect(response).toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'user_id is required', + }); + expect(sendGroupMessage).not.toHaveBeenCalled(); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('shapes a parse failure as BAD_REQUEST wording', async () => { + const response = await sendMsg.toHandler(asCtx({}))({}); + + expect(response).toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'message: is required', + }); + }); +}); + +describe('send_private_msg', () => { + it('parses group_id 0 and defaults auto_escape', () => { + expect(sendPrivateMsg.parse({ + user_id: 24680, + message: 'plain private', + group_id: 0, + })).toEqual({ + ok: true, + value: { + user_id: 24680, + message: 'plain private', + group_id: 0, + auto_escape: false, + }, + }); + }); + + it('rejects a negative group_id before sending', () => { + expect(sendPrivateMsg.parse({ + user_id: 24680, + message: 'x', + group_id: -1, + })).toEqual({ + ok: false, + field: 'group_id', + reason: 'must be >= 0', + }); + }); + + it('sends a friend private message when group_id is absent', async () => { + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9101 })); + const response = await sendPrivateMsg.toHandler(asCtx({ sendPrivateMessage }))({ + user_id: 24680, + message: 'friend hi', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9101 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[24680, 'friend hi', false, undefined]]); + }); + + it('treats group_id 0 as no temp session', async () => { + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9102 })); + const response = await sendPrivateMsg.toHandler(asCtx({ sendPrivateMessage }))({ + user_id: 24682, + group_id: 0, + message: 'zero group', + auto_escape: true, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9102 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[24682, 'zero group', true, undefined]]); + }); + + it('forwards a positive group_id as the temp-session source', async () => { + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9103 })); + const response = await sendPrivateMsg.toHandler(asCtx({ sendPrivateMessage }))({ + user_id: 24681, + group_id: 70002, + message: 'temp from group', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9103 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[24681, 'temp from group', false, 70002]]); + }); +}); + +describe('send_group_msg', () => { + it('requires group_id from the groupAction preset', () => { + expect(sendGroupMsg.parse({ message: 'need group' })).toEqual({ + ok: false, + field: 'group_id', + reason: 'is required', + }); + expect(sendGroupMsg.parse({ group_id: 888001, message: 'ok' })).toEqual({ + ok: true, + value: { + group_id: 888001, + message: 'ok', + auto_escape: false, + }, + }); + }); + + it('sends the group message and returns the receipt id', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9201 })); + const response = await sendGroupMsg.toHandler(asCtx({ sendGroupMessage }))({ + group_id: 888001, + message: 'group body', + auto_escape: true, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9201 } }); + expect(sendGroupMessage.mock.calls).toEqual([[888001, 'group body', true]]); + }); +}); + +describe('get_msg', () => { + it('accepts a negative message_id and rejects 0', () => { + expect(getMsg.parse({ message_id: -2147483648 })).toEqual({ + ok: true, + value: { message_id: -2147483648 }, + }); + expect(getMsg.parse({ message_id: 0 })).toEqual({ + ok: false, + field: 'message_id', + reason: 'must not be 0', + }); + }); + + it('returns ACTION_FAILED when the store has no event', async () => { + const getMessage = vi.fn(() => null); + const response = await getMsg.toHandler(asCtx({ getMessage }))({ message_id: 424243 }); + + expect(response).toEqual({ + status: 'failed', + retcode: 100, + data: null, + wording: 'message not found', + }); + expect(getMessage.mock.calls).toEqual([[424243]]); + }); + + it('strips post_type/self_id and sets real_id from the stored message_id', async () => { + const stored: JsonObject = { + post_type: 'message', + self_id: 10001, + message_id: 424242, + message_type: 'group', + group_id: 314159, + user_id: 271828, + message: 'plain stored text', + time: 1700000000, + }; + const getMessage = vi.fn(() => stored); + const getImageInfo = vi.fn(async () => ({ url: 'https://unused.example/img' })); + const response = await getMsg.toHandler(asCtx({ getMessage, getImageInfo }))({ + message_id: 424242, + }); + + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_id: 424242, + message_type: 'group', + group_id: 314159, + user_id: 271828, + message: 'plain stored text', + time: 1700000000, + real_id: 424242, + }, + }); + expect(stored).toEqual({ + post_type: 'message', + self_id: 10001, + message_id: 424242, + message_type: 'group', + group_id: 314159, + user_id: 271828, + message: 'plain stored text', + time: 1700000000, + }); + expect(getImageInfo).not.toHaveBeenCalled(); + }); + + it('falls back to the request message_id when the stored event has none', async () => { + const getMessage = vi.fn(() => ({ + message_type: 'private', + user_id: 13579, + message: 'no stored id', + })); + const response = await getMsg.toHandler(asCtx({ getMessage }))({ message_id: 555001 }); + + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_type: 'private', + user_id: 13579, + message: 'no stored id', + real_id: 555001, + }, + }); + }); + + it('refreshes image URLs from file, then file_id, and skips unusable segments', async () => { + const fileImage: JsonObject = { + file: 'ABC.jpg', + file_id: 'SHOULD_NOT_WIN.jpg', + url: 'https://old.example/ABC.jpg', + }; + const fileIdImage: JsonObject = { + file_id: 'BY_FILE_ID.jpg', + url: 'https://old.example/file-id.jpg', + }; + const emptyFileImage: JsonObject = { + file: '', + file_id: 'SHOULD_NOT_USE.jpg', + url: 'https://old.example/empty-file.jpg', + }; + const keepEmptyUrl: JsonObject = { + file: 'KEEP_EMPTY.jpg', + url: 'https://old.example/keep-empty.jpg', + }; + const keepNull: JsonObject = { + file: 'KEEP_NULL.jpg', + url: 'https://old.example/keep-null.jpg', + }; + const keepNonString: JsonObject = { + file: 'KEEP_NONSTRING.jpg', + url: 'https://old.example/keep-nonstring.jpg', + }; + const noHandle: JsonObject = { + url: 'https://old.example/no-file.jpg', + }; + const stored: JsonObject = { + message_id: 777001, + message: [ + null, + 'skip-me', + 12, + { type: 'text', data: { text: 'plain' } }, + { type: 'image', data: 'not-object' }, + { type: 'image' }, + { type: 'image', data: emptyFileImage }, + { type: 'image', data: noHandle }, + { type: 'image', data: fileIdImage }, + { type: 'image', data: keepEmptyUrl }, + { type: 'image', data: keepNull }, + { type: 'image', data: keepNonString }, + { type: 'image', data: fileImage }, + ], + }; + const getImageInfo = vi.fn(async (file: string) => { + if (file === 'ABC.jpg') return { url: 'https://new.example/ABC.jpg?rkey=FRESH' }; + if (file === 'BY_FILE_ID.jpg') return { url: 'https://new.example/file-id.jpg?rkey=FRESH' }; + if (file === 'KEEP_EMPTY.jpg') return { url: '' }; + if (file === 'KEEP_NULL.jpg') return null; + if (file === 'KEEP_NONSTRING.jpg') return { url: 1 }; + return { url: 'https://should-not-apply.example/' }; + }); + + const response = await getMsg.toHandler(asCtx({ + getMessage: () => stored, + getImageInfo, + }))({ message_id: 777001 }); + + expect(getImageInfo.mock.calls).toEqual([ + ['BY_FILE_ID.jpg'], + ['KEEP_EMPTY.jpg'], + ['KEEP_NULL.jpg'], + ['KEEP_NONSTRING.jpg'], + ['ABC.jpg'], + ]); + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_id: 777001, + real_id: 777001, + message: [ + null, + 'skip-me', + 12, + { type: 'text', data: { text: 'plain' } }, + { type: 'image', data: 'not-object' }, + { type: 'image' }, + { type: 'image', data: emptyFileImage }, + { type: 'image', data: noHandle }, + { type: 'image', data: fileIdImage }, + { type: 'image', data: keepEmptyUrl }, + { type: 'image', data: keepNull }, + { type: 'image', data: keepNonString }, + { type: 'image', data: fileImage }, + ], + }, + }); + expect(fileImage.url).toBe('https://new.example/ABC.jpg?rkey=FRESH'); + expect(fileIdImage.url).toBe('https://new.example/file-id.jpg?rkey=FRESH'); + expect(emptyFileImage.url).toBe('https://old.example/empty-file.jpg'); + expect(keepEmptyUrl.url).toBe('https://old.example/keep-empty.jpg'); + expect(keepNull.url).toBe('https://old.example/keep-null.jpg'); + expect(keepNonString.url).toBe('https://old.example/keep-nonstring.jpg'); + expect(noHandle.url).toBe('https://old.example/no-file.jpg'); + }); + + it('keeps the stored image URL when getImageInfo throws', async () => { + const imageData: JsonObject = { + file: 'THROW.jpg', + url: 'https://old.example/throw.jpg', + }; + const getImageInfo = vi.fn(async () => { + throw new Error('rkey fetch failed'); + }); + const response = await getMsg.toHandler(asCtx({ + getMessage: () => ({ + message_id: 777002, + message: [{ type: 'image', data: imageData }], + }), + getImageInfo, + }))({ message_id: 777002 }); + + expect(getImageInfo.mock.calls).toEqual([['THROW.jpg']]); + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_id: 777002, + real_id: 777002, + message: [{ type: 'image', data: imageData }], + }, + }); + expect(imageData.url).toBe('https://old.example/throw.jpg'); + }); +}); + +describe('delete_msg', () => { + it('returns ACTION_FAILED when no retractable meta exists', async () => { + const getMessageMeta = vi.fn(() => null); + const deleteMessage = vi.fn(async () => {}); + const response = await deleteMsg.toHandler(asCtx({ getMessageMeta, deleteMessage }))({ + message_id: 424245, + }); + + expect(response).toEqual({ + status: 'failed', + retcode: 100, + data: null, + wording: 'message not found or not retractable', + }); + expect(getMessageMeta.mock.calls).toEqual([[424245]]); + expect(deleteMessage).not.toHaveBeenCalled(); + }); + + it('deletes with the stored meta and returns an empty ok payload', async () => { + const meta: MessageMeta = { + isGroup: true, + targetId: 314159, + sequence: 77, + sequenceAuthoritative: true, + eventName: 'group_message', + clientSequence: 0, + random: 123, + timestamp: 1700000000, + }; + const getMessageMeta = vi.fn(() => meta); + const deleteMessage = vi.fn(async () => {}); + const response = await deleteMsg.toHandler(asCtx({ getMessageMeta, deleteMessage }))({ + message_id: -424244, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: null }); + expect(getMessageMeta.mock.calls).toEqual([[-424244]]); + expect(deleteMessage.mock.calls).toEqual([[-424244, meta]]); + }); +}); diff --git a/packages/onebot/tests/instance-context.test.ts b/packages/onebot/tests/instance-context.test.ts new file mode 100644 index 00000000..f8d1e2ea --- /dev/null +++ b/packages/onebot/tests/instance-context.test.ts @@ -0,0 +1,1227 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { GroupMemberInfo, GroupRequestInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; +import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context'; +import { + GROUP_MESSAGE_EVENT, + PRIVATE_NT_MESSAGE_EVENT, + hashMessageIdInt32, +} from '../src/message-id'; +import { TempSessionStore } from '../src/temp-session-store'; +import type { JsonObject, MessageMeta, OneBotConfig } from '../src/types'; + +const SELF_UIN = '10001'; +const SELF_ID = 10001; +const PEER_ID = 20002; +const GROUP_ID = 710001; +const RECEIPT = { + messageId: 900001, + sequence: 77, + clientSequence: 14, + random: 424242, + timestamp: 1_725_000_000, +}; + +function groupMeta(overrides: Partial = {}): MessageMeta { + return { + isGroup: true, + targetId: GROUP_ID, + sequence: 42, + sequenceAuthoritative: true, + eventName: GROUP_MESSAGE_EVENT, + clientSequence: 0, + random: 7, + timestamp: 1_725_000_000, + ...overrides, + }; +} + +function privateMeta(overrides: Partial = {}): MessageMeta { + return { + isGroup: false, + targetId: PEER_ID, + sequence: 42, + sequenceAuthoritative: true, + eventName: PRIVATE_NT_MESSAGE_EVENT, + clientSequence: 9, + random: 7, + timestamp: 1_725_000_000, + ...overrides, + }; +} + +function makeGroup(groupId: number, groupName: string, extras: Partial = {}): QQGroupInfo { + return { + groupId, + groupName, + remark: '', + memberCount: 3, + memberMax: 200, + members: new Map(), + ...extras, + }; +} + +function makeMember(uin: number, nickname: string, extras: Partial = {}): GroupMemberInfo { + return { + uin, + uid: `u_${uin}`, + nickname, + card: '', + isRobot: false, + role: 'member', + level: 4, + title: '', + joinTime: 1_700_000_100, + lastSentTime: 1_700_000_200, + shutUpTime: 0, + ...extras, + }; +} + +function makeRequest(overrides: Partial = {}): GroupRequestInfo { + return { + groupId: 710010, + groupName: 'sys-group', + targetUid: 'u_20002', + targetUin: PEER_ID, + targetName: 'applicant', + invitorUid: 'u_inviter', + invitorUin: 30003, + invitorName: 'inviter', + operatorUid: 'u_operator', + operatorUin: 40004, + operatorName: 'operator', + sequence: 888, + state: 1, + notifyType: 7, + eventType: 22, + comment: 'please add', + filtered: false, + ...overrides, + }; +} + +function makeRef(overrides: { + uin?: string; + selfId?: number; + identity?: Record; + apis?: Record>; + messageStore?: Record; + mediaStore?: Record; + reactionStore?: Record; + converterCtx?: Record; + extraBridge?: Record; +} = {}): { + ref: OneBotInstanceContext; + api: ReturnType; + dispatchEvent: ReturnType; + cacheMessageMeta: ReturnType; + events: Map; + metas: Map; +} { + const events = new Map(); + const metas = new Map(); + const dispatchEvent = vi.fn(); + const cacheMessageMeta = vi.fn((messageId: number, meta: MessageMeta) => { + metas.set(messageId, meta); + }); + + const messageStore = { + findEvent: (messageId: number) => events.get(messageId) ?? null, + findMeta: (messageId: number) => metas.get(messageId) ?? null, + storeMetas: (entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>) => { + for (const entry of entries) metas.set(entry.messageId, entry.meta); + }, + storeEvent: ( + messageId: number, + _isGroup: boolean, + _sessionId: number, + _sequence: number, + _eventName: string, + event: JsonObject, + ) => { + events.set(messageId, event); + }, + listReadSessions: vi.fn(() => ({ groupIds: [GROUP_ID], privateUserIds: [PEER_ID] })), + resolveReplySequence: () => null, + findLatestAuthoritativeSequence: () => null, + listSessionEvents: vi.fn(() => []), + ...overrides.messageStore, + }; + + const bridge = { + identity: { + uin: SELF_UIN, + nickname: 'SnowLuma', + groups: [] as QQGroupInfo[], + friends: [] as Array<{ uin: number; nickname: string; remark: string }>, + findGroup: () => null, + findGroupMember: () => null, + findUserProfile: () => null, + findFriend: () => null, + findUinByUid: () => undefined, + ...overrides.identity, + }, + apis: { + message: { + sendPrivate: vi.fn(async () => RECEIPT), + sendGroup: vi.fn(async () => RECEIPT), + sendGroupTempMessage: vi.fn(async () => RECEIPT), + recallGroup: vi.fn(async () => undefined), + recallPrivate: vi.fn(async () => undefined), + getGroupHistory: vi.fn(async () => []), + getC2cHistory: vi.fn(async () => []), + getC2cLatestHistory: vi.fn(async () => []), + ...overrides.apis?.message, + }, + contacts: { + fetchFriendList: vi.fn(async () => []), + fetchGroupList: vi.fn(async () => []), + fetchGroupDetail: vi.fn(async () => null), + fetchGroupMemberList: vi.fn(async () => []), + fetchUserProfile: vi.fn(async () => { + throw new Error('no profile'); + }), + fetchGroupRequests: vi.fn(async () => []), + fetchDownloadRKeys: vi.fn(async () => []), + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + getGroupInviteCardSequence: vi.fn(() => undefined), + ...overrides.apis?.contacts, + }, + groupFile: { + list: vi.fn(async () => ({ files: [], folders: [] })), + getPttUrl: vi.fn(async () => ''), + getPrivatePttUrl: vi.fn(async () => ''), + ...overrides.apis?.groupFile, + }, + groupAdmin: { + setAddRequest: vi.fn(async () => undefined), + ...overrides.apis?.groupAdmin, + }, + interaction: { + setReaction: vi.fn(async () => undefined), + fetchReactionSummary: vi.fn(async () => []), + setEssence: vi.fn(async () => undefined), + ...overrides.apis?.interaction, + }, + forward: { + upload: vi.fn(async () => 'forward-res-id'), + fetch: vi.fn(async () => []), + ...overrides.apis?.forward, + }, + extras: { + translatePttToText: vi.fn(async () => ''), + ...overrides.apis?.extras, + }, + }, + resolveUserUid: vi.fn(async () => 'u_peer'), + ...overrides.extraBridge, + }; + + const ref = { + uin: overrides.uin ?? SELF_UIN, + selfId: overrides.selfId ?? SELF_ID, + bridge, + messageStore, + mediaStore: { + findImage: () => null, + findRecord: () => null, + updateRecordUrl: vi.fn(), + ...overrides.mediaStore, + }, + reactionStore: { + listUsers: vi.fn(() => []), + countUsers: vi.fn(() => 0), + ...overrides.reactionStore, + }, + tempSessions: new TempSessionStore(), + converterCtx: { + selfId: overrides.selfId ?? SELF_ID, + imageUrlResolver: null, + mediaUrlResolver: null, + messageIdResolver: null, + mediaSegmentSink: null, + ...overrides.converterCtx, + }, + config: { + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + } as OneBotConfig, + cacheMessageMeta, + dispatchEvent, + } as unknown as OneBotInstanceContext; + + return { + ref, + api: buildApiContext(ref), + dispatchEvent, + cacheMessageMeta, + events, + metas, + }; +} + +describe('buildApiContext capabilities', () => { + it('reports the account as online and able to send image or record', () => { + const { api } = makeRef(); + expect(api.isOnline()).toBe(true); + expect(api.canSendImage()).toBe(true); + expect(api.canSendRecord()).toBe(true); + }); +}); + +describe('buildApiContext getLoginInfo', () => { + it('parses uin and uses the identity nickname', () => { + const { api } = makeRef({ + uin: '188001', + identity: { nickname: 'login-nick' }, + }); + expect(api.getLoginInfo()).toEqual({ userId: 188001, nickname: 'login-nick' }); + }); + + it('falls back to the uin string when the nickname is empty', () => { + const { api } = makeRef({ + uin: '188002', + identity: { nickname: '' }, + }); + expect(api.getLoginInfo()).toEqual({ userId: 188002, nickname: '188002' }); + }); + + it('uses userId 0 when uin is not a number', () => { + const { api } = makeRef({ + uin: 'not-a-uin', + identity: { nickname: 'fallback-nick' }, + }); + expect(api.getLoginInfo()).toEqual({ userId: 0, nickname: 'fallback-nick' }); + }); +}); + +describe('buildApiContext message-store passthroughs', () => { + it('reads events and metas through the message store', () => { + const storedEvent = { + post_type: 'message', + message_type: 'group', + message_id: -55, + raw_message: 'stored', + }; + const storedMeta = groupMeta({ sequence: 91 }); + const { api, events, metas } = makeRef(); + events.set(-55, storedEvent); + metas.set(-55, storedMeta); + + expect(api.getMessage(-55)).toEqual({ + post_type: 'message', + message_type: 'group', + message_id: -55, + raw_message: 'stored', + }); + expect(api.getMessage(1)).toBeNull(); + expect(api.getMessageMeta(-55)).toEqual({ + isGroup: true, + targetId: GROUP_ID, + sequence: 91, + sequenceAuthoritative: true, + eventName: GROUP_MESSAGE_EVENT, + clientSequence: 0, + random: 7, + timestamp: 1_725_000_000, + }); + }); + + it('stores meta batches on the message store', () => { + const storeMetas = vi.fn(); + const { api } = makeRef({ messageStore: { storeMetas } }); + const entries = [{ messageId: -12, meta: privateMeta({ sequence: 8 }) }]; + + api.cacheMessageMetas(entries); + + expect(storeMetas).toHaveBeenCalledOnce(); + expect(storeMetas).toHaveBeenCalledWith(entries); + }); + + it('lists read sessions from the current identity group ids', () => { + const listReadSessions = vi.fn(() => ({ + groupIds: [710101, 710102], + privateUserIds: [50001], + })); + const { api } = makeRef({ + identity: { + groups: [makeGroup(710101, 'A'), makeGroup(710102, 'B')], + }, + messageStore: { listReadSessions }, + }); + + expect(api.listReadSessions()).toEqual({ + groupIds: [710101, 710102], + privateUserIds: [50001], + }); + expect(listReadSessions).toHaveBeenCalledWith([710101, 710102]); + }); +}); + +describe('buildApiContext setMsgEmojiLike', () => { + it('throws when the message is missing', async () => { + const { api } = makeRef(); + await expect(api.setMsgEmojiLike(-1, '76', true)).rejects.toThrow('message not found'); + }); + + it('throws when the message is private', async () => { + const { api, metas } = makeRef(); + metas.set(-2, privateMeta()); + await expect(api.setMsgEmojiLike(-2, '76', true)) + .rejects.toThrow('emoji reactions are not supported on private messages'); + }); + + it('throws when the stored sequence is not authoritative', async () => { + const { api, metas } = makeRef(); + metas.set(-3, groupMeta({ sequenceAuthoritative: false, sequence: 42 })); + await expect(api.setMsgEmojiLike(-3, '76', true)) + .rejects.toThrow('message has no authoritative QQ sequence'); + }); + + it('throws when the stored sequence is not a positive integer', async () => { + const { api, metas } = makeRef(); + metas.set(-4, groupMeta({ sequence: 0 })); + await expect(api.setMsgEmojiLike(-4, '76', true)) + .rejects.toThrow('message has no authoritative QQ sequence'); + }); + + it('sets the reaction on the group message', async () => { + const setReaction = vi.fn(async () => undefined); + const { api, metas, ref } = makeRef({ + apis: { interaction: { setReaction, fetchReactionSummary: vi.fn(async () => []) } }, + }); + metas.set(-5, groupMeta({ targetId: 710201, sequence: 4242 })); + + await api.setMsgEmojiLike(-5, '76', true); + + expect(setReaction).toHaveBeenCalledWith(710201, 4242, '76', true); + expect(ref.bridge.apis.interaction.setReaction).toHaveBeenCalledOnce(); + }); + + it('clears the reaction when set is false', async () => { + const setReaction = vi.fn(async () => undefined); + const { api, metas } = makeRef({ + apis: { interaction: { setReaction, fetchReactionSummary: vi.fn(async () => []) } }, + }); + metas.set(-6, groupMeta({ targetId: 710202, sequence: 88 })); + + await api.setMsgEmojiLike(-6, '144', false); + + expect(setReaction).toHaveBeenCalledWith(710202, 88, '144', false); + }); +}); + +describe('buildApiContext fetchEmojiLikeUsers', () => { + it('throws when the message is missing', async () => { + const { api } = makeRef(); + await expect(api.fetchEmojiLikeUsers(-1, '76', 20)).rejects.toThrow('message not found'); + }); + + it('throws when the message is private', async () => { + const { api, metas } = makeRef(); + metas.set(-2, privateMeta()); + await expect(api.fetchEmojiLikeUsers(-2, '76', 20)) + .rejects.toThrow('emoji reactions are not supported on private messages'); + }); + + it('throws when the stored sequence is not authoritative', async () => { + const { api, metas } = makeRef(); + metas.set(-3, groupMeta({ sequence: 1.5 })); + await expect(api.fetchEmojiLikeUsers(-3, '76', 20)) + .rejects.toThrow('message has no authoritative QQ sequence'); + }); + + it('maps cached users and defaults the offset to 0', async () => { + const listUsers = vi.fn(() => [ + { operatorUin: 20002, operatorUid: 'u_20002', setAt: 1_700_000_001 }, + ]); + const countUsers = vi.fn(() => 1); + const fetchReactionSummary = vi.fn(async () => [{ emojiId: '76', count: 1 }]); + const { api, metas } = makeRef({ + reactionStore: { listUsers, countUsers }, + apis: { interaction: { setReaction: vi.fn(), fetchReactionSummary } }, + }); + metas.set(-7, groupMeta({ targetId: 710301, sequence: 55 })); + + await expect(api.fetchEmojiLikeUsers(-7, '76', 20)).resolves.toEqual({ + users: [{ uin: 20002, uid: 'u_20002', setAt: 1_700_000_001 }], + cachedCount: 1, + serverCount: 1, + complete: true, + }); + expect(listUsers).toHaveBeenCalledWith(710301, 55, '76', 20, 0); + expect(countUsers).toHaveBeenCalledWith(710301, 55, '76'); + }); + + it('forwards a custom offset to the reaction store', async () => { + const listUsers = vi.fn(() => []); + const countUsers = vi.fn(() => 0); + const { api, metas } = makeRef({ + reactionStore: { listUsers, countUsers }, + }); + metas.set(-8, groupMeta({ targetId: 710302, sequence: 9 })); + + await api.fetchEmojiLikeUsers(-8, '144', 5, 3); + + expect(listUsers).toHaveBeenCalledWith(710302, 9, '144', 5, 3); + }); + + it('uses the matching server summary count and reports incomplete when cache is short', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [{ operatorUin: 1, operatorUid: 'u_1', setAt: 10 }], + countUsers: () => 2, + }, + apis: { + interaction: { + setReaction: vi.fn(), + fetchReactionSummary: vi.fn(async () => [ + { emojiId: '99', count: 4 }, + { emojiId: '76', count: 8 }, + ]), + }, + }, + }); + metas.set(-9, groupMeta({ targetId: 710303, sequence: 12 })); + + await expect(api.fetchEmojiLikeUsers(-9, '76', 10)).resolves.toEqual({ + users: [{ uin: 1, uid: 'u_1', setAt: 10 }], + cachedCount: 2, + serverCount: 8, + complete: false, + }); + }); + + it('keeps the cached count when the summary has no matching emoji', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [], + countUsers: () => 3, + }, + apis: { + interaction: { + setReaction: vi.fn(), + fetchReactionSummary: vi.fn(async () => [{ emojiId: '99', count: 9 }]), + }, + }, + }); + metas.set(-10, groupMeta({ targetId: 710304, sequence: 13 })); + + await expect(api.fetchEmojiLikeUsers(-10, '76', 10)).resolves.toEqual({ + users: [], + cachedCount: 3, + serverCount: 3, + complete: true, + }); + }); + + it('reports complete when the cache already exceeds the server count', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [], + countUsers: () => 6, + }, + apis: { + interaction: { + fetchReactionSummary: vi.fn(async () => [{ emojiId: '76', count: 5 }]), + }, + }, + }); + metas.set(-12, groupMeta({ targetId: 710306, sequence: 15 })); + + await expect(api.fetchEmojiLikeUsers(-12, '76', 10)).resolves.toEqual({ + users: [], + cachedCount: 6, + serverCount: 5, + complete: true, + }); + }); + + it('keeps the cached count when the summary fetch fails', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [], + countUsers: () => 4, + }, + apis: { + interaction: { + setReaction: vi.fn(), + fetchReactionSummary: vi.fn(async () => { + throw new Error('summary down'); + }), + }, + }, + }); + metas.set(-11, groupMeta({ targetId: 710305, sequence: 14 })); + + await expect(api.fetchEmojiLikeUsers(-11, '76', 10)).resolves.toEqual({ + users: [], + cachedCount: 4, + serverCount: 4, + complete: true, + }); + }); +}); + +describe('buildApiContext recall and essence', () => { + it('recalls a group message by target and sequence', async () => { + const recallGroup = vi.fn(async () => undefined); + const { api, ref } = makeRef({ + apis: { message: { recallGroup } }, + }); + + await api.deleteMessage(-20, groupMeta({ targetId: 710401, sequence: 33 })); + + expect(recallGroup).toHaveBeenCalledWith(710401, 33); + expect(ref.bridge.apis.message.recallPrivate).not.toHaveBeenCalled(); + }); + + it('recalls a private message with client sequence, random and timestamp', async () => { + const { api, ref } = makeRef(); + const meta = privateMeta({ + targetId: 20099, + clientSequence: 18, + sequence: 66, + random: 1234, + timestamp: 1_725_111_000, + }); + + await api.deleteMessage(-21, meta); + + expect(ref.bridge.apis.message.recallPrivate).toHaveBeenCalledWith( + 20099, + 18, + 66, + 1234, + 1_725_111_000, + ); + expect(ref.bridge.apis.message.recallGroup).not.toHaveBeenCalled(); + }); + + it('enables and disables essence through the same interaction API', async () => { + const setEssence = vi.fn(async () => undefined); + const { api, metas, ref } = makeRef({ + apis: { interaction: { setReaction: vi.fn(), fetchReactionSummary: vi.fn(), setEssence } }, + }); + metas.set(-22, groupMeta({ targetId: 710402, sequence: 50, random: 9 })); + + await api.setEssenceMsg(-22); + await api.deleteEssenceMsg(-22); + + expect(setEssence).toHaveBeenNthCalledWith(1, 710402, 50, 9, true); + expect(setEssence).toHaveBeenNthCalledWith(2, 710402, 50, 9, false); + expect(ref.bridge.apis.interaction.setEssence).toHaveBeenCalledTimes(2); + }); +}); + +describe('buildApiContext handleGroupRequest', () => { + it('approves a canonical flag and ignores the unused sub_type argument', async () => { + const setAddRequest = vi.fn(async () => undefined); + const fetchGroupRequests = vi.fn(async () => []); + const { api, ref } = makeRef({ + apis: { + groupAdmin: { setAddRequest }, + contacts: { fetchGroupRequests }, + }, + }); + + await api.handleGroupRequest('slreq:1:123456:710410:22:1', 'add', true, 'welcome'); + + expect(setAddRequest).toHaveBeenCalledWith(710410, 123456, 22, true, 'welcome', true); + expect(fetchGroupRequests).not.toHaveBeenCalled(); + expect(ref.bridge.apis.groupAdmin.setAddRequest).toHaveBeenCalledOnce(); + }); +}); + +describe('buildApiContext contact reads', () => { + it('maps the friend list into OneBot fields', async () => { + const { api } = makeRef({ + apis: { + contacts: { + fetchFriendList: vi.fn(async () => [ + { uin: 22222, uid: 'u_22222', nickname: 'alice', remark: 'best-friend' }, + ]), + }, + }, + }); + + await expect(api.getFriendList()).resolves.toEqual([ + { user_id: 22222, nickname: 'alice', remark: 'best-friend' }, + ]); + }); + + it('maps the cached group list and forces a refresh when noCache is true', async () => { + const groups = [makeGroup(710501, 'Group A', { + remark: 'work', + createTime: 100, + level: 2, + memo: 'rules', + allMuted: true, + })]; + const fetchGroupList = vi.fn(async () => groups); + const { api } = makeRef({ + identity: { groups }, + apis: { contacts: { fetchGroupList } }, + }); + + await expect(api.getGroupList()).resolves.toEqual([{ + group_id: 710501, + group_name: 'Group A', + group_remark: 'work', + member_count: 3, + max_member_count: 200, + group_create_time: 100, + group_level: 2, + group_memo: 'rules', + group_all_shut: -1, + }]); + expect(fetchGroupList).not.toHaveBeenCalled(); + + await api.getGroupList(true); + expect(fetchGroupList).toHaveBeenCalledOnce(); + }); + + it('returns joined-group info including the detail level', async () => { + const cached = makeGroup(710502, 'Group E', { remark: '常用群', allMuted: false }); + const { api } = makeRef({ + identity: { findGroup: (groupId: number) => groupId === 710502 ? cached : null }, + apis: { + contacts: { + fetchGroupDetail: vi.fn(async () => ({ ...cached, level: 6 })), + }, + }, + }); + + await expect(api.getGroupInfo(710502)).resolves.toEqual({ + group_id: 710502, + group_name: 'Group E', + group_remark: '常用群', + member_count: 3, + max_member_count: 200, + group_create_time: 0, + group_level: 6, + group_memo: '', + group_all_shut: 0, + }); + }); + + it('maps group members and a single member lookup', async () => { + const member = makeMember(20002, 'bob', { card: 'card-bob', isRobot: true, role: 'admin', title: 't' }); + const fetchGroupMemberList = vi.fn(async () => [member]); + const { api } = makeRef({ + identity: { + findGroupMember: (groupId: number, userId: number) => + groupId === 710503 && userId === 20002 ? member : null, + }, + apis: { contacts: { fetchGroupMemberList } }, + }); + + await expect(api.getGroupMemberList(710503)).resolves.toEqual([{ + group_id: 710503, + user_id: 20002, + nickname: 'bob', + card: 'card-bob', + is_robot: true, + sex: 'unknown', + age: 0, + join_time: 1_700_000_100, + last_sent_time: 1_700_000_200, + shut_up_timestamp: 0, + level: '4', + role: 'admin', + title: 't', + area: '', + unfriendly: false, + title_expire_time: 0, + card_changeable: true, + }]); + await expect(api.getGroupMemberInfo(710503, 20002)).resolves.toMatchObject({ + group_id: 710503, + user_id: 20002, + nickname: 'bob', + is_robot: true, + }); + }); + + it('maps a stranger profile from the contacts API', async () => { + const { api } = makeRef({ + apis: { + contacts: { + fetchUserProfile: vi.fn(async () => ({ + uin: 20002, + uid: 'u_20002', + nickname: 'stranger', + remark: 'r', + sex: 'female', + age: 21, + sign: 'hello sign', + level: 17, + })), + }, + }, + }); + + await expect(api.getStrangerInfo(20002)).resolves.toEqual({ + user_id: 20002, + nickname: 'stranger', + remark: 'r', + sex: 'female', + age: 21, + long_nick: 'hello sign', + qq_level: 17, + level: 17, + }); + }); + + it('lists group files and defaults a missing folder id to /', async () => { + const list = vi.fn(async () => ({ + files: [{ + fileId: 'f1', + fileName: 'a.txt', + busId: 102, + fileSize: 12, + uploadTime: 10, + deadTime: 0, + modifyTime: 11, + downloadTimes: 2, + uploader: 20002, + uploaderName: 'alice', + }], + folders: [{ + folderId: 'd1', + folderName: 'dir', + createTime: 100, + creator: 123, + creatorName: 'creator', + totalFileCount: 2, + lastUploadTime: 200, + lastUploader: 5_000_000_001, + lastUploaderName: 'uploader', + }], + })); + const { api } = makeRef({ + apis: { groupFile: { list, getPttUrl: vi.fn(), getPrivatePttUrl: vi.fn() } }, + }); + + await expect(api.getGroupFiles(710504)).resolves.toEqual({ + files: [{ + group_id: 710504, + file_id: 'f1', + file_name: 'a.txt', + busid: 102, + file_size: 12, + upload_time: 10, + dead_time: 0, + modify_time: 11, + download_times: 2, + uploader: 20002, + uploader_name: 'alice', + }], + folders: [{ + group_id: 710504, + folder_id: 'd1', + folder_name: 'dir', + create_time: 100, + creator: 123, + create_name: 'creator', + total_file_count: 2, + last_upload_time: 200, + last_uploader: 5_000_000_001, + last_uploader_name: 'uploader', + }], + }); + expect(list).toHaveBeenCalledWith(710504, '/'); + }); + + it('maps download rkeys and returns an empty list when the fetch fails', async () => { + const ok = makeRef({ + apis: { + contacts: { + fetchDownloadRKeys: vi.fn(async () => [ + { rkey: 'rk', type: 20, ttlSeconds: 3600, createTime: 100 }, + ]), + }, + }, + }); + await expect(ok.api.getDownloadRKeys()).resolves.toEqual([ + { rkey: 'rk', type: 20, ttl: 3600, create_time: 100 }, + ]); + + const failed = makeRef({ + apis: { + contacts: { + fetchDownloadRKeys: vi.fn(async () => { + throw new Error('rkey down'); + }), + }, + }, + }); + await expect(failed.api.getDownloadRKeys()).resolves.toEqual([]); + }); + + it('maps pending group system messages for the supplied query', async () => { + const { api } = makeRef({ + apis: { + contacts: { + fetchGroupRequests: vi.fn(async (filtered: boolean) => + filtered ? [] : [makeRequest()]), + }, + }, + }); + + await expect(api.handleGetGroupSystemMsg({ + groupId: 710010, + onlyPending: true, + count: 10, + })).resolves.toEqual([{ + group_id: 710010, + group_name: 'sys-group', + request_id: 888, + requester_uin: 20002, + requester_nick: 'applicant', + message: 'please add', + checked: false, + flag: 'slreq:1:888:710010:22:0', + }]); + }); +}); + +describe('buildApiContext media', () => { + it('resolves image info with the converter imageUrlResolver', async () => { + const resolver = vi.fn(async () => 'https://cdn.example/fresh'); + const { api } = makeRef({ + mediaStore: { + findImage: (file: string) => file === 'pic.jpg' + ? { + file: 'pic.jpg', + url: 'https://cdn.example/stale', + fileSize: 64, + fileName: 'pic.jpg', + subType: 0, + summary: '', + isGroup: true, + sessionId: GROUP_ID, + imageUrl: 'https://cdn.example/raw', + } + : null, + }, + converterCtx: { imageUrlResolver: resolver }, + }); + + await expect(api.getImageInfo('pic.jpg')).resolves.toEqual({ + file: 'https://cdn.example/fresh', + url: 'https://cdn.example/fresh', + file_size: '64', + file_name: 'pic.jpg', + }); + expect(resolver).toHaveBeenCalledWith( + { type: 'image', imageUrl: 'https://cdn.example/raw', subType: 0 }, + true, + ); + await expect(api.getImageInfo('missing.jpg')).resolves.toBeNull(); + }); + + it('returns cached record info and refetches a missing group ptt url', async () => { + const getPttUrl = vi.fn(async () => 'https://ptt.example/group'); + const updateRecordUrl = vi.fn(); + const mediaNode = { fileUuid: 'uuid-1' }; + const { api } = makeRef({ + mediaStore: { + findRecord: (file: string) => file === 'voice.amr' + ? { + file: 'voice.amr', + fileId: 'rec-1', + url: '', + fileSize: 32, + fileName: 'voice.amr', + duration: 3, + fileHash: 'hash', + mediaNode, + isGroup: true, + sessionId: GROUP_ID, + } + : null, + updateRecordUrl, + }, + apis: { groupFile: { list: vi.fn(), getPttUrl, getPrivatePttUrl: vi.fn() } }, + }); + + await expect(api.getRecordInfo('voice.amr')).resolves.toEqual({ + file: 'https://ptt.example/group', + url: 'https://ptt.example/group', + file_size: '32', + file_name: 'voice.amr', + }); + expect(getPttUrl).toHaveBeenCalledWith(GROUP_ID, mediaNode); + expect(updateRecordUrl).toHaveBeenCalledWith('voice.amr', 'https://ptt.example/group'); + await expect(api.getRecordInfo('missing.amr')).resolves.toBeNull(); + }); + + it('transcribes a private ptt using the instance selfId as peer', async () => { + const translatePttToText = vi.fn(async () => 'hello text'); + const { api, events } = makeRef({ + selfId: 188003, + mediaStore: { + findRecord: () => ({ + file: 'voice.silk', + fileId: 'ptt-uuid', + url: 'https://ptt.example/c2c', + fileSize: 16, + fileName: 'voice.silk', + duration: 2, + fileHash: 'hash', + isGroup: false, + sessionId: PEER_ID, + md5Hex: 'aa', + voiceFormat: 1, + }), + }, + apis: { extras: { translatePttToText } }, + }); + events.set(-30, { + message_type: 'private', + user_id: PEER_ID, + message: [{ type: 'record', data: { file: 'voice.silk' } }], + }); + + await expect(api.fetchPttText(-30)).resolves.toEqual({ text: 'hello text' }); + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: -30, + senderUin: PEER_ID, + peerUin: 188003, + uuid: 'ptt-uuid', + md5Hex: 'aa', + duration: 2, + size: 16, + format: 1, + }); + }); + + it('rejects ptt transcription when the stored event is missing', async () => { + const { api } = makeRef(); + await expect(api.fetchPttText(-31)).rejects.toThrow('消息不存在或已被撤回'); + }); +}); + +describe('buildApiContext send and forward dispatch', () => { + it('dispatches a friend private send as a message_sent event', async () => { + const { api, dispatchEvent, ref } = makeRef(); + + const result = await api.sendPrivateMessage(PEER_ID, [ + { type: 'text', data: { text: 'hello' } }, + ], false); + + expect(result.messageId).toBe(hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT)); + expect(ref.bridge.apis.message.sendPrivate).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledWith({ + time: 1_725_000_000, + self_id: SELF_ID, + post_type: 'message_sent', + message_type: 'private', + sub_type: 'friend', + message_id: hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT), + message_seq: 14, + user_id: SELF_ID, + message: [{ type: 'text', data: { text: 'hello' } }], + raw_message: 'hello', + font: 0, + sender: { user_id: SELF_ID, nickname: 'SnowLuma', sex: 'unknown', age: 0 }, + target_id: PEER_ID, + }, 'send'); + }); + + it('does not dispatch a temp-session private send', async () => { + const { api, dispatchEvent, ref } = makeRef(); + ref.tempSessions.record(PEER_ID, GROUP_ID); + + const result = await api.sendPrivateMessage( + PEER_ID, + [{ type: 'text', data: { text: 'temp hi' } }], + false, + GROUP_ID, + ); + + expect(result.messageId).toBe(hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT)); + expect(ref.bridge.apis.message.sendGroupTempMessage).toHaveBeenCalledWith( + PEER_ID, + GROUP_ID, + [{ type: 'text', text: 'temp hi' }], + ); + expect(ref.bridge.apis.message.sendPrivate).not.toHaveBeenCalled(); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + + it('sends a group message without a self-sent dispatch callback', async () => { + const { api, dispatchEvent, ref } = makeRef(); + + const result = await api.sendGroupMessage(GROUP_ID, [ + { type: 'text', data: { text: 'group hi' } }, + ], false); + + expect(result.messageId).toBe(hashMessageIdInt32(77, GROUP_ID, GROUP_MESSAGE_EVENT)); + expect(ref.bridge.apis.message.sendGroup).toHaveBeenCalledWith( + GROUP_ID, + [{ type: 'text', text: 'group hi' }], + ); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + + it('dispatches a private forward send', async () => { + const { api, dispatchEvent, ref } = makeRef(); + + const result = await api.sendPrivateForwardMsg(PEER_ID, [{ + type: 'node', + data: { + user_id: SELF_ID, + nickname: 'SnowLuma', + content: [{ type: 'text', data: { text: 'forwarded' } }], + }, + }]); + + expect(result).toEqual({ + messageId: hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT), + forwardId: 'forward-res-id', + }); + expect(ref.bridge.apis.forward.upload).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent.mock.calls[0][1]).toBe('send'); + expect(dispatchEvent.mock.calls[0][0]).toMatchObject({ + post_type: 'message_sent', + message_type: 'private', + self_id: SELF_ID, + user_id: SELF_ID, + target_id: PEER_ID, + message_seq: 14, + }); + }); + + it('dispatches a single-message forward to a friend and not to a group', async () => { + const friend = makeRef(); + friend.events.set(-40, { + message_id: -40, + message_type: 'private', + user_id: PEER_ID, + message: [{ type: 'text', data: { text: 'forward me' } }], + }); + + await expect(friend.api.forwardSingleMsg(-40, { userId: PEER_ID })).resolves.toEqual({ + messageId: hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT), + }); + expect(friend.dispatchEvent).toHaveBeenCalledOnce(); + expect(friend.dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({ + post_type: 'message_sent', + message_type: 'private', + target_id: PEER_ID, + message: [{ type: 'text', data: { text: 'forward me' } }], + }), 'send'); + + const group = makeRef(); + group.events.set(-41, { + message_id: -41, + message_type: 'group', + group_id: GROUP_ID, + user_id: PEER_ID, + message: [{ type: 'text', data: { text: 'to group' } }], + }); + + await expect(group.api.forwardSingleMsg(-41, { groupId: GROUP_ID })).resolves.toEqual({ + messageId: hashMessageIdInt32(77, GROUP_ID, GROUP_MESSAGE_EVENT), + }); + expect(group.ref.bridge.apis.message.sendGroup).toHaveBeenCalledOnce(); + expect(group.dispatchEvent).not.toHaveBeenCalled(); + }); + + it('uploads a forward pack and sends a group forward card', async () => { + const { api, ref, dispatchEvent } = makeRef(); + const nodes = [{ + type: 'node', + data: { + user_id: SELF_ID, + nickname: 'SnowLuma', + content: [{ type: 'text', data: { text: 'pack' } }], + }, + }]; + + await expect(api.sendForwardMsg(nodes, GROUP_ID)).resolves.toEqual({ + forwardId: 'forward-res-id', + }); + expect(ref.bridge.apis.forward.upload).toHaveBeenCalledOnce(); + + await expect(api.sendGroupForwardMsg(GROUP_ID, nodes)).resolves.toEqual({ + messageId: hashMessageIdInt32(77, GROUP_ID, GROUP_MESSAGE_EVENT), + forwardId: 'forward-res-id', + }); + expect(ref.bridge.apis.message.sendGroup).toHaveBeenCalledOnce(); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + + it('loads a stored forward by res_id', async () => { + const fetch = vi.fn(async () => [{ + messageType: 'private', + userUin: PEER_ID, + nickname: 'peer', + time: 1_725_000_100, + msgId: 11, + msgSeq: 12, + elements: [{ type: 'text', text: 'from-forward' }], + }]); + const { api } = makeRef({ + apis: { forward: { upload: vi.fn(), fetch } }, + }); + + await expect(api.getForwardMsg('res-abc')).resolves.toEqual([{ + self_id: SELF_ID, + user_id: PEER_ID, + time: 1_725_000_100, + message_id: 11, + message_seq: 12, + real_id: 11, + message_type: 'private', + sender: { user_id: PEER_ID, nickname: 'peer' }, + raw_message: '', + font: 14, + sub_type: 'friend', + message: [{ type: 'text', data: { text: 'from-forward' } }], + message_format: 'array', + post_type: 'message', + }]); + expect(fetch).toHaveBeenCalledWith('res-abc'); + }); +}); + +describe('buildApiContext history', () => { + it('returns an empty list for non-positive session ids', async () => { + const { api } = makeRef(); + await expect(api.getGroupMsgHistory(0)).resolves.toEqual([]); + await expect(api.getFriendMsgHistory(-5)).resolves.toEqual([]); + }); + + it('falls back to the local group store when there is no server anchor', async () => { + const stored = { + post_type: 'message', + self_id: SELF_ID, + message_type: 'group', + group_id: GROUP_ID, + message_id: -50, + raw_message: 'old', + }; + const listSessionEvents = vi.fn(() => [stored]); + const { api } = makeRef({ + messageStore: { + findLatestAuthoritativeSequence: () => null, + listSessionEvents, + }, + }); + + await expect(api.getGroupMsgHistory(GROUP_ID, undefined, 5, false)).resolves.toEqual([{ + message_type: 'group', + group_id: GROUP_ID, + message_id: -50, + raw_message: 'old', + real_id: -50, + }]); + expect(listSessionEvents).toHaveBeenCalledWith(true, GROUP_ID, 5, undefined, false); + }); +}); diff --git a/packages/onebot/tests/media-actions-more.test.ts b/packages/onebot/tests/media-actions-more.test.ts new file mode 100644 index 00000000..30f428d7 --- /dev/null +++ b/packages/onebot/tests/media-actions-more.test.ts @@ -0,0 +1,851 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { + fetchPttText, + getImageInfo, + getRecordInfo, +} from '../src/modules/media-actions'; +import { + deliverPttTransText, + failPttTransWaiter, + pttTransKey, +} from '../src/modules/ptt-trans-waiter'; +import type { CachedImage, CachedRecord, MediaStore } from '../src/media-store'; +import type { MessageStore } from '../src/message-store'; +import type { JsonObject } from '../src/types'; + +const SELF_ID = 7654321; +const PEER_UIN = 20002; +const GROUP_ID = 710010; +const RAW_IMAGE = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=DEF'; + +const usedPttKeys = new Set(); + +afterEach(() => { + vi.useRealTimers(); + for (const key of usedPttKeys) { + failPttTransWaiter(key, new Error('test cleanup')); + } + usedPttKeys.clear(); +}); + +function trackPttKey(selfId: number, messageId: number): string { + const key = pttTransKey(selfId, messageId); + usedPttKeys.add(key); + return key; +} + +function fakeMessageStore(event: JsonObject | null): MessageStore { + return { findEvent: () => event } as unknown as MessageStore; +} + +function fakeImageStore(image: CachedImage | null): MediaStore { + return { findImage: () => image } as unknown as MediaStore; +} + +function fakeRecordStore( + record: CachedRecord | null, + extras: { updateRecordUrl?: ReturnType } = {}, +): MediaStore { + return { + findRecord: () => record, + updateRecordUrl: extras.updateRecordUrl ?? vi.fn(), + } as unknown as MediaStore; +} + +function cachedImage(overrides: Partial = {}): CachedImage { + return { + file: 'DEF.jpg', + url: `${RAW_IMAGE}&rkey=STALE`, + fileSize: 2048, + fileName: 'DEF.jpg', + subType: 1, + summary: '', + isGroup: false, + sessionId: PEER_UIN, + imageUrl: RAW_IMAGE, + ...overrides, + }; +} + +function cachedRecord(overrides: Partial = {}): CachedRecord { + return { + file: 'voice.silk', + fileId: 'ptt-uuid-1', + url: 'https://ptt.example/c2c.silk', + fileSize: 4096, + fileName: 'voice.silk', + duration: 7, + fileHash: 'deadbeef', + isGroup: false, + sessionId: PEER_UIN, + md5Hex: 'aabbccddeeff00112233445566778899', + voiceFormat: 1, + ...overrides, + }; +} + +function recordEvent(overrides: JsonObject = {}): JsonObject { + return { + message_type: 'private', + user_id: PEER_UIN, + message: [{ type: 'record', data: { file: 'voice.silk' } }], + ...overrides, + }; +} + +function fakeBridge(overrides: { + translatePttToText?: ReturnType; + getPttUrl?: ReturnType; + getPrivatePttUrl?: ReturnType; +} = {}): BridgeInterface { + return { + apis: { + extras: { + translatePttToText: overrides.translatePttToText ?? vi.fn(async () => ''), + }, + groupFile: { + getPttUrl: overrides.getPttUrl ?? vi.fn(async () => ''), + getPrivatePttUrl: overrides.getPrivatePttUrl ?? vi.fn(async () => ''), + }, + }, + } as unknown as BridgeInterface; +} + +describe('fetchPttText', () => { + it('throws when the message event is missing', async () => { + await expect(fetchPttText( + fakeMessageStore(null), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40001, + )).rejects.toThrow('消息不存在或已被撤回'); + }); + + it('throws when event.message is not an array', async () => { + await expect(fetchPttText( + fakeMessageStore({ + message_type: 'private', + user_id: PEER_UIN, + message: '[CQ:record,file=voice.silk]', + }), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40002, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('throws when the message has no record segment', async () => { + await expect(fetchPttText( + fakeMessageStore({ + message_type: 'private', + user_id: PEER_UIN, + message: [{ type: 'text', data: { text: 'hi' } }], + }), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40003, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('skips non-object segments and non-record types before finding a record', async () => { + const translatePttToText = vi.fn(async () => '跳过垃圾段落后转写'); + const store = { + findRecord: vi.fn((file: string) => file === 'keep.silk' ? cachedRecord({ file: 'keep.silk' }) : null), + } as unknown as MediaStore; + const event = { + message_type: 'private', + user_id: PEER_UIN, + message: [ + null, + 'x', + 12, + ['record'], + { type: 'image', data: { file: 'pic.jpg' } }, + { type: 'record', data: { file: 'keep.silk' } }, + ], + }; + + trackPttKey(SELF_ID, 40004); + await expect(fetchPttText( + fakeMessageStore(event), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40004, + )).resolves.toEqual({ text: '跳过垃圾段落后转写' }); + expect(store.findRecord).toHaveBeenCalledWith('keep.silk'); + }); + + it('throws when the record segment has no file and no url', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: {} }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40005, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('throws when record data is not a plain object', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: 'voice.silk' }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40006, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('throws when record data is an array', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: [{ file: 'voice.silk' }] }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40007, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('does not fall back to url when file is an empty string', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: { file: '', url: 'https://ptt.example/ignored.silk' } }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40008, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('looks the record up by data.url when data.file is absent', async () => { + const translatePttToText = vi.fn(async () => 'url 字段转写'); + const store = { + findRecord: vi.fn((file: string) => ( + file === 'https://ptt.example/by-url.silk' + ? cachedRecord({ file: 'https://ptt.example/by-url.silk' }) + : null + )), + } as unknown as MediaStore; + + trackPttKey(SELF_ID, 40009); + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: { url: 'https://ptt.example/by-url.silk' } }], + })), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40009, + )).resolves.toEqual({ text: 'url 字段转写' }); + expect(store.findRecord).toHaveBeenCalledWith('https://ptt.example/by-url.silk'); + }); + + it('uses the first record segment even when a later one exists', async () => { + const translatePttToText = vi.fn(async () => '第一段'); + const store = { + findRecord: vi.fn((file: string) => ( + file === 'first.silk' ? cachedRecord({ file: 'first.silk' }) : null + )), + } as unknown as MediaStore; + + trackPttKey(SELF_ID, 40010); + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [ + { type: 'record', data: { file: 'first.silk' } }, + { type: 'record', data: { file: 'second.silk' } }, + ], + })), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40010, + )).resolves.toEqual({ text: '第一段' }); + expect(store.findRecord).toHaveBeenCalledWith('first.silk'); + expect(store.findRecord).not.toHaveBeenCalledWith('second.silk'); + }); + + it('stringifies a numeric file id before cache lookup', async () => { + const translatePttToText = vi.fn(async () => '数字 file'); + const store = { + findRecord: vi.fn((file: string) => file === '9001' ? cachedRecord({ file: '9001' }) : null), + } as unknown as MediaStore; + + trackPttKey(SELF_ID, 40011); + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: { file: 9001 } }], + })), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40011, + )).resolves.toEqual({ text: '数字 file' }); + expect(store.findRecord).toHaveBeenCalledWith('9001'); + }); + + it('throws when the record is not in the media cache', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(null), + fakeBridge(), + SELF_ID, + 40012, + )).rejects.toThrow('语音不在缓存中,无法转写'); + }); + + it('transcribes a private ptt with selfId as peerUin and inline text', async () => { + const translatePttToText = vi.fn(async () => '今天天气不错'); + trackPttKey(SELF_ID, 40013); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40013, + )).resolves.toEqual({ text: '今天天气不错' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: 40013, + senderUin: 20002, + peerUin: 7654321, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('treats message_type group as a group ptt and uses group_id as peerUin', async () => { + const translatePttToText = vi.fn(async () => '群语音'); + trackPttKey(SELF_ID, 40014); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message_type: 'group', + group_id: GROUP_ID, + user_id: PEER_UIN, + })), + fakeRecordStore(cachedRecord({ isGroup: false, sessionId: 1 })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40014, + )).resolves.toEqual({ text: '群语音' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: true, + msgId: 40014, + senderUin: 20002, + peerUin: 710010, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('uses cached.sessionId when group_id is missing or zero', async () => { + const translatePttToText = vi.fn(async () => 'session 回退'); + trackPttKey(SELF_ID, 40015); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message_type: 'group', + group_id: 0, + user_id: PEER_UIN, + })), + fakeRecordStore(cachedRecord({ isGroup: true, sessionId: 888001 })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40015, + )).resolves.toEqual({ text: 'session 回退' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: true, + msgId: 40015, + senderUin: 20002, + peerUin: 888001, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('treats a private event as group when the cached record is a group ptt', async () => { + const translatePttToText = vi.fn(async () => '缓存标记群'); + trackPttKey(SELF_ID, 40016); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message_type: 'private', + group_id: 555000, + })), + fakeRecordStore(cachedRecord({ isGroup: true, sessionId: 555000 })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40016, + )).resolves.toEqual({ text: '缓存标记群' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: true, + msgId: 40016, + senderUin: 20002, + peerUin: 555000, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('defaults senderUin and fingerprint fields when they are missing', async () => { + const translatePttToText = vi.fn(async () => '缺省指纹'); + trackPttKey(SELF_ID, 40017); + + await expect(fetchPttText( + fakeMessageStore({ + message_type: 'private', + message: [{ type: 'record', data: { file: 'voice.silk' } }], + }), + fakeRecordStore(cachedRecord({ + fileId: '', + md5Hex: undefined, + duration: undefined as unknown as number, + fileSize: undefined as unknown as number, + voiceFormat: undefined, + })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40017, + )).resolves.toEqual({ text: '缺省指纹' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: 40017, + senderUin: 0, + peerUin: 7654321, + uuid: '', + md5Hex: '', + duration: 0, + size: 0, + format: 0, + }); + }); + + it('coerces a string user_id to senderUin', async () => { + const translatePttToText = vi.fn(async () => '字符串 uin'); + trackPttKey(SELF_ID, 40018); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ user_id: '20002' })), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40018, + )).resolves.toEqual({ text: '字符串 uin' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: 40018, + senderUin: 20002, + peerUin: 7654321, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('registers the waiter before triggering so an inline push cannot race', async () => { + const key = trackPttKey(SELF_ID, 40019); + const translatePttToText = vi.fn(async () => { + deliverPttTransText(key, '推送先到'); + return ''; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40019, + )).resolves.toEqual({ text: '推送先到' }); + }); + + it('keeps the push text when the trigger later also returns inline text', async () => { + const key = trackPttKey(SELF_ID, 40020); + const translatePttToText = vi.fn(async () => { + deliverPttTransText(key, '推送文本'); + return '同步文本'; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40020, + )).resolves.toEqual({ text: '推送文本' }); + }); + + it('waits for an async push when the trigger returns an empty string', async () => { + const key = trackPttKey(SELF_ID, 40021); + const translatePttToText = vi.fn(async () => { + queueMicrotask(() => deliverPttTransText(key, '异步推送转写')); + return ''; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40021, + )).resolves.toEqual({ text: '异步推送转写' }); + }); + + it('rejects with the trigger Error', async () => { + trackPttKey(SELF_ID, 40022); + const err = new Error('桥接失败'); + const translatePttToText = vi.fn(async () => { + throw err; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40022, + )).rejects.toBe(err); + }); + + it('wraps a non-Error trigger rejection', async () => { + trackPttKey(SELF_ID, 40023); + const translatePttToText = vi.fn(async () => { + throw 'boom'; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40023, + )).rejects.toThrow('boom'); + }); + + it('times out after 20000ms when neither inline text nor a push arrives', async () => { + vi.useFakeTimers(); + trackPttKey(SELF_ID, 40024); + const translatePttToText = vi.fn(async () => ''); + + const pending = fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40024, + ); + const rejected = expect(pending).rejects.toThrow('语音转文字超时(未收到结果推送)'); + await vi.advanceTimersByTimeAsync(19_999); + await vi.advanceTimersByTimeAsync(1); + await rejected; + }); +}); + +describe('getImageInfo', () => { + it('returns the full info object after a successful re-sign', async () => { + const resolver = vi.fn(async () => `${RAW_IMAGE}&rkey=FRESH`); + + await expect(getImageInfo(fakeImageStore(cachedImage()), 'DEF.jpg', resolver)).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=FRESH`, + url: `${RAW_IMAGE}&rkey=FRESH`, + file_size: '2048', + file_name: 'DEF.jpg', + }); + expect(resolver).toHaveBeenCalledWith( + { type: 'image', imageUrl: RAW_IMAGE, subType: 1 }, + false, + ); + }); + + it('keeps the stored URL when the resolver returns an empty string', async () => { + const resolver = vi.fn(async () => ''); + await expect(getImageInfo(fakeImageStore(cachedImage()), 'DEF.jpg', resolver)).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=STALE`, + url: `${RAW_IMAGE}&rkey=STALE`, + file_size: '2048', + file_name: 'DEF.jpg', + }); + }); + + it('does not call a null resolver', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage()), 'DEF.jpg', null)).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=STALE`, + url: `${RAW_IMAGE}&rkey=STALE`, + file_size: '2048', + file_name: 'DEF.jpg', + }); + }); + + it('falls file back to the cache key when both url fields are empty', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage({ + file: 'orphan.jpg', + url: '', + imageUrl: '', + fileName: 'named.jpg', + fileSize: 12, + })), 'orphan.jpg')).resolves.toEqual({ + file: 'orphan.jpg', + url: '', + file_size: '12', + file_name: 'named.jpg', + }); + }); + + it('uses imageUrl as the unsigned url when the stored signed url is empty', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage({ + url: '', + imageUrl: RAW_IMAGE, + })), 'DEF.jpg')).resolves.toEqual({ + file: RAW_IMAGE, + url: RAW_IMAGE, + file_size: '2048', + file_name: 'DEF.jpg', + }); + }); + + it('stringifies a missing fileSize as 0 and falls file_name back to file', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage({ + file: 'fallback-name.jpg', + fileName: '', + fileSize: undefined as unknown as number, + })), 'fallback-name.jpg')).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=STALE`, + url: `${RAW_IMAGE}&rkey=STALE`, + file_size: '0', + file_name: 'fallback-name.jpg', + }); + }); + + it('passes isGroup true through to the resolver', async () => { + const resolver = vi.fn(async () => 'https://cdn.example/group-fresh'); + await expect(getImageInfo( + fakeImageStore(cachedImage({ isGroup: true, sessionId: GROUP_ID })), + 'DEF.jpg', + resolver, + )).resolves.toEqual({ + file: 'https://cdn.example/group-fresh', + url: 'https://cdn.example/group-fresh', + file_size: '2048', + file_name: 'DEF.jpg', + }); + expect(resolver).toHaveBeenCalledWith( + { type: 'image', imageUrl: RAW_IMAGE, subType: 1 }, + true, + ); + }); +}); + +describe('getRecordInfo', () => { + it('returns null when the record is not cached', async () => { + await expect(getRecordInfo(fakeBridge(), fakeRecordStore(null), 'missing.silk')).resolves.toBeNull(); + }); + + it('returns the stored url without refetching', async () => { + const getPttUrl = vi.fn(async () => 'https://ptt.example/should-not-run'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/should-not-run'); + const updateRecordUrl = vi.fn(); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: 'https://ptt.example/cached.silk', + mediaNode: { fileUuid: 'uuid-1' }, + }), { updateRecordUrl }), + 'voice.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/cached.silk', + url: 'https://ptt.example/cached.silk', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPttUrl).not.toHaveBeenCalled(); + expect(getPrivatePttUrl).not.toHaveBeenCalled(); + expect(updateRecordUrl).not.toHaveBeenCalled(); + }); + + it('does not refetch when the url is empty and there is no mediaNode', async () => { + const getPttUrl = vi.fn(async () => 'https://ptt.example/group'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private'); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ url: '', mediaNode: undefined })), + 'voice.silk', + )).resolves.toEqual({ + file: 'voice.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPttUrl).not.toHaveBeenCalled(); + expect(getPrivatePttUrl).not.toHaveBeenCalled(); + }); + + it('refetches a group ptt url and writes it back under the lookup key', async () => { + const mediaNode = { fileUuid: 'group-uuid', storeId: 1 }; + const getPttUrl = vi.fn(async () => 'https://ptt.example/group-fresh'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private'); + const updateRecordUrl = vi.fn(); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + file: 'primary.silk', + url: '', + isGroup: true, + sessionId: GROUP_ID, + mediaNode, + }), { updateRecordUrl }), + 'alias.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/group-fresh', + url: 'https://ptt.example/group-fresh', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPttUrl).toHaveBeenCalledWith(710010, mediaNode); + expect(getPrivatePttUrl).not.toHaveBeenCalled(); + expect(updateRecordUrl).toHaveBeenCalledWith('alias.silk', 'https://ptt.example/group-fresh'); + }); + + it('refetches a private ptt url from the media node only', async () => { + const mediaNode = { fileUuid: 'c2c-uuid' }; + const getPttUrl = vi.fn(async () => 'https://ptt.example/group'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private-fresh'); + const updateRecordUrl = vi.fn(); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: '', + isGroup: false, + mediaNode, + }), { updateRecordUrl }), + 'voice.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/private-fresh', + url: 'https://ptt.example/private-fresh', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPrivatePttUrl).toHaveBeenCalledWith(mediaNode); + expect(getPttUrl).not.toHaveBeenCalled(); + expect(updateRecordUrl).toHaveBeenCalledWith('voice.silk', 'https://ptt.example/private-fresh'); + }); + + it('does not write back an empty refetch result', async () => { + const updateRecordUrl = vi.fn(); + const getPrivatePttUrl = vi.fn(async () => ''); + + await expect(getRecordInfo( + fakeBridge({ getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: '', + mediaNode: { fileUuid: 'empty-uuid' }, + }), { updateRecordUrl }), + 'voice.silk', + )).resolves.toEqual({ + file: 'voice.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(updateRecordUrl).not.toHaveBeenCalled(); + }); + + it('returns the cached file after a refetch Error', async () => { + const updateRecordUrl = vi.fn(); + const getPttUrl = vi.fn(async () => { + throw new Error('cdn timeout'); + }); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl }), + fakeRecordStore(cachedRecord({ + file: 'keep.silk', + url: '', + isGroup: true, + sessionId: GROUP_ID, + mediaNode: { fileUuid: 'fail-uuid' }, + }), { updateRecordUrl }), + 'keep.silk', + )).resolves.toEqual({ + file: 'keep.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(updateRecordUrl).not.toHaveBeenCalled(); + }); + + it('returns the cached file after a non-Error refetch rejection', async () => { + const getPrivatePttUrl = vi.fn(async () => { + throw 'offline'; + }); + + await expect(getRecordInfo( + fakeBridge({ getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: '', + isGroup: false, + mediaNode: { fileUuid: 'offline-uuid' }, + })), + 'voice.silk', + )).resolves.toEqual({ + file: 'voice.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + }); + + it('stringifies a missing fileSize as 0 and falls file_name back to file', async () => { + await expect(getRecordInfo( + fakeBridge(), + fakeRecordStore(cachedRecord({ + file: 'fallback.silk', + fileName: '', + fileSize: undefined as unknown as number, + url: 'https://ptt.example/named.silk', + })), + 'fallback.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/named.silk', + url: 'https://ptt.example/named.silk', + file_size: '0', + file_name: 'fallback.silk', + }); + }); +}); diff --git a/packages/onebot/tests/ptt-trans-waiter.test.ts b/packages/onebot/tests/ptt-trans-waiter.test.ts new file mode 100644 index 00000000..0f3bcab1 --- /dev/null +++ b/packages/onebot/tests/ptt-trans-waiter.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + deliverPttTransText, + failPttTransWaiter, + pttTransKey, + waitPttTransText, +} from '../src/modules/ptt-trans-waiter'; + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('pttTransKey', () => { + it('joins selfUin and msgId with a colon', () => { + expect(pttTransKey(1787882683, 4001)).toBe('1787882683:4001'); + expect(pttTransKey(10001, 42)).toBe('10001:42'); + expect(pttTransKey(0, 0)).toBe('0:0'); + }); +}); + +describe('waitPttTransText / deliverPttTransText', () => { + it('resolves with the delivered text', async () => { + const waiter = waitPttTransText('1787882683:4001', 20_000); + deliverPttTransText('1787882683:4001', '今天天气不错'); + await expect(waiter).resolves.toBe('今天天气不错'); + }); + + it('resolves empty text the same way as any other string', async () => { + const waiter = waitPttTransText('10001:1', 20_000); + deliverPttTransText('10001:1', ''); + await expect(waiter).resolves.toBe(''); + }); + + it('is a no-op when no waiter is registered', () => { + expect(() => deliverPttTransText('10001:missing', '不会被消费')).not.toThrow(); + }); + + it('is a no-op after the waiter has already settled', async () => { + const waiter = waitPttTransText('10001:2', 20_000); + deliverPttTransText('10001:2', '第一次'); + await expect(waiter).resolves.toBe('第一次'); + expect(() => deliverPttTransText('10001:2', '第二次')).not.toThrow(); + }); + + it('does not resolve a different key', async () => { + const a = waitPttTransText('10001:10', 20_000); + const b = waitPttTransText('10001:11', 20_000); + deliverPttTransText('10001:10', '甲'); + await expect(a).resolves.toBe('甲'); + failPttTransWaiter('10001:11', new Error('桥接失败')); + await expect(b).rejects.toThrow('桥接失败'); + }); + + it('allows a new waiter on the same key after settle', async () => { + const first = waitPttTransText('10001:3', 20_000); + deliverPttTransText('10001:3', '一次'); + await expect(first).resolves.toBe('一次'); + + const second = waitPttTransText('10001:3', 20_000); + deliverPttTransText('10001:3', '二次'); + await expect(second).resolves.toBe('二次'); + }); +}); + +describe('failPttTransWaiter', () => { + it('rejects the waiter with the provided error', async () => { + const err = new Error('触发失败'); + const waiter = waitPttTransText('10001:20', 20_000); + failPttTransWaiter('10001:20', err); + await expect(waiter).rejects.toBe(err); + }); + + it('is a no-op when no waiter is registered', () => { + expect(() => failPttTransWaiter('10001:gone', new Error('无人等待'))).not.toThrow(); + }); + + it('is a no-op after the waiter has already settled', async () => { + const waiter = waitPttTransText('10001:21', 20_000); + failPttTransWaiter('10001:21', new Error('第一次失败')); + await expect(waiter).rejects.toThrow('第一次失败'); + expect(() => failPttTransWaiter('10001:21', new Error('第二次失败'))).not.toThrow(); + }); +}); + +describe('waitPttTransText supersede', () => { + it('rejects the previous waiter when the same key is waited again', async () => { + const first = waitPttTransText('10001:30', 20_000); + const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代'); + const second = waitPttTransText('10001:30', 20_000); + await firstRejected; + deliverPttTransText('10001:30', '新请求结果'); + await expect(second).resolves.toBe('新请求结果'); + }); + + it('lets failPttTransWaiter settle only the replacement waiter', async () => { + const first = waitPttTransText('10001:31', 20_000); + const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代'); + const second = waitPttTransText('10001:31', 20_000); + await firstRejected; + const err = new Error('trigger failed'); + failPttTransWaiter('10001:31', err); + await expect(second).rejects.toBe(err); + }); + + it('does not time out the replacement when the superseded timeout would have fired', async () => { + vi.useFakeTimers(); + const first = waitPttTransText('10001:32', 1_000); + const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代'); + const second = waitPttTransText('10001:32', 20_000); + await firstRejected; + await vi.advanceTimersByTimeAsync(1_000); + deliverPttTransText('10001:32', '未被旧超时打断'); + await expect(second).resolves.toBe('未被旧超时打断'); + }); +}); + +describe('waitPttTransText timeout', () => { + it('rejects after timeoutMs when no result is delivered', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:40', 20_000); + const rejected = expect(waiter).rejects.toThrow('语音转文字超时(未收到结果推送)'); + await vi.advanceTimersByTimeAsync(19_999); + await vi.advanceTimersByTimeAsync(1); + await rejected; + }); + + it('does not reject after deliver even if the original timeout later elapses', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:41', 20_000); + deliverPttTransText('10001:41', '同步转写'); + await expect(waiter).resolves.toBe('同步转写'); + await vi.advanceTimersByTimeAsync(20_000); + }); + + it('does not reject again after fail even if the original timeout later elapses', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:42', 20_000); + failPttTransWaiter('10001:42', new Error('请求失败')); + await expect(waiter).rejects.toThrow('请求失败'); + await vi.advanceTimersByTimeAsync(20_000); + }); + + it('ignores deliver and fail after the timeout has already settled the waiter', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:43', 20_000); + const rejected = expect(waiter).rejects.toThrow('语音转文字超时(未收到结果推送)'); + await vi.advanceTimersByTimeAsync(20_000); + await rejected; + expect(() => deliverPttTransText('10001:43', '来晚了')).not.toThrow(); + expect(() => failPttTransWaiter('10001:43', new Error('也来晚了'))).not.toThrow(); + }); +}); diff --git a/packages/onebot/tests/quick-operation.test.ts b/packages/onebot/tests/quick-operation.test.ts new file mode 100644 index 00000000..606225f7 --- /dev/null +++ b/packages/onebot/tests/quick-operation.test.ts @@ -0,0 +1,560 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiHandler } from '../src/api-handler'; +import { executeQuickOperation } from '../src/network/quick-operation'; +import type { JsonObject } from '../src/types'; + +function mockApi(): { api: ApiHandler; handle: ReturnType } { + const handle = vi.fn(); + return { api: { handle } as unknown as ApiHandler, handle }; +} + +const GROUP_MESSAGE: JsonObject = { + post_type: 'message', + message_type: 'group', + group_id: 314159, + user_id: 271828, + message_id: 424242, +}; + +const PRIVATE_MESSAGE: JsonObject = { + post_type: 'message', + message_type: 'private', + user_id: 13579, + message_id: 24680, +}; + +describe('executeQuickOperation', () => { + describe('message reply', () => { + it('prepends an at segment to a group string reply and forces auto_escape off', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'hello group', + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: [ + { type: 'at', data: { qq: '271828' } }, + { type: 'text', data: { text: 'hello group' } }, + ], + auto_escape: false, + }], + ]); + }); + + it('sends a raw group string reply when at_sender is false', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'no at', + at_sender: false, + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'no at', + auto_escape: true, + }], + ]); + }); + + it('defaults auto_escape to false for a group string reply without at', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'plain', + at_sender: false, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'plain', + auto_escape: false, + }], + ]); + }); + + it('prepends an at segment to a group array reply without forcing auto_escape', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: [ + { type: 'text', data: { text: 'hi' } }, + { type: 'face', data: { id: '14' } }, + ], + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: [ + { type: 'at', data: { qq: '271828' } }, + { type: 'text', data: { text: 'hi' } }, + { type: 'face', data: { id: '14' } }, + ], + auto_escape: true, + }], + ]); + }); + + it('leaves a non-string non-array group reply unwrapped when at_sender is on', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: { type: 'image', data: { file: 'pic.jpg' } }, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: { type: 'image', data: { file: 'pic.jpg' } }, + auto_escape: false, + }], + ]); + }); + + it('does not at-wrap a group reply when the event has no user_id', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'message', + message_type: 'group', + group_id: 314159, + message_id: 424242, + }, { + reply: 'nobody', + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'nobody', + auto_escape: true, + }], + ]); + }); + + it('does not at-wrap a group reply when user_id is 0', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'message', + message_type: 'group', + group_id: 314159, + user_id: 0, + message_id: 424242, + }, { reply: 'zero-user' }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'zero-user', + auto_escape: false, + }], + ]); + }); + + it('at-wraps a group string reply when at_sender is explicitly true', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'explicit', + at_sender: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: [ + { type: 'at', data: { qq: '271828' } }, + { type: 'text', data: { text: 'explicit' } }, + ], + auto_escape: false, + }], + ]); + }); + + it('sends a private reply without at-wrapping', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { + reply: 'hello pm', + auto_escape: true, + at_sender: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_private_msg', { + user_id: 13579, + message: 'hello pm', + auto_escape: true, + }], + ]); + }); + + it('coerces a truthy auto_escape on a private reply', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { + reply: [{ type: 'text', data: { text: 'seg' } }], + auto_escape: 1, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_private_msg', { + user_id: 13579, + message: [{ type: 'text', data: { text: 'seg' } }], + auto_escape: true, + }], + ]); + }); + + it('does not send a reply for an unknown message_type', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'message', + message_type: 'guild', + user_id: 9, + message_id: 8, + }, { reply: 'ignored' }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + + it.each([ + ['undefined', { reply: undefined }], + ['null', { reply: null }], + ['empty string', { reply: '' }], + ] as const)('does not send a reply when reply is %s', async (_label, operation) => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { ...operation }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('message delete', () => { + it('deletes the event message_id', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { delete: true }, api); + + expect(handle.mock.calls).toEqual([ + ['delete_msg', { message_id: 424242 }], + ]); + }); + + it('does not delete when delete is falsy', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { delete: 0 }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('message ban', () => { + it('bans a group sender for an explicit duration', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + ban: true, + ban_duration: 60, + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 60, + }], + ]); + }); + + it('bans for 0 seconds when ban_duration is 0', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + ban: true, + ban_duration: 0, + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 0, + }], + ]); + }); + + it.each([ + ['omitted', {}], + ['a string', { ban_duration: '90' }], + ['null', { ban_duration: null }], + ])('bans for 1800s when ban_duration is %s', async (_label, extra) => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { ban: true, ...extra }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 1800, + }], + ]); + }); + + it('does not ban on a private message', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { + ban: true, + ban_duration: 30, + }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('message kick', () => { + it('kicks a group sender and rejects later requests when asked', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + kick: true, + reject_add_request: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: true, + }], + ]); + }); + + it('kicks without reject_add_request when the flag is omitted', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { kick: true }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: false, + }], + ]); + }); + + it('coerces a truthy reject_add_request', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + kick: 1, + reject_add_request: 'yes', + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: true, + }], + ]); + }); + + it('does not kick on a private message', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { kick: true }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('request approve', () => { + it('approves a friend request with a remark', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'friend', + flag: 'flag-friend-7', + }, { + approve: true, + remark: 'buddy', + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_friend_add_request', { + flag: 'flag-friend-7', + approve: true, + remark: 'buddy', + }], + ]); + }); + + it('rejects a friend request with an empty default remark', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'friend', + flag: 'flag-friend-7', + }, { approve: false }, api); + + expect(handle.mock.calls).toEqual([ + ['set_friend_add_request', { + flag: 'flag-friend-7', + approve: false, + remark: '', + }], + ]); + }); + + it('approves a group request with a reason', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'group', + sub_type: 'add', + flag: 'flag-group-9', + }, { + approve: true, + reason: 'ok', + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_add_request', { + flag: 'flag-group-9', + sub_type: 'add', + approve: true, + reason: 'ok', + }], + ]); + }); + + it('rejects a group request with an empty default reason', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'group', + sub_type: 'invite', + flag: 'flag-group-9', + }, { approve: false }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_add_request', { + flag: 'flag-group-9', + sub_type: 'invite', + approve: false, + reason: '', + }], + ]); + }); + + it('does not handle a request when approve is omitted', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'friend', + flag: 'flag-friend-7', + }, { remark: 'unused' }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + + it('does not handle an unknown request_type', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'business', + flag: 'flag-x', + }, { approve: true }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('combined and ignored operations', () => { + it('runs reply, delete, ban, then kick in that order', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'bye', + at_sender: false, + delete: true, + ban: true, + ban_duration: 120, + kick: true, + reject_add_request: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'bye', + auto_escape: false, + }], + ['delete_msg', { message_id: 424242 }], + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 120, + }], + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: true, + }], + ]); + }); + + it('does nothing for a non-message non-request event', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'notice', + notice_type: 'group_increase', + group_id: 314159, + user_id: 271828, + }, { + reply: 'x', + delete: true, + ban: true, + kick: true, + approve: true, + }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + + it('propagates a rejected api.handle call', async () => { + const { api, handle } = mockApi(); + handle.mockRejectedValueOnce(new Error('send failed')); + + await expect(executeQuickOperation(GROUP_MESSAGE, { + reply: 'fail', + at_sender: false, + }, api)).rejects.toThrow('send failed'); + }); + }); +});