diff --git a/packages/core/src/bridge/actions/profile.ts b/packages/core/src/bridge/actions/profile.ts deleted file mode 100644 index 2c3cd7d6..00000000 --- a/packages/core/src/bridge/actions/profile.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '../bridge-oidb'; -import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; -import { computeHashes, loadBinarySource } from '../highway/utils'; -import { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - FaceroamOpReq, - FaceroamOpResp, - GroupAvatarExtra, - Oidb0x112aReq, - Oidb0x112aResp, - Oidb0x7edReq, - Oidb0x7edResp, - Oidb0xcd4Req, - Oidb0xcd4Resp, - Oidb0xe17Req, - Oidb0xe17Resp, - OidbSetProfile, - SetStatusReq, - SetStatusResp, -} from '@snowluma/proto-defs/oidb-actions/base'; -import { resolveSelfUid } from './shared'; - -// ─────────────── status / profile setters ─────────────── - -export async function setOnlineStatus( - bridge: Bridge, - status: number, - extStatus: number = 0, - batteryStatus: number = 100, -): Promise { - await dispatchSetStatus(bridge, { status, extStatus, batteryStatus }); -} - -/** - * DIY (custom) online status. napcat fixes status=10 / extStatus=2000 - * — the values QQ associates with "I have a custom status string" — - * and threads the faceId / wording / faceType through the customExt - * sub-message of the same SetStatus wire call. - */ -export async function setDiyOnlineStatus( - bridge: Bridge, - faceId: number, - wording: string, - faceType: number, -): Promise { - await dispatchSetStatus(bridge, { - status: 10, - extStatus: 2000, - batteryStatus: 0, - customExt: { faceId, text: wording, faceType }, - }); -} - -async function dispatchSetStatus( - bridge: Bridge, - value: { - status: number; - extStatus: number; - batteryStatus: number; - customExt?: { faceId: number; text: string; faceType: number }; - }, -): Promise { - const request = protobuf_encode(value); - - const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request); - - if (!result.success) { - throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); - } - - if (result.responseData && result.responseData.length > 0) { - const resp = protobuf_decode(result.responseData); - if (!resp) { - throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); - } - if (resp.errCode !== undefined && resp.errCode !== 0) { - throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`); - } - } -} - -export async function setProfile( - bridge: Bridge, - nickname?: string, - personalNote?: string, -): Promise { - const uin = BigInt(bridge.identity.uin); - const stringProfiles: any[] = []; - const intProfiles: any[] = []; - - if (nickname !== undefined) { - stringProfiles.push({ fieldId: 20002, value: nickname }); - } - - if (personalNote !== undefined) { - stringProfiles.push({ fieldId: 102, value: personalNote }); - } - - if (stringProfiles.length === 0 && intProfiles.length === 0) { - return; - } - - const req = { - uin, - stringProfiles, - }; - - const env = makeOidbEnvelope(0x112A, 2, req); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); -} - -export async function setSelfLongNick( - bridge: Bridge, - longNick: string, -) { - const req = { - uin: BigInt(bridge.identity.uin), - profile: { - tag: 102, - value: String(longNick), - }, - }; - - const env = makeOidbEnvelope(0x112A, 2, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); - // Decode just to maintain the original behaviour of "consume the response". - protobuf_decode>(respBytes); -} - -export async function setInputStatus( - bridge: Bridge, - userId: number, - eventType: number, -) { - const targetUid = await bridge.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - reqBody: { - uid: targetUid, - chatType: 0, - eventType: eventType, - }, - }; - - const env = makeOidbEnvelope(0xCD4, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', protobuf_encode>(env)); - // Decode just to maintain the original behaviour of "consume the response". - protobuf_decode>(respBytes); -} - -export async function setAvatar( - bridge: Bridge, - source: string, -): Promise { - const loaded = await loadBinarySource(source, 'avatar'); - if (!loaded.bytes.length) throw new Error('avatar file is empty'); - - const hashes = computeHashes(loaded.bytes); - const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0)); -} - -/** - * Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar: - * - same highway HTTP upload as personal avatar - * - cmdId 3000 (instead of 90) - * - GroupAvatarExtra proto carried as the `extend` blob, with the - * four protocol-prescribed constants (type=101, field5=3, field6=1, - * field3.field1=1) and the target groupUin. - * - * Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar. - */ -export async function setGroupAvatar( - bridge: Bridge, - groupId: number, - source: string, -): Promise { - const loaded = await loadBinarySource(source, 'group-avatar'); - if (!loaded.bytes.length) throw new Error('group avatar file is empty'); - - const hashes = computeHashes(loaded.bytes); - const session = await fetchHighwaySession(bridge); - const extra = protobuf_encode({ - type: 101, - groupUin: groupId, - field3: { field1: 1 }, - field5: 3, - field6: 1, - }); - await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra); -} - -// ─────────────── queries on me / my contacts ─────────────── - -export async function getProfileLike( - bridge: Bridge, - userId?: number, - start: number = 0, - limit: number = 10, -) { - const isSelf = !userId; - const targetUid = isSelf - ? await resolveSelfUid(bridge) - : await bridge.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - targetUid: targetUid, - basic: 1, - vote: 1, - favorite: 1, - start: start, - limit: limit, - }; - - const env = makeOidbEnvelope(0x7ED, 12, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - const data = result?.userLikeInfos?.[0]; - if (!data) { - throw new Error('get profile like info empty'); - } - - return { - uid: data.uid, - time: Number(data.time), - favoriteInfo: { - total_count: data.favoriteInfo?.totalCount || 0, - last_time: Number(data.favoriteInfo?.lastTime || 0), - today_count: data.favoriteInfo?.newCount || 0, - userInfos: [], - }, - voteInfo: { - total_count: data.voteInfo?.totalCount || 0, - new_count: data.voteInfo?.newCount || 0, - new_nearby_count: 0, - last_visit_time: Number(data.voteInfo?.lastTime || 0), - userInfos: [], - }, - }; -} - -export async function getUnidirectionalFriendList( - bridge: Bridge, -) { - const reqObj = { - uint64_uin: String(bridge.identity.uin), - uint64_top: 0, - uint32_req_num: 99, - bytes_cookies: '', - }; - - const req = { - jsonBody: JSON.stringify(reqObj), - }; - - const env = makeOidbEnvelope(0xE17, 0, req); - const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - if (!result || !result.jsonBody) { - throw new Error('get unidirectional friend list empty'); - } - - const parsed = JSON.parse(result.jsonBody); - return parsed.rpt_block_list || []; -} - -export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise { - const req = { - inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' }, - uin: BigInt(bridge.identity.uin), - field3: 1, - field6: 1, - }; - const request = protobuf_encode(req); - const result = await bridge.sendRawPacket('Faceroam.OpReq', request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'fetch custom face failed'); - } - const resp = protobuf_decode(result.responseData); - if (!resp || (resp as any).retCode !== 0) { - throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`); - } - const faceIds = (resp as any).item?.faceIds || []; - return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.identity.uin}/${id}/0`); -} diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts index 0ba25d0a..60ac462b 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -28,6 +28,7 @@ import { GroupAlbumApi } from './group-album'; import { GroupFileApi } from './group-file'; import { InteractionApi } from './interaction'; import { MessageApi } from './message'; +import { ProfileApi } from './profile'; export interface ApiHub { /** Send/recall/markRead operations across c2c + group + c2c-file. */ @@ -44,6 +45,8 @@ export interface ApiHub { readonly interaction: InteractionApi; /** Friend roster mutations: handleRequest / delete / setRemark. */ readonly friend: FriendApi; + /** Personal profile: status / avatar / nickname / likes / custom-faces. */ + readonly profile: ProfileApi; // Pending — added as later commits land: // readonly interaction: InteractionApi; // readonly profile: ProfileApi; @@ -70,6 +73,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { groupAlbum: new GroupAlbumApi(ctx), interaction: new InteractionApi(ctx), friend: new FriendApi(ctx), + profile: new ProfileApi(ctx), }; } @@ -83,3 +87,4 @@ export { GroupAlbumApi } from './group-album'; export { GroupFileApi } from './group-file'; export { InteractionApi } from './interaction'; export { MessageApi } from './message'; +export { ProfileApi } from './profile'; diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts new file mode 100644 index 00000000..867effc0 --- /dev/null +++ b/packages/core/src/bridge/apis/profile.ts @@ -0,0 +1,271 @@ +// ProfileApi — personal profile + status + avatar + likes + custom +// faces + unidirectional friend list. Inlined from +// `actions/profile.ts` (deleted alongside actions/* in commit 13). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FaceroamOpReq, + FaceroamOpResp, + GroupAvatarExtra, + Oidb0x112aReq, + Oidb0x112aResp, + Oidb0x7edReq, + Oidb0x7edResp, + Oidb0xcd4Req, + Oidb0xcd4Resp, + Oidb0xe17Req, + Oidb0xe17Resp, + OidbSetProfile, + SetStatusReq, + SetStatusResp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '../bridge-oidb'; +import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; +import { computeHashes, loadBinarySource } from '../highway/utils'; +import { resolveSelfUid } from '../actions/shared'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +export class ProfileApi { + constructor(private readonly ctx: BridgeContext) {} + + // ─────────────── status / profile setters ─────────────── + + async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise { + await this.dispatchSetStatus({ status, extStatus, batteryStatus }); + } + + /** + * DIY (custom) online status. napcat fixes status=10 / extStatus=2000 + * — the values QQ associates with "I have a custom status string" — + * and threads the faceId / wording / faceType through the customExt + * sub-message of the same SetStatus wire call. + */ + async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise { + await this.dispatchSetStatus({ + status: 10, + extStatus: 2000, + batteryStatus: 0, + customExt: { faceId, text: wording, faceType }, + }); + } + + private async dispatchSetStatus(value: { + status: number; + extStatus: number; + batteryStatus: number; + customExt?: { faceId: number; text: string; faceType: number }; + }): Promise { + const request = protobuf_encode(value); + const result = await this.ctx.sendRawPacket( + 'trpc.qq_new_tech.status_svc.StatusService.SetStatus', + request, + ); + + if (!result.success) { + throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); + } + + if (result.responseData && result.responseData.length > 0) { + const resp = protobuf_decode(result.responseData); + if (!resp) { + throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); + } + if (resp.errCode !== undefined && resp.errCode !== 0) { + throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`); + } + } + } + + async setProfile(nickname?: string, personalNote?: string): Promise { + const bridge = asBridge(this.ctx); + const uin = BigInt(this.ctx.identity.uin); + const stringProfiles: any[] = []; + const intProfiles: any[] = []; + + if (nickname !== undefined) { + stringProfiles.push({ fieldId: 20002, value: nickname }); + } + + if (personalNote !== undefined) { + stringProfiles.push({ fieldId: 102, value: personalNote }); + } + + if (stringProfiles.length === 0 && intProfiles.length === 0) { + return; + } + + const req = { uin, stringProfiles }; + const env = makeOidbEnvelope(0x112A, 2, req); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); + } + + async setSelfLongNick(longNick: string): Promise { + const bridge = asBridge(this.ctx); + const req = { + uin: BigInt(this.ctx.identity.uin), + profile: { + tag: 102, + value: String(longNick), + }, + }; + + const env = makeOidbEnvelope(0x112A, 2, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); + // Decode just to maintain the original behaviour of "consume the response". + protobuf_decode>(respBytes); + } + + async setInputStatus(userId: number, eventType: number): Promise { + const bridge = asBridge(this.ctx); + const targetUid = await this.ctx.resolveUserUid(userId); + + if (!targetUid) { + throw new Error('target uid not found'); + } + + const req = { + reqBody: { + uid: targetUid, + chatType: 0, + eventType, + }, + }; + + const env = makeOidbEnvelope(0xCD4, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', protobuf_encode>(env)); + protobuf_decode>(respBytes); + } + + async setAvatar(source: string): Promise { + const bridge = asBridge(this.ctx); + const loaded = await loadBinarySource(source, 'avatar'); + if (!loaded.bytes.length) throw new Error('avatar file is empty'); + + const hashes = computeHashes(loaded.bytes); + const session = await fetchHighwaySession(bridge); + await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0)); + } + + /** + * Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar: + * - same highway HTTP upload as personal avatar + * - cmdId 3000 (instead of 90) + * - GroupAvatarExtra proto carried as the `extend` blob, with the + * four protocol-prescribed constants (type=101, field5=3, field6=1, + * field3.field1=1) and the target groupUin. + * + * Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar. + */ + async setGroupAvatar(groupId: number, source: string): Promise { + const bridge = asBridge(this.ctx); + const loaded = await loadBinarySource(source, 'group-avatar'); + if (!loaded.bytes.length) throw new Error('group avatar file is empty'); + + const hashes = computeHashes(loaded.bytes); + const session = await fetchHighwaySession(bridge); + const extra = protobuf_encode({ + type: 101, + groupUin: groupId, + field3: { field1: 1 }, + field5: 3, + field6: 1, + }); + await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra); + } + + // ─────────────── queries on me / my contacts ─────────────── + + async getLike(userId?: number, start = 0, limit = 10): Promise { + const bridge = asBridge(this.ctx); + const isSelf = !userId; + const targetUid = isSelf + ? await resolveSelfUid(bridge) + : await this.ctx.resolveUserUid(userId); + + if (!targetUid) { + throw new Error('target uid not found'); + } + + const req = { + targetUid, + basic: 1, + vote: 1, + favorite: 1, + start, + limit, + }; + + const env = makeOidbEnvelope(0x7ED, 12, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', protobuf_encode>(env)); + const result = protobuf_decode>(respBytes).body; + + const data = result?.userLikeInfos?.[0]; + if (!data) { + throw new Error('get profile like info empty'); + } + + return { + uid: data.uid, + time: Number(data.time), + favoriteInfo: { + total_count: data.favoriteInfo?.totalCount || 0, + last_time: Number(data.favoriteInfo?.lastTime || 0), + today_count: data.favoriteInfo?.newCount || 0, + userInfos: [], + }, + voteInfo: { + total_count: data.voteInfo?.totalCount || 0, + new_count: data.voteInfo?.newCount || 0, + new_nearby_count: 0, + last_visit_time: Number(data.voteInfo?.lastTime || 0), + userInfos: [], + }, + }; + } + + async getUnidirectionalFriendList(): Promise { + const bridge = asBridge(this.ctx); + const reqObj = { + uint64_uin: String(this.ctx.identity.uin), + uint64_top: 0, + uint32_req_num: 99, + bytes_cookies: '', + }; + + const req = { jsonBody: JSON.stringify(reqObj) }; + const env = makeOidbEnvelope(0xE17, 0, req); + const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', protobuf_encode>(env)); + const result = protobuf_decode>(respBytes).body; + + if (!result || !result.jsonBody) { + throw new Error('get unidirectional friend list empty'); + } + + const parsed = JSON.parse(result.jsonBody); + return parsed.rpt_block_list || []; + } + + async fetchCustomFace(count = 10): Promise { + const req = { + inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' }, + uin: BigInt(this.ctx.identity.uin), + field3: 1, + field6: 1, + }; + const request = protobuf_encode(req); + const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'fetch custom face failed'); + } + const resp = protobuf_decode(result.responseData); + if (!resp || (resp as any).retCode !== 0) { + throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`); + } + const faceIds = (resp as any).item?.faceIds || []; + return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`); + } +} diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index c2a6b838..ea5f52fa 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -83,17 +83,11 @@ export interface BridgeInterface { getCsrfToken(): Promise; getCredentials(domain: string): Promise; - // ─── Personal profile ─── - setOnlineStatus(status: number, extStatus?: number, batteryStatus?: number): Promise; - setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise; - setProfile(nickname?: string, personalNote?: string): Promise; - setSelfLongNick(longNick: string): Promise; - setInputStatus(userId: number, eventType: number): Promise; - setAvatar(source: string): Promise; - setGroupAvatar(groupId: number, source: string): Promise; - fetchCustomFace(count?: number): Promise; - getProfileLike(userId?: number, start?: number, limit?: number): Promise; - getUnidirectionalFriendList(): Promise; + // ─── Personal profile (moved to apis.profile) ─── + // - setOnlineStatus / setDiyOnlineStatus + // - setProfile / setSelfLongNick / setInputStatus + // - setAvatar / setGroupAvatar / fetchCustomFace + // - getLike / getUnidirectionalFriendList // ─── Misc ─── translateEn2Zh(words: string[]): Promise; diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 09ed4e61..794531d8 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -45,18 +45,7 @@ import { sendGroupSign as sendGroupSign_, translateEn2Zh as translateEn2Zh_, } from './actions/misc'; -import { - fetchCustomFace as fetchCustomFace_, - getProfileLike as getProfileLike_, - getUnidirectionalFriendList as getUnidirectionalFriendList_, - setAvatar as setAvatar_, - setDiyOnlineStatus as setDiyOnlineStatus_, - setGroupAvatar as setGroupAvatar_, - setInputStatus as setInputStatus_, - setOnlineStatus as setOnlineStatus_, - setProfile as setProfile_, - setSelfLongNick as setSelfLongNick_, -} from './actions/profile'; +// actions/profile.ts removed — moved to apis/profile.ts::ProfileApi. // `bridge-contacts.ts` removed — its 6 functions are now methods on // `apis.contacts` (see `apis/contacts.ts::ContactsApi`). import { BridgeEventBus } from './event-bus'; @@ -353,30 +342,13 @@ export class Bridge implements BridgeInterface { } // extend - async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise { - return setOnlineStatus_(this, status, extStatus, batteryStatus); - } - async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise { - return setDiyOnlineStatus_(this, faceId, wording, faceType); - } - async setProfile(nickname?: string, personalNote?: string): Promise { - return setProfile_(this, nickname, personalNote); - } + // Profile methods (setOnlineStatus / setDiyOnlineStatus / setProfile / + // setSelfLongNick / setInputStatus / setAvatar / setGroupAvatar / + // fetchCustomFace / getLike / getUnidirectionalFriendList) moved to + // apis.profile. async getCookiesStr(domain: string): Promise { return getCookiesStr_(this, domain); } async getCsrfToken(): Promise { return getCsrfToken_(this); } async getCredentials(domain: string) { return getCredentials_(this, domain); } - async getProfileLike(userId?: number, start?: number, limit?: number) { - return getProfileLike_(this, userId, start, limit); - } - async getUnidirectionalFriendList() { - return getUnidirectionalFriendList_(this); - } - async setSelfLongNick(longNick: string) { - return setSelfLongNick_(this, longNick); - } - async setInputStatus(userId: number, eventType: number) { - return setInputStatus_(this, userId, eventType); - } async translateEn2Zh(words: string[]) { return translateEn2Zh_(this, words); } @@ -389,15 +361,6 @@ export class Bridge implements BridgeInterface { async sendGroupSign(groupId: number) { return sendGroupSign_(this, groupId); } - async setAvatar(source: string): Promise { - return setAvatar_(this, source); - } - async setGroupAvatar(groupId: number, source: string): Promise { - return setGroupAvatar_(this, groupId, source); - } - async fetchCustomFace(count?: number): Promise { - return fetchCustomFace_(this, count); - } // --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) --- diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index 624a68b3..91ad3e06 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -661,7 +661,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setProfile(nickname, personalNote); + await ctx.bridge.apis.profile.setProfile(nickname, personalNote); return okResponse(); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -681,7 +681,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setOnlineStatus(status, extStatus, batteryStatus); + await ctx.bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus); return okResponse(); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -699,7 +699,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const wording = asString(params.wording); if (!faceId) return failedResponse(RETCODE.BAD_REQUEST, 'face_id is required'); try { - await ctx.bridge.setDiyOnlineStatus(faceId, wording, faceType); + await ctx.bridge.apis.profile.setDiyOnlineStatus(faceId, wording, faceType); return okResponse(); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); @@ -808,7 +808,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('fetch_custom_face', async (params) => { const count = asNumber(params.count) || 10; try { - const urls = await ctx.bridge.fetchCustomFace(count); + const urls = await ctx.bridge.apis.profile.fetchCustomFace(count); return okResponse(urls); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -898,7 +898,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_unidirectional_friend_list', async () => { try { - const data = await ctx.bridge.getUnidirectionalFriendList(); + const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); return okResponse(data); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -914,7 +914,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setSelfLongNick(longNick); + await ctx.bridge.apis.profile.setSelfLongNick(longNick); return okResponse({}); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -935,7 +935,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setAvatar(file); + await ctx.bridge.apis.profile.setAvatar(file); return okResponse(); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -957,7 +957,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { - await ctx.bridge.setInputStatus(userId, eventType); + await ctx.bridge.apis.profile.setInputStatus(userId, eventType); return okResponse({}); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); diff --git a/packages/core/src/onebot/actions/group-admin.ts b/packages/core/src/onebot/actions/group-admin.ts index c5bb2a74..0c1adc31 100644 --- a/packages/core/src/onebot/actions/group-admin.ts +++ b/packages/core/src/onebot/actions/group-admin.ts @@ -113,7 +113,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); try { - await ctx.bridge.setGroupAvatar(groupId, file); + await ctx.bridge.apis.profile.setGroupAvatar(groupId, file); return okResponse(); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index 41811038..074dae25 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -146,7 +146,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { // Profile-like / get_group_essence — OneBot-specific defaults that the // action handlers don't supply. - getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit), + getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.apis.profile.getLike(userId, start, limit), getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit), // Message-store-backed history reads. @@ -165,7 +165,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { forceFetchClientKey: () => bridge.forceFetchClientKey(), setFriendRemark: (userId, remark) => bridge.apis.friend.setRemark(userId, remark), setGroupRemark: (groupId, remark) => bridge.apis.groupAdmin.setRemark(groupId, remark), - setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source), + setGroupAvatar: (groupId, source) => bridge.apis.profile.setGroupAvatar(groupId, source), getGroupFileCount: (groupId) => bridge.apis.groupFile.getCount(groupId), // Cross-store: looks up the meta then routes through Bridge. @@ -180,8 +180,8 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { }, markGroupMsgAsRead: (groupId, sequence) => bridge.apis.message.markGroupRead(groupId, sequence), markPrivateMsgAsRead: (userId, sequence) => bridge.apis.message.markPrivateRead(userId, sequence), - setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus), - setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote), + setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus), + setProfile: (nickname?: string, personalNote?: string) => bridge.apis.profile.setProfile(nickname, personalNote), // Web-backed actions. getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type), @@ -200,7 +200,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getCredentials: (domain) => bridge.getCredentials(domain), // Extended - fetchCustomFace: (count) => bridge.fetchCustomFace(count), + fetchCustomFace: (count) => bridge.apis.profile.fetchCustomFace(count), getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.apis.interaction.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie), // Media lookup. diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index e96d88bc..30dc0756 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -38,10 +38,10 @@ vi.mock('../../src/bridge/highway/utils', () => ({ import * as oidb from '../../src/bridge/bridge-oidb'; import * as highwayClient from '../../src/bridge/highway/highway-client'; -import * as profile from '../../src/bridge/actions/profile'; +import { ProfileApi } from '../../src/bridge/apis/profile'; import { mockBridge } from './_helpers'; -describe('actions/profile', () => { +describe('apis/profile', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -52,14 +52,14 @@ describe('actions/profile', () => { it('setOnlineStatus sends to status_svc.SetStatus and accepts an empty response', async () => { const bridge = mockBridge(); - await profile.setOnlineStatus(bridge as any, 11, 0, 100); + await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100); const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus'); }); it('setOnlineStatus does NOT include the customExt field 4 (varint 0x22 absent in body)', async () => { const bridge = mockBridge(); - await profile.setOnlineStatus(bridge as any, 11, 0, 100); + await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100); const [, body] = bridge.sendRawPacket.mock.calls[0]!; // proto field 4 length-delimited tag = (4 << 3) | 2 = 0x22. The // body should not contain that byte; if encoder ever leaks an @@ -69,7 +69,7 @@ describe('actions/profile', () => { it('setDiyOnlineStatus hardcodes status=10 / extStatus=2000 and packs faceId+wording+faceType into customExt', async () => { const bridge = mockBridge(); - await profile.setDiyOnlineStatus(bridge as any, 1234, '摸鱼中', 2); + await new ProfileApi(bridge as any).setDiyOnlineStatus( 1234, '摸鱼中', 2); const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus'); // Decode the wire bytes back through the same schema to assert @@ -90,7 +90,7 @@ describe('actions/profile', () => { bridge.sendRawPacket.mockResolvedValueOnce({ success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf, } as any); - await expect(profile.setDiyOnlineStatus(bridge as any, 1, 't', 1)).rejects.toThrow(/denied/); + await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/denied/); }); it('setDiyOnlineStatus rejects when the transport itself fails', async () => { @@ -98,18 +98,18 @@ describe('actions/profile', () => { bridge.sendRawPacket.mockResolvedValueOnce({ success: false, gotResponse: false, errorCode: -1, errorMessage: 'pipe closed', responseData: null, } as any); - await expect(profile.setDiyOnlineStatus(bridge as any, 1, 't', 1)).rejects.toThrow(/pipe closed/); + await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/pipe closed/); }); it('setProfile is a no-op when both arguments are undefined', async () => { const bridge = mockBridge(); - await profile.setProfile(bridge as any); + await new ProfileApi(bridge as any).setProfile(); expect(oidb.runOidb).not.toHaveBeenCalled(); }); it('setProfile only sends non-undefined fields', async () => { const bridge = mockBridge(); - await profile.setProfile(bridge as any, 'New Nick'); + await new ProfileApi(bridge as any).setProfile('New Nick'); expect(oidb.runOidb).toHaveBeenCalledOnce(); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); @@ -117,14 +117,14 @@ describe('actions/profile', () => { it('setSelfLongNick wraps the long nick in profile tag 102', async () => { const bridge = mockBridge(); - await profile.setSelfLongNick(bridge as any, 'hello world'); + await new ProfileApi(bridge as any).setSelfLongNick( 'hello world'); const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' }); }); it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { const bridge = mockBridge(); - await profile.setInputStatus(bridge as any, 10001, 1); + await new ProfileApi(bridge as any).setInputStatus( 10001, 1); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); @@ -132,7 +132,7 @@ describe('actions/profile', () => { it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { const bridge = mockBridge(); - await profile.setAvatar(bridge as any, '/some/avatar.png'); + await new ProfileApi(bridge as any).setAvatar( '/some/avatar.png'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!; @@ -142,7 +142,7 @@ describe('actions/profile', () => { it('setGroupAvatar uses cmdId 3000 and packs the Lagrange GroupAvatarExtra constants', async () => { const bridge = mockBridge(); - await profile.setGroupAvatar(bridge as any, 12345, '/some/group-avatar.png'); + await new ProfileApi(bridge as any).setGroupAvatar( 12345, '/some/group-avatar.png'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!; @@ -165,7 +165,7 @@ describe('actions/profile', () => { vi.mocked(loadBinarySource).mockResolvedValueOnce({ bytes: new Uint8Array(0), fileName: 'empty.png', } as any); - await expect(profile.setGroupAvatar(bridge as any, 1, 'empty.png')).rejects.toThrow(/empty/); + await expect(new ProfileApi(bridge as any).setGroupAvatar( 1, 'empty.png')).rejects.toThrow(/empty/); expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled(); }); @@ -183,7 +183,7 @@ describe('actions/profile', () => { } as any, }), ); - const out = await profile.getProfileLike(bridge as any); + const out = await new ProfileApi(bridge as any).getLike(); expect(out.favoriteInfo.total_count).toBe(5); expect(out.voteInfo.total_count).toBe(7); }); @@ -193,7 +193,7 @@ describe('actions/profile', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { userLikeInfos: [] } as any }), ); - await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/); + await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/); }); it('getUnidirectionalFriendList parses the embedded JSON body', async () => { @@ -203,7 +203,7 @@ describe('actions/profile', () => { body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any, }), ); - const out = await profile.getUnidirectionalFriendList(bridge as any); + const out = await new ProfileApi(bridge as any).getUnidirectionalFriendList(); expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); }); }); diff --git a/packages/core/tests/onebot/extended-actions.test.ts b/packages/core/tests/onebot/extended-actions.test.ts index ab351319..c4554391 100644 --- a/packages/core/tests/onebot/extended-actions.test.ts +++ b/packages/core/tests/onebot/extended-actions.test.ts @@ -44,6 +44,24 @@ const APIS_ROUTING: Record = { // the area name already says it. deleteGroupFileFolder: ['groupFile', 'deleteFolder'], fetchGroupPttUrlByNode: ['groupFile', 'getPttUrl'], + // InteractionApi: methods drop the redundant `Group` prefix. + sendLike: ['interaction', 'sendLike'], + setGroupReaction: ['interaction', 'setReaction'], + // ProfileApi: a few methods rename (getProfileLike → getLike). + setOnlineStatus: ['profile', 'setOnlineStatus'], + setDiyOnlineStatus: ['profile', 'setDiyOnlineStatus'], + setProfile: ['profile', 'setProfile'], + setSelfLongNick: ['profile', 'setSelfLongNick'], + setInputStatus: ['profile', 'setInputStatus'], + setAvatar: ['profile', 'setAvatar'], + setGroupAvatar: ['profile', 'setGroupAvatar'], + fetchCustomFace: ['profile', 'fetchCustomFace'], + getProfileLike: ['profile', 'getLike'], + getUnidirectionalFriendList: ['profile', 'getUnidirectionalFriendList'], + // FriendApi: handleRequest/delete/setRemark. + setFriendRemark: ['friend', 'setRemark'], + deleteFriend: ['friend', 'delete'], + setFriendAddRequest: ['friend', 'handleRequest'], }; function fakeBridge(overrides: Record = {}): BridgeInterface {