The three highway uploaders — image-upload, ptt-upload, video-upload —
each implemented the same NTV2 envelope assembly, OIDB response decode,
error handling, and Highway PUT loop, with the only real per-format
differences being the file-info fields, the extBizInfo blob, and the
Highway command id. The duplicated boilerplate had drifted slightly
between files and any future NTQQ protocol change would have needed
parallel edits in three places.
New: packages/core/src/bridge/highway/pipeline.ts (249 lines).
runNtv2Upload({ bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd,
requestId, businessType, uploadInfo, compatQmsgSceneType,
extBizInfo, uploads, label })
-> awaited upload object
Builds the full reqHead + upload envelope, sends through OIDB,
decodes the response, runs the per-sub-file Highway PUTs (caching
the Highway session across them — video uses two PUTs and now only
fetches the session once), and surfaces a typed fastOnlyError when
the server demands bytes but the caller passed a fingerprint.
finalizeMediaMsgInfo(upload, defaultPic?) -> Uint8Array
Encodes the outgoing commonElem MsgInfo. `defaultPic` is the
image-only fallback: image fills bizType + textSummary when the
server omits the pic ext-biz-info; ptt / video pass undefined.
hexToBytes(hex), makeClientRandomId(): shared helpers used by every
uploader's fingerprint payload + client-randomId generation.
MediaSubFileUpload models per-sub-file routing:
- source: 'top' -> upload.uKey + upload.ipv4s (main file)
- source: N -> upload.subFileInfos[N].uKey + .ipv4s (video thumb)
- cmdId, bytes, md5, sha1, subFileIndex, fastOnlyError
Each upload file shrinks to its format-specific logic only:
image-upload.ts: 237 -> 163 (-31%)
format detection, picFormat mapping, pic/reserveTroop/reserveC2c
extBizInfo, group/c2c command id choice, finalize with defaultPic.
ptt-upload.ts: 300 -> 205 (-32%)
silk transcoding, temp-file cleanup, NapCat-style bytesGeneralFlags
(different per group/c2c), voiceFormat honouring.
video-upload.ts: 584 -> 507 (-13%)
Sha1StreamState (per-1MB streaming SHA1 for the main Highway PUT),
ffmpeg-driven thumb extraction with FALLBACK_THUMB, the two-sub-file
OIDB body (main mp4 + thumb jpg with subFileType 100), and the
fastOnlyError asymmetry (main file has it; thumb always has bytes).
Video stays the largest because its load step is genuinely the most
work — the share-out gain here is in concentration, not line count.
Behavior preserved end-to-end. Same NTV2 OIDB cmd numbers (image
0x11C4/5, ptt 0x126E/D, video 0x11EA/9), same service-cmd strings,
same requestId (image=1, ptt=group:1/c2c:4, video=3), same
compatQmsgSceneType (image+ptt: isGroup?2:1; video: 2), same
NapCat-derived bytesGeneralFlags, same fastUpload fallback strings.
Adds 42 happy-path tests across 4 new files in tests/highway/ :
pipeline.test.ts 22 envelope construction, response decode,
OIDB error paths, group vs c2c scene,
Highway PUT trigger + fast-path skip,
sub-file routing, session caching,
fastOnlyError fire / silent-skip,
finalize with/without defaultPic, helpers.
image-upload.test.ts 7 group/c2c oidbCmd + cmdId mapping,
fingerprint payload shape, picFormat /
dimensions wiring, subType -> bizType.
ptt-upload.test.ts 6 group requestId=1 / c2c requestId=4,
per-scene bytesGeneralFlags, voiceFormat
default and override, fingerprint
preconditions, finalize-without-pic.
video-upload.test.ts 7 two-sub-file shape, thumb subFileInfos[0]
routing, fastOnlyError asymmetry,
uploadInfo[mp4+jpg] with subFileType 0+100,
FALLBACK_THUMB always has bytes.
Tests mock highway-client for transport and the pipeline module (for
per-uploader tests) so each suite hits exactly the contract it's
testing. Pipeline tests roundtrip a real OIDB envelope through
protobuf encode/decode to exercise the actual decode path.
285 tests pass (was 244). Same pre-existing macOS-arm64 websocket
addon failure, unrelated.
206 lines
6.8 KiB
TypeScript
206 lines
6.8 KiB
TypeScript
// Voice (PTT) upload: stage the audio bytes (convert to NT silk if
|
|
// necessary), 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 owns the silk transcoding, the temp-file
|
|
// cleanup hooks, and the PTT-specific OIDB fields.
|
|
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import crypto from 'crypto';
|
|
|
|
import type { Bridge } from '../bridge';
|
|
import type { MessageElement } from '../events';
|
|
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
|
|
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
|
|
import { createLogger } from '../../utils/logger';
|
|
import {
|
|
finalizeMediaMsgInfo,
|
|
hexToBytes,
|
|
runNtv2Upload,
|
|
type MediaSubFileUpload,
|
|
} from './pipeline';
|
|
|
|
const log = createLogger('Ptt');
|
|
|
|
export const PRIVATE_PTT_CMD_ID = 1007;
|
|
export const GROUP_PTT_CMD_ID = 1008;
|
|
|
|
interface PttPayload {
|
|
/** Silk bytes uploaded to Highway. Empty when forwarding from cached fingerprints. */
|
|
bytes: Uint8Array;
|
|
md5: Uint8Array;
|
|
sha1: Uint8Array;
|
|
md5Hex: string;
|
|
sha1Hex: string;
|
|
fileName: string;
|
|
fileSize: number;
|
|
/** Whole seconds, >= 1. */
|
|
duration: number;
|
|
voiceFormat: number;
|
|
/** True when bytes is empty; pipeline throws fastOnlyError if the
|
|
* server demands the bytes anyway. */
|
|
fastOnly: boolean;
|
|
/** Cleanup hooks for any temp silk files staged during loadPtt. */
|
|
cleanups: Array<() => void>;
|
|
}
|
|
|
|
function pttPayloadFromFingerprint(element: MessageElement): PttPayload {
|
|
return {
|
|
bytes: new Uint8Array(0),
|
|
md5: hexToBytes(element.md5Hex ?? ''),
|
|
sha1: hexToBytes(element.sha1Hex ?? ''),
|
|
md5Hex: element.md5Hex ?? '',
|
|
sha1Hex: element.sha1Hex ?? '',
|
|
fileName: element.fileName || `${element.md5Hex ?? 'record'}.amr`,
|
|
fileSize: element.fileSize ?? 0,
|
|
duration: element.duration ?? 1,
|
|
// Voice format: 1 = silk (NTV2 standard). Honour any fingerprint that
|
|
// declares a different format; legacy NTQQ paths all use 1.
|
|
voiceFormat: element.voiceFormat || 1,
|
|
fastOnly: true,
|
|
cleanups: [],
|
|
};
|
|
}
|
|
|
|
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
|
|
if (element.noByteFallback) {
|
|
if (!element.md5Hex || !element.sha1Hex) {
|
|
throw new Error('record fast-upload requires md5Hex + sha1Hex');
|
|
}
|
|
return pttPayloadFromFingerprint(element);
|
|
}
|
|
|
|
const source = element.url || element.fileId || '';
|
|
if (!source) throw new Error('record source is empty');
|
|
|
|
const cleanups: Array<() => void> = [];
|
|
// Run all queued cleanups; called both on the success path (via the
|
|
// returned `cleanups` array) and on the failure path (try/catch below).
|
|
const runCleanups = () => {
|
|
while (cleanups.length > 0) {
|
|
const fn = cleanups.pop();
|
|
if (!fn) continue;
|
|
try { fn(); } catch { /* best-effort */ }
|
|
}
|
|
};
|
|
|
|
fs.mkdirSync(tempDir, { recursive: true });
|
|
|
|
try {
|
|
// Resolve the on-disk path the addon should read. Anything that isn't
|
|
// already a local file (base64, HTTP) gets staged into the temp dir.
|
|
let inputPath: string;
|
|
const local = resolveLocalFilePath(source);
|
|
if (local && fs.existsSync(local)) {
|
|
inputPath = local;
|
|
} else {
|
|
const loaded = await loadBinarySource(source, 'record');
|
|
inputPath = path.join(tempDir, `snowluma-ptt-in-${crypto.randomUUID()}`);
|
|
fs.writeFileSync(inputPath, Buffer.from(loaded.bytes));
|
|
cleanups.push(() => { try { fs.unlinkSync(inputPath); } catch { /* ignore */ } });
|
|
}
|
|
|
|
const silk = await encodeSilk(inputPath, tempDir);
|
|
if (silk.converted) {
|
|
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
|
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
|
}
|
|
|
|
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
|
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
|
|
|
|
const hashes = computeHashes(silkBytes);
|
|
return {
|
|
bytes: silkBytes,
|
|
md5: hashes.md5,
|
|
sha1: hashes.sha1,
|
|
md5Hex: hashes.md5Hex,
|
|
sha1Hex: hashes.sha1Hex,
|
|
fileName: `${hashes.md5Hex}.amr`,
|
|
fileSize: silkBytes.length,
|
|
duration: silk.duration,
|
|
voiceFormat: 1,
|
|
fastOnly: false,
|
|
cleanups: [...cleanups],
|
|
};
|
|
} catch (err) {
|
|
runCleanups();
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
|
|
* a `commonElem { serviceType: 48, businessType: 22 }`.
|
|
*/
|
|
export async function uploadPttMsgInfo(
|
|
bridge: Bridge,
|
|
isGroup: boolean,
|
|
targetIdOrUid: string | number,
|
|
element: MessageElement,
|
|
): Promise<Uint8Array> {
|
|
const tempDir = defaultPttTempDir();
|
|
const ptt = await loadPtt(element, tempDir);
|
|
try {
|
|
const uploads: MediaSubFileUpload[] = [{
|
|
source: 'top',
|
|
cmdId: isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID,
|
|
bytes: ptt.bytes,
|
|
md5: ptt.md5,
|
|
sha1: ptt.sha1,
|
|
fastOnlyError: 'record fast-upload not available (server requires bytes)',
|
|
}];
|
|
|
|
const upload = await runNtv2Upload({
|
|
bridge,
|
|
isGroup,
|
|
targetIdOrUid,
|
|
oidbCmd: isGroup ? 0x126E : 0x126D,
|
|
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100',
|
|
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
|
|
requestId: isGroup ? 1 : 4,
|
|
businessType: 3,
|
|
uploadInfo: [{
|
|
fileInfo: {
|
|
fileSize: ptt.fileSize,
|
|
fileHash: ptt.md5Hex,
|
|
fileSha1: ptt.sha1Hex,
|
|
fileName: ptt.fileName,
|
|
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: ptt.voiceFormat },
|
|
width: 0,
|
|
height: 0,
|
|
time: ptt.duration,
|
|
original: 0,
|
|
},
|
|
subFileType: 0,
|
|
}],
|
|
compatQmsgSceneType: isGroup ? 2 : 1,
|
|
extBizInfo: {
|
|
// NapCat fills in a placeholder textSummary so the legacy compat
|
|
// QMsg path still has something to render. Mirror it.
|
|
pic: { textSummary: 'Nya~' },
|
|
video: { bytesPbReserve: new Uint8Array(0) },
|
|
ptt: {
|
|
bytesReserve: new Uint8Array([0x08, 0x00, 0x38, 0x00]),
|
|
bytesPbReserve: new Uint8Array(0),
|
|
// `bytesGeneralFlags` differs between group / c2c voice. Lifted
|
|
// verbatim from NapCat (UploadGroupPtt.ts / UploadPrivatePtt.ts).
|
|
bytesGeneralFlags: isGroup
|
|
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
|
|
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
|
|
},
|
|
},
|
|
uploads,
|
|
label: 'ptt',
|
|
});
|
|
|
|
return finalizeMediaMsgInfo(upload);
|
|
} finally {
|
|
for (const fn of ptt.cleanups) {
|
|
try { fn(); } catch { /* best-effort cleanup */ }
|
|
}
|
|
}
|
|
}
|