diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index a7e42610..bd99ce47 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -1,4 +1,3 @@ -import { toHexUpper } from '@snowluma/common/hex'; import { createLogger } from '@snowluma/common/logger'; import type { FileUploadExt } from '@snowluma/proto-defs/highway'; import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; @@ -83,11 +82,6 @@ function normalizeDirectory(dir?: string): string { return dir; } -function bytesToHexUpper(data: unknown): string { - if (!(data instanceof Uint8Array) || data.length === 0) return ''; - return toHexUpper(data); -} - // Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives // little-endian-packed (byte0 = first dotted octet) and we unpack it the // same way. Force-unsigned the shift to keep negative ints (high bit set) @@ -568,9 +562,8 @@ export class GroupFileApi { groupId, targetDirectory, startIndex, pageSize, }); if (!list) break; - ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording); - for (const item of list.items ?? []) { + for (const item of list.items) { const type = toInt(item?.type); if (type === 1 && item?.fileInfo) { const file = item.fileInfo; @@ -627,34 +620,14 @@ export class GroupFileApi { // ─────────────── url fetch (group / private files) ─────────────── async getUrl(groupId: number, fileId: string, busId = 102): Promise { - const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId }); - ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording); - - const dns = (typeof download.downloadDns === 'string' && download.downloadDns) - || (typeof download.downloadIp === 'string' && download.downloadIp) - || ''; - const hexUrl = bytesToHexUpper(download.downloadUrl); - if (!dns || !hexUrl) { - throw new Error('group file url response invalid'); - } - - // Keep the same behavior as Lagrange: append file_id after ?fname= - return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`; + return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId }); } async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise { const bridge = asBridge(this.ctx); const selfUid = await resolveSelfUid(bridge); void userId; - const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash }); - - const server = typeof result?.server === 'string' ? result.server : ''; - const port = toInt(result?.port); - const url = typeof result?.url === 'string' ? result.url : ''; - if (!server || !port || !url) { - throw new Error('private file url response invalid'); - } - return `http://${server}:${port}${url}&isthumb=0`; + return GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash }); } // ─────────────── delete / move ─────────────── diff --git a/packages/core/src/bridge/apis/shared.ts b/packages/core/src/bridge/apis/shared.ts index 71d531a5..0927dc5d 100644 --- a/packages/core/src/bridge/apis/shared.ts +++ b/packages/core/src/bridge/apis/shared.ts @@ -11,19 +11,6 @@ export function toInt(value: unknown): number { return 0; } -/** - * Standard OIDB response check: throw a typed Error if retCode != 0. - * Prefers `wording` over `msg` for the human-facing message, falling - * back to a generic string. All themed action modules use this for - * their OIDB error-path uniformity. - */ -export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown, wording: unknown): void { - const retCode = toInt(code); - if (retCode === 0) return; - const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error'; - throw new Error(`${operation} failed: code=${retCode} msg=${text}`); -} - // The bot's-own-UID resolver is the single source of truth in @snowluma/protocol // (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing // `resolveSelfUid(bridge)` call sites in this package keep importing from shared. diff --git a/packages/protocol/src/oidb-services/group-file/get-group-file-url.ts b/packages/protocol/src/oidb-services/group-file/get-group-file-url.ts index 30d271aa..ea7ddb85 100644 --- a/packages/protocol/src/oidb-services/group-file/get-group-file-url.ts +++ b/packages/protocol/src/oidb-services/group-file/get-group-file-url.ts @@ -1,14 +1,30 @@ // 0x6D6_2 — resolve a group file_id → ftn_handler download URL. The // server returns a `downloadUrl` blob (raw bytes that hex-encode the -// download key) and a `downloadDns` host. The facade composes the -// final `https:///ftn_handler//?fname=` string. +// download key) and a `downloadDns` host. This namespace owns retCode +// and the `https:///ftn_handler//?fname=` string. +import { toHexUpper } from '@snowluma/common/hex'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbGroupFileReq, OidbGroupFileResp, OidbGroupFileDownloadResp, } from '@snowluma/proto-defs/oidb-actions/group-file'; import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +function composeGroupFileUrl(download: OidbGroupFileDownloadResp, fileId: string): string { + ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording); + const dns = (typeof download.downloadDns === 'string' && download.downloadDns) + || (typeof download.downloadIp === 'string' && download.downloadIp) + || ''; + const hexUrl = download.downloadUrl instanceof Uint8Array && download.downloadUrl.length > 0 + ? toHexUpper(download.downloadUrl) + : ''; + if (!dns || !hexUrl) { + throw new Error('group file url response invalid'); + } + return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`; +} export namespace GetGroupFileUrl { export const command = 0x6D6; @@ -27,10 +43,11 @@ export namespace GetGroupFileUrl { }, }); - export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): OidbGroupFileDownloadResp => { + // Default deserialize has no fileId for fname=; invoke() rewires it. + export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): string => { const download = body.download; if (!download) throw new Error('group file url response missing'); - return download; + return composeGroupFileUrl(download, ''); }; export const encode = (env: OidbBase): Uint8Array => @@ -39,6 +56,13 @@ export namespace GetGroupFileUrl { export const decode = (bytes: Uint8Array): OidbBase => protobuf_decode>(bytes); - export const invoke = (deps: Deps, params: Params): Promise => - invokeOidb(deps, GetGroupFileUrl, params); + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, { + ...GetGroupFileUrl, + deserialize: (_ctx, body) => { + const download = body.download; + if (!download) throw new Error('group file url response missing'); + return composeGroupFileUrl(download, params.fileId); + }, + }, params); } diff --git a/packages/protocol/src/oidb-services/group-file/get-private-file-url.ts b/packages/protocol/src/oidb-services/group-file/get-private-file-url.ts index 50ea9750..fdc0e0c5 100644 --- a/packages/protocol/src/oidb-services/group-file/get-private-file-url.ts +++ b/packages/protocol/src/oidb-services/group-file/get-private-file-url.ts @@ -1,7 +1,7 @@ // 0xE37_1200 — resolve a private (c2c) file_id → http download URL. // Carries an opaque 4-byte `field99999` magic the server's deserializer -// requires (Lagrange has the same constant). The facade composes the -// final `http://:&isthumb=0` string. +// requires (Lagrange has the same constant). This namespace owns the +// `http://:&isthumb=0` string. // // 5s timeout matches the original facade — the server batches these // at low priority and stalls past the default 30s. @@ -10,9 +10,9 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbPrivateFileDownloadReq, OidbPrivateFileDownloadResp, - OidbPrivateFileDownloadRespResult, } from '@snowluma/proto-defs/oidb-actions/media'; import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { toInt } from '../shared'; const TIMEOUT_MS = 5000; @@ -39,10 +39,16 @@ export namespace GetPrivateFileUrl { field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), }); - export const deserialize = (_ctx: Deps, body: OidbPrivateFileDownloadResp): OidbPrivateFileDownloadRespResult => { + export const deserialize = (_ctx: Deps, body: OidbPrivateFileDownloadResp): string => { const result = body.body?.result; if (!result) throw new Error('private file url response invalid'); - return result; + const server = typeof result.server === 'string' ? result.server : ''; + const port = toInt(result.port); + const url = typeof result.url === 'string' ? result.url : ''; + if (!server || !port || !url) { + throw new Error('private file url response invalid'); + } + return `http://${server}:${port}${url}&isthumb=0`; }; export const encode = (env: OidbBase): Uint8Array => @@ -51,6 +57,6 @@ export namespace GetPrivateFileUrl { export const decode = (bytes: Uint8Array): OidbBase => protobuf_decode>(bytes); - export const invoke = (deps: Deps, params: Params): Promise => + export const invoke = (deps: Deps, params: Params): Promise => invokeOidb(deps, GetPrivateFileUrl, params, TIMEOUT_MS); } diff --git a/packages/protocol/src/oidb-services/group-file/list-group-files-page.ts b/packages/protocol/src/oidb-services/group-file/list-group-files-page.ts index 9f8199ea..353062d6 100644 --- a/packages/protocol/src/oidb-services/group-file/list-group-files-page.ts +++ b/packages/protocol/src/oidb-services/group-file/list-group-files-page.ts @@ -6,9 +6,17 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { - OidbGroupFileViewReq, OidbGroupFileViewResp, OidbGroupFileListResp, + OidbGroupFileListItemResp, + OidbGroupFileViewReq, + OidbGroupFileViewResp, } from '@snowluma/proto-defs/oidb-actions/group-file'; import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export interface GroupFileListPage { + items: OidbGroupFileListItemResp[]; + isEnd: boolean; +} export namespace ListGroupFilesPage { export const command = 0x6D8; @@ -37,11 +45,13 @@ export namespace ListGroupFilesPage { }, }); - /** Returns the list body directly so the facade can inspect - * `items`, `isEnd`, and `retCode` in one place. Returns null when + /** Returns items + isEnd after checking list.retCode. Returns null when * the server elides the list entirely (end-of-stream sentinel). */ - export const deserialize = (_ctx: Deps, body: OidbGroupFileViewResp): OidbGroupFileListResp | null => { - return body.list ?? null; + export const deserialize = (_ctx: Deps, body: OidbGroupFileViewResp): GroupFileListPage | null => { + const list = body.list; + if (!list) return null; + ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording); + return { items: list.items ?? [], isEnd: !!list.isEnd }; }; export const encode = (env: OidbBase): Uint8Array => @@ -50,6 +60,6 @@ export namespace ListGroupFilesPage { export const decode = (bytes: Uint8Array): OidbBase => protobuf_decode>(bytes); - export const invoke = (deps: Deps, params: Params): Promise => + export const invoke = (deps: Deps, params: Params): Promise => invokeOidb(deps, ListGroupFilesPage, params); } diff --git a/packages/protocol/src/oidb-services/group-file/ntv2-download.ts b/packages/protocol/src/oidb-services/group-file/ntv2-download.ts index f34a9be4..070846c1 100644 --- a/packages/protocol/src/oidb-services/group-file/ntv2-download.ts +++ b/packages/protocol/src/oidb-services/group-file/ntv2-download.ts @@ -10,7 +10,7 @@ // rKeyParam` triple → composed into `https://`. import type { NTV2IndexNode, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; -import { ensureRetCodeZero } from '../shared'; +import { ensureRetCodeZero, toInt } from '../shared'; export function parseNtv2DownloadUrl(body: NTV2RichMediaResp): string { ensureRetCodeZero('ntv2 download', body.respHead?.retCode, body.respHead?.message, undefined); @@ -56,12 +56,6 @@ export function normalizeMediaNode(node: NtMediaIndex): NTV2IndexNode { }; } -function toInt(value: unknown): number { - if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); - if (typeof value === 'bigint') return Number(value); - return 0; -} - export interface NtMediaIndex { info?: { fileSize?: number; diff --git a/packages/protocol/tests/oidb-services/group-file/get-group-file-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-group-file-url.test.ts index b313a931..2111f059 100644 --- a/packages/protocol/tests/oidb-services/group-file/get-group-file-url.test.ts +++ b/packages/protocol/tests/oidb-services/group-file/get-group-file-url.test.ts @@ -34,12 +34,18 @@ describe('GetGroupFileUrl namespace', () => { }); }); - it('returns the download sub-message verbatim (URL composition lives on the facade)', async () => { - const deps = makeDeps({ download: { downloadDns: 'cdn', downloadUrl: new Uint8Array([0x01]) } as any }); - const out = await GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'f', busId: 102 }); - expect(out.downloadDns).toBe('cdn'); - // proton round-trips bytes through a Node Buffer; assert the byte values, not the wrapper class. - expect(Array.from(out.downloadUrl ?? new Uint8Array())).toEqual([0x01]); + it('composes the https ftn_handler URL and checks download.retCode', async () => { + const deps = makeDeps({ download: { downloadDns: 'cdn', downloadUrl: new Uint8Array([0x01, 0x02]) } as any }); + await expect(GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'fid-xyz', busId: 102 })) + .resolves.toBe('https://cdn/ftn_handler/0102/?fname=fid-xyz'); + }); + + it('throws when download.retCode is non-zero', async () => { + const deps = makeDeps({ + download: { retCode: 1, retMsg: 'denied', downloadDns: 'cdn', downloadUrl: new Uint8Array([1]) } as any, + }); + await expect(GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'f', busId: 102 })) + .rejects.toThrow(/group file url failed: code=1/); }); it('throws when the download sub-message is missing', async () => { @@ -47,4 +53,12 @@ describe('GetGroupFileUrl namespace', () => { await expect(GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'f', busId: 102 })) .rejects.toThrow(/url response missing/); }); + + it('falls back to downloadIp when downloadDns is empty', async () => { + const deps = makeDeps({ + download: { downloadIp: '1.2.3.4', downloadUrl: new Uint8Array([0xab]) } as any, + }); + await expect(GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'fid', busId: 102 })) + .resolves.toBe('https://1.2.3.4/ftn_handler/AB/?fname=fid'); + }); }); diff --git a/packages/protocol/tests/oidb-services/group-file/get-private-file-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-private-file-url.test.ts index 06f1693b..b9d76b80 100644 --- a/packages/protocol/tests/oidb-services/group-file/get-private-file-url.test.ts +++ b/packages/protocol/tests/oidb-services/group-file/get-private-file-url.test.ts @@ -43,14 +43,12 @@ describe('GetPrivateFileUrl namespace', () => { expect(env.body?.field99999).toEqual(new Uint8Array([0xC0, 0x85, 0x2C, 0x01])); }); - it('returns the result sub-message verbatim', async () => { + it('composes the http download URL', async () => { const deps = makeDeps({ body: { result: { server: 'srv', port: 8080, url: '/path' } } as any, }); - const out = await GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' }); - expect(out.server).toBe('srv'); - expect(out.port).toBe(8080); - expect(out.url).toBe('/path'); + await expect(GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' })) + .resolves.toBe('http://srv:8080/path&isthumb=0'); }); it('throws when result is missing', async () => { @@ -58,4 +56,12 @@ describe('GetPrivateFileUrl namespace', () => { await expect(GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' })) .rejects.toThrow(/private file url response invalid/); }); + + it('throws when server/port/url is incomplete', async () => { + const deps = makeDeps({ + body: { result: { server: 'srv', port: 0, url: '/path' } } as any, + }); + await expect(GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' })) + .rejects.toThrow(/private file url response invalid/); + }); }); diff --git a/packages/protocol/tests/oidb-services/group-file/list-group-files-page.test.ts b/packages/protocol/tests/oidb-services/group-file/list-group-files-page.test.ts index fc21cdc9..b90c3412 100644 --- a/packages/protocol/tests/oidb-services/group-file/list-group-files-page.test.ts +++ b/packages/protocol/tests/oidb-services/group-file/list-group-files-page.test.ts @@ -68,15 +68,23 @@ describe('ListGroupFilesPage namespace', () => { }); }); - it('returns the list body so the facade can walk items / isEnd', async () => { + it('returns items and isEnd after checking list.retCode', async () => { const deps = makeDeps({ list: { isEnd: false, items: [{ type: 1 }] } as any, }); const out = await ListGroupFilesPage.invoke(deps, { groupId: 1, targetDirectory: '/', startIndex: 0, pageSize: 10, }); - expect(out?.isEnd ?? false).toBe(false); - expect(out?.items).toHaveLength(1); + expect(out).toEqual({ items: [expect.objectContaining({ type: 1 })], isEnd: false }); + }); + + it('throws when list.retCode is non-zero', async () => { + const deps = makeDeps({ + list: { retCode: 2, retMsg: 'busy', isEnd: true, items: [] } as any, + }); + await expect(ListGroupFilesPage.invoke(deps, { + groupId: 1, targetDirectory: '/', startIndex: 0, pageSize: 10, + })).rejects.toThrow(/group file list failed: code=2/); }); it('decodes the folder last-upload metadata from the QQ wire fields', async () => {