refactor(protocol): send leftover OIDB envelopes through the shared caller
Moving a friend who is already in the target category still succeeds. Media upload preflight now uses the same envelope success and error rules as other OIDB calls.
This commit is contained in:
@@ -27,7 +27,6 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { gunzipSync } from 'zlib';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
encodeOidbEnv: vi.fn(() => new Uint8Array()),
|
||||
decodeOidbEnv: vi.fn(() => ({ body: {} })),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
encodeOidbEnv: vi.fn(() => new Uint8Array()),
|
||||
decodeOidbEnv: vi.fn(() => ({ body: {} })),
|
||||
|
||||
@@ -13,7 +13,6 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
encodeOidbEnv: vi.fn(() => new Uint8Array()),
|
||||
decodeOidbEnv: vi.fn(() => ({ body: {} })),
|
||||
|
||||
@@ -33,7 +33,7 @@ describe('apis/interaction', () => {
|
||||
|
||||
it('setReaction picks _1 for set and _2 for unset', async () => {
|
||||
// setReaction now forwards through the SetReaction namespace, which
|
||||
// calls bridge.sendRawPacket directly (bypassing runOidb).
|
||||
// calls bridge.sendRawPacket directly.
|
||||
const bridge = mockBridge();
|
||||
const api = new InteractionApi(bridge as any);
|
||||
await api.setReaction(12345, 99, '128516', true);
|
||||
|
||||
@@ -12,18 +12,12 @@ import type {
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
|
||||
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
|
||||
// (substituted at the call site with the inlined codec). Mocking them on
|
||||
// the module object is a no-op — proton has already inlined the call.
|
||||
// We mock `runOidb` (non-generic) to return real proton-encoded bytes
|
||||
// that the production-side codec actually decodes.
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', async () => {
|
||||
const actual = await vi.importActual<typeof import('@snowluma/protocol/bridge-oidb')>(
|
||||
'@snowluma/protocol/bridge-oidb',
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
};
|
||||
});
|
||||
@@ -47,8 +41,6 @@ import { mockBridge } from './_helpers';
|
||||
|
||||
describe('apis/profile', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(oidb.runOidb).mockReset();
|
||||
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
|
||||
vi.mocked(oidb.makeOidbEnvelope).mockClear();
|
||||
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
|
||||
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb';
|
||||
// Sender capability is the minimal interface needed by runOidb. The
|
||||
// concrete BridgeContext (and the Bridge class extending it) is
|
||||
// structurally a superset, so callers keep passing `bridge` unchanged.
|
||||
import type { OidbSender } from './oidb-service';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
|
||||
/**
|
||||
* Build the OidbBase<T>-shaped TS value. Pure helper, no protobuf
|
||||
@@ -31,39 +26,3 @@ export function makeOidbEnvelope<T>(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Issue one OIDB request and return the raw response bytes.
|
||||
*
|
||||
* Typical usage:
|
||||
* const env = makeOidbEnvelope<MyReq>(0x1253, 1, value);
|
||||
* const buf = await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
|
||||
* const resp = decodeOidbEnv<MyResp>(buf).body;
|
||||
*
|
||||
* Fire-and-check (no body decode):
|
||||
* await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
|
||||
*
|
||||
* Always peeks at the envelope errorCode via the non-generic
|
||||
* `OidbBaseMeta` view so a server-side rejection cannot slip past
|
||||
* silently. Returns the raw response bytes (empty `Uint8Array` if the
|
||||
* packet carried no payload).
|
||||
*/
|
||||
export async function runOidb(
|
||||
sender: OidbSender,
|
||||
cmd: string,
|
||||
envelopeBytes: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<Uint8Array> {
|
||||
const result = await sender.sendRawPacket(cmd, envelopeBytes, timeoutMs);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||
|
||||
const bytes = result.responseData ?? new Uint8Array(0);
|
||||
if (bytes.length > 0) {
|
||||
const meta = protobuf_decode<OidbBaseMeta>(bytes);
|
||||
const code = meta?.errorCode;
|
||||
if (code && code !== 0) {
|
||||
throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`);
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@@ -9,14 +9,11 @@ import type {
|
||||
NTV2ExtBizInfo,
|
||||
NTV2UploadInfo,
|
||||
NTV2UploadRespBody,
|
||||
NTV2UploadRichMediaReq,
|
||||
NTV2UploadRichMediaResp,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import crypto from 'crypto';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { makeOidbEnvelope } from '../bridge-oidb';
|
||||
import { OidbError } from '../oidb-service';
|
||||
import { Ntv2UploadRequest } from '../oidb-services/highway/ntv2-upload-request';
|
||||
import { BufferChunkSource, FileChunkSource, buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
@@ -189,7 +186,7 @@ async function runNtv2UploadOperation(
|
||||
params: NtV2UploadParams,
|
||||
setState: (failureReason: string, didPut?: boolean) => void,
|
||||
): Promise<NTV2UploadRespBody> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
@@ -204,67 +201,30 @@ async function runNtv2UploadOperation(
|
||||
// `pb<bool>` when it's `true`, so `tryFast === false` omits field 2 —
|
||||
// the server reads that as "don't fast-upload" (the opt-in default).
|
||||
const requestUpload = async (tryFast: boolean): Promise<NTV2UploadRespBody> => {
|
||||
const body: NTV2UploadRichMediaReq = {
|
||||
reqHead: {
|
||||
common: { requestId: params.requestId, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: params.businessType,
|
||||
sceneType: isGroup ? 2 : 1,
|
||||
...(isGroup
|
||||
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
setState('request_failed');
|
||||
try {
|
||||
return await Ntv2UploadRequest.invoke(bridge, {
|
||||
oidbCmd,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
requestId: params.requestId,
|
||||
businessType: params.businessType,
|
||||
uploadInfo: params.uploadInfo,
|
||||
tryFastUploadCompleted: tryFast,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
compatQmsgSceneType: params.compatQmsgSceneType,
|
||||
extBizInfo: params.extBizInfo,
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
|
||||
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
|
||||
|
||||
setState('request_failed');
|
||||
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
|
||||
log.trace(() => [
|
||||
'highway_media_branch branch=oidb_response success=%s gotResponse=%s errorCode=%d errorMessage=%j responseBytes=%d',
|
||||
result.success,
|
||||
result.gotResponse,
|
||||
result.errorCode,
|
||||
result.errorMessage ?? '',
|
||||
result.responseData?.byteLength ?? 0,
|
||||
]);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || `${label} upload request failed`);
|
||||
tryFast,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OidbError) setState('oidb_rejected');
|
||||
else if (error instanceof Error && error.message.includes('missing msgInfo')) setState('response_invalid');
|
||||
else if (error instanceof Error && error.message.includes('upload failed')) setState('business_rejected');
|
||||
log.trace(() => [
|
||||
'highway_media_branch branch=oidb_response error=%j',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
|
||||
setState('response_decode_failed');
|
||||
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
|
||||
if (!resp) throw new Error(`failed to decode ${label} upload response`);
|
||||
if (resp.errorCode && resp.errorCode !== 0) {
|
||||
setState('oidb_rejected');
|
||||
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const uploadBody = resp.body;
|
||||
setState('response_invalid');
|
||||
if (!uploadBody) throw new Error(`${label} upload response body missing`);
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
setState('business_rejected');
|
||||
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
|
||||
}
|
||||
const upload = uploadBody.upload;
|
||||
if (!upload) throw new Error(`${label} upload response body missing`);
|
||||
if (!upload.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
return upload;
|
||||
};
|
||||
|
||||
// Highway PUTs. Session is lazily fetched and cached — video does two
|
||||
|
||||
@@ -54,12 +54,15 @@ export interface OidbSender {
|
||||
*
|
||||
* One of `subCommand` (static) or `resolveSubCommand` (dynamic from
|
||||
* params and context) must be present. `resolveSubCommand` wins if both
|
||||
* are given.
|
||||
* are given. `resolveCommand` likewise wins over static `command`.
|
||||
*/
|
||||
export interface OidbCallSpec<TCtx extends OidbSender, TReq, TResp, TParams, TResult> {
|
||||
command: number;
|
||||
resolveCommand?(params: TParams, ctx: TCtx): number;
|
||||
subCommand?: number;
|
||||
resolveSubCommand?(params: TParams, ctx: TCtx): number;
|
||||
/** Packet and body envelope codes treated as success in addition to 0. */
|
||||
acceptedEnvelopeCodes?: readonly number[];
|
||||
/** Set OIDB envelope `reserved = 1` (UIN-form variant, see makeOidbEnvelope's isUid). */
|
||||
uinForm?: boolean;
|
||||
/** Override the default `OidbSvcTrpcTcp.0xNNNN_N` wire name. A few
|
||||
@@ -79,6 +82,28 @@ export interface OidbCallSpec<TCtx extends OidbSender, TReq, TResp, TParams, TRe
|
||||
decode(bytes: Uint8Array): OidbBase<TResp>;
|
||||
}
|
||||
|
||||
function resolveOidbCall<TCtx extends OidbSender, TReq, TResp, TParams, TResult>(
|
||||
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
|
||||
params: TParams,
|
||||
ctx: TCtx,
|
||||
): { command: number; subCommand: number } {
|
||||
const command = spec.resolveCommand
|
||||
? spec.resolveCommand(params, ctx)
|
||||
: spec.command;
|
||||
const subCommand = spec.resolveSubCommand
|
||||
? spec.resolveSubCommand(params, ctx)
|
||||
: spec.subCommand!;
|
||||
return { command, subCommand };
|
||||
}
|
||||
|
||||
function isAcceptedEnvelopeCode<TCtx extends OidbSender, TReq, TResp, TParams, TResult>(
|
||||
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
|
||||
code: number | null | undefined,
|
||||
): boolean {
|
||||
if (code == null || code === 0) return true;
|
||||
return spec.acceptedEnvelopeCodes?.includes(code) === true;
|
||||
}
|
||||
|
||||
export class OidbError extends Error {
|
||||
constructor(
|
||||
readonly code: number,
|
||||
@@ -107,39 +132,40 @@ export async function invokeOidb<TCtx extends OidbSender, TReq, TResp, TParams,
|
||||
params: TParams,
|
||||
timeoutMs?: number,
|
||||
): Promise<TResult> {
|
||||
const subCommand = spec.resolveSubCommand
|
||||
? spec.resolveSubCommand(params, ctx)
|
||||
: spec.subCommand!;
|
||||
const { command, subCommand } = resolveOidbCall(spec, params, ctx);
|
||||
const reqBody = await spec.serialize(ctx, params);
|
||||
const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false);
|
||||
const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false);
|
||||
const reqBytes = spec.encode(env);
|
||||
const wireName = spec.wireName
|
||||
? spec.wireName(spec.command, subCommand)
|
||||
: `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
|
||||
? spec.wireName(command, subCommand)
|
||||
: `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`;
|
||||
|
||||
const result = await ctx.sendRawPacket(wireName, reqBytes, timeoutMs);
|
||||
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||
|
||||
if (!result.success) {
|
||||
if (result.errorCode && result.errorCode !== 0) {
|
||||
throw new OidbError(
|
||||
result.errorCode,
|
||||
result.errorMessage || '',
|
||||
spec.command,
|
||||
subCommand
|
||||
);
|
||||
if (!isAcceptedEnvelopeCode(spec, result.errorCode)) {
|
||||
throw new OidbError(
|
||||
result.errorCode,
|
||||
result.errorMessage || '',
|
||||
command,
|
||||
subCommand
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// success=false without an OIDB error code = the packet send itself failed;
|
||||
// surface it instead of silently resolving with an undecoded response.
|
||||
throw new Error(result.errorMessage || 'packet send failed');
|
||||
}
|
||||
// success=false without an OIDB error code = the packet send itself failed;
|
||||
// surface it instead of silently resolving with an undecoded response.
|
||||
throw new Error(result.errorMessage || 'packet send failed');
|
||||
}
|
||||
|
||||
const respBytes = result.responseData ?? new Uint8Array(0);
|
||||
if (respBytes.length > 0) {
|
||||
const meta = protobuf_decode<OidbBaseMeta>(respBytes);
|
||||
const code = meta?.errorCode;
|
||||
if (code && code !== 0) {
|
||||
throw new OidbError(code, meta?.errorMsg ?? '', spec.command, subCommand);
|
||||
if (code && code !== 0 && !isAcceptedEnvelopeCode(spec, code)) {
|
||||
throw new OidbError(code, meta?.errorMsg ?? '', command, subCommand);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,15 +189,13 @@ export async function buildOidbRequest<TCtx extends OidbSender, TReq, TResp, TPa
|
||||
spec: OidbCallSpec<TCtx, TReq, TResp, TParams, TResult>,
|
||||
params: TParams,
|
||||
): Promise<{ wireName: string; bytes: Uint8Array }> {
|
||||
const subCommand = spec.resolveSubCommand
|
||||
? spec.resolveSubCommand(params, ctx)
|
||||
: spec.subCommand!;
|
||||
const { command, subCommand } = resolveOidbCall(spec, params, ctx);
|
||||
const reqBody = await spec.serialize(ctx, params);
|
||||
const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false);
|
||||
const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false);
|
||||
const bytes = spec.encode(env);
|
||||
const wireName = spec.wireName
|
||||
? spec.wireName(spec.command, subCommand)
|
||||
: `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
|
||||
? spec.wireName(command, subCommand)
|
||||
: `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`;
|
||||
return { wireName, bytes };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbSetFriendCategoryRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { makeOidbEnvelope } from '../../bridge-oidb';
|
||||
import { OidbError, type OidbSender } from '../../oidb-service';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
/**
|
||||
* Move one friend into a category.
|
||||
*
|
||||
* The desktop client treats 2001002 as an idempotent success result, so this
|
||||
* call intentionally validates the response itself instead of using the
|
||||
* generic OIDB helper that rejects every non-zero application code.
|
||||
* The desktop client treats 2001002 as an idempotent success result.
|
||||
*/
|
||||
export namespace SetFriendCategory {
|
||||
export const command = 0x1255;
|
||||
export const subCommand = 0;
|
||||
export const uinForm = true;
|
||||
export const alreadyAppliedCode = 2_001_002;
|
||||
export const acceptedEnvelopeCodes = [alreadyAppliedCode] as const;
|
||||
|
||||
export interface Params {
|
||||
uid: string;
|
||||
@@ -29,35 +27,14 @@ export namespace SetFriendCategory {
|
||||
categoryId: params.categoryId,
|
||||
});
|
||||
|
||||
function accepted(code: number | null | undefined): boolean {
|
||||
return code == null || code === 0 || code === alreadyAppliedCode;
|
||||
}
|
||||
export const deserialize = (): void => undefined;
|
||||
|
||||
export async function invoke(deps: Deps, params: Params): Promise<void> {
|
||||
const body = serialize(deps, params);
|
||||
const bytes = protobuf_encode<OidbBase<OidbSetFriendCategoryRequest>>(
|
||||
makeOidbEnvelope(command, subCommand, body, uinForm),
|
||||
);
|
||||
const result = await deps.sendRawPacket('OidbSvcTrpcTcp.0x1255_0', bytes);
|
||||
export const encode = (env: OidbBase<OidbSetFriendCategoryRequest>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbSetFriendCategoryRequest>>(env);
|
||||
|
||||
if (!result.gotResponse) {
|
||||
throw new Error(result.errorMessage || 'no response');
|
||||
}
|
||||
if (!result.success && result.errorCode !== alreadyAppliedCode) {
|
||||
if (result.errorCode) {
|
||||
throw new OidbError(result.errorCode, result.errorMessage, command, subCommand);
|
||||
}
|
||||
throw new Error(result.errorMessage || 'packet send failed');
|
||||
}
|
||||
if (!accepted(result.errorCode)) {
|
||||
throw new OidbError(result.errorCode, result.errorMessage, command, subCommand);
|
||||
}
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbSetFriendCategoryRequest> =>
|
||||
protobuf_decode<OidbBase<OidbSetFriendCategoryRequest>>(bytes);
|
||||
|
||||
const response = result.responseData ?? new Uint8Array(0);
|
||||
if (response.length === 0) return;
|
||||
const meta = protobuf_decode<OidbBaseMeta>(response);
|
||||
if (!accepted(meta.errorCode)) {
|
||||
throw new OidbError(meta.errorCode!, meta.errorMsg ?? '', command, subCommand);
|
||||
}
|
||||
}
|
||||
export const invoke = (deps: Deps, params: Params): Promise<void> =>
|
||||
invokeOidb(deps, SetFriendCategory, params);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
NTV2ExtBizInfo,
|
||||
NTV2UploadInfo,
|
||||
NTV2UploadRespBody,
|
||||
NTV2UploadRichMediaReq,
|
||||
NTV2UploadRichMediaResp,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
/**
|
||||
* NTV2 rich-media upload preflight. Image / PTT / video share one Req/Resp
|
||||
* type; command (0x11C4 / 0x11C5 / …) comes from the caller. Highway PUTs
|
||||
* stay in the pipeline.
|
||||
*/
|
||||
export namespace Ntv2UploadRequest {
|
||||
export const command = 0;
|
||||
export const subCommand = 100;
|
||||
export const uinForm = true;
|
||||
|
||||
export interface Params {
|
||||
oidbCmd: number;
|
||||
isGroup: boolean;
|
||||
targetIdOrUid: string | number;
|
||||
requestId: number;
|
||||
businessType: number;
|
||||
uploadInfo: NTV2UploadInfo[];
|
||||
compatQmsgSceneType: number;
|
||||
extBizInfo: NTV2ExtBizInfo;
|
||||
tryFast: boolean;
|
||||
clientRandomId: bigint;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const resolveCommand = (params: Params): number => params.oidbCmd;
|
||||
|
||||
export const serialize = (_ctx: Deps, params: Params): NTV2UploadRichMediaReq => ({
|
||||
reqHead: {
|
||||
common: { requestId: params.requestId, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: params.businessType,
|
||||
sceneType: params.isGroup ? 2 : 1,
|
||||
...(params.isGroup
|
||||
? { group: { groupUin: Number(params.targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(params.targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
uploadInfo: params.uploadInfo,
|
||||
tryFastUploadCompleted: params.tryFast,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: params.clientRandomId,
|
||||
compatQmsgSceneType: params.compatQmsgSceneType,
|
||||
extBizInfo: params.extBizInfo,
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
});
|
||||
|
||||
export const deserialize = (_ctx: Deps, body: NTV2UploadRichMediaResp): NTV2UploadRespBody => {
|
||||
if (!body) throw new Error('media upload response body missing');
|
||||
if (body.respHead?.retCode && body.respHead.retCode !== 0) {
|
||||
throw new Error(body.respHead.message ?? 'media upload failed');
|
||||
}
|
||||
const upload = body.upload;
|
||||
if (!upload) throw new Error('media upload response body missing');
|
||||
if (!upload.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
return upload;
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<NTV2UploadRichMediaReq>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<NTV2UploadRichMediaResp> =>
|
||||
protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<NTV2UploadRespBody> =>
|
||||
invokeOidb(deps, Ntv2UploadRequest, params);
|
||||
}
|
||||
@@ -231,6 +231,33 @@ describe('invokeOidb', () => {
|
||||
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
|
||||
expect(env.reserved ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it('treats registered envelope codes as success on the packet and body', async () => {
|
||||
const spec = { ...staticSubSpec, acceptedEnvelopeCodes: [2_001_002] };
|
||||
const bodyBytes = protobuf_encode<OidbBase<OidbEmpty>>({
|
||||
command: 0xEAC, subCommand: 1, errorCode: 2_001_002, errorMsg: 'already applied',
|
||||
});
|
||||
await expect(invokeOidb(makeSender({ responseData: Buffer.from(bodyBytes) }), spec, { groupId: 1 }))
|
||||
.resolves.toBeUndefined();
|
||||
await expect(invokeOidb(makeSender({
|
||||
success: false,
|
||||
errorCode: 2_001_002,
|
||||
errorMessage: 'already applied',
|
||||
responseData: null,
|
||||
}), spec, { groupId: 1 })).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('uses resolveCommand for the wire name and envelope command', async () => {
|
||||
const spec = {
|
||||
...staticSubSpec,
|
||||
command: 0,
|
||||
resolveCommand: () => 0x11C5,
|
||||
subCommand: 100,
|
||||
};
|
||||
const sender = makeSender();
|
||||
await invokeOidb(sender, spec, { groupId: 1 });
|
||||
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x11c5_100');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildOidbRequest', () => {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
|
||||
import { OidbError } from '../../../src/oidb-service';
|
||||
import { Ntv2UploadRequest } from '../../../src/oidb-services/highway/ntv2-upload-request';
|
||||
|
||||
function packet(body: NTV2UploadRichMediaResp, errorCode = 0): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
|
||||
command: 0x11C5,
|
||||
subCommand: 100,
|
||||
errorCode,
|
||||
errorMsg: errorCode ? 'denied' : '',
|
||||
body,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
const params: Ntv2UploadRequest.Params = {
|
||||
oidbCmd: 0x11C5,
|
||||
isGroup: false,
|
||||
targetIdOrUid: 'u_peer',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [],
|
||||
compatQmsgSceneType: 1,
|
||||
extBizInfo: {},
|
||||
tryFast: true,
|
||||
clientRandomId: 1n,
|
||||
};
|
||||
|
||||
describe('Ntv2UploadRequest', () => {
|
||||
it('sends the resolved command on the default OIDB wire name', async () => {
|
||||
const sendRawPacket = vi.fn(async () => packet({
|
||||
upload: { msgInfo: { msgInfoBody: [] } },
|
||||
}));
|
||||
await Ntv2UploadRequest.invoke({ sendRawPacket }, params);
|
||||
expect(sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x11c5_100');
|
||||
});
|
||||
|
||||
it('raises OidbError when the envelope is rejected', async () => {
|
||||
const sendRawPacket = vi.fn(async () => packet({ upload: { msgInfo: {} } }, 42));
|
||||
await expect(Ntv2UploadRequest.invoke({ sendRawPacket }, params)).rejects.toBeInstanceOf(OidbError);
|
||||
});
|
||||
|
||||
it('fails in deserialize when msgInfo is missing', async () => {
|
||||
const sendRawPacket = vi.fn(async () => packet({ upload: { uKey: 'k' } }));
|
||||
await expect(Ntv2UploadRequest.invoke({ sendRawPacket }, params))
|
||||
.rejects.toThrow('upload response missing msgInfo');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user