Migrate project to pnpm monorepo
Restructure the repository into a pnpm workspace under packages/ (core, webui, runtime). Move source files for core and webui into packages/*, add package manifests for @snowluma/core and @snowluma/runtime, and remove the old launcher package.json. Update root package.json to be a monorepo controller (scripts delegate to pnpm filters, set packageManager and Node engine). Configure build outputs to emit into the repo-root dist/ (vite config changes) so the existing release pipeline continues to work. Add .npmrc with mirrors, expand .gitignore for monorepo layout, add tsconfig base and package-level tsconfigs, and add vitest config for the core package. Adjust injector native search paths and update tests import paths to the new package layout. Small CI/workflow comment added to clarify build behavior and README updated with monorepo structure and common commands.
This commit is contained in:
1 parent
6bba36bba6
commit
39f1672b29
122 files changed
+279
-85
No files matched your search
@@ -0,0 +1,216 @@
|
||||
// Highway HTTP client: session fetch and chunked binary upload.
|
||||
// Port of src/bridge/src/highway_client.cpp
|
||||
|
||||
import net from 'net';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { protoEncode, protoDecode } from '../../protobuf/decode';
|
||||
import {
|
||||
HttpConn0x6FF501RequestSchema,
|
||||
HttpConn0x6FF501ResponseSchema,
|
||||
ReqDataHighwayHeadSchema,
|
||||
RespDataHighwayHeadSchema,
|
||||
NTV2RichMediaHighwayExtSchema,
|
||||
HighwayMsgInfoBodySchema,
|
||||
} from '../proto/highway';
|
||||
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
|
||||
|
||||
const HIGHWAY_APP_ID = 1600001604;
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
export const PRIVATE_IMAGE_CMD_ID = 1003;
|
||||
export const GROUP_IMAGE_CMD_ID = 1004;
|
||||
|
||||
export interface HighwaySession {
|
||||
sigSession: Uint8Array;
|
||||
sessionKey: Uint8Array;
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
function ipv4ToString(value: number): string {
|
||||
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
|
||||
}
|
||||
|
||||
export async function fetchHighwaySession(bridge: Bridge): Promise<HighwaySession> {
|
||||
const request = protoEncode({
|
||||
httpConn: {
|
||||
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
|
||||
serviceTypes: [1, 5, 10, 21],
|
||||
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
|
||||
},
|
||||
}, HttpConn0x6FF501RequestSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'HttpConn request failed');
|
||||
}
|
||||
|
||||
const resp = protoDecode(result.responseData, HttpConn0x6FF501ResponseSchema);
|
||||
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
|
||||
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
|
||||
throw new Error('HttpConn response missing sig_session');
|
||||
}
|
||||
|
||||
const session: HighwaySession = {
|
||||
sigSession: resp.httpConn.sigSession as Uint8Array,
|
||||
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
|
||||
host: 'htdata3.qq.com',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
for (const si of resp.httpConn.serverInfos ?? []) {
|
||||
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
|
||||
for (const addr of si.serverAddrs) {
|
||||
const ip = addr.ip ?? 0;
|
||||
const port = addr.port ?? 0;
|
||||
if (ip && port) {
|
||||
session.host = ipv4ToString(ip);
|
||||
session.port = port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
|
||||
return session;
|
||||
}
|
||||
|
||||
function makeHighwayHead(
|
||||
uin: string, commandId: number, fileSize: number, offset: number, length: number,
|
||||
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
|
||||
): Uint8Array {
|
||||
return protoEncode({
|
||||
msgBaseHead: {
|
||||
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
|
||||
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
|
||||
},
|
||||
msgSegHead: {
|
||||
serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length,
|
||||
retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0,
|
||||
},
|
||||
bytesReqExtendInfo: extend,
|
||||
timestamp: 0n,
|
||||
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
|
||||
}, ReqDataHighwayHeadSchema);
|
||||
}
|
||||
|
||||
export function buildHighwayExtend(
|
||||
uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array,
|
||||
): Uint8Array {
|
||||
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
|
||||
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
|
||||
|
||||
const first = msgInfoBody[0];
|
||||
const networkIpv4s: any[] = [];
|
||||
for (const ipv4 of ipv4s ?? []) {
|
||||
const ip = ipv4.outIp ?? 0;
|
||||
const port = ipv4.outPort ?? 0;
|
||||
if (ip && port) {
|
||||
networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port });
|
||||
}
|
||||
}
|
||||
|
||||
return protoEncode({
|
||||
fileUuid: first?.index?.fileUuid ?? '',
|
||||
uKey,
|
||||
network: { ipv4s: networkIpv4s },
|
||||
msgInfoBody: msgInfoBody.map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
})),
|
||||
blockSize: HIGHWAY_BLOCK_SIZE,
|
||||
hash: { fileSha1: [sha1] },
|
||||
}, NTV2RichMediaHighwayExtSchema);
|
||||
}
|
||||
|
||||
// --- TCP-based HTTP highway upload ---
|
||||
|
||||
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection({ host, port }, () => resolve(socket));
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
|
||||
socket.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.write(data, (err) => err ? reject(err) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let headerEnd = -1;
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
|
||||
const checkComplete = () => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd < 0) {
|
||||
const idx = buf.indexOf('\r\n\r\n');
|
||||
if (idx >= 0) {
|
||||
headerEnd = idx + 4;
|
||||
const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase();
|
||||
const clMatch = headerStr.match(/content-length:\s*(\d+)/);
|
||||
contentLength = clMatch ? parseInt(clMatch[1], 10) : 0;
|
||||
totalNeeded = headerEnd + contentLength;
|
||||
}
|
||||
}
|
||||
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||
socket.removeAllListeners('data');
|
||||
socket.removeAllListeners('error');
|
||||
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
|
||||
}
|
||||
};
|
||||
|
||||
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
|
||||
socket.on('error', reject);
|
||||
socket.on('close', () => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function httpPostFrame(
|
||||
socket: net.Socket, host: string, path: string, body: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||
if (body.length > 0) await socketWrite(socket, body);
|
||||
return readHttpResponseBody(socket);
|
||||
}
|
||||
|
||||
export async function uploadHighwayHttp(
|
||||
bridge: Bridge, session: HighwaySession, commandId: number,
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protoDecode(respHead, RespDataHighwayHeadSchema);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`highway upload error_code=${resp.errorCode}`);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
}
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// Image upload pipeline: load image, OIDB upload request, highway upload, build message element.
|
||||
// Port of src/bridge/src/highway_upload_req.cpp + highway_client.cpp (image parts)
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { protoEncode, protoDecode } from '../../protobuf/decode';
|
||||
import { makeOidbBaseSchema } from '../proto/oidb';
|
||||
import {
|
||||
NTV2UploadRichMediaReqSchema,
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
EncodableMediaMsgInfoSchema,
|
||||
} from '../proto/highway';
|
||||
import {
|
||||
loadBinarySource, computeHashes, detectImageFormat,
|
||||
} from './utils';
|
||||
import {
|
||||
fetchHighwaySession, uploadHighwayHttp, buildHighwayExtend,
|
||||
PRIVATE_IMAGE_CMD_ID, GROUP_IMAGE_CMD_ID,
|
||||
} from './highway-client';
|
||||
|
||||
interface ImageData {
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
summary: string;
|
||||
subType: number;
|
||||
width: number;
|
||||
height: number;
|
||||
picFormat: number;
|
||||
}
|
||||
|
||||
function loadImage(element: MessageElement): Promise<ImageData> {
|
||||
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,
|
||||
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
|
||||
subType,
|
||||
width: fmt.width,
|
||||
height: fmt.height,
|
||||
picFormat: fmt.format,
|
||||
};
|
||||
}
|
||||
|
||||
async function startImageUpload(bridge: Bridge, isGroup: boolean, targetIdOrUid: string | number, image: ImageData): Promise<any> {
|
||||
const body: any = {
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: 1,
|
||||
sceneType: isGroup ? 2 : 1,
|
||||
...(isGroup
|
||||
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: image.bytes.length,
|
||||
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,
|
||||
}],
|
||||
tryFastUploadCompleted: true,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: BigInt(Math.floor(Math.random() * 0x7FFFFFFFFFFFFFFF)),
|
||||
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),
|
||||
},
|
||||
},
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
};
|
||||
|
||||
const oidbCmd = isGroup ? 0x11C4 : 0x11C5;
|
||||
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100';
|
||||
|
||||
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
|
||||
const request = protoEncode({
|
||||
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
|
||||
}, baseSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket(serviceCmd, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'image upload request failed');
|
||||
}
|
||||
|
||||
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
|
||||
const resp: any = protoDecode(result.responseData, respBaseSchema);
|
||||
if (!resp) throw new Error('failed to decode upload response');
|
||||
if (resp.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const uploadBody = resp.body;
|
||||
if (!uploadBody) throw new Error('upload response body missing');
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
throw new Error(uploadBody.respHead.message ?? 'image upload failed');
|
||||
}
|
||||
return uploadBody.upload;
|
||||
}
|
||||
|
||||
function finalizeImageMsgInfo(upload: any, image: ImageData): Uint8Array {
|
||||
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
|
||||
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
}));
|
||||
|
||||
const extBizInfo: any = {};
|
||||
if (upload.msgInfo.extBizInfo?.pic) {
|
||||
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
|
||||
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? image.subType;
|
||||
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? image.summary;
|
||||
} else {
|
||||
extBizInfo.pic = { bizType: image.subType, textSummary: image.summary };
|
||||
}
|
||||
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
|
||||
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
|
||||
if (upload.msgInfo.extBizInfo?.busiType !== undefined) extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
|
||||
|
||||
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an image and return the encoded MsgInfo bytes to embed in a CommonElem.
|
||||
*/
|
||||
export async function uploadImageMsgInfo(
|
||||
bridge: Bridge,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const image = await loadImage(element);
|
||||
const upload = await startImageUpload(bridge, isGroup, targetIdOrUid, image);
|
||||
|
||||
// Upload binary if uKey is present (not fast-uploaded)
|
||||
const uKey = upload?.uKey ?? '';
|
||||
if (uKey && upload?.msgInfo) {
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], image.sha1);
|
||||
const commandId = isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID;
|
||||
await uploadHighwayHttp(bridge, session, commandId, image.bytes, image.md5, extend);
|
||||
}
|
||||
|
||||
return finalizeImageMsgInfo(upload, image);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// Highway utilities: binary source loading, hashing, image format detection, frame packing.
|
||||
// Port of src/bridge/src/highway_utils.h/.cpp
|
||||
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
}
|
||||
|
||||
export interface ImageFormat {
|
||||
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// --- Binary source loading ---
|
||||
|
||||
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (source.startsWith('base64://')) {
|
||||
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
|
||||
}
|
||||
|
||||
if (source.startsWith('http://') || source.startsWith('https://')) {
|
||||
const resp = await fetch(source);
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
// File path (strip file:// prefix)
|
||||
let filePath = source;
|
||||
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
|
||||
// Windows: strip leading / before drive letter
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
function guessFileNameFromUrl(url: string): string {
|
||||
const queryPos = url.search(/[?#]/);
|
||||
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
|
||||
}
|
||||
|
||||
// --- Hashing ---
|
||||
|
||||
export function computeHashes(data: Uint8Array): ImageHashes {
|
||||
const md5 = createHash('md5').update(data).digest();
|
||||
const sha1 = createHash('sha1').update(data).digest();
|
||||
return {
|
||||
md5: new Uint8Array(md5),
|
||||
sha1: new Uint8Array(sha1),
|
||||
md5Hex: md5.toString('hex'),
|
||||
sha1Hex: sha1.toString('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
export function computeMd5(data: Uint8Array): Uint8Array {
|
||||
return new Uint8Array(createHash('md5').update(data).digest());
|
||||
}
|
||||
|
||||
// --- Image format detection (port of C++ detect_image_format) ---
|
||||
|
||||
function readBE16(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 8) | data[offset + 1];
|
||||
}
|
||||
|
||||
function readBE32(data: Uint8Array, offset: number): number {
|
||||
return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
|
||||
}
|
||||
|
||||
function readLE16(data: Uint8Array, offset: number): number {
|
||||
return data[offset] | (data[offset + 1] << 8);
|
||||
}
|
||||
|
||||
function readLE32(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
|
||||
}
|
||||
|
||||
function readBE24(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
|
||||
}
|
||||
|
||||
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
|
||||
// PNG
|
||||
if (bytes.length >= 24 &&
|
||||
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||
width = readBE32(bytes, 16);
|
||||
height = readBE32(bytes, 20);
|
||||
return { format: 1001, width, height };
|
||||
}
|
||||
|
||||
// GIF
|
||||
if (bytes.length >= 10 &&
|
||||
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
|
||||
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
|
||||
width = readLE16(bytes, 6);
|
||||
height = readLE16(bytes, 8);
|
||||
return { format: 2000, width, height };
|
||||
}
|
||||
|
||||
// BMP
|
||||
if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) {
|
||||
width = readLE32(bytes, 18);
|
||||
height = readLE32(bytes, 22);
|
||||
return { format: 1005, width, height };
|
||||
}
|
||||
|
||||
// WebP
|
||||
if (bytes.length >= 30 &&
|
||||
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
|
||||
width = readLE16(bytes, 26);
|
||||
height = readLE16(bytes, 28);
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) {
|
||||
const bits = readLE32(bytes, 21);
|
||||
width = (bits & 0x3FFF) + 1;
|
||||
height = ((bits >> 14) & 0x3FFF) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) {
|
||||
width = readBE24(bytes, 24) + 1;
|
||||
height = readBE24(bytes, 27) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
}
|
||||
|
||||
// JPEG
|
||||
if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) {
|
||||
let offset = 2;
|
||||
while (offset + 9 <= bytes.length) {
|
||||
if (bytes[offset] !== 0xFF) { offset++; continue; }
|
||||
const marker = bytes[offset + 1];
|
||||
if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; }
|
||||
if (offset + 4 > bytes.length) break;
|
||||
const segLen = readBE16(bytes, offset + 2);
|
||||
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
|
||||
if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) {
|
||||
height = readBE16(bytes, offset + 5);
|
||||
width = readBE16(bytes, offset + 7);
|
||||
return { format: 1000, width, height };
|
||||
}
|
||||
offset += 2 + segLen;
|
||||
}
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
// --- Highway frame packing/unpacking ---
|
||||
|
||||
export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array {
|
||||
const frame = new Uint8Array(9 + head.length + body.length + 1);
|
||||
frame[0] = 0x28;
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
dv.setUint32(1, head.length, false);
|
||||
dv.setUint32(5, body.length, false);
|
||||
frame.set(head, 9);
|
||||
frame.set(body, 9 + head.length);
|
||||
frame[frame.length - 1] = 0x29;
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } {
|
||||
if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) {
|
||||
throw new Error('invalid highway response frame');
|
||||
}
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
const headLen = dv.getUint32(1, false);
|
||||
const bodyLen = dv.getUint32(5, false);
|
||||
return {
|
||||
head: frame.subarray(9, 9 + headLen),
|
||||
body: frame.subarray(9 + headLen, 9 + headLen + bodyLen),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user