Files
SnowLuma/packages/core/src/bridge/highway/image-upload.ts
T
DrSmoothl 7ec479bb88 feat(logger): protocol-layer observability for highway and msg-push
Highway upload path now emits per-type entry + shared pipeline ops:

  DEBUG [Highway.Image]  uploading 234567 bytes md5=abc12345... → group 12345
  DEBUG [Highway]        image OIDB requires bytes, PUT 234567 bytes (sub=top)
  DEBUG [Highway]        image PUT done in 1234ms
  -- or --
  DEBUG [Highway]        image fast-upload hit (server already had bytes)

The three pipeline-side lines come from runNtv2Upload() and are
shared across image/video/ptt; the per-type entry log lives in each
*-upload.ts wrapper so the scope identifies the media kind. md5 is
truncated to its first 8 hex chars for line width; PUT latency is
reported in ms.

MsgPush silent dispatch defaults are now visible at debug:

  DEBUG [MsgPush.Unknown] no decoder for PkgType=999 subType=0
  DEBUG [MsgPush.Unknown] Event0x2DC unknown subType=42
  DEBUG [MsgPush.Unknown] Event0x210 unknown subType=42

Captures protocol drift (new NT QQ subtypes) and "we forgot to
register this PkgType" oversights, neither of which used to leave
any trace in the log.

All new lines are debug-level so console output (default info) stays
unchanged; file transport sees them for post-mortem.
2026-05-18 01:29:06 +08:00

179 lines
5.4 KiB
TypeScript

// Image upload: load the source, run NTV2 upload + (optional) Highway PUT,
// return the encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT live in
// pipeline.ts; this file just supplies the image-specific bits (format
// detection, picFormat, bizType, command ids).
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { createLogger } from '../../utils/logger';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
const moduleLog = createLogger('Highway.Image');
function loggerFor(bridge: Bridge) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
}
interface ImageData {
/** Empty when the caller is forwarding from cached fingerprints. */
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
fileName: string;
fileSize: number;
summary: string;
subType: number;
width: number;
height: number;
picFormat: number;
/** True when `bytes` is empty; runNtv2Upload throws fastOnlyError if
* the server demands the bytes anyway. */
fastOnly: boolean;
}
function imageDataFromFingerprint(element: MessageElement): ImageData {
return {
bytes: new Uint8Array(0),
md5: hexToBytes(element.md5Hex ?? ''),
sha1: hexToBytes(element.sha1Hex ?? ''),
md5Hex: element.md5Hex ?? '',
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'image'}.jpg`,
fileSize: element.fileSize ?? 0,
summary: element.summary || (element.subType === 0 ? '[image]' : '[sticker]'),
subType: element.subType ?? 0,
width: element.width ?? 0,
height: element.height ?? 0,
picFormat: element.picFormat ?? 1000,
fastOnly: true,
};
}
function loadImage(element: MessageElement): Promise<ImageData> {
if (element.noByteFallback) {
if (!element.md5Hex || !element.sha1Hex) {
return Promise.reject(new Error('image fast-upload requires md5Hex + sha1Hex'));
}
return Promise.resolve(imageDataFromFingerprint(element));
}
return loadImageFromSource(
element.url || element.fileId || '',
element.fileName ?? '',
element.subType ?? 0,
element.summary ?? '',
);
}
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
const loaded = await loadBinarySource(source, 'image');
const hashes = computeHashes(loaded.bytes);
const fmt = detectImageFormat(loaded.bytes);
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
const ext = extMap[fmt.format] ?? '.jpg';
let finalName = fileName || loaded.fileName;
if (!finalName) finalName = hashes.md5Hex + ext;
return {
bytes: loaded.bytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: finalName,
fileSize: loaded.bytes.length,
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
subType,
width: fmt.width,
height: fmt.height,
picFormat: fmt.format,
fastOnly: false,
};
}
/**
* Upload an image and return the encoded MsgInfo bytes for the outgoing
* commonElem.
*/
export async function uploadImageMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const image = await loadImage(element);
log.debug('uploading %d bytes md5=%s... → %s %s',
image.fileSize,
image.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid));
const uploads: MediaSubFileUpload[] = [{
source: 'top',
cmdId: isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID,
bytes: image.bytes,
md5: image.md5,
sha1: image.sha1,
fastOnlyError: 'image fast-upload not available (server requires bytes)',
}];
const upload = await runNtv2Upload({
bridge,
isGroup,
targetIdOrUid,
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
requestId: 1,
businessType: 1,
uploadInfo: [{
fileInfo: {
fileSize: image.fileSize,
fileHash: image.md5Hex,
fileSha1: image.sha1Hex,
fileName: image.fileName,
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
width: image.width,
height: image.height,
time: 0,
original: 1,
},
subFileType: 0,
}],
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
pic: {
bizType: image.subType,
textSummary: image.summary,
...(isGroup
? { reserveTroop: { subType: image.subType } }
: { reserveC2c: { subType: image.subType } }),
},
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array(0),
bytesPbReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
uploads,
label: 'image',
});
return finalizeMediaMsgInfo(upload, { bizType: image.subType, textSummary: image.summary });
}