This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+484 -366
View File
@@ -1,11 +1,11 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
CollectionItem as CollectionItemWire,
CollectionRequestBody,
CollectionRequestHead,
CollectionResponseBody,
CollectionResponseHead,
GetCollectionListRequest,
CollectionItem as CollectionItemWire,
CollectionRequestBody,
CollectionRequestHead,
CollectionResponseBody,
CollectionResponseHead,
GetCollectionListRequest,
} from '@snowluma/proto-defs/collection';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
@@ -20,429 +20,547 @@ const COLLECTION_MAX_PAGES = 100;
const COLLECTION_TIMEOUT_MS = 10_000;
const COLLECTION_OPERATION_TIMEOUT_MS = 60_000;
const COLLECTION_RESPONSE_LIMIT = 16 * 1024 * 1024;
const INITIAL_TIMESTAMP = 0xFFFF_FFFF_FFFF_FFFFn;
const INITIAL_TIMESTAMP = 0xffff_ffff_ffff_ffffn;
const MAGIC = Uint8Array.from([0x20, 0x13, 0x03, 0x29]);
const VERSION = Uint8Array.from([0x00, 0x01]);
export interface CollectionHttpRequest {
readonly url: string;
readonly headers: Readonly<Record<string, string>>;
readonly body: Uint8Array;
readonly timeoutMs: number;
readonly url: string;
readonly headers: Readonly<Record<string, string>>;
readonly body: Uint8Array;
readonly timeoutMs: number;
}
export type CollectionTransport = (request: CollectionHttpRequest) => Promise<Uint8Array>;
export interface GetCollectionListParams {
readonly uin: string;
readonly pskey: string;
readonly category?: number;
readonly count?: number;
readonly transport?: CollectionTransport;
readonly uin: string;
readonly pskey: string;
readonly category?: number;
readonly count?: number;
readonly transport?: CollectionTransport;
}
export interface CollectionAuthor extends JsonObject {
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
}
export interface CollectionSummary extends JsonObject {
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
}
export interface CollectionItem extends JsonObject {
cid: string;
type: number;
status: number;
author: CollectionAuthor;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummary;
cid: string;
type: number;
status: number;
author: CollectionAuthor;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummary;
}
export interface CollectionSearchList extends JsonObject {
collectionItemList: CollectionItem[];
hasMore: boolean;
bottomTimeStamp: string;
collectionItemList: CollectionItem[];
hasMore: boolean;
bottomTimeStamp: string;
}
export interface CollectionListResult extends JsonObject {
errCode: 0;
errMsg: string;
collectionSearchList: CollectionSearchList;
errCode: 0;
errMsg: string;
collectionSearchList: CollectionSearchList;
}
function positiveUin(value: string): bigint {
if (!/^[1-9]\d*$/.test(value)) throw new Error('collection uin must be a positive integer');
const uin = BigInt(value);
if (uin > INITIAL_TIMESTAMP) throw new Error('collection uin exceeds uint64 range');
return uin;
if (!/^[1-9]\d*$/.test(value)) {
throw new Error('collection uin must be a positive integer');
}
const uin = BigInt(value);
if (uin > INITIAL_TIMESTAMP) {
throw new Error('collection uin exceeds uint64 range');
}
return uin;
}
function positiveCount(value: number): number {
if (!Number.isSafeInteger(value) || value < 1 || value > COLLECTION_MAX_COUNT) {
throw new Error(`collection count must be between 1 and ${COLLECTION_MAX_COUNT}`);
}
return value;
if (!Number.isSafeInteger(value) || value < 1 || value > COLLECTION_MAX_COUNT) {
throw new Error(`collection count must be between 1 and ${COLLECTION_MAX_COUNT}`);
}
return value;
}
function validCategory(value: number): number {
if (!Number.isSafeInteger(value) || value < 0) {
throw new Error('collection category must be a non-negative safe integer');
}
return value;
if (!Number.isSafeInteger(value) || value < 0) {
throw new Error('collection category must be a non-negative safe integer');
}
return value;
}
function encodeEnvelope(head: Uint8Array, body: Uint8Array): Uint8Array {
const totalLength = 16 + head.length + body.length;
const output = Buffer.allocUnsafe(totalLength);
output.set(MAGIC, 0);
output.set(VERSION, 4);
output.writeUInt32BE(totalLength, 6);
output.writeUInt32BE(body.length, 10);
output.writeUInt16BE(0, 14);
output.set(head, 16);
output.set(body, 16 + head.length);
return output;
const totalLength = 16 + head.length + body.length;
const output = Buffer.allocUnsafe(totalLength);
output.set(MAGIC, 0);
output.set(VERSION, 4);
output.writeUInt32BE(totalLength, 6);
output.writeUInt32BE(body.length, 10);
output.writeUInt16BE(0, 14);
output.set(head, 16);
output.set(body, 16 + head.length);
return output;
}
function decodeEnvelope(bytes: Uint8Array): {
head: CollectionResponseHead;
body: CollectionResponseBody;
head: CollectionResponseHead;
body: CollectionResponseBody;
} {
const input = Buffer.from(bytes);
if (input.length <= 16) throw new Error('collection response is too short');
if (!input.subarray(0, 4).equals(Buffer.from(MAGIC))) {
throw new Error('collection response has invalid magic');
}
if (!input.subarray(4, 6).equals(Buffer.from(VERSION))) {
throw new Error('collection response has unsupported version');
}
const totalLength = input.readUInt32BE(6);
if (totalLength !== input.length) {
throw new Error(`collection response length mismatch: ${totalLength} != ${input.length}`);
}
const bodyLength = input.readUInt32BE(10);
if (input.readUInt16BE(14) !== 0) throw new Error('collection response has invalid reserved bytes');
if (bodyLength === 0 || bodyLength >= totalLength - 16) {
throw new Error('collection response has invalid body length');
}
const bodyOffset = totalLength - bodyLength;
return {
head: protobuf_decode<CollectionResponseHead>(input.subarray(16, bodyOffset)),
body: protobuf_decode<CollectionResponseBody>(input.subarray(bodyOffset)),
};
const input = Buffer.from(bytes);
if (input.length <= 16) {
throw new Error('collection response is too short');
}
if (!input.subarray(0, 4).equals(Buffer.from(MAGIC))) {
throw new Error('collection response has invalid magic');
}
if (!input.subarray(4, 6).equals(Buffer.from(VERSION))) {
throw new Error('collection response has unsupported version');
}
const totalLength = input.readUInt32BE(6);
if (totalLength !== input.length) {
throw new Error(`collection response length mismatch: ${totalLength} != ${input.length}`);
}
const bodyLength = input.readUInt32BE(10);
if (input.readUInt16BE(14) !== 0) {
throw new Error('collection response has invalid reserved bytes');
}
if (bodyLength === 0 || bodyLength >= totalLength - 16) {
throw new Error('collection response has invalid body length');
}
const bodyOffset = totalLength - bodyLength;
return {
head: protobuf_decode<CollectionResponseHead>(input.subarray(16, bodyOffset)),
body: protobuf_decode<CollectionResponseBody>(input.subarray(bodyOffset)),
};
}
function jsonSafe(value: unknown): JsonValue {
if (value === null || value === undefined) return null;
if (typeof value === 'bigint') return value.toString();
if (typeof value === 'number') {
if (!Number.isFinite(value)) throw new Error('collection response contains a non-finite number');
return value;
}
if (typeof value === 'string' || typeof value === 'boolean') return value;
if (value instanceof Uint8Array) return Buffer.from(value).toString('base64');
if (Array.isArray(value)) return value.map(jsonSafe);
if (typeof value === 'object') {
const output: JsonObject = {};
for (const [key, field] of Object.entries(value)) output[key] = jsonSafe(field);
return output;
}
throw new Error(`collection response contains unsupported value type: ${typeof value}`);
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'bigint') {
return value.toString();
}
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
throw new Error('collection response contains a non-finite number');
}
return value;
}
if (typeof value === 'string' || typeof value === 'boolean') {
return value;
}
if (value instanceof Uint8Array) {
return Buffer.from(value).toString('base64');
}
if (Array.isArray(value)) {
return value.map(jsonSafe);
}
if (typeof value === 'object') {
const output: JsonObject = {};
for (const [key, field] of Object.entries(value)) {
output[key] = jsonSafe(field);
}
return output;
}
throw new Error(`collection response contains unsupported value type: ${typeof value}`);
}
function mapItem(item: CollectionItemWire): CollectionItem {
const author = item.author ?? {};
const summary = item.summary ?? {};
const textSummary = summary.textSummary;
const richMediaSummary = summary.richMediaSummary;
return {
cid: item.cid ?? '',
type: item.type ?? 0,
status: item.status ?? 0,
author: {
type: author.type ?? 0,
numId: (author.numId ?? 0n).toString(),
strId: author.strId ?? '',
groupId: (author.groupId ?? 0n).toString(),
groupName: author.groupName ?? '',
uid: author.uid ?? '',
},
bid: item.bid ?? 0,
category: item.category ?? 0,
createTime: (item.createTime ?? 0n).toString(),
collectTime: (item.collectTime ?? 0n).toString(),
modifyTime: (item.modifyTime ?? 0n).toString(),
sequence: (item.sequence ?? 0n).toString(),
shareUrl: item.shareUrl ?? '',
customGroupId: item.customGroupId ?? 0,
securityBeat: item.securityBeat ?? false,
summary: {
textSummary: textSummary ? {
text: textSummary.text ?? '',
truncated: textSummary.truncated ?? false,
} : null,
linkSummary: jsonSafe(summary.linkSummary),
gallerySummary: jsonSafe(summary.gallerySummary),
audioSummary: jsonSafe(summary.audioSummary),
videoSummary: jsonSafe(summary.videoSummary),
fileSummary: jsonSafe(summary.fileSummary),
locationSummary: jsonSafe(summary.locationSummary),
richMediaSummary: richMediaSummary ? {
title: richMediaSummary.title ?? '',
subTitle: richMediaSummary.subTitle ?? '',
brief: richMediaSummary.brief ?? '',
picList: jsonSafe(richMediaSummary.picList ?? []),
contentType: richMediaSummary.contentType ?? 0,
originalUri: richMediaSummary.originalUri ?? '',
publisher: richMediaSummary.publisher ?? '',
richMediaVersion: richMediaSummary.richMediaVersion ?? 0,
} : null,
},
};
const author = item.author ?? {};
const summary = item.summary ?? {};
const textSummary = summary.textSummary;
const richMediaSummary = summary.richMediaSummary;
return {
cid: item.cid ?? '',
type: item.type ?? 0,
status: item.status ?? 0,
author: {
type: author.type ?? 0,
numId: (author.numId ?? 0n).toString(),
strId: author.strId ?? '',
groupId: (author.groupId ?? 0n).toString(),
groupName: author.groupName ?? '',
uid: author.uid ?? '',
},
bid: item.bid ?? 0,
category: item.category ?? 0,
createTime: (item.createTime ?? 0n).toString(),
collectTime: (item.collectTime ?? 0n).toString(),
modifyTime: (item.modifyTime ?? 0n).toString(),
sequence: (item.sequence ?? 0n).toString(),
shareUrl: item.shareUrl ?? '',
customGroupId: item.customGroupId ?? 0,
securityBeat: item.securityBeat ?? false,
summary: {
textSummary: textSummary
? {
text: textSummary.text ?? '',
truncated: textSummary.truncated ?? false,
}
: null,
linkSummary: jsonSafe(summary.linkSummary),
gallerySummary: jsonSafe(summary.gallerySummary),
audioSummary: jsonSafe(summary.audioSummary),
videoSummary: jsonSafe(summary.videoSummary),
fileSummary: jsonSafe(summary.fileSummary),
locationSummary: jsonSafe(summary.locationSummary),
richMediaSummary: richMediaSummary
? {
title: richMediaSummary.title ?? '',
subTitle: richMediaSummary.subTitle ?? '',
brief: richMediaSummary.brief ?? '',
picList: jsonSafe(richMediaSummary.picList ?? []),
contentType: richMediaSummary.contentType ?? 0,
originalUri: richMediaSummary.originalUri ?? '',
publisher: richMediaSummary.publisher ?? '',
richMediaVersion: richMediaSummary.richMediaVersion ?? 0,
}
: null,
},
};
}
function validateItem(item: CollectionItemWire): void {
if (!item.cid) throw new Error('collection item is missing cid');
if (!item.author) throw new Error(`collection item ${item.cid} is missing author`);
if (item.modifyTime === null || item.modifyTime === undefined || item.modifyTime <= 0n) {
throw new Error(`collection item ${item.cid} is missing modifyTime`);
}
if (!item.cid) {
throw new Error('collection item is missing cid');
}
if (!item.author) {
throw new Error(`collection item ${item.cid} is missing author`);
}
if (item.modifyTime === null || item.modifyTime === undefined || item.modifyTime <= 0n) {
throw new Error(`collection item ${item.cid} is missing modifyTime`);
}
}
async function failAfterCleanup(
primaryError: Error,
cleanup?: () => Promise<void>,
primaryError: Error,
cleanup?: () => Promise<void>,
): Promise<never> {
if (cleanup) {
try {
await cleanup();
} catch (cleanupError) {
throw new AggregateError(
[primaryError, cleanupError],
`${primaryError.message}; response body cleanup also failed`,
);
if (cleanup) {
try {
await cleanup();
} catch (cleanupError) {
throw new AggregateError(
[primaryError, cleanupError],
`${primaryError.message}; response body cleanup also failed`,
);
}
}
}
throw primaryError;
throw primaryError;
}
async function defaultTransport(request: CollectionHttpRequest): Promise<Uint8Array> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), request.timeoutMs);
try {
const response = await fetch(request.url, {
method: 'POST',
headers: request.headers,
body: Buffer.from(request.body),
signal: controller.signal,
});
if (!response.ok) {
const error = new Error(`collection HTTP request failed: ${response.status} ${response.statusText}`);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), request.timeoutMs);
const declaredLength = response.headers.get('content-length');
if (declaredLength !== null) {
if (!/^\d+$/.test(declaredLength)) {
const error = new Error('collection response has invalid content-length');
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
if (Number(declaredLength) > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
}
if (!response.body) throw new Error('collection HTTP response has no body');
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
total += value.length;
if (total > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`);
await failAfterCleanup(error, () => reader.cancel(error));
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const response = await fetch(request.url, {
method: 'POST',
headers: request.headers,
body: Buffer.from(request.body),
signal: controller.signal,
});
const output = Buffer.allocUnsafe(total);
let offset = 0;
for (const chunk of chunks) {
output.set(chunk, offset);
offset += chunk.length;
if (!response.ok) {
const error = new Error(
`collection HTTP request failed: ${response.status} ${response.statusText}`,
);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
const declaredLength = response.headers.get('content-length');
if (declaredLength !== null) {
if (!/^\d+$/.test(declaredLength)) {
const error = new Error('collection response has invalid content-length');
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
if (Number(declaredLength) > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(
`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`,
);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
}
if (!response.body) {
throw new Error('collection HTTP response has no body');
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
total += value.length;
if (total > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(
`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`,
);
await failAfterCleanup(error, () => reader.cancel(error));
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const output = Buffer.allocUnsafe(total);
let offset = 0;
for (const chunk of chunks) {
output.set(chunk, offset);
offset += chunk.length;
}
return output;
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`collection HTTP request timed out after ${request.timeoutMs}ms`, {
cause: error,
});
}
throw error;
} finally {
clearTimeout(timeout);
}
return output;
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`collection HTTP request timed out after ${request.timeoutMs}ms`, { cause: error });
}
throw error;
} finally {
clearTimeout(timeout);
}
}
function requestBytes(uin: bigint, pskey: string, sequence: number, timeStamp: bigint): Uint8Array {
const head = protobuf_encode<CollectionRequestHead>({
uin,
sequence,
commandType: 1,
operationId: COLLECTION_OPERATION_ID,
clientVersion: 0x6105F5E164Fn,
platform: 4,
ticketType: COLLECTION_TICKET_TYPE,
reserved: 0,
ticket: pskey,
field14: 8,
field15: 9,
});
const request: GetCollectionListRequest = {
field1: 0,
field2: 0,
field3: 0,
timeStamp,
orderType: 2,
groupId: 0n,
count: COLLECTION_PAGE_SIZE,
searchDown: 1,
field9: 0,
};
const body = protobuf_encode<CollectionRequestBody>({
operation: { getCollectionList: request },
});
return encodeEnvelope(head, body);
}
export async function getCollectionList(params: GetCollectionListParams): Promise<CollectionListResult> {
const uin = positiveUin(params.uin);
if (params.pskey === '') throw new Error('collection p_skey is empty');
const category = validCategory(params.category ?? 0);
const count = positiveCount(params.count ?? COLLECTION_PAGE_SIZE);
const targetMatchCount = category === 0 ? count : count + 1;
const transport = params.transport ?? defaultTransport;
const headers = {
'Content-Type': 'application/octet-stream',
Cookie: `uin=${params.uin};vt=${COLLECTION_TICKET_TYPE};vi=${params.pskey};appid=${COLLECTION_APP_ID}`,
Host: COLLECTION_HOST,
Range: 'bytes=0-',
} as const;
const matched: CollectionItem[] = [];
const seen = new Set<string>();
let sequence = 1;
let timeStamp = INITIAL_TIMESTAMP;
let serverHasMore = true;
let errMsg = '';
let pages = 0;
const operationDeadline = Date.now() + COLLECTION_OPERATION_TIMEOUT_MS;
while (matched.length < targetMatchCount && serverHasMore) {
if (pages >= COLLECTION_MAX_PAGES) {
throw new Error(`collection pagination exceeded ${COLLECTION_MAX_PAGES} pages`);
}
const remainingMs = operationDeadline - Date.now();
if (remainingMs <= 0) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
pages += 1;
const responseBytes = await transport({
url: COLLECTION_ENDPOINT,
headers,
body: requestBytes(uin, params.pskey, sequence, timeStamp),
timeoutMs: Math.min(COLLECTION_TIMEOUT_MS, remainingMs),
const head = protobuf_encode<CollectionRequestHead>({
uin,
sequence,
commandType: 1,
operationId: COLLECTION_OPERATION_ID,
clientVersion: 0x6105f5e164fn,
platform: 4,
ticketType: COLLECTION_TICKET_TYPE,
reserved: 0,
ticket: pskey,
field14: 8,
field15: 9,
});
if (Date.now() >= operationDeadline) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
const response = decodeEnvelope(responseBytes);
const retCode = response.head.retCode ?? 0;
if (retCode !== 0) {
const message = response.head.retMsg || response.head.promptMsg || 'unknown error';
throw new Error(`collection service error ${retCode}: ${message}`);
}
errMsg = response.head.retMsg ?? '';
const page = response.body.operation?.getCollectionList;
if (!page) throw new Error('collection response is missing operation 20000');
const wireItems = page.items ?? [];
serverHasMore = (page.reachedBottom ?? 0) === 0;
let nextTimeStamp: bigint | null = null;
for (const wireItem of wireItems) {
validateItem(wireItem);
const modifyTime = wireItem.modifyTime ?? 0n;
if (nextTimeStamp === null || modifyTime < nextTimeStamp) nextTimeStamp = modifyTime;
const item = mapItem(wireItem);
const identity = `cid:${item.cid}`;
if (seen.has(identity)) continue;
seen.add(identity);
if (category === 0 || item.category === category) matched.push(item);
}
if (matched.length >= targetMatchCount || !serverHasMore) break;
if (wireItems.length === 0 || nextTimeStamp === null || nextTimeStamp === 0n) {
throw new Error('collection pagination made no progress while more data was reported');
}
if (nextTimeStamp >= timeStamp) {
throw new Error(`collection pagination cursor did not decrease: ${nextTimeStamp}`);
}
timeStamp = nextTimeStamp;
sequence += 1;
}
const collectionItemList = matched.slice(0, count);
let publicBottomTimeStamp = 0n;
for (const item of collectionItemList) {
const itemTime = BigInt(item.modifyTime);
if (publicBottomTimeStamp === 0n || itemTime < publicBottomTimeStamp) {
publicBottomTimeStamp = itemTime;
}
}
return {
errCode: 0,
errMsg,
collectionSearchList: {
collectionItemList,
hasMore: category === 0 ? serverHasMore || matched.length > count : matched.length > count,
bottomTimeStamp: publicBottomTimeStamp.toString(),
},
};
const request: GetCollectionListRequest = {
field1: 0,
field2: 0,
field3: 0,
timeStamp,
orderType: 2,
groupId: 0n,
count: COLLECTION_PAGE_SIZE,
searchDown: 1,
field9: 0,
};
const body = protobuf_encode<CollectionRequestBody>({
operation: { getCollectionList: request },
});
return encodeEnvelope(head, body);
}
export async function getCollectionList(
params: GetCollectionListParams,
): Promise<CollectionListResult> {
const uin = positiveUin(params.uin);
if (params.pskey === '') {
throw new Error('collection p_skey is empty');
}
const category = validCategory(params.category ?? 0);
const count = positiveCount(params.count ?? COLLECTION_PAGE_SIZE);
const targetMatchCount = category === 0 ? count : count + 1;
const transport = params.transport ?? defaultTransport;
const headers = {
'Content-Type': 'application/octet-stream',
Cookie: `uin=${params.uin};vt=${COLLECTION_TICKET_TYPE};vi=${params.pskey};appid=${COLLECTION_APP_ID}`,
Host: COLLECTION_HOST,
Range: 'bytes=0-',
} as const;
const matched: CollectionItem[] = [];
const seen = new Set<string>();
let sequence = 1;
let timeStamp = INITIAL_TIMESTAMP;
let serverHasMore = true;
let errMsg = '';
let pages = 0;
const operationDeadline = Date.now() + COLLECTION_OPERATION_TIMEOUT_MS;
while (matched.length < targetMatchCount && serverHasMore) {
if (pages >= COLLECTION_MAX_PAGES) {
throw new Error(`collection pagination exceeded ${COLLECTION_MAX_PAGES} pages`);
}
const remainingMs = operationDeadline - Date.now();
if (remainingMs <= 0) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
pages += 1;
const responseBytes = await transport({
url: COLLECTION_ENDPOINT,
headers,
body: requestBytes(uin, params.pskey, sequence, timeStamp),
timeoutMs: Math.min(COLLECTION_TIMEOUT_MS, remainingMs),
});
if (Date.now() >= operationDeadline) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
const response = decodeEnvelope(responseBytes);
const retCode = response.head.retCode ?? 0;
if (retCode !== 0) {
const message = response.head.retMsg || response.head.promptMsg || 'unknown error';
throw new Error(`collection service error ${retCode}: ${message}`);
}
errMsg = response.head.retMsg ?? '';
const page = response.body.operation?.getCollectionList;
if (!page) {
throw new Error('collection response is missing operation 20000');
}
const wireItems = page.items ?? [];
serverHasMore = (page.reachedBottom ?? 0) === 0;
let nextTimeStamp: bigint | null = null;
for (const wireItem of wireItems) {
validateItem(wireItem);
const modifyTime = wireItem.modifyTime ?? 0n;
if (nextTimeStamp === null || modifyTime < nextTimeStamp) {
nextTimeStamp = modifyTime;
}
const item = mapItem(wireItem);
const identity = `cid:${item.cid}`;
if (seen.has(identity)) {
continue;
}
seen.add(identity);
if (category === 0 || item.category === category) {
matched.push(item);
}
}
if (matched.length >= targetMatchCount || !serverHasMore) {
break;
}
if (wireItems.length === 0 || nextTimeStamp === null || nextTimeStamp === 0n) {
throw new Error('collection pagination made no progress while more data was reported');
}
if (nextTimeStamp >= timeStamp) {
throw new Error(`collection pagination cursor did not decrease: ${nextTimeStamp}`);
}
timeStamp = nextTimeStamp;
sequence += 1;
}
const collectionItemList = matched.slice(0, count);
let publicBottomTimeStamp = 0n;
for (const item of collectionItemList) {
const itemTime = BigInt(item.modifyTime);
if (publicBottomTimeStamp === 0n || itemTime < publicBottomTimeStamp) {
publicBottomTimeStamp = itemTime;
}
}
return {
errCode: 0,
errMsg,
collectionSearchList: {
collectionItemList,
hasMore:
category === 0 ? serverHasMore || matched.length > count : matched.length > count,
bottomTimeStamp: publicBottomTimeStamp.toString(),
},
};
}
+255 -199
View File
@@ -1,65 +1,65 @@
import { RequestUtil, cookieToString } from './request-util';
export interface WebFriendDressItem {
[key: string]: import('@snowluma/common/json').JsonValue;
/** 装扮业务 id(QQ 会员 appId,决定类别)。 */
app_id: number;
/** 人类可读类别(按 appId 映射,未知则为 appId=<n>)。 */
kind: string;
/** 装扮 id(默认款为 0)。 */
item_id: number;
name: string;
/** 静态预览图 url。 */
preview_url: string;
/** 动态预览视频 url(名片/来电才有,否则空串)。 */
video_url: string;
/** 商城价(非默认款才有,否则 0)。 */
price: number;
[key: string]: import('@snowluma/common/json').JsonValue;
/** 装扮业务 id(QQ 会员 appId,决定类别)。 */
app_id: number;
/** 人类可读类别(按 appId 映射,未知则为 appId=<n>)。 */
kind: string;
/** 装扮 id(默认款为 0)。 */
item_id: number;
name: string;
/** 静态预览图 url。 */
preview_url: string;
/** 动态预览视频 url(名片/来电才有,否则空串)。 */
video_url: string;
/** 商城价(非默认款才有,否则 0)。 */
price: number;
}
export interface WebFriendDress {
[key: string]: import('@snowluma/common/json').JsonValue;
target_uin: string;
is_svip: boolean;
/** 对方头像图 url(装扮页附带,非"头像装扮")。 */
avatar_url: string;
/** 对方正在用的装扮(已剔除服务器不回真值的气泡/字体/头像)。 */
items: WebFriendDressItem[];
[key: string]: import('@snowluma/common/json').JsonValue;
target_uin: string;
is_svip: boolean;
/** 对方头像图 url(装扮页附带,非"头像装扮")。 */
avatar_url: string;
/** 对方正在用的装扮(已剔除服务器不回真值的气泡/字体/头像)。 */
items: WebFriendDressItem[];
}
/** 装扮查询失败的具体环节 —— 调用方据此给出可区分的错误提示。 */
export type FriendDressErrorKind =
/** HTTP 请求本身失败(网络/非 2xx)。 */
| 'network'
/** HTML 里抠不到 __INITIAL_ASYNCDATA__(未登录态/风控/页面改版)。 */
| 'parse'
/** 抠到了 JSON 但结构不符合预期(页面改版)。 */
| 'structure'
/** 页面返回的 targetUin 与请求的不一致(串号数据,不可信)。 */
| 'uin_mismatch';
/** HTTP 请求本身失败(网络/非 2xx)。 */
| 'network'
/** HTML 里抠不到 __INITIAL_ASYNCDATA__(未登录态/风控/页面改版)。 */
| 'parse'
/** 抠到了 JSON 但结构不符合预期(页面改版)。 */
| 'structure'
/** 页面返回的 targetUin 与请求的不一致(串号数据,不可信)。 */
| 'uin_mismatch';
export class FriendDressError extends Error {
constructor(
readonly kind: FriendDressErrorKind,
message: string,
options?: ErrorOptions,
) {
super(message, options);
this.name = 'FriendDressError';
}
constructor(
readonly kind: FriendDressErrorKind,
message: string,
options?: ErrorOptions,
) {
super(message, options);
this.name = 'FriendDressError';
}
}
/** appId → 装扮类别(取自装扮页 business-name / tab 文案)。 */
const APP_KIND: Record<number, string> = {
2: '气泡',
4: '挂件',
5: '字体',
15: '名片',
17: '来电',
22: '彩色屏保',
23: '头像',
47: '头像双击动作',
352: '输入状态',
2: '气泡',
4: '挂件',
5: '字体',
15: '名片',
17: '来电',
22: '彩色屏保',
23: '头像',
47: '头像双击动作',
352: '输入状态',
};
/**
@@ -73,126 +73,158 @@ const UNRESOLVABLE_APPS = new Set([2, 5, 23]);
* 与 targetUin 无关,固定值;已是编码后的串,拼接时不可再被二次编码。
*/
const TRACE_DETAIL =
'base64-eyJhcHBpZCI6InRvYWlvIiwicGFnZV9pZCI6IjM3IiwiaXRlbV9pZCI6IiIsIml0ZW1fdHlwZSI6%0AIiJ9%0A';
'base64-eyJhcHBpZCI6InRvYWlvIiwicGFnZV9pZCI6IjM3IiwiaXRlbV9pZCI6IiIsIml0ZW1fdHlwZSI6%0AIiJ9%0A';
/** aio webview 的移动端 UA(照 HAR;桌面 UA 可能返回不同壳)。 */
const DRESS_UA =
'Mozilla/5.0 (Linux; Android 13; 2109119BC Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/121.0.6167.71 MQQBrowser/6.2 TBS/047925 Mobile Safari/537.36 V1_AND_SQ_9.2.66_13188_YYB_D QQ/9.2.66.33870 NetType/WIFI WebP/0.3.0 AppId/537339358';
'Mozilla/5.0 (Linux; Android 13; 2109119BC Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/121.0.6167.71 MQQBrowser/6.2 TBS/047925 Mobile Safari/537.36 V1_AND_SQ_9.2.66_13188_YYB_D QQ/9.2.66.33870 NetType/WIFI WebP/0.3.0 AppId/537339358';
const DRESS_RESPONSE_LIMITS = {
timeoutMs: 10_000,
maxResponseBytes: 2 * 1024 * 1024,
timeoutMs: 10_000,
maxResponseBytes: 2 * 1024 * 1024,
} as const;
interface RawDressItem {
appId: number;
itemId?: number;
name?: string;
image?: string;
extrainfo?: { price?: number };
extraappinfo?: { extraInfo?: { immersiveMaterial?: string } };
appId: number;
itemId?: number;
name?: string;
image?: string;
extrainfo?: { price?: number };
extraappinfo?: { extraInfo?: { immersiveMaterial?: string } };
}
interface RawAsyncData {
targetUin?: string;
isSvip?: boolean;
avatarImage?: string;
rawUsingList?: RawDressItem[];
targetUin?: string;
isSvip?: boolean;
avatarImage?: string;
rawUsingList?: RawDressItem[];
}
/** 按 targetUin 拼装扮页 URL(结构照 HAR)。 */
function buildDressUrl(targetUin: string): string {
const inner =
`https://zb.vip.qq.com/v2/pages/aioDressPage?fromPage=1&targetUin=${targetUin}` +
`&widgetId=0&fontEffectId=0&bgId=custom&chatId=${targetUin}` +
`&isGroup=0&traceDetail=${TRACE_DETAIL}`;
const params = new URLSearchParams({
fromPage: '1',
enteranceId: 'aio',
url: inner,
fontEffectId: '0',
chatId: targetUin,
widgetId: '0',
targetUin,
isGroup: '0',
bgId: 'custom',
});
// traceDetail 已是编码后的 base64-... 串,单独拼避免被二次编码。
return `https://zb.vip.qq.com/v2/pages/aioDressPage?${params.toString()}&traceDetail=${TRACE_DETAIL}`;
const inner =
`https://zb.vip.qq.com/v2/pages/aioDressPage?fromPage=1&targetUin=${targetUin}` +
`&widgetId=0&fontEffectId=0&bgId=custom&chatId=${targetUin}` +
`&isGroup=0&traceDetail=${TRACE_DETAIL}`;
const params = new URLSearchParams({
fromPage: '1',
enteranceId: 'aio',
url: inner,
fontEffectId: '0',
chatId: targetUin,
widgetId: '0',
targetUin,
isGroup: '0',
bgId: 'custom',
});
// traceDetail 已是编码后的 base64-... 串,单独拼避免被二次编码。
return `https://zb.vip.qq.com/v2/pages/aioDressPage?${params.toString()}&traceDetail=${TRACE_DETAIL}`;
}
/** 从 SSR HTML 抠出 window.__INITIAL_ASYNCDATA__ 的 JSON(抠不到/坏 JSON 抛 parse)。 */
function parseAsyncData(html: string): unknown {
const m = html.match(/window\.__INITIAL_ASYNCDATA__\s*=\s*(\{[\s\S]*?\});\(function/);
if (!m?.[1]) {
throw new FriendDressError('parse', '装扮页中未找到 __INITIAL_ASYNCDATA__(未登录态/风控/页面改版)');
}
try {
return JSON.parse(m[1]) as unknown;
} catch (e) {
throw new FriendDressError('parse', '__INITIAL_ASYNCDATA__ 不是合法 JSON', { cause: e });
}
const m = html.match(/window\.__INITIAL_ASYNCDATA__\s*=\s*(\{[\s\S]*?\});\(function/);
if (!m?.[1]) {
throw new FriendDressError(
'parse',
'装扮页中未找到 __INITIAL_ASYNCDATA__(未登录态/风控/页面改版)',
);
}
try {
return JSON.parse(m[1]) as unknown;
} catch (e) {
throw new FriendDressError('parse', '__INITIAL_ASYNCDATA__ 不是合法 JSON', { cause: e });
}
}
/** 运行时结构校验:不符合预期的一律抛 structure,绝不带着畸形数据继续。 */
function validateAsyncData(
data: unknown,
data: unknown,
): RawAsyncData & { targetUin: string; rawUsingList: RawDressItem[] } {
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
throw new FriendDressError('structure', '__INITIAL_ASYNCDATA__ 顶层不是对象');
}
const d = data as Record<string, unknown>;
if (typeof d['targetUin'] !== 'string' || d['targetUin'].length === 0) {
throw new FriendDressError('structure', 'targetUin 缺失或不是非空字符串');
}
if (d['isSvip'] !== undefined && typeof d['isSvip'] !== 'boolean') {
throw new FriendDressError('structure', 'isSvip 不是布尔值');
}
if (d['avatarImage'] !== undefined && typeof d['avatarImage'] !== 'string') {
throw new FriendDressError('structure', 'avatarImage 不是字符串');
}
if (!Array.isArray(d['rawUsingList'])) {
throw new FriendDressError('structure', 'rawUsingList 缺失或不是数组');
}
d['rawUsingList'].forEach((item: unknown, i: number) => {
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
throw new FriendDressError('structure', `rawUsingList[${i}] 不是对象`);
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
throw new FriendDressError('structure', '__INITIAL_ASYNCDATA__ 顶层不是对象');
}
const r = item as Record<string, unknown>;
if (typeof r['appId'] !== 'number') {
throw new FriendDressError('structure', `rawUsingList[${i}].appId 缺失或不是数字`);
const d = data as Record<string, unknown>;
if (typeof d['targetUin'] !== 'string' || d['targetUin'].length === 0) {
throw new FriendDressError('structure', 'targetUin 缺失或不是非空字符串');
}
if (r['itemId'] !== undefined && typeof r['itemId'] !== 'number') {
throw new FriendDressError('structure', `rawUsingList[${i}].itemId 不是数字`);
if (d['isSvip'] !== undefined && typeof d['isSvip'] !== 'boolean') {
throw new FriendDressError('structure', 'isSvip 不是布尔值');
}
if (r['name'] !== undefined && typeof r['name'] !== 'string') {
throw new FriendDressError('structure', `rawUsingList[${i}].name 不是字符串`);
if (d['avatarImage'] !== undefined && typeof d['avatarImage'] !== 'string') {
throw new FriendDressError('structure', 'avatarImage 不是字符串');
}
if (r['image'] !== undefined && typeof r['image'] !== 'string') {
throw new FriendDressError('structure', `rawUsingList[${i}].image 不是字符串`);
if (!Array.isArray(d['rawUsingList'])) {
throw new FriendDressError('structure', 'rawUsingList 缺失或不是数组');
}
if (r['extraappinfo'] !== undefined) {
if (r['extraappinfo'] === null
|| typeof r['extraappinfo'] !== 'object'
|| Array.isArray(r['extraappinfo'])) {
throw new FriendDressError('structure', `rawUsingList[${i}].extraappinfo 不是对象`);
}
const extraInfo = (r['extraappinfo'] as Record<string, unknown>)['extraInfo'];
if (extraInfo !== undefined) {
if (extraInfo === null || typeof extraInfo !== 'object' || Array.isArray(extraInfo)) {
throw new FriendDressError('structure', `rawUsingList[${i}].extraappinfo.extraInfo 不是对象`);
d['rawUsingList'].forEach((item: unknown, i: number) => {
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
throw new FriendDressError('structure', `rawUsingList[${i}] 不是对象`);
}
const immersiveMaterial = (extraInfo as Record<string, unknown>)['immersiveMaterial'];
if (immersiveMaterial !== undefined && typeof immersiveMaterial !== 'string') {
throw new FriendDressError(
'structure',
`rawUsingList[${i}].extraappinfo.extraInfo.immersiveMaterial 不是字符串`,
);
const r = item as Record<string, unknown>;
if (typeof r['appId'] !== 'number') {
throw new FriendDressError('structure', `rawUsingList[${i}].appId 缺失或不是数字`);
}
}
}
});
return data as RawAsyncData & { targetUin: string; rawUsingList: RawDressItem[] };
if (r['itemId'] !== undefined && typeof r['itemId'] !== 'number') {
throw new FriendDressError('structure', `rawUsingList[${i}].itemId 不是数字`);
}
if (r['name'] !== undefined && typeof r['name'] !== 'string') {
throw new FriendDressError('structure', `rawUsingList[${i}].name 不是字符串`);
}
if (r['image'] !== undefined && typeof r['image'] !== 'string') {
throw new FriendDressError('structure', `rawUsingList[${i}].image 不是字符串`);
}
if (r['extraappinfo'] !== undefined) {
if (
r['extraappinfo'] === null ||
typeof r['extraappinfo'] !== 'object' ||
Array.isArray(r['extraappinfo'])
) {
throw new FriendDressError('structure', `rawUsingList[${i}].extraappinfo 不是对象`);
}
const extraInfo = (r['extraappinfo'] as Record<string, unknown>)['extraInfo'];
if (extraInfo !== undefined) {
if (
extraInfo === null ||
typeof extraInfo !== 'object' ||
Array.isArray(extraInfo)
) {
throw new FriendDressError(
'structure',
`rawUsingList[${i}].extraappinfo.extraInfo 不是对象`,
);
}
const immersiveMaterial = (extraInfo as Record<string, unknown>)[
'immersiveMaterial'
];
if (immersiveMaterial !== undefined && typeof immersiveMaterial !== 'string') {
throw new FriendDressError(
'structure',
`rawUsingList[${i}].extraappinfo.extraInfo.immersiveMaterial 不是字符串`,
);
}
}
}
});
return data as RawAsyncData & { targetUin: string; rawUsingList: RawDressItem[] };
}
/**
@@ -202,50 +234,61 @@ function validateAsyncData(
* (funCall/item/{itemId}/media.mp4,已验证可访问);文件名不匹配时不猜测,返回空串。
*/
function resolveVideoUrl(r: RawDressItem): string {
if (r.appId === 15) {
const raw = r.extraappinfo?.extraInfo?.immersiveMaterial;
if (raw === undefined) return '';
let material: unknown;
try {
material = JSON.parse(raw) as unknown;
} catch (error) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial 不是合法 JSON`,
{ cause: error },
);
if (r.appId === 15) {
const raw = r.extraappinfo?.extraInfo?.immersiveMaterial;
if (raw === undefined) {
return '';
}
let material: unknown;
try {
material = JSON.parse(raw) as unknown;
} catch (error) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial 不是合法 JSON`,
{ cause: error },
);
}
if (material === null || typeof material !== 'object' || Array.isArray(material)) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial 不是对象`,
);
}
const videoUrl = (material as Record<string, unknown>)['videoUrl'];
if (typeof videoUrl !== 'string' || videoUrl.length === 0) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial.videoUrl 缺失或不是非空字符串`,
);
}
return videoUrl;
}
if (material === null || typeof material !== 'object' || Array.isArray(material)) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial 不是对象`,
);
if (r.appId === 17 && r.image && /\/(?:web_)?image\.jpg$/.test(r.image)) {
return r.image.replace(/\/(?:web_)?image\.jpg$/, '/media.mp4');
}
const videoUrl = (material as Record<string, unknown>)['videoUrl'];
if (typeof videoUrl !== 'string' || videoUrl.length === 0) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial.videoUrl 缺失或不是非空字符串`,
);
}
return videoUrl;
}
if (r.appId === 17 && r.image && /\/(?:web_)?image\.jpg$/.test(r.image)) {
return r.image.replace(/\/(?:web_)?image\.jpg$/, '/media.mp4');
}
return '';
return '';
}
function toItem(r: RawDressItem): WebFriendDressItem {
return {
app_id: r.appId,
kind: APP_KIND[r.appId] ?? `appId=${r.appId}`,
item_id: r.itemId ?? 0,
name: r.name ?? '',
preview_url: r.image ?? '',
video_url: resolveVideoUrl(r),
price: typeof r.extrainfo?.price === 'number' ? r.extrainfo.price : 0,
};
return {
app_id: r.appId,
kind: APP_KIND[r.appId] ?? `appId=${r.appId}`,
item_id: r.itemId ?? 0,
name: r.name ?? '',
preview_url: r.image ?? '',
video_url: resolveVideoUrl(r),
price: typeof r.extrainfo?.price === 'number' ? r.extrainfo.price : 0,
};
}
/**
@@ -254,32 +297,45 @@ function toItem(r: RawDressItem): WebFriendDressItem {
* 带 kind 区分网络、未登录态/风控、页面改版、串号数据。
*/
export async function getFriendDressWebAPI(
cookieObject: Record<string, string>,
targetUin: string,
cookieObject: Record<string, string>,
targetUin: string,
): Promise<WebFriendDress> {
let html: string;
try {
html = await RequestUtil.HttpGetText(buildDressUrl(targetUin), 'GET', '', {
Cookie: cookieToString(cookieObject),
'User-Agent': DRESS_UA,
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9',
}, DRESS_RESPONSE_LIMITS);
} catch (e) {
throw new FriendDressError('network', `装扮页请求失败: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
}
let html: string;
const data = validateAsyncData(parseAsyncData(html));
if (data.targetUin !== targetUin) {
throw new FriendDressError('uin_mismatch', `装扮页返回账号 ${data.targetUin} 与请求账号 ${targetUin} 不一致`);
}
try {
html = await RequestUtil.HttpGetText(
buildDressUrl(targetUin),
'GET',
'',
{
Cookie: cookieToString(cookieObject),
'User-Agent': DRESS_UA,
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9',
},
DRESS_RESPONSE_LIMITS,
);
} catch (e) {
throw new FriendDressError(
'network',
`装扮页请求失败: ${e instanceof Error ? e.message : String(e)}`,
{ cause: e },
);
}
return {
target_uin: data.targetUin,
is_svip: data.isSvip ?? false,
avatar_url: data.avatarImage ?? '',
items: data.rawUsingList
.filter((r) => !UNRESOLVABLE_APPS.has(r.appId))
.map(toItem),
};
const data = validateAsyncData(parseAsyncData(html));
if (data.targetUin !== targetUin) {
throw new FriendDressError(
'uin_mismatch',
`装扮页返回账号 ${data.targetUin} 与请求账号 ${targetUin} 不一致`,
);
}
return {
target_uin: data.targetUin,
is_svip: data.isSvip ?? false,
avatar_url: data.avatarImage ?? '',
items: data.rawUsingList.filter((r) => !UNRESOLVABLE_APPS.has(r.appId)).map(toItem),
};
}
File diff suppressed because it is too large. Load diff
+119 -107
View File
@@ -5,141 +5,153 @@ const log = createLogger('Bridge.Web');
const MAX_ESSENCE_PAGES = 20;
export interface GroupEssenceContent {
msg_type: number;
text?: string;
face_index?: number;
image_url?: string;
file_name?: string;
file_bus_id?: number | string;
file_id?: string;
file_thumbnail_url?: string;
file_size?: number | string;
share_title?: string;
share_summary?: string;
share_brief?: string;
share_url?: string;
msg_type: number;
text?: string;
face_index?: number;
image_url?: string;
file_name?: string;
file_bus_id?: number | string;
file_id?: string;
file_thumbnail_url?: string;
file_size?: number | string;
share_title?: string;
share_summary?: string;
share_brief?: string;
share_url?: string;
}
export interface GroupEssenceMessage {
group_code: string;
msg_seq: number;
msg_random: number;
sender_uin: string;
sender_nick: string;
sender_time: number;
add_digest_uin: string;
add_digest_nick: string;
add_digest_time: number;
msg_content: GroupEssenceContent[];
can_be_removed: boolean;
group_code: string;
msg_seq: number;
msg_random: number;
sender_uin: string;
sender_nick: string;
sender_time: number;
add_digest_uin: string;
add_digest_nick: string;
add_digest_time: number;
msg_content: GroupEssenceContent[];
can_be_removed: boolean;
}
export interface GroupEssenceMsgRet {
retcode: number;
retmsg?: string;
data: {
is_end: boolean;
msg_list: Array<GroupEssenceMessage | null>;
group_role?: number;
config_page_url?: string;
};
retcode: number;
retmsg?: string;
data: {
is_end: boolean;
msg_list: Array<GroupEssenceMessage | null>;
group_role?: number;
config_page_url?: string;
};
}
interface RawGroupEssenceMsgRet {
retcode: number;
retmsg?: string;
data?: {
is_end?: unknown;
msg_list?: Array<GroupEssenceMessage | null> | null;
group_role?: number;
config_page_url?: string;
} | null;
retcode: number;
retmsg?: string;
data?: {
is_end?: unknown;
msg_list?: Array<GroupEssenceMessage | null> | null;
group_role?: number;
config_page_url?: string;
} | null;
}
/**
* 分页获取群精华消息
*/
export async function getGroupEssenceMsg(
cookieObject: Record<string, string>,
groupCode: string,
pageStart: number = 0,
pageLimit: number = 50
cookieObject: Record<string, string>,
groupCode: string,
pageStart: number = 0,
pageLimit: number = 50,
): Promise<GroupEssenceMsgRet> {
const bkn = getBknFromCookie(cookieObject);
const bkn = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
bkn: bkn,
page_start: pageStart.toString(),
page_limit: pageLimit.toString(),
group_code: groupCode,
}).toString()}`;
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
bkn: bkn,
page_start: pageStart.toString(),
page_limit: pageLimit.toString(),
group_code: groupCode,
}).toString()}`;
try {
const ret = await RequestUtil.HttpGetJson<RawGroupEssenceMsgRet>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
if (ret.retcode !== 0) {
throw new Error(
`group essence request failed with retcode ${ret.retcode}: ${ret.retmsg ?? 'unknown error'}`,
);
try {
const ret = await RequestUtil.HttpGetJson<RawGroupEssenceMsgRet>(url, 'GET', '', {
Cookie: cookieToString(cookieObject),
});
if (ret.retcode !== 0) {
throw new Error(
`group essence request failed with retcode ${ret.retcode}: ${ret.retmsg ?? 'unknown error'}`,
);
}
if (ret.data?.is_end === true && ret.data.msg_list == null) {
log.debug(
'normalized empty group essence response (group=%s page=%d/%d)',
groupCode,
pageStart,
pageLimit,
);
return {
...ret,
data: {
...ret.data,
is_end: true,
msg_list: [],
},
};
}
if (
!ret.data ||
typeof ret.data.is_end !== 'boolean' ||
!Array.isArray(ret.data.msg_list)
) {
throw new Error(
'invalid group essence response: data.is_end or data.msg_list is missing',
);
}
return {
...ret,
data: {
...ret.data,
is_end: ret.data.is_end,
msg_list: ret.data.msg_list,
},
};
} catch (e) {
log.warn(
'getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
groupCode,
pageStart,
pageLimit,
e instanceof Error ? (e.stack ?? e.message) : String(e),
);
throw e;
}
if (ret.data?.is_end === true && ret.data.msg_list == null) {
log.debug(
'normalized empty group essence response (group=%s page=%d/%d)',
groupCode,
pageStart,
pageLimit,
);
return {
...ret,
data: {
...ret.data,
is_end: true,
msg_list: [],
},
};
}
if (!ret.data
|| typeof ret.data.is_end !== 'boolean'
|| !Array.isArray(ret.data.msg_list)) {
throw new Error('invalid group essence response: data.is_end or data.msg_list is missing');
}
return {
...ret,
data: {
...ret.data,
is_end: ret.data.is_end,
msg_list: ret.data.msg_list,
},
};
} catch (e) {
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
throw e;
}
}
/**
* 获取所有群精华消息 (最多循环 20 页)
*/
export async function getGroupEssenceMsgAll(
cookieObject: Record<string, string>,
groupCode: string
cookieObject: Record<string, string>,
groupCode: string,
): Promise<GroupEssenceMsgRet[]> {
const ret: GroupEssenceMsgRet[] = [];
const ret: GroupEssenceMsgRet[] = [];
for (let i = 0; i < MAX_ESSENCE_PAGES; i++) {
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
for (let i = 0; i < MAX_ESSENCE_PAGES; i++) {
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
ret.push(data);
ret.push(data);
if (data.data.is_end) return ret;
}
if (data.data.is_end) {
return ret;
}
}
throw new Error(
`group essence pagination exceeded ${MAX_ESSENCE_PAGES} pages for group ${groupCode}`,
);
throw new Error(
`group essence pagination exceeded ${MAX_ESSENCE_PAGES} pages for group ${groupCode}`,
);
}
+67 -50
View File
@@ -4,70 +4,87 @@ import { RequestUtil, cookieToString } from './request-util';
const log = createLogger('Bridge.Web');
export interface WebHonorItem {
[key: string]: import('@snowluma/common/json').JsonValue;
user_id: number | string | null;
nickname: string;
avatar: string;
description: string;
[key: string]: import('@snowluma/common/json').JsonValue;
user_id: number | string | null;
nickname: string;
avatar: string;
description: string;
}
interface RawHonorItem {
uin?: number | string;
name?: string;
avatar?: string;
desc?: string;
uin?: number | string;
name?: string;
avatar?: string;
desc?: string;
}
interface HonorInitialState {
talkativeList?: RawHonorItem[];
actorList?: RawHonorItem[];
talkativeList?: RawHonorItem[];
actorList?: RawHonorItem[];
}
export enum WebHonorType {
TALKATIVE = 'talkative',
PERFORMER = 'performer',
LEGEND = 'legend',
EMOTION = 'emotion',
ALL = 'all',
TALKATIVE = 'talkative',
PERFORMER = 'performer',
LEGEND = 'legend',
EMOTION = 'emotion',
ALL = 'all',
}
async function fetchHonorData(
cookieObject: Record<string, string>,
groupCode: string,
type: number,
): Promise<RawHonorItem[] | undefined> {
let resJson: HonorInitialState | undefined;
async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number): Promise<RawHonorItem[] | undefined> {
let resJson: HonorInitialState | undefined;
try {
const res = await RequestUtil.HttpGetText(
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
gc: groupCode,
type: type.toString(),
}).toString()}`,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
if (match?.[1]) {
resJson = JSON.parse(match[1].trim()) as HonorInitialState;
try {
const res = await RequestUtil.HttpGetText(
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
gc: groupCode,
type: type.toString(),
}).toString()}`,
'GET',
'',
{ Cookie: cookieToString(cookieObject) },
);
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
if (match?.[1]) {
resJson = JSON.parse(match[1].trim()) as HonorInitialState;
}
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
} catch (e) {
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
}
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
} catch (e) {
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
}
}
export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number): Promise<WebHonorItem[]> {
try {
const data = await fetchHonorData(cookieObject, groupCode, type);
if (!data) return [];
export async function getHonorListWebAPI(
cookieObject: Record<string, string>,
groupCode: string,
type: number,
): Promise<WebHonorItem[]> {
try {
const data = await fetchHonorData(cookieObject, groupCode, type);
return data.map((item) => ({
user_id: item?.uin ?? null,
nickname: item?.name ?? '',
avatar: item?.avatar ?? '',
description: item?.desc ?? '',
}));
} catch (e) {
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
}
if (!data) {
return [];
}
return data.map((item) => ({
user_id: item?.uin ?? null,
nickname: item?.name ?? '',
avatar: item?.avatar ?? '',
description: item?.desc ?? '',
}));
} catch (e) {
log.warn(
'getHonorListWebAPI failed (group=%s type=%d): %s',
groupCode,
type,
e instanceof Error ? (e.stack ?? e.message) : String(e),
);
return [];
}
}
+361 -287
View File
@@ -6,16 +6,16 @@ import { RequestUtil, cookieToString } from './request-util';
const log = createLogger('Bridge.Web');
export interface SetNoticeRetSuccess {
ec?: number;
em?: string;
[key: string]: JsonValue | undefined;
ec?: number;
em?: string;
[key: string]: JsonValue | undefined;
}
export interface UploadImageRetSuccess {
ec?: number;
em?: string;
id?: string;
[key: string]: JsonValue | undefined;
ec?: number;
em?: string;
id?: string;
[key: string]: JsonValue | undefined;
}
export const GROUP_NOTICE_TYPE_NORMAL = 1;
@@ -25,367 +25,441 @@ const GROUP_NOTICE_IMAGE_CDN = 'https://gdynamic.qpic.cn/gdynamic';
/** Public download URL for a group-notice picture id from list_announce. */
export function groupNoticeImageUrl(id: string): string {
const trimmed = id.trim();
if (!trimmed) throw new Error('group notice image id is empty');
if (/[/?#\s]/.test(trimmed)) throw new Error('group notice image id is malformed');
return `${GROUP_NOTICE_IMAGE_CDN}/${encodeURIComponent(trimmed)}/0`;
const trimmed = id.trim();
if (!trimmed) {
throw new Error('group notice image id is empty');
}
if (/[/?#\s]/.test(trimmed)) {
throw new Error('group notice image id is malformed');
}
return `${GROUP_NOTICE_IMAGE_CDN}/${encodeURIComponent(trimmed)}/0`;
}
export interface SetGroupNoticeOptions {
pinned?: number;
/** Raw publish type kept for OneBot compatibility: 1=regular, 20=new members. */
type?: number;
/** Semantic alias for selecting the new-member announcement endpoint. */
sendToNewMembers?: boolean;
isShowEditCard?: number;
/** QQ uses inverted semantics here: 0=show popup, 1=do not show popup. */
tipWindowType?: number;
confirmRequired?: number;
picId?: string;
imgWidth?: number;
imgHeight?: number;
pinned?: number;
/** Raw publish type kept for OneBot compatibility: 1=regular, 20=new members. */
type?: number;
/** Semantic alias for selecting the new-member announcement endpoint. */
sendToNewMembers?: boolean;
isShowEditCard?: number;
/** QQ uses inverted semantics here: 0=show popup, 1=do not show popup. */
tipWindowType?: number;
confirmRequired?: number;
picId?: string;
imgWidth?: number;
imgHeight?: number;
}
export interface ResolvedGroupNoticeOptions {
pinned: 0 | 1;
type: typeof GROUP_NOTICE_TYPE_NORMAL | typeof GROUP_NOTICE_TYPE_NEW_MEMBERS;
sendToNewMembers: boolean;
isShowEditCard: 0 | 1;
tipWindowType: 0 | 1;
confirmRequired: 0 | 1;
picId: string;
imgWidth: number;
imgHeight: number;
pinned: 0 | 1;
type: typeof GROUP_NOTICE_TYPE_NORMAL | typeof GROUP_NOTICE_TYPE_NEW_MEMBERS;
sendToNewMembers: boolean;
isShowEditCard: 0 | 1;
tipWindowType: 0 | 1;
confirmRequired: 0 | 1;
picId: string;
imgWidth: number;
imgHeight: number;
}
export interface WebApiGroupNoticeFeed {
fid: string;
u: number;
pubt: number;
type?: number | string;
pinned?: number | string;
msg: {
text: string;
pics?: Array<{ id: string; w: number | string; h: number | string }>;
};
settings: JsonValue;
read_num: number;
[key: string]: JsonValue | undefined;
fid: string;
u: number;
pubt: number;
type?: number | string;
pinned?: number | string;
msg: {
text: string;
pics?: Array<{ id: string; w: number | string; h: number | string }>;
};
settings: JsonValue;
read_num: number;
[key: string]: JsonValue | undefined;
}
export type WebApiGroupNoticeCollection = WebApiGroupNoticeFeed[] | Record<string, WebApiGroupNoticeFeed>;
export type WebApiGroupNoticeCollection =
WebApiGroupNoticeFeed[] | Record<string, WebApiGroupNoticeFeed>;
export interface WebApiGroupNoticeRet {
ec: number;
em?: string;
feeds?: WebApiGroupNoticeCollection;
/** Announcements shown to members when they newly join the group. */
inst?: WebApiGroupNoticeCollection;
[key: string]: JsonValue | WebApiGroupNoticeCollection | undefined;
ec: number;
em?: string;
feeds?: WebApiGroupNoticeCollection;
/** Announcements shown to members when they newly join the group. */
inst?: WebApiGroupNoticeCollection;
[key: string]: JsonValue | WebApiGroupNoticeCollection | undefined;
}
export function calculateBkn(key: string): string {
let hash = 5381;
for (let i = 0; i < key.length; i++) {
const code = key.charCodeAt(i);
hash = hash + (hash << 5) + code;
}
return (hash & 0x7FFFFFFF).toString();
let hash = 5381;
for (let i = 0; i < key.length; i++) {
const code = key.charCodeAt(i);
hash = hash + (hash << 5) + code;
}
return (hash & 0x7fffffff).toString();
}
function binaryOption(name: string, value: number | undefined, fallback: 0 | 1): 0 | 1 {
const resolved = value ?? fallback;
if (resolved !== 0 && resolved !== 1) {
throw new RangeError(`${name} must be 0 or 1, received ${resolved}`);
}
return resolved;
const resolved = value ?? fallback;
if (resolved !== 0 && resolved !== 1) {
throw new RangeError(`${name} must be 0 or 1, received ${resolved}`);
}
return resolved;
}
/**
* Resolve the public compatibility fields into the exact QQ request mode.
* Kept pure so both runtime callers and tests share one conflict check.
*/
export function resolveGroupNoticeOptions(options: SetGroupNoticeOptions = {}): ResolvedGroupNoticeOptions {
if (options.sendToNewMembers !== undefined && typeof options.sendToNewMembers !== 'boolean') {
throw new TypeError(`sendToNewMembers must be a boolean, received ${typeof options.sendToNewMembers}`);
}
if (
options.type !== undefined &&
options.type !== GROUP_NOTICE_TYPE_NORMAL &&
options.type !== GROUP_NOTICE_TYPE_NEW_MEMBERS
) {
throw new RangeError(
`type must be ${GROUP_NOTICE_TYPE_NORMAL} (regular) or ${GROUP_NOTICE_TYPE_NEW_MEMBERS} (new members), received ${options.type}`,
);
}
export function resolveGroupNoticeOptions(
options: SetGroupNoticeOptions = {},
): ResolvedGroupNoticeOptions {
if (options.sendToNewMembers !== undefined && typeof options.sendToNewMembers !== 'boolean') {
throw new TypeError(
`sendToNewMembers must be a boolean, received ${typeof options.sendToNewMembers}`,
);
}
const semanticType = options.sendToNewMembers === undefined
? undefined
: options.sendToNewMembers
? GROUP_NOTICE_TYPE_NEW_MEMBERS
: GROUP_NOTICE_TYPE_NORMAL;
if (
options.type !== undefined &&
options.type !== GROUP_NOTICE_TYPE_NORMAL &&
options.type !== GROUP_NOTICE_TYPE_NEW_MEMBERS
) {
throw new RangeError(
`type must be ${GROUP_NOTICE_TYPE_NORMAL} (regular) or ${GROUP_NOTICE_TYPE_NEW_MEMBERS} (new members), received ${options.type}`,
);
}
if (options.type !== undefined && semanticType !== undefined && options.type !== semanticType) {
throw new Error(
`sendToNewMembers=${options.sendToNewMembers} conflicts with type=${options.type}`,
);
}
const semanticType =
options.sendToNewMembers === undefined
? undefined
: options.sendToNewMembers
? GROUP_NOTICE_TYPE_NEW_MEMBERS
: GROUP_NOTICE_TYPE_NORMAL;
const type = options.type ?? semanticType ?? GROUP_NOTICE_TYPE_NORMAL;
const imgWidth = options.imgWidth ?? 540;
const imgHeight = options.imgHeight ?? 300;
if (!Number.isFinite(imgWidth) || imgWidth <= 0 || !Number.isFinite(imgHeight) || imgHeight <= 0) {
throw new RangeError(`group notice image dimensions must be positive finite numbers, received ${imgWidth}x${imgHeight}`);
}
if (options.type !== undefined && semanticType !== undefined && options.type !== semanticType) {
throw new Error(
`sendToNewMembers=${options.sendToNewMembers} conflicts with type=${options.type}`,
);
}
return {
pinned: binaryOption('pinned', options.pinned, 0),
type,
sendToNewMembers: type === GROUP_NOTICE_TYPE_NEW_MEMBERS,
// Preserve SnowLuma's established defaults for existing callers.
isShowEditCard: binaryOption('isShowEditCard', options.isShowEditCard, 1),
tipWindowType: binaryOption('tipWindowType', options.tipWindowType, 1),
confirmRequired: binaryOption('confirmRequired', options.confirmRequired, 1),
picId: options.picId ?? '',
imgWidth,
imgHeight,
};
const type = options.type ?? semanticType ?? GROUP_NOTICE_TYPE_NORMAL;
const imgWidth = options.imgWidth ?? 540;
const imgHeight = options.imgHeight ?? 300;
if (
!Number.isFinite(imgWidth) ||
imgWidth <= 0 ||
!Number.isFinite(imgHeight) ||
imgHeight <= 0
) {
throw new RangeError(
`group notice image dimensions must be positive finite numbers, received ${imgWidth}x${imgHeight}`,
);
}
return {
pinned: binaryOption('pinned', options.pinned, 0),
type,
sendToNewMembers: type === GROUP_NOTICE_TYPE_NEW_MEMBERS,
// Preserve SnowLuma's established defaults for existing callers.
isShowEditCard: binaryOption('isShowEditCard', options.isShowEditCard, 1),
tipWindowType: binaryOption('tipWindowType', options.tipWindowType, 1),
confirmRequired: binaryOption('confirmRequired', options.confirmRequired, 1),
picId: options.picId ?? '',
imgWidth,
imgHeight,
};
}
/** Parse QQ's HTML-escaped JSON metadata returned by the image upload CGI. */
export function parseGroupNoticeImageUploadResponse(data: string): { id: string; width: number; height: number } {
let result: UploadImageRetSuccess;
try {
result = JSON.parse(data) as UploadImageRetSuccess;
} catch (cause) {
throw new Error('group notice image upload returned invalid JSON', { cause });
}
export function parseGroupNoticeImageUploadResponse(data: string): {
id: string;
width: number;
height: number;
} {
let result: UploadImageRetSuccess;
if (result.ec !== 0 || !result.id) {
throw new Error(`group notice image upload failed: ec=${result.ec ?? 'missing'} em=${result.em ?? 'missing'}`);
}
try {
result = JSON.parse(data) as UploadImageRetSuccess;
} catch (cause) {
throw new Error('group notice image upload returned invalid JSON', { cause });
}
let idObj: { id?: unknown; w?: unknown; h?: unknown };
try {
idObj = JSON.parse(result.id.replace(/&quot;/g, '"')) as { id?: unknown; w?: unknown; h?: unknown };
} catch (cause) {
throw new Error('group notice image upload returned invalid image metadata JSON', { cause });
}
if (result.ec !== 0 || !result.id) {
throw new Error(
`group notice image upload failed: ec=${result.ec ?? 'missing'} em=${result.em ?? 'missing'}`,
);
}
const width = Number(idObj.w);
const height = Number(idObj.h);
if (
typeof idObj.id !== 'string' ||
idObj.id.length === 0 ||
!Number.isFinite(width) ||
width <= 0 ||
!Number.isFinite(height) ||
height <= 0
) {
throw new Error('group notice image upload returned malformed image metadata');
}
return { id: idObj.id, width, height };
let idObj: { id?: unknown; w?: unknown; h?: unknown };
try {
idObj = JSON.parse(result.id.replace(/&quot;/g, '"')) as {
id?: unknown;
w?: unknown;
h?: unknown;
};
} catch (cause) {
throw new Error('group notice image upload returned invalid image metadata JSON', {
cause,
});
}
const width = Number(idObj.w);
const height = Number(idObj.h);
if (
typeof idObj.id !== 'string' ||
idObj.id.length === 0 ||
!Number.isFinite(width) ||
width <= 0 ||
!Number.isFinite(height) ||
height <= 0
) {
throw new Error('group notice image upload returned malformed image metadata');
}
return { id: idObj.id, width, height };
}
/**
* 发送群公告 Web API
*/
export async function setGroupNoticeWebAPI(
cookieObject: Record<string, string>,
groupCode: string,
content: string,
options: SetGroupNoticeOptions = {},
cookieObject: Record<string, string>,
groupCode: string,
content: string,
options: SetGroupNoticeOptions = {},
): Promise<SetNoticeRetSuccess> {
const resolved = resolveGroupNoticeOptions(options);
const resolved = resolveGroupNoticeOptions(options);
// QQ validates these independently: the body token comes from skey while
// the URL token comes from p_skey (falling back to skey when absent).
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
// QQ validates these independently: the body token comes from skey while
// the URL token comes from p_skey (falling back to skey when absent).
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
const settings = JSON.stringify({
is_show_edit_card: resolved.isShowEditCard,
tip_window_type: resolved.tipWindowType,
confirm_required: resolved.confirmRequired,
});
const settings = JSON.stringify({
is_show_edit_card: resolved.isShowEditCard,
tip_window_type: resolved.tipWindowType,
confirm_required: resolved.confirmRequired,
});
const bodyParams: Record<string, string> = {
qid: groupCode,
bkn: bodyBkn,
text: content,
pinned: resolved.pinned.toString(),
type: resolved.type.toString(),
settings,
};
const bodyParams: Record<string, string> = {
qid: groupCode,
bkn: bodyBkn,
text: content,
pinned: resolved.pinned.toString(),
type: resolved.type.toString(),
settings,
};
if (resolved.picId !== '') {
bodyParams.pic = resolved.picId;
bodyParams.imgWidth = resolved.imgWidth.toString();
bodyParams.imgHeight = resolved.imgHeight.toString();
}
if (resolved.picId !== '') {
bodyParams.pic = resolved.picId;
bodyParams.imgWidth = resolved.imgWidth.toString();
bodyParams.imgHeight = resolved.imgHeight.toString();
}
const endpoint = resolved.sendToNewMembers ? 'add_qun_instruction' : 'add_qun_notice';
const url = `https://web.qun.qq.com/cgi-bin/announce/${endpoint}?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
const endpoint = resolved.sendToNewMembers ? 'add_qun_instruction' : 'add_qun_notice';
const url = `https://web.qun.qq.com/cgi-bin/announce/${endpoint}?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
log.debug(
'group-notice publish: group=%s target=%s pinned=%d edit-card=%d popup=%s confirm=%d image=%s',
groupCode,
resolved.sendToNewMembers ? 'new-members' : 'regular',
resolved.pinned,
resolved.isShowEditCard,
resolved.tipWindowType === 0 ? 'on' : 'off',
resolved.confirmRequired,
resolved.picId ? 'yes' : 'no',
);
log.debug(
'group-notice publish: group=%s target=%s pinned=%d edit-card=%d popup=%s confirm=%d image=%s',
groupCode,
resolved.sendToNewMembers ? 'new-members' : 'regular',
resolved.pinned,
resolved.isShowEditCard,
resolved.tipWindowType === 0 ? 'on' : 'off',
resolved.confirmRequired,
resolved.picId ? 'yes' : 'no',
);
return RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
},
true,
false,
);
return RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
},
true,
false,
);
}
/**
* 获取群公告列表 Web API
*/
export async function getGroupNoticeWebAPI(
cookieObject: Record<string, string>,
groupCode: string,
start: number = -1, // -1 表示第一页
count: number = 20 // 抓包中是 10,你可以根据需要调整
cookieObject: Record<string, string>,
groupCode: string,
start: number = -1, // -1 表示第一页
count: number = 20, // 抓包中是 10,你可以根据需要调整
): Promise<WebApiGroupNoticeRet> {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
const bodyParams = new URLSearchParams({
qid: groupCode,
bkn: bodyBkn,
ft: '23',
s: start.toString(),
n: count.toString(),
i: '1',
ni: '1',
}).toString();
const bodyParams = new URLSearchParams({
qid: groupCode,
bkn: bodyBkn,
ft: '23',
s: start.toString(),
n: count.toString(),
i: '1',
ni: '1',
}).toString();
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
return RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
url,
'POST',
bodyParams,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148',
},
true,
false,
);
return RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
url,
'POST',
bodyParams,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
Referer: 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148',
},
true,
false,
);
}
/**
* 上传群公告图片 Web API
*/
export async function uploadGroupNoticeImage(
cookieObject: Record<string, string>,
imageBuffer: Buffer
cookieObject: Record<string, string>,
imageBuffer: Buffer,
): Promise<{ id: string; width: number; height: number }> {
const bkn = calculateBkn(cookieObject['skey'] || '');
const boundary = `-----------------------------${Date.now()}`;
const bkn = calculateBkn(cookieObject['skey'] || '');
const boundary = `-----------------------------${Date.now()}`;
const parts: Buffer[] = [];
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
parts.push(imageBuffer);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
const parts: Buffer[] = [];
parts.push(
Buffer.from(
`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`,
),
);
parts.push(
Buffer.from(
`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`,
),
);
parts.push(
Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`),
);
parts.push(
Buffer.from(
`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`,
),
);
parts.push(imageBuffer);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
const body = Buffer.concat(parts);
const body = Buffer.concat(parts);
const options = {
hostname: 'web.qun.qq.com',
path: '/cgi-bin/announce/upload_img',
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length,
'Cookie': cookieToString(cookieObject),
},
};
const options = {
hostname: 'web.qun.qq.com',
path: '/cgi-bin/announce/upload_img',
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length,
Cookie: cookieToString(cookieObject),
},
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
reject(new Error(`group notice image upload returned HTTP ${res.statusCode ?? 'unknown'}`));
return;
}
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
reject(
new Error(
`group notice image upload returned HTTP ${res.statusCode ?? 'unknown'}`,
),
);
return;
}
try {
resolve(parseGroupNoticeImageUploadResponse(data));
} catch (error) {
reject(error instanceof Error ? error : new Error(String(error)));
}
});
try {
resolve(parseGroupNoticeImageUploadResponse(data));
} catch (error) {
reject(error instanceof Error ? error : new Error(String(error)));
}
});
});
req.on('error', (error) =>
reject(
new Error(`group notice image upload transport error: ${error.message}`, {
cause: error,
}),
),
);
req.write(body);
req.end();
});
req.on('error', (error) => reject(new Error(`group notice image upload transport error: ${error.message}`, { cause: error })));
req.write(body);
req.end();
});
}
/**
* 删除群公告 Web API
*/
export async function deleteGroupNotice(
cookieObject: Record<string, string>,
groupCode: string,
fid: string
cookieObject: Record<string, string>,
groupCode: string,
fid: string,
): Promise<boolean> {
try {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
try {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
const params = new URLSearchParams({
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
fid: fid,
qid: groupCode,
}).toString();
const params = new URLSearchParams({
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
fid: fid,
qid: groupCode,
}).toString();
// 注意这里:URL 拼接 urlBkn
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
// 注意这里:URL 拼接 urlBkn
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
params,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret?.ec === 0;
} catch (e) {
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
return false;
}
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
params,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
},
true,
false,
);
return ret?.ec === 0;
} catch (e) {
log.warn(
'deleteGroupNotice failed (group=%s fid=%s): %s',
groupCode,
fid,
e instanceof Error ? (e.stack ?? e.message) : String(e),
);
return false;
}
}
+69 -60
View File
@@ -5,29 +5,29 @@ const log = createLogger('Bridge.Web');
// Raw shapes from qun.qq.com `v2/signin/trpc/GetDaySignedList`.
export interface DaySignedInfo {
uid: string;
uidGroupNick: string;
signedTimeStamp: string;
signInRank: number;
uid: string;
uidGroupNick: string;
signedTimeStamp: string;
signInRank: number;
}
export interface DaySignedListResponse {
retCode: number;
costTime?: number;
funcCode: number;
response: {
ret?: { code: string; msg: string };
page?: Array<{ infos?: DaySignedInfo[]; offset: number; total: number }>;
};
retCode: number;
costTime?: number;
funcCode: number;
response: {
ret?: { code: string; msg: string };
page?: Array<{ infos?: DaySignedInfo[]; offset: number; total: number }>;
};
}
/** OneBot-facing signed-in member, matching the napcat surface. */
export interface SignedListMember {
[key: string]: import('@snowluma/common/json').JsonValue;
user_id: number;
nick: string;
time: number;
rank: number;
[key: string]: import('@snowluma/common/json').JsonValue;
user_id: number;
nick: string;
time: number;
rank: number;
}
/**
@@ -39,25 +39,29 @@ export interface SignedListMember {
* is an empty result, not an error.
*/
export function mapDaySignedList(data: DaySignedListResponse): SignedListMember[] {
const infos = data.response?.page?.[0]?.infos;
if (!infos) return [];
return infos.map((info) => ({
user_id: Number(info.uid),
nick: info.uidGroupNick,
time: Number(info.signedTimeStamp),
// signInRank arrives on a doubled/offset scale (1,3,5,…); de-skew to a
// human 1-based rank. Number() guards against the server sending it as
// a string, which trpc endpoints occasionally do.
rank: (Number(info.signInRank) - 1) / 2 + 1,
}));
const infos = data.response?.page?.[0]?.infos;
if (!infos) {
return [];
}
return infos.map((info) => ({
user_id: Number(info.uid),
nick: info.uidGroupNick,
time: Number(info.signedTimeStamp),
// signInRank arrives on a doubled/offset scale (1,3,5,…); de-skew to a
// human 1-based rank. Number() guards against the server sending it as
// a string, which trpc endpoints occasionally do.
rank: (Number(info.signInRank) - 1) / 2 + 1,
}));
}
/** YYYYMMDD for the given Date (defaults to today), the form the endpoint wants. */
function yyyymmdd(d: Date = new Date()): string {
// Local date (not UTC) on purpose: "today's 打卡" is a CN-clock concept,
// so the local calendar day is the right one near the UTC midnight seam.
// (NapCat uses UTC here; this is a deliberate divergence.)
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
// Local date (not UTC) on purpose: "today's 打卡" is a CN-clock concept,
// so the local calendar day is the right one near the UTC midnight seam.
// (NapCat uses UTC here; this is a deliberate divergence.)
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
}
/**
@@ -73,34 +77,39 @@ function yyyymmdd(d: Date = new Date()): string {
* response. Matches NapCat, which throws on a missing page.
*/
export async function getDaySignedListWebAPI(
cookieObject: Record<string, string>,
groupCode: string,
selfUin: string,
day?: Date,
cookieObject: Record<string, string>,
groupCode: string,
selfUin: string,
day?: Date,
): Promise<SignedListMember[]> {
const gtk = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${gtk}`;
const body = {
dayYmd: yyyymmdd(day),
offset: 0,
limit: 100,
uid: selfUin,
groupId: groupCode,
};
const data = await RequestUtil.HttpGetJson<DaySignedListResponse>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/json',
},
true,
true,
);
if (!data.response?.page) {
log.warn('getDaySignedList: no page in response (group=%s) — likely auth/cookie failure', groupCode);
throw new Error('无法获取该群组打卡列表');
}
return mapDaySignedList(data);
const gtk = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${gtk}`;
const body = {
dayYmd: yyyymmdd(day),
offset: 0,
limit: 100,
uid: selfUin,
groupId: groupCode,
};
const data = await RequestUtil.HttpGetJson<DaySignedListResponse>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/json',
},
true,
true,
);
if (!data.response?.page) {
log.warn(
'getDaySignedList: no page in response (group=%s) — likely auth/cookie failure',
groupCode,
);
throw new Error('无法获取该群组打卡列表');
}
return mapDaySignedList(data);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff