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

+18 -18
View File
@@ -1,28 +1,28 @@
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import {
getCollectionList,
type CollectionListResult,
} from '@snowluma/protocol/web/collection';
import { getCollectionList, type CollectionListResult } from '@snowluma/protocol/web/collection';
import type { BridgeContext } from '../bridge-context';
const COLLECTION_DOMAIN = 'weiyun.com';
/** Read-only access to the account's QQ collection list. */
export class CollectionApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) {}
async list(category = 0, count = 50): Promise<CollectionListResult> {
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
domainList: [COLLECTION_DOMAIN],
});
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
async list(category = 0, count = 50): Promise<CollectionListResult> {
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
domainList: [COLLECTION_DOMAIN],
});
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
return getCollectionList({
uin: this.ctx.identity.uin,
pskey,
category,
count,
});
}
if (!pskey) {
throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
}
return getCollectionList({
uin: this.ctx.identity.uin,
pskey,
category,
count,
});
}
}
File diff suppressed because it is too large. Load diff
+372 -281
View File
@@ -1,12 +1,15 @@
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
import {
FetchAiVoiceList,
type AiVoiceCategory as NamespaceAiVoiceCategory,
FetchAiVoiceList,
type AiVoiceCategory as NamespaceAiVoiceCategory,
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import {
GetGroupTodoList,
type GroupTodoListItem as NamespaceGroupTodoListItem,
GetStrangerStatus,
type StrangerStatus as NamespaceStrangerStatus,
} from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import {
GetGroupTodoList,
type GroupTodoListItem as NamespaceGroupTodoListItem,
} from '@snowluma/protocol/oidb-services/extras/get-group-todo-list';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
@@ -22,18 +25,18 @@ import type { MediaIndexNode } from './shared';
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
* the uins + scene from the message meta. */
export interface PttTransInput {
isGroup: boolean;
msgId: number;
senderUin: number;
/** Receiver uin (c2c) or group uin (group). */
peerUin: number;
uuid: string;
md5Hex: string;
duration: number;
size: number;
format: number;
/** Group ptt numeric file id (group only; optional). */
fileId?: number;
isGroup: boolean;
msgId: number;
senderUin: number;
/** Receiver uin (c2c) or group uin (group). */
peerUin: number;
uuid: string;
md5Hex: string;
duration: number;
size: number;
format: number;
/** Group ptt numeric file id (group only; optional). */
fileId?: number;
}
// ─────────────── public types (re-exported from bridge.ts as before) ───
@@ -42,21 +45,21 @@ export type StrangerStatus = NamespaceStrangerStatus;
export type GroupTodoListItem = NamespaceGroupTodoListItem;
export const AiVoiceChatType = {
Unknown: 0,
Sound: 1,
Sing: 2,
Unknown: 0,
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export type AiVoiceChatType = (typeof AiVoiceChatType)[keyof typeof AiVoiceChatType];
export type AiVoiceCategory = NamespaceAiVoiceCategory;
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceSendReceipt {
sequence: number;
sequence: number;
}
const log = createLogger('Bridge.Extras');
@@ -67,280 +70,368 @@ const AI_VOICE_CLAIM_LIMIT = 256;
type GroupMessageEvent = Extract<QQEventVariant, { kind: 'group_message' }>;
function normalizeMediaUuid(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
return typeof value === 'string' ? value.trim() : '';
}
function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean {
const expectedUuid = normalizeMediaUuid(node.fileUuid);
if (!expectedUuid) return false;
for (const element of event.elements) {
if (element.type !== 'record') continue;
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
if (actualUuid === expectedUuid) return true;
}
return false;
const expectedUuid = normalizeMediaUuid(node.fileUuid);
if (!expectedUuid) {
return false;
}
for (const element of event.elements) {
if (element.type !== 'record') {
continue;
}
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
if (actualUuid === expectedUuid) {
return true;
}
}
return false;
}
function describeAiVoiceFingerprint(node: MediaIndexNode): string {
const uuid = normalizeMediaUuid(node.fileUuid);
if (uuid) return `uuid:${uuid.slice(-12)}`;
return 'missing';
const uuid = normalizeMediaUuid(node.fileUuid);
if (uuid) {
return `uuid:${uuid.slice(-12)}`;
}
return 'missing';
}
export class ExtrasApi {
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
// ─────────────── Group todo query / mutations (0x9474 / 0xF90) ───────────────
// ─────────────── Group todo query / mutations (0x9474 / 0xF90) ───────────────
async getGroupTodoList(groupId: number): Promise<GroupTodoListItem[]> {
const items = await GetGroupTodoList.invoke(this.ctx, { groupId });
log.debug('group todo list fetched group=%d count=%d', groupId, items.length);
return items;
}
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
}
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
}
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
/**
* Keeps the action response user-safe while retaining the underlying
* failure in the service log for diagnosis.
*/
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
try {
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
if (!status) log.warn('user status query returned no status target=%d', uin);
return status;
} catch (error) {
log.warn(
'user status query failed target=%d: %s',
uin,
error instanceof Error ? error.message : String(error),
);
return null;
async getGroupTodoList(groupId: number): Promise<GroupTodoListItem[]> {
const items = await GetGroupTodoList.invoke(this.ctx, { groupId });
log.debug('group todo list fetched group=%d count=%d', groupId, items.length);
return items;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
}
/**
* Trigger AI voice synthesis. Server may return an empty msgInfo while
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned node plugs directly into
* `apis.groupFile.getPttUrl`, which already handles every other
* download-URL fetch in SnowLuma. The synthesis response does not contain a
* reliable message sequence; callers that need one must use `sendAiVoice`,
* which correlates the subsequent self-message receipt.
*/
async fetchAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
if (node) {
log.debug(
'AI voice synthesis completed group=%d media=%s polls=%d',
groupId,
describeAiVoiceFingerprint(node),
i + 1,
);
return node as MediaIndexNode;
}
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
/**
* Publish an AI voice and wait for QQ's canonical self-message receipt.
*
* The 0x929B completion response carries the media node but, on live QQ,
* omits the group message sequence. Subscribe before publishing so an echo
* that wins the response race is buffered, then correlate by the exact media
* UUID. Never guess from content hashes or "the next voice in the group":
* concurrent requests can legitimately render byte-identical audio.
*/
async sendAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
): Promise<AiVoiceSendReceipt> {
const candidates: GroupMessageEvent[] = [];
let candidatesOverflowed = false;
let expectedNode: MediaIndexNode | null = null;
let receiptSettled = false;
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
resolveReceipt = resolve;
});
const claim = (event: GroupMessageEvent): boolean => {
if (receiptSettled) return false;
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
this.claimedAiVoiceReceiptKeys.add(key);
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest);
}
receiptSettled = true;
return true;
};
const accept = (event: GroupMessageEvent): void => {
if (event.groupId !== groupId || event.senderUin !== event.selfUin) return;
if (!event.elements.some(element => element.type === 'record')) return;
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
resolveReceipt?.(event);
return;
}
candidates.push(event);
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
candidates.shift();
candidatesOverflowed = true;
}
};
const unsubscribe = this.ctx.events.on('group_message', accept);
let timeout: ReturnType<typeof setTimeout> | null = null;
try {
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
expectedNode = node;
const fingerprint = describeAiVoiceFingerprint(node);
if (fingerprint === 'missing') {
throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation');
}
const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event));
if (!buffered && candidatesOverflowed) {
throw new Error(
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
);
}
const event = buffered ?? await Promise.race([
receiptPromise,
new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => {
reject(new Error(
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms `
+ `(group=${groupId} media=${fingerprint})`,
));
}, receiptTimeoutMs);
timeout.unref?.();
}),
]);
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`);
}
log.debug(
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
groupId,
fingerprint,
event.msgSeq,
event.msgId,
);
return {
sequence: event.msgSeq,
};
} finally {
if (timeout) clearTimeout(timeout);
unsubscribe();
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
}
}
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
/**
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
* return the recognised text IF the response carries it inline (the
* already-transcribed case). For a freshly-received voice the response is an
* empty ack and the text is delivered later via the async Event 0x210
* subType-61 push — callers should treat `''` as "pending" and wait for the
* `ptt_trans_result` event (correlated by msgId).
*/
async translatePttToText(input: PttTransInput): Promise<string> {
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
const md5 = input.md5Hex.toLowerCase();
const req: PttTransReq = input.isGroup
? {
type: 1,
groupItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
format: input.format, uuid: input.uuid,
},
}
: {
type: 2,
c2cItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
},
};
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'ptt translate request failed');
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
}
const resp = protobuf_decode<PttTransResp>(result.responseData);
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
if (item?.errCode) {
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
// sourced from cache, to tell a server-side ASR failure apart from our own
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
log.warn(
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
item.errCode, input.isGroup,
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
);
throw new Error(`ptt translate failed: error=${item.errCode}`);
}
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
}
/**
* Transcode a voice record (`get_record out_format`, #165). `source` is a
* URL / local path / `base64://…` (the record's download URL in practice);
* it is loaded then transcoded to `format` via the bundled SILK-capable
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
* failed conversion.
*/
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
// default so a tampered/oversized source can't be pulled in.
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
return convertAudioBytes(bytes, format);
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
/**
* Keeps the action response user-safe while retaining the underlying
* failure in the service log for diagnosis.
*/
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
try {
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
if (!status) {
log.warn('user status query returned no status target=%d', uin);
}
return status;
} catch (error) {
log.warn(
'user status query failed target=%d: %s',
uin,
error instanceof Error ? error.message : String(error),
);
return null;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
fetchAiVoiceList(
groupId: number,
chatType: AiVoiceChatType | number,
): Promise<AiVoiceCategory[]> {
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
}
/**
* Trigger AI voice synthesis. Server may return an empty msgInfo while
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned node plugs directly into
* `apis.groupFile.getPttUrl`, which already handles every other
* download-URL fetch in SnowLuma. The synthesis response does not contain a
* reliable message sequence; callers that need one must use `sendAiVoice`,
* which correlates the subsequent self-message receipt.
*/
async fetchAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xffffffff) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const node = await FetchAiVoice.invoke(this.ctx, {
groupId,
voiceId,
text,
chatType,
sessionId,
});
if (node) {
log.debug(
'AI voice synthesis completed group=%d media=%s polls=%d',
groupId,
describeAiVoiceFingerprint(node),
i + 1,
);
return node as MediaIndexNode;
}
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
/**
* Publish an AI voice and wait for QQ's canonical self-message receipt.
*
* The 0x929B completion response carries the media node but, on live QQ,
* omits the group message sequence. Subscribe before publishing so an echo
* that wins the response race is buffered, then correlate by the exact media
* UUID. Never guess from content hashes or "the next voice in the group":
* concurrent requests can legitimately render byte-identical audio.
*/
async sendAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
): Promise<AiVoiceSendReceipt> {
const candidates: GroupMessageEvent[] = [];
let candidatesOverflowed = false;
let expectedNode: MediaIndexNode | null = null;
let receiptSettled = false;
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
resolveReceipt = resolve;
});
const claim = (event: GroupMessageEvent): boolean => {
if (receiptSettled) {
return false;
}
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
if (this.claimedAiVoiceReceiptKeys.has(key)) {
return false;
}
this.claimedAiVoiceReceiptKeys.add(key);
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
if (oldest !== undefined) {
this.claimedAiVoiceReceiptKeys.delete(oldest);
}
}
receiptSettled = true;
return true;
};
const accept = (event: GroupMessageEvent): void => {
if (event.groupId !== groupId || event.senderUin !== event.selfUin) {
return;
}
if (!event.elements.some((element) => element.type === 'record')) {
return;
}
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
resolveReceipt?.(event);
return;
}
candidates.push(event);
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
candidates.shift();
candidatesOverflowed = true;
}
};
const unsubscribe = this.ctx.events.on('group_message', accept);
let timeout: ReturnType<typeof setTimeout> | null = null;
try {
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
expectedNode = node;
const fingerprint = describeAiVoiceFingerprint(node);
if (fingerprint === 'missing') {
throw new Error(
'AI voice was published but QQ returned no exact media identifier for receipt correlation',
);
}
const buffered = candidates.find(
(event) => matchesAiVoiceEvent(node, event) && claim(event),
);
if (!buffered && candidatesOverflowed) {
throw new Error(
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} ` +
`unmatched self voice messages (group=${groupId} media=${fingerprint})`,
);
}
const event =
buffered ??
(await Promise.race([
receiptPromise,
new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => {
reject(
new Error(
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms ` +
`(group=${groupId} media=${fingerprint})`,
),
);
}, receiptTimeoutMs);
timeout.unref?.();
}),
]));
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
throw new Error(
`AI voice receipt carried invalid message sequence: ${event.msgSeq}`,
);
}
log.debug(
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
groupId,
fingerprint,
event.msgSeq,
event.msgId,
);
return {
sequence: event.msgSeq,
};
} finally {
if (timeout) {
clearTimeout(timeout);
}
unsubscribe();
}
}
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
/**
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
* return the recognised text IF the response carries it inline (the
* already-transcribed case). For a freshly-received voice the response is an
* empty ack and the text is delivered later via the async Event 0x210
* subType-61 push — callers should treat `''` as "pending" and wait for the
* `ptt_trans_result` event (correlated by msgId).
*/
async translatePttToText(input: PttTransInput): Promise<string> {
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
const md5 = input.md5Hex.toLowerCase();
const req: PttTransReq = input.isGroup
? {
type: 1,
groupItem: {
msgId: BigInt(input.msgId),
senderUin: BigInt(input.senderUin),
groupUin: BigInt(input.peerUin),
fileId: input.fileId ?? 0,
md5,
duration: input.duration,
size: input.size,
format: input.format,
uuid: input.uuid,
},
}
: {
type: 2,
c2cItem: {
msgId: BigInt(input.msgId),
senderUin: BigInt(input.senderUin),
receiverUin: BigInt(input.peerUin),
uuid: input.uuid,
duration: input.duration,
size: input.size,
format: input.format,
md5,
},
};
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'ptt translate request failed');
}
const resp = protobuf_decode<PttTransResp>(result.responseData);
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
if (item?.errCode) {
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
// sourced from cache, to tell a server-side ASR failure apart from our own
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
log.warn(
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
item.errCode,
input.isGroup,
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
input.format,
input.uuid ? 'set' : 'EMPTY',
input.duration,
input.size,
);
throw new Error(`ptt translate failed: error=${item.errCode}`);
}
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
}
/**
* Transcode a voice record (`get_record out_format`, #165). `source` is a
* URL / local path / `base64://…` (the record's download URL in practice);
* it is loaded then transcoded to `format` via the bundled SILK-capable
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
* failed conversion.
*/
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
// default so a tampered/oversized source can't be pulled in.
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
return convertAudioBytes(bytes, format);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+100 -86
View File
@@ -3,7 +3,10 @@ import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-cont
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
import { GetDoubtBuddyReq, type DoubtBuddyRequest } from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
import {
GetDoubtBuddyReq,
type DoubtBuddyRequest,
} from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { RejectDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/reject-doubt-buddy-req';
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
@@ -14,96 +17,107 @@ export type { DoubtBuddyRequest };
const log = createLogger('Bridge.Friend');
export class FriendApi {
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
/**
* Accept or reject an inbound friend request. `uidOrFlag` is either a
* pre-resolved UID string or a numeric uin (then resolved on the fly).
*/
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
}
async delete(userId: number, block = false): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact cannot be deleted');
/**
* Accept or reject an inbound friend request. `uidOrFlag` is either a
* pre-resolved UID string or a numeric uin (then resolved on the fly).
*/
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
}
await DeleteFriend.invoke(this.ctx, { userId, block });
// The server-side delete has already completed. A refresh failure must be
// visible, but throwing here would misreport the delete itself as failed
// and encourage callers to repeat a destructive request.
try {
await this.ctx.apis.contacts.fetchFriendList();
} catch (err: unknown) {
log.warn(
'friend-list refresh failed after deleting user=%d: %s',
userId,
err instanceof Error ? err.message : String(err),
);
}
}
async setRemark(userId: number, remark: string): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact does not support remarks');
}
if (remark === '') {
await ClearFriendRemark.invoke(this.ctx, { userId });
return;
}
await SetFriendRemark.invoke(this.ctx, { userId, remark });
}
/** List doubtful friend-add requests (可能认识的人). */
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
return Promise.all(list.map(async (item) => {
let uid = item.uid;
let userId = item.user_id;
if (userId <= 0 && uid) {
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
}
// Applicants need not be friends or share a group. Use Identity's
// profile lookup when the list only supplies an account number.
if (!uid && userId > 0) {
try {
uid = await this.ctx.resolveUserUid(userId);
} catch (err: unknown) {
log.warn(
'doubt-request uid resolve failed: user=%d err=%s',
userId,
err instanceof Error ? err.message : String(err),
);
async delete(userId: number, block = false): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact cannot be deleted');
}
}
return { ...item, uid: uid || '', user_id: userId };
}));
}
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
log.trace('doubt-request approval: resolving applicant');
const uid = await this.resolveDoubtFlag(uidOrFlag);
log.trace('doubt-request approval: submitting request');
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
log.trace('doubt-request approval: completed');
}
await DeleteFriend.invoke(this.ctx, { userId, block });
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
async rejectDoubtRequest(uidOrFlag: string): Promise<void> {
return RejectDoubtBuddyReq.invoke(this.ctx, {
uid: await this.resolveDoubtFlag(uidOrFlag),
});
}
// The server-side delete has already completed. A refresh failure must be
// visible, but throwing here would misreport the delete itself as failed
// and encourage callers to repeat a destructive request.
try {
await this.ctx.apis.contacts.fetchFriendList();
} catch (err: unknown) {
log.warn(
'friend-list refresh failed after deleting user=%d: %s',
userId,
err instanceof Error ? err.message : String(err),
);
}
}
/**
* Digit-only flags are account numbers and must be translated before the
* approval/reject packet is built. A raw number in that packet is rejected
* by the server. Same rule as inbound friend-request handling.
*/
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
if (!/^\d+$/.test(uidOrFlag)) return Promise.resolve(uidOrFlag);
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
}
async setRemark(userId: number, remark: string): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact does not support remarks');
}
if (remark === '') {
await ClearFriendRemark.invoke(this.ctx, { userId });
return;
}
await SetFriendRemark.invoke(this.ctx, { userId, remark });
}
/** List doubtful friend-add requests (可能认识的人). */
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
return Promise.all(
list.map(async (item) => {
let uid = item.uid;
let userId = item.user_id;
if (userId <= 0 && uid) {
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
}
// Applicants need not be friends or share a group. Use Identity's
// profile lookup when the list only supplies an account number.
if (!uid && userId > 0) {
try {
uid = await this.ctx.resolveUserUid(userId);
} catch (err: unknown) {
log.warn(
'doubt-request uid resolve failed: user=%d err=%s',
userId,
err instanceof Error ? err.message : String(err),
);
}
}
return { ...item, uid: uid || '', user_id: userId };
}),
);
}
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
log.trace('doubt-request approval: resolving applicant');
const uid = await this.resolveDoubtFlag(uidOrFlag);
log.trace('doubt-request approval: submitting request');
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
log.trace('doubt-request approval: completed');
}
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
async rejectDoubtRequest(uidOrFlag: string): Promise<void> {
return RejectDoubtBuddyReq.invoke(this.ctx, {
uid: await this.resolveDoubtFlag(uidOrFlag),
});
}
/**
* Digit-only flags are account numbers and must be translated before the
* approval/reject packet is built. A raw number in that packet is rejected
* by the server. Same rule as inbound friend-request handling.
*/
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
if (!/^\d+$/.test(uidOrFlag)) {
return Promise.resolve(uidOrFlag);
}
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
}
}
+314 -262
View File
@@ -13,22 +13,22 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
import {
decodeMemberInvitePolicy,
MEMBER_INVITE_PRIVILEGE_MASK,
mergeMemberInvitePrivilegeFlag,
SetMemberInvitePolicy,
type GroupMemberInvitePolicy,
decodeMemberInvitePolicy,
MEMBER_INVITE_PRIVILEGE_MASK,
mergeMemberInvitePrivilegeFlag,
SetMemberInvitePolicy,
type GroupMemberInvitePolicy,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
import {
decodeGroupHistoryVisibility,
SetNewMemberHistoryVisibility,
decodeGroupHistoryVisibility,
SetNewMemberHistoryVisibility,
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
import {
decodeGroupMemberPermissions,
GROUP_MEMBER_PERMISSION_MASKS,
mergeGroupMemberPermission,
SetMemberPermission,
type GroupMemberPermission,
decodeGroupMemberPermissions,
GROUP_MEMBER_PERMISSION_MASKS,
mergeGroupMemberPermission,
SetMemberPermission,
type GroupMemberPermission,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
@@ -41,282 +41,334 @@ import type { BridgeContext } from '../bridge-context';
/** QQ only accepts this write from the group owner (#411). */
export const MEMBER_PERMISSIONS_OWNER_ONLY =
'only the group owner can change group member permissions';
'only the group owner can change group member permissions';
export type GroupAdminSettings = {
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: GroupMemberInvitePolicy;
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: GroupMemberInvitePolicy;
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
};
export interface GroupMemberPermissions {
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
allowMemberCreateGroup?: boolean;
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
allowMemberCreateGroup?: boolean;
}
export class GroupAdminApi {
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
/** Set the group's robot-add option (switch / examine) via group ext-info. */
setRobotAddOption(groupId: number, robotMemberSwitch?: number, robotMemberExamine?: number): Promise<void> {
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
}
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
const [detail, robot] = await Promise.all([
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
]);
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read group admin settings for group ${groupId}`);
}
const privilegeFlag = results.privilegeFlag ?? 0;
const permissions = decodeGroupMemberPermissions(privilegeFlag);
return {
add_type: results.addType ?? 0,
group_question: results.question ?? '',
group_answer: results.answer ?? '',
robot_member_switch: robot.robotMemberSwitch,
robot_member_examine: robot.robotMemberExamine,
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
allow_member_upload_album: permissions.allowMemberUploadAlbum,
allow_member_temporary_session: permissions.allowMemberTemporarySession,
allow_member_create_group: permissions.allowMemberCreateGroup,
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
no_finger_open: results.noFingerOpen ?? 0,
no_code_finger_open: results.noCodeFingerOpen ?? 0,
};
}
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
muteAll(groupId: number, enable: boolean): Promise<void> {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
setAddOption(
groupId: number,
addType: number,
groupQuestion?: string,
groupAnswer?: string,
): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
}
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
}
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
}
addCategoryTag(groupClass: number, name: string): Promise<void> {
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
removeCategoryTag(groupClass: number, name: string): Promise<void> {
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member invite policy',
'before update',
);
const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy);
await SetMemberInvitePolicy.invoke(this.ctx, {
groupId,
currentPrivilegeFlag,
policy,
});
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member invite policy',
'after update',
);
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
throw new Error(`group member invite policy was not applied for group ${groupId}`);
}
}
private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise<number> {
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
}
private async fetchGroupPrivilegeState(
groupId: number,
setting: string,
phase: string,
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return {
privilegeFlag: results.privilegeFlag ?? 0,
ownerUid: results.ownerUid,
};
}
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
['upload_album', permissions.allowMemberUploadAlbum],
['temporary_session', permissions.allowMemberTemporarySession],
['create_group', permissions.allowMemberCreateGroup],
];
if (!updates.some(([, allow]) => allow !== undefined)) {
throw new Error('at least one member permission must be specified');
}
const before = await this.fetchGroupPrivilegeState(
groupId,
'group member permissions',
'before update',
);
const selfUid = this.ctx.identity.selfUid;
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
let expectedPrivilegeFlag = before.privilegeFlag;
let combinedMask = 0n;
for (const [permission, allow] of updates) {
if (allow === undefined) continue;
try {
await SetMemberPermission.invoke(this.ctx, {
groupId,
currentPrivilegeFlag: expectedPrivilegeFlag,
permission,
allow,
/** Set the group's robot-add option (switch / examine) via group ext-info. */
setRobotAddOption(
groupId: number,
robotMemberSwitch?: number,
robotMemberExamine?: number,
): Promise<void> {
return ModifyGroupExtInfo.invoke(this.ctx, {
groupId,
robotMemberSwitch,
robotMemberExamine,
});
} catch (error) {
if (error instanceof OidbError && error.code === 1287) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
const [detail, robot] = await Promise.all([
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
]);
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read group admin settings for group ${groupId}`);
}
throw error;
}
expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow);
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
const privilegeFlag = results.privilegeFlag ?? 0;
const permissions = decodeGroupMemberPermissions(privilegeFlag);
return {
add_type: results.addType ?? 0,
group_question: results.question ?? '',
group_answer: results.answer ?? '',
robot_member_switch: robot.robotMemberSwitch,
robot_member_examine: robot.robotMemberExamine,
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
allow_member_upload_album: permissions.allowMemberUploadAlbum,
allow_member_temporary_session: permissions.allowMemberTemporarySession,
allow_member_create_group: permissions.allowMemberCreateGroup,
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
no_finger_open: results.noFingerOpen ?? 0,
no_code_finger_open: results.noCodeFingerOpen ?? 0,
};
}
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member permissions',
'after update',
);
if ((BigInt(actualPrivilegeFlag) & combinedMask) !== (BigInt(expectedPrivilegeFlag) & combinedMask)) {
throw new Error(`group member permissions were not applied for group ${groupId}`);
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
}
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
muteAll(groupId: number, enable: boolean): Promise<void> {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
}
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
setAddOption(
groupId: number,
addType: number,
groupQuestion?: string,
groupAnswer?: string,
): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
}
return results.groupFlagExt4 ?? 0;
}
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
operateTransInfo?: Uint8Array,
): Promise<void> {
return SetAddRequest.invoke(this.ctx, {
groupId, sequence, eventType, approve, reason, filtered, operateTransInfo,
});
}
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
}
listCategoryTags(
groupClass: number,
): Promise<{ tags: { id: number; name: string; type: number }[] }> {
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
}
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
}
addCategoryTag(groupClass: number, name: string): Promise<void> {
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
async leave(groupId: number): Promise<void> {
await LeaveGroup.invoke(this.ctx, { groupId });
// The server doesn't push a member-decrease back to the member who left of
// its own accord, so synthesize the self group_member_leave here — otherwise
// downstream never sees notice.group_decrease and keeps a "zombie" group in
// its cache (#133). Also drop the group from our own roster.
const selfUin = Number(this.ctx.identity.uin) || 0;
const selfUid = this.ctx.identity.selfUid ?? '';
await this.ctx.events.emit({
kind: 'group_member_leave',
time: Math.floor(Date.now() / 1000),
selfUin,
groupId,
userUin: selfUin,
operatorUin: selfUin,
userUid: selfUid,
operatorUid: selfUid,
leaveType: 'leave',
});
this.ctx.identity.forgetGroup(groupId);
}
removeCategoryTag(groupClass: number, name: string): Promise<void> {
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
}
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member invite policy',
'before update',
);
const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy);
setCard(groupId: number, userId: number, card: string): Promise<void> {
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
}
await SetMemberInvitePolicy.invoke(this.ctx, {
groupId,
currentPrivilegeFlag,
policy,
});
setName(groupId: number, name: string): Promise<void> {
return SetGroupName.invoke(this.ctx, { groupId, name });
}
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member invite policy',
'after update',
);
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
}
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
throw new Error(`group member invite policy was not applied for group ${groupId}`);
}
}
/**
* The bot's local-only label for a group. Lives here rather than
* `FriendApi` because the semantic is "operate on a group" rather
* than "operate on a contact list".
*/
setRemark(groupId: number, remark: string): Promise<void> {
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
}
private async fetchGroupPrivilegeFlag(
groupId: number,
setting: string,
phase: string,
): Promise<number> {
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
}
getAtAllRemain(groupId: number): Promise<{
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}> {
return GetAtAllRemain.invoke(this.ctx, { groupId });
}
private async fetchGroupPrivilegeState(
groupId: number,
setting: string,
phase: string,
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return {
privilegeFlag: results.privilegeFlag ?? 0,
ownerUid: results.ownerUid,
};
}
async setMemberPermissions(
groupId: number,
permissions: GroupMemberPermissions,
): Promise<void> {
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
['upload_album', permissions.allowMemberUploadAlbum],
['temporary_session', permissions.allowMemberTemporarySession],
['create_group', permissions.allowMemberCreateGroup],
];
if (!updates.some(([, allow]) => allow !== undefined)) {
throw new Error('at least one member permission must be specified');
}
const before = await this.fetchGroupPrivilegeState(
groupId,
'group member permissions',
'before update',
);
const selfUid = this.ctx.identity.selfUid;
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
let expectedPrivilegeFlag = before.privilegeFlag;
let combinedMask = 0n;
for (const [permission, allow] of updates) {
if (allow === undefined) {
continue;
}
try {
await SetMemberPermission.invoke(this.ctx, {
groupId,
currentPrivilegeFlag: expectedPrivilegeFlag,
permission,
allow,
});
} catch (error) {
if (error instanceof OidbError && error.code === 1287) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
throw error;
}
expectedPrivilegeFlag = mergeGroupMemberPermission(
expectedPrivilegeFlag,
permission,
allow,
);
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
}
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member permissions',
'after update',
);
if (
(BigInt(actualPrivilegeFlag) & combinedMask) !==
(BigInt(expectedPrivilegeFlag) & combinedMask)
) {
throw new Error(`group member permissions were not applied for group ${groupId}`);
}
}
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
}
}
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(
`unable to read new-member history visibility ${phase} for group ${groupId}`,
);
}
return results.groupFlagExt4 ?? 0;
}
setAddRequest(
groupId: number,
sequence: number,
eventType: number,
approve: boolean,
reason = '',
filtered = false,
operateTransInfo?: Uint8Array,
): Promise<void> {
return SetAddRequest.invoke(this.ctx, {
groupId,
sequence,
eventType,
approve,
reason,
filtered,
operateTransInfo,
});
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
}
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
}
async leave(groupId: number): Promise<void> {
await LeaveGroup.invoke(this.ctx, { groupId });
// The server doesn't push a member-decrease back to the member who left of
// its own accord, so synthesize the self group_member_leave here — otherwise
// downstream never sees notice.group_decrease and keeps a "zombie" group in
// its cache (#133). Also drop the group from our own roster.
const selfUin = Number(this.ctx.identity.uin) || 0;
const selfUid = this.ctx.identity.selfUid ?? '';
await this.ctx.events.emit({
kind: 'group_member_leave',
time: Math.floor(Date.now() / 1000),
selfUin,
groupId,
userUin: selfUin,
operatorUin: selfUin,
userUid: selfUid,
operatorUid: selfUid,
leaveType: 'leave',
});
this.ctx.identity.forgetGroup(groupId);
}
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
}
setCard(groupId: number, userId: number, card: string): Promise<void> {
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
}
setName(groupId: number, name: string): Promise<void> {
return SetGroupName.invoke(this.ctx, { groupId, name });
}
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
}
/**
* The bot's local-only label for a group. Lives here rather than
* `FriendApi` because the semantic is "operate on a group" rather
* than "operate on a contact list".
*/
setRemark(groupId: number, remark: string): Promise<void> {
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
}
getAtAllRemain(groupId: number): Promise<{
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}> {
return GetAtAllRemain.invoke(this.ctx, { groupId });
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,11 +1,11 @@
export interface HistoryRequestGateClock {
now(): number;
sleep(ms: number, signal?: AbortSignal): Promise<void>;
now(): number;
sleep(ms: number, signal?: AbortSignal): Promise<void>;
}
const SYSTEM_CLOCK: HistoryRequestGateClock = {
now: () => Date.now(),
sleep: (ms, signal) => abortableSleep(ms, signal),
now: () => Date.now(),
sleep: (ms, signal) => abortableSleep(ms, signal),
};
/**
@@ -16,93 +16,95 @@ const SYSTEM_CLOCK: HistoryRequestGateClock = {
* both sides of an automatic history-sync request.
*/
export class HistoryRequestGate {
private tail: Promise<void> = Promise.resolve();
private lastStartedAt: number | null = null;
private nextAllowedAt = 0;
private tail: Promise<void> = Promise.resolve();
private lastStartedAt: number | null = null;
private nextAllowedAt = 0;
constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {}
constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {}
run<T>(
minimumGapMs: number,
operation: () => Promise<T>,
signal?: AbortSignal,
): Promise<T> {
if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) {
return Promise.reject(new Error(`history request gap is invalid: ${String(minimumGapMs)}`));
run<T>(minimumGapMs: number, operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {
if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) {
return Promise.reject(
new Error(`history request gap is invalid: ${String(minimumGapMs)}`),
);
}
let operationStarted = false;
const result = this.tail.then(async () => {
throwIfAborted(signal);
const now = this.clock.now();
const requestedBoundary =
this.lastStartedAt === null ? now : this.lastStartedAt + minimumGapMs;
const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now;
if (wait > 0) {
await this.clock.sleep(wait, signal);
}
throwIfAborted(signal);
const startedAt = this.clock.now();
this.lastStartedAt = startedAt;
this.nextAllowedAt = startedAt + minimumGapMs;
operationStarted = true;
return operation();
});
this.tail = result.then(
() => undefined,
() => undefined,
);
return signal ? rejectWhileQueuedOnAbort(result, signal, () => operationStarted) : result;
}
let operationStarted = false;
const result = this.tail.then(async () => {
throwIfAborted(signal);
const now = this.clock.now();
const requestedBoundary = this.lastStartedAt === null
? now
: this.lastStartedAt + minimumGapMs;
const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now;
if (wait > 0) await this.clock.sleep(wait, signal);
throwIfAborted(signal);
const startedAt = this.clock.now();
this.lastStartedAt = startedAt;
this.nextAllowedAt = startedAt + minimumGapMs;
operationStarted = true;
return operation();
});
this.tail = result.then(
() => undefined,
() => undefined,
);
return signal
? rejectWhileQueuedOnAbort(result, signal, () => operationStarted)
: result;
}
}
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw signal.reason ?? new Error('history request aborted');
}
if (signal?.aborted) {
throw signal.reason ?? new Error('history request aborted');
}
}
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
throwIfAborted(signal);
if (!signal) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
throwIfAborted(signal);
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
signal.removeEventListener('abort', onAbort);
reject(signal.reason ?? new Error('history request aborted'));
};
signal.addEventListener('abort', onAbort, { once: true });
});
if (!signal) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
signal.removeEventListener('abort', onAbort);
reject(signal.reason ?? new Error('history request aborted'));
};
signal.addEventListener('abort', onAbort, { once: true });
});
}
function rejectWhileQueuedOnAbort<T>(
result: Promise<T>,
signal: AbortSignal,
hasStarted: () => boolean,
result: Promise<T>,
signal: AbortSignal,
hasStarted: () => boolean,
): Promise<T> {
if (signal.aborted && !hasStarted()) {
return Promise.reject(signal.reason ?? new Error('history request aborted'));
}
if (signal.aborted && !hasStarted()) {
return Promise.reject(signal.reason ?? new Error('history request aborted'));
}
return new Promise<T>((resolve, reject) => {
const onAbort = () => {
if (!hasStarted()) {
reject(signal.reason ?? new Error('history request aborted'));
}
};
signal.addEventListener('abort', onAbort);
result.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
return new Promise<T>((resolve, reject) => {
const onAbort = () => {
if (!hasStarted()) {
reject(signal.reason ?? new Error('history request aborted'));
}
};
signal.addEventListener('abort', onAbort);
result.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
});
});
});
}
+56 -56
View File
@@ -17,38 +17,38 @@ import { WebApi } from './web';
import { SystemFaceApi } from './system-face';
export interface ApiHub {
/** Personal QQ collections: authenticated list retrieval and pagination. */
readonly collection: CollectionApi;
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
readonly contacts: ContactsApi;
/** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */
readonly groupAdmin: GroupAdminApi;
/** Group file CRUD + private (c2c) file upload + media URL resolvers. */
readonly groupFile: GroupFileApi;
/** Group photo album: list/upload/comment/like/delete + media listing. */
readonly groupAlbum: GroupAlbumApi;
/** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */
readonly qzone: QzoneApi;
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
readonly interaction: InteractionApi;
/** Friend roster mutations: handleRequest / delete / setRemark. */
readonly friend: FriendApi;
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
readonly profile: ProfileApi;
/** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */
readonly flashTransfer: FlashTransferApi;
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
readonly forward: ForwardApi;
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
readonly misc: MiscApi;
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
readonly extras: ExtrasApi;
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
readonly web: WebApi;
/** QQ system-face directory: durable catalog, id lookup, and search. */
readonly systemFace: SystemFaceApi;
/** Personal QQ collections: authenticated list retrieval and pagination. */
readonly collection: CollectionApi;
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
readonly contacts: ContactsApi;
/** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */
readonly groupAdmin: GroupAdminApi;
/** Group file CRUD + private (c2c) file upload + media URL resolvers. */
readonly groupFile: GroupFileApi;
/** Group photo album: list/upload/comment/like/delete + media listing. */
readonly groupAlbum: GroupAlbumApi;
/** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */
readonly qzone: QzoneApi;
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
readonly interaction: InteractionApi;
/** Friend roster mutations: handleRequest / delete / setRemark. */
readonly friend: FriendApi;
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
readonly profile: ProfileApi;
/** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */
readonly flashTransfer: FlashTransferApi;
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
readonly forward: ForwardApi;
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
readonly misc: MiscApi;
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
readonly extras: ExtrasApi;
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
readonly web: WebApi;
/** QQ system-face directory: durable catalog, id lookup, and search. */
readonly systemFace: SystemFaceApi;
}
/**
@@ -60,24 +60,24 @@ export interface ApiHub {
* complexity for ~13 small classes.
*/
export function buildApiHub(ctx: BridgeContext): ApiHub {
return {
collection: new CollectionApi(ctx),
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
groupAdmin: new GroupAdminApi(ctx),
groupFile: new GroupFileApi(ctx),
groupAlbum: new GroupAlbumApi(ctx),
qzone: new QzoneApi(ctx),
interaction: new InteractionApi(ctx),
friend: new FriendApi(ctx),
profile: new ProfileApi(ctx),
flashTransfer: new FlashTransferApi(ctx),
forward: new ForwardApi(ctx),
misc: new MiscApi(ctx),
extras: new ExtrasApi(ctx),
web: new WebApi(ctx),
systemFace: new SystemFaceApi(ctx),
};
return {
collection: new CollectionApi(ctx),
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
groupAdmin: new GroupAdminApi(ctx),
groupFile: new GroupFileApi(ctx),
groupAlbum: new GroupAlbumApi(ctx),
qzone: new QzoneApi(ctx),
interaction: new InteractionApi(ctx),
friend: new FriendApi(ctx),
profile: new ProfileApi(ctx),
flashTransfer: new FlashTransferApi(ctx),
forward: new ForwardApi(ctx),
misc: new MiscApi(ctx),
extras: new ExtrasApi(ctx),
web: new WebApi(ctx),
systemFace: new SystemFaceApi(ctx),
};
}
// Re-export the Api classes themselves so callers can write
@@ -93,12 +93,12 @@ export { GroupAlbumApi } from './group-album';
export { GroupFileApi } from './group-file';
export { InteractionApi } from './interaction';
export {
MessageApi,
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS,
type GroupHistorySyncState,
type HistorySyncPrivateTarget,
type HistorySyncState,
type PrivateHistorySyncState,
MessageApi,
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS,
type GroupHistorySyncState,
type HistorySyncPrivateTarget,
type HistorySyncState,
type PrivateHistorySyncState,
} from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
+49 -40
View File
@@ -15,47 +15,56 @@ import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-react
import type { BridgeContext } from '../bridge-context';
export class InteractionApi {
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
}
sendLike(userId: number, count: number): Promise<void> {
return SendLike.invoke(this.ctx, { userId, count });
}
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
}
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
}
/** Fetch the reactor list for one emoji on a group message. */
async getEmojiLikes(
groupId: number,
sequence: number,
emojiId: string,
emojiType = 1,
count = 10,
cookie = '',
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
try {
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
} catch {
return { users: [], cookie: '', isLast: true };
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
}
}
/**
* Recent-used emoji catalog (0x9084_1). Not a per-message reaction list.
*/
fetchReactionSummary(
groupId: number,
sequence: number,
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
}
sendLike(userId: number, count: number): Promise<void> {
return SendLike.invoke(this.ctx, { userId, count });
}
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
}
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
}
/** Fetch the reactor list for one emoji on a group message. */
async getEmojiLikes(
groupId: number,
sequence: number,
emojiId: string,
emojiType = 1,
count = 10,
cookie = '',
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
try {
return await GetEmojiLikes.invoke(this.ctx, {
groupId,
sequence,
emojiId,
emojiType,
count,
cookie,
});
} catch {
return { users: [], cookie: '', isLast: true };
}
}
/**
* Recent-used emoji catalog (0x9084_1). Not a per-message reaction list.
*/
fetchReactionSummary(
groupId: number,
sequence: number,
): Promise<
Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>
> {
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
}
}
File diff suppressed because it is too large. Load diff
+95 -73
View File
@@ -1,8 +1,5 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
MiniAppShareReq,
MiniAppShareResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { MiniAppShareReq, MiniAppShareResp } from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
// Migrated OIDB cmds — facade methods are one-line forwarders.
@@ -13,83 +10,108 @@ import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decr
import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr';
export class MiscApi {
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
translateEn2Zh(words: string[]): Promise<string[]> {
return TranslateEnToZh.invoke(this.ctx, { words });
}
ocrImage(imageUrl: string): Promise<OcrResult> {
return ImageOcr.invoke(this.ctx, { imageUrl });
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
let appid = '1109937557'; // default: bilibili
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
if (type === 'weibo') {
appid = '1109224783';
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
} else if (type !== 'bili') {
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
translateEn2Zh(words: string[]): Promise<string[]> {
return TranslateEnToZh.invoke(this.ctx, { words });
}
const request = protobuf_encode<MiniAppShareReq>({
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
});
const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
ocrImage(imageUrl: string): Promise<OcrResult> {
return ImageOcr.invoke(this.ctx, { imageUrl });
}
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
const jsonStr = decoded?.body?.jsonStr;
async getMiniAppArk(
type: string,
title: string,
desc: string,
picUrl: string,
jumpUrl: string,
): Promise<JsonObject> {
let appid = '1109937557'; // default: bilibili
let iconUrl =
'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
if (!jsonStr) {
throw new Error('mini app share json empty');
if (type === 'weibo') {
appid = '1109224783';
iconUrl =
'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
} else if (type !== 'bili') {
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
}
const request = protobuf_encode<MiniAppShareReq>({
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
});
const result = await this.ctx.sendRawPacket(
'LightAppSvc.mini_app_share.AdaptShareInfo',
request,
);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
}
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
const jsonStr = decoded?.body?.jsonStr;
if (!jsonStr) {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr) as Record<
string,
JsonObject | string | number | boolean | null
>;
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
},
};
}
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
},
};
}
clickInlineKeyboardButton(
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
): Promise<JsonValue> {
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
}
sendGroupSign(groupId: number): Promise<void> {
return SendGroupSign.invoke(this.ctx, { groupId });
}
async getDecryptKey(dbSalt: string): Promise<string> {
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
if (!result.success) {
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
clickInlineKeyboardButton(
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
): Promise<JsonValue> {
return ClickInlineKeyboardButton.invoke(this.ctx, {
groupId,
botAppid,
buttonId,
callbackData,
msgSeq,
});
}
if (!result.dbKey) {
throw new Error('Decrypt key is empty');
sendGroupSign(groupId: number): Promise<void> {
return SendGroupSign.invoke(this.ctx, { groupId });
}
async getDecryptKey(dbSalt: string): Promise<string> {
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
if (!result.success) {
throw new Error(
result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`,
);
}
if (!result.dbKey) {
throw new Error('Decrypt key is empty');
}
return result.dbKey;
}
return result.dbKey;
}
}
+264 -208
View File
@@ -1,7 +1,7 @@
import type {
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
@@ -10,10 +10,17 @@ import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-fac
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import {
BufferChunkSource,
fetchHighwaySession,
uploadHighwayHttp,
} from '@snowluma/protocol/highway';
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
import {
GetUnidirectionalFriendList,
type UnidirectionalFriendEntry,
} from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
@@ -21,226 +28,273 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
export interface CustomFaceDetail {
emojiId: string;
url: string;
md5: string;
desc: string;
emojiId: string;
url: string;
md5: string;
desc: string;
}
export class ProfileApi {
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
// ─────────────── status / profile setters ───────────────
// ─────────────── status / profile setters ───────────────
async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise<void> {
await this.dispatchSetStatus({ status, extStatus, batteryStatus });
}
/**
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
* — the values QQ associates with "I have a custom status string" —
* and threads the faceId / wording / faceType through the customExt
* sub-message of the same SetStatus wire call.
*/
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
await this.dispatchSetStatus({
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
private async dispatchSetStatus(value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
}): Promise<void> {
const request = protobuf_encode<SetStatusReq>(value);
const result = await this.ctx.sendRawPacket(
'trpc.qq_new_tech.status_svc.StatusService.SetStatus',
request,
);
if (!result.success) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise<void> {
await this.dispatchSetStatus({ status, extStatus, batteryStatus });
}
if (result.responseData && result.responseData.length > 0) {
const resp = protobuf_decode<SetStatusResp>(result.responseData);
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
const message = resp.errMsg ?? '';
if (message !== '' && message !== 'set status success') {
throw new Error(message);
}
/**
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
* — the values QQ associates with "I have a custom status string" —
* and threads the faceId / wording / faceType through the customExt
* sub-message of the same SetStatus wire call.
*/
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
await this.dispatchSetStatus({
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
}
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
}
private async dispatchSetStatus(value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
}): Promise<void> {
const request = protobuf_encode<SetStatusReq>(value);
const result = await this.ctx.sendRawPacket(
'trpc.qq_new_tech.status_svc.StatusService.SetStatus',
request,
);
setSelfLongNick(longNick: string): Promise<void> {
return SetSelfLongNick.invoke(this.ctx, { longNick });
}
if (!result.success) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
setInputStatus(userId: number, eventType: number): Promise<void> {
return SetInputStatus.invoke(this.ctx, { userId, eventType });
}
if (result.responseData && result.responseData.length > 0) {
const resp = protobuf_decode<SetStatusResp>(result.responseData);
async setAvatar(source: string): Promise<void> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'avatar');
if (!loaded.bytes.length) throw new Error('avatar file is empty');
if (!resp) {
throw new Error(
result.errorMessage || 'set online status failed (network/timeout)',
);
}
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
}
const message = resp.errMsg ?? '';
/**
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
* - same highway HTTP upload as personal avatar
* - cmdId 3000 (instead of 90)
* - GroupAvatarExtra proto carried as the `extend` blob, with the
* four protocol-prescribed constants (type=101, field5=3, field6=1,
* field3.field1=1) and the target groupUin.
*
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
async setGroupAvatar(groupId: number, source: string): Promise<void> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
const extra = protobuf_encode<GroupAvatarExtra>({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
});
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
return GetLike.invoke(this.ctx, { userId, start, limit });
}
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
return GetUnidirectionalFriendList.invoke(this.ctx);
}
async fetchCustomFace(count = 10): Promise<string[]> {
const faceIds = await this.fetchCustomFaceIds(count);
return faceIds.map((id) => this.customFaceUrl(id));
}
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
const faceIds = await this.fetchCustomFaceIds(count);
if (faceIds.length === 0) return [];
const emojis = faceIds.map((emojiId) => ({
emojiId,
md5: md5FromEmojiId(emojiId),
}));
const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis });
const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc]));
return emojis.map(({ emojiId, md5 }) => ({
emojiId,
url: this.customFaceUrl(emojiId),
md5,
// The detail response may omit entries which have never had a remark.
desc: descriptions.get(emojiId) ?? '',
}));
}
async fetchCustomFaceIds(count = 10): Promise<string[]> {
if (!Number.isInteger(count) || count < 0) {
throw new Error('custom face count must be a non-negative integer');
if (message !== '' && message !== 'set status success') {
throw new Error(message);
}
}
}
if (count === 0) return [];
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
return faceIds.slice(0, count);
}
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
}
private customFaceUrl(emojiId: string): string {
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
}
setSelfLongNick(longNick: string): Promise<void> {
return SetSelfLongNick.invoke(this.ctx, { longNick });
}
/** Resolve an existing saved sticker by its resource id or content MD5. */
async resolveCustomFace(identifier: string): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
const wanted = identifier.trim();
if (!wanted) throw new Error('custom face identifier is empty');
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
const emojiId = ids.find((id) => byMd5
? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase()
: id === wanted);
if (!emojiId) throw new Error('custom face is not in the saved sticker list');
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
}
setInputStatus(userId: number, eventType: number): Promise<void> {
return SetInputStatus.invoke(this.ctx, { userId, eventType });
}
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
deleteCustomFace(emojiId: string): Promise<void> {
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
}
async setAvatar(source: string): Promise<void> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'avatar');
/**
* 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s)://
* (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。
*/
async addCustomFace(imageSource: string): Promise<string> {
const { bytes } = await loadBinarySource(imageSource, 'custom-face');
return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes });
}
if (!loaded.bytes.length) {
throw new Error('avatar file is empty');
}
/**
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
*/
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
return ModifyCustomFace.invoke(this.ctx, {
emojiId,
md5: md5FromEmojiId(emojiId),
desc,
});
}
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(
bridge,
session,
90,
new BufferChunkSource(loaded.bytes),
hashes.md5,
new Uint8Array(0),
);
}
/**
* 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层
* (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f
* 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。
* 两步都发才生效。
*/
async moveCustomFaceToFront(emojiId: string): Promise<void> {
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
const ids = await this.fetchCustomFaceIds(1000);
const idx = ids.indexOf(emojiId);
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
// 新顺序:目标挪到第一,其余按原顺序
const reordered = ids.slice();
reordered.splice(idx, 1);
reordered.unshift(emojiId);
// 2. 0x902f 移动指令(f3=1 = 移到最前)
await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 });
// 3. 0x902e opType=2 上传新顺序
await MoveCustomFace.invoke(this.ctx, {
emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })),
});
}
/**
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
* - same highway HTTP upload as personal avatar
* - cmdId 3000 (instead of 90)
* - GroupAvatarExtra proto carried as the `extend` blob, with the
* four protocol-prescribed constants (type=101, field5=3, field6=1,
* field3.field1=1) and the target groupUin.
*
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
async setGroupAvatar(groupId: number, source: string): Promise<void> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) {
throw new Error('group avatar file is empty');
}
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
const extra = protobuf_encode<GroupAvatarExtra>({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
});
await uploadHighwayHttp(
bridge,
session,
3000,
new BufferChunkSource(loaded.bytes),
hashes.md5,
extra,
);
}
// ─────────────── queries on me / my contacts ───────────────
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
return GetLike.invoke(this.ctx, { userId, start, limit });
}
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
return GetUnidirectionalFriendList.invoke(this.ctx);
}
async fetchCustomFace(count = 10): Promise<string[]> {
const faceIds = await this.fetchCustomFaceIds(count);
return faceIds.map((id) => this.customFaceUrl(id));
}
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
const faceIds = await this.fetchCustomFaceIds(count);
if (faceIds.length === 0) {
return [];
}
const emojis = faceIds.map((emojiId) => ({
emojiId,
md5: md5FromEmojiId(emojiId),
}));
const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis });
const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc]));
return emojis.map(({ emojiId, md5 }) => ({
emojiId,
url: this.customFaceUrl(emojiId),
md5,
// The detail response may omit entries which have never had a remark.
desc: descriptions.get(emojiId) ?? '',
}));
}
async fetchCustomFaceIds(count = 10): Promise<string[]> {
if (!Number.isInteger(count) || count < 0) {
throw new Error('custom face count must be a non-negative integer');
}
if (count === 0) {
return [];
}
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
return faceIds.slice(0, count);
}
private customFaceUrl(emojiId: string): string {
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
}
/** Resolve an existing saved sticker by its resource id or content MD5. */
async resolveCustomFace(
identifier: string,
): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
const wanted = identifier.trim();
if (!wanted) {
throw new Error('custom face identifier is empty');
}
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
const emojiId = ids.find((id) =>
byMd5 ? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase() : id === wanted,
);
if (!emojiId) {
throw new Error('custom face is not in the saved sticker list');
}
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
}
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
deleteCustomFace(emojiId: string): Promise<void> {
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
}
/**
* 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s)://
* (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。
*/
async addCustomFace(imageSource: string): Promise<string> {
const { bytes } = await loadBinarySource(imageSource, 'custom-face');
return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes });
}
/**
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
*/
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
return ModifyCustomFace.invoke(this.ctx, {
emojiId,
md5: md5FromEmojiId(emojiId),
desc,
});
}
/**
* 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层
* (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f
* 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。
* 两步都发才生效。
*/
async moveCustomFaceToFront(emojiId: string): Promise<void> {
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
const ids = await this.fetchCustomFaceIds(1000);
const idx = ids.indexOf(emojiId);
if (idx < 0) {
throw new Error(`emoji_id not in list: ${emojiId}`);
}
// 新顺序:目标挪到第一,其余按原顺序
const reordered = ids.slice();
reordered.splice(idx, 1);
reordered.unshift(emojiId);
// 2. 0x902f 移动指令(f3=1 = 移到最前)
await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 });
// 3. 0x902e opType=2 上传新顺序
await MoveCustomFace.invoke(this.ctx, {
emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })),
});
}
}
/**
@@ -249,11 +303,13 @@ export class ProfileApi {
* 传空串让服务端拒绝更早定位问题。
*/
function md5FromEmojiId(emojiId: string): string {
const parts = emojiId.split('_');
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
const md5 = parts[4];
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
}
return md5.toUpperCase();
const parts = emojiId.split('_');
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
const md5 = parts[4];
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
}
return md5.toUpperCase();
}
+124 -107
View File
@@ -1,19 +1,19 @@
import {
commentQzoneMsg,
deleteQzoneMsg,
getQzoneFeeds,
getQzoneMsgList,
publishQzoneMsg,
setQzoneBlack,
setQzoneLike,
updateQzoneMsgRight,
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsResult,
type QzoneMsgListResult,
type QzonePublishResult,
type QzoneUpdateRightResult,
type QzoneUploadImageResult,
commentQzoneMsg,
deleteQzoneMsg,
getQzoneFeeds,
getQzoneMsgList,
publishQzoneMsg,
setQzoneBlack,
setQzoneLike,
updateQzoneMsgRight,
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsResult,
type QzoneMsgListResult,
type QzonePublishResult,
type QzoneUpdateRightResult,
type QzoneUploadImageResult,
} from '@snowluma/protocol/web/qzone';
import type { BridgeContext } from '../bridge-context';
@@ -24,105 +24,122 @@ import type { BridgeContext } from '../bridge-context';
* Distinct from the group-album surface, which lives on GroupAlbumApi.
*/
export class QzoneApi {
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
/**
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
*/
async getMsgList(targetUin?: number, pos = 0, num = 20): Promise<QzoneMsgListResult> {
const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneMsgList(cookieObject, uin, pos, num);
}
/**
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
*/
async getMsgList(targetUin?: number, pos = 0, num = 20): Promise<QzoneMsgListResult> {
const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneMsgList(cookieObject, uin, pos, num);
}
/**
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
* 始终以机器人自己的身份拉取好友动态。
*/
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
}
/**
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
* 始终以机器人自己的身份拉取好友动态。
*/
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
}
/**
* 从来源上传图片到 QQ 空间。
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
*/
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
}
/**
* 从来源上传图片到 QQ 空间。
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
*/
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
}
/**
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
*/
async publish(
content: string,
richType?: number,
richval?: string,
ugcRight = 1,
targetUins?: string,
): Promise<QzonePublishResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
}
/**
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
*/
async publish(
content: string,
richType?: number,
richval?: string,
ugcRight = 1,
targetUins?: string,
): Promise<QzonePublishResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(
cookieObject,
this.ctx.identity.uin,
content,
richType,
richval,
ugcRight,
targetUins,
);
}
/** 删除机器人自己空间的一条说说(按 tid)。 */
async delete(tid: string): Promise<void> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
}
/** 删除机器人自己空间的一条说说(按 tid)。 */
async delete(tid: string): Promise<void> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
}
/**
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
*/
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
}
/**
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
*/
async updateRight(
tid: string,
ugcRight: number,
targetUins?: string,
): Promise<QzoneUpdateRightResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
}
/**
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
*/
async like(tid: string, targetUin: number | undefined, like: boolean, abstime = 0): Promise<void> {
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime);
}
/**
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
*/
async like(
tid: string,
targetUin: number | undefined,
like: boolean,
abstime = 0,
): Promise<void> {
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime);
}
/**
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
* (从 uploadImageFromSource 的 url 字段获取)。
*/
async comment(
tid: string,
content: string,
targetUin: number | undefined,
richType?: number,
richval?: string,
): Promise<QzoneCommentResult> {
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
}
/**
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
* (从 uploadImageFromSource 的 url 字段获取)。
*/
async comment(
tid: string,
content: string,
targetUin: number | undefined,
richType?: number,
richval?: string,
): Promise<QzoneCommentResult> {
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
}
/**
* 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。
* `ban=true` 拉黑,`ban=false` 解除拉黑。
*/
async setBlack(targetUin: number, ban: boolean): Promise<void> {
const selfUin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban);
}
/**
* 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。
* `ban=true` 拉黑,`ban=false` 解除拉黑。
*/
async setBlack(targetUin: number, ban: boolean): Promise<void> {
const selfUin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban);
}
}
+35 -30
View File
@@ -1,14 +1,19 @@
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
return 0;
if (typeof value === 'number' && Number.isFinite(value)) {
return Math.trunc(value);
}
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
return 0;
}
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
@@ -22,25 +27,25 @@ export { resolveSelfUid } from '@snowluma/protocol/self-uid';
* fetchers in group-file.ts.
*/
export interface MediaIndexNode {
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
};
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
}
+23 -22
View File
@@ -1,7 +1,7 @@
import {
sysFaceStore,
type SysFaceEntry,
type SysFacePackEntry,
sysFaceStore,
type SysFaceEntry,
type SysFacePackEntry,
} from '@snowluma/protocol/sys-face-store';
import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces';
import type { BridgeContext } from '../bridge-context';
@@ -9,27 +9,28 @@ import type { BridgeContext } from '../bridge-context';
/** QQ's account-independent system-face directory. The shared store owns
* persistence and refresh coalescing; this API binds it to one live sender. */
export class SystemFaceApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) {}
fetchCatalog(refresh = false): Promise<SysFacePackEntry[]> {
return sysFaceStore.getCatalog(this.ctx, refresh);
}
async fetchFace(faceId: number, refresh = false): Promise<SysFaceEntry | null> {
if (refresh) {
await sysFaceStore.refresh(this.ctx);
return sysFaceStore.lookup(faceId);
fetchCatalog(refresh = false): Promise<SysFacePackEntry[]> {
return sysFaceStore.getCatalog(this.ctx, refresh);
}
return sysFaceStore.resolve(this.ctx, faceId);
}
async search(query: string): Promise<SysFaceEntry[]> {
await sysFaceStore.ensureReady(this.ctx);
return sysFaceStore.search(query);
}
async fetchFace(faceId: number, refresh = false): Promise<SysFaceEntry | null> {
if (refresh) {
await sysFaceStore.refresh(this.ctx);
return sysFaceStore.lookup(faceId);
}
async isSuper(faceId: number, refresh = false): Promise<boolean> {
const face = await this.fetchFace(faceId, refresh);
return face !== null && isSuperFaceEntry(face);
}
return sysFaceStore.resolve(this.ctx, faceId);
}
async search(query: string): Promise<SysFaceEntry[]> {
await sysFaceStore.ensureReady(this.ctx);
return sysFaceStore.search(query);
}
async isSuper(faceId: number, refresh = false): Promise<boolean> {
const face = await this.fetchFace(faceId, refresh);
return face !== null && isSuperFaceEntry(face);
}
}
+408 -340
View File
@@ -1,226 +1,288 @@
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import {
ForceFetchClientKey,
type ClientKeyInfo as NamespaceClientKeyInfo,
} from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
import {
getGroupEssenceMsg,
getGroupEssenceMsgAll,
type GroupEssenceMsgRet,
} from '@snowluma/protocol/web/group-essence';
import { getFriendDressWebAPI, type WebFriendDress } from '@snowluma/protocol/web/friend-dress';
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
import {
getHonorListWebAPI,
WebHonorType,
type WebHonorItem,
} from '@snowluma/protocol/web/group-honor';
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
import {
deleteGroupNotice as deleteGroupNoticeHttp,
GROUP_NOTICE_TYPE_NEW_MEMBERS,
GROUP_NOTICE_TYPE_NORMAL,
getGroupNoticeWebAPI,
groupNoticeImageUrl,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
type WebApiGroupNoticeCollection,
type WebApiGroupNoticeFeed,
type WebApiGroupNoticeRet,
deleteGroupNotice as deleteGroupNoticeHttp,
GROUP_NOTICE_TYPE_NEW_MEMBERS,
GROUP_NOTICE_TYPE_NORMAL,
getGroupNoticeWebAPI,
groupNoticeImageUrl,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
type WebApiGroupNoticeCollection,
type WebApiGroupNoticeFeed,
type WebApiGroupNoticeRet,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
export type ClientKeyInfo = NamespaceClientKeyInfo;
export interface WebHonorInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
group_id: number;
current_talkative: WebHonorItem | null;
talkative_list: WebHonorItem[];
performer_list: WebHonorItem[];
legend_list: WebHonorItem[];
emotion_list: WebHonorItem[];
strong_newbie_list: WebHonorItem[];
[key: string]: import('@snowluma/common/json').JsonValue;
group_id: number;
current_talkative: WebHonorItem | null;
talkative_list: WebHonorItem[];
performer_list: WebHonorItem[];
legend_list: WebHonorItem[];
emotion_list: WebHonorItem[];
strong_newbie_list: WebHonorItem[];
}
export interface WebNoticeInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; url: string; height: number; width: number }>;
images: Array<{ id: string; url: string; height: number; width: number }>;
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
/** Server response type. Regular notices are commonly returned as 6. */
type: number;
pinned: number;
send_to_new_members: boolean;
[key: string]: import('@snowluma/common/json').JsonValue;
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; url: string; height: number; width: number }>;
images: Array<{ id: string; url: string; height: number; width: number }>;
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
/** Server response type. Regular notices are commonly returned as 6. */
type: number;
pinned: number;
send_to_new_members: boolean;
}
export interface SendNoticeOptions {
image?: string;
pinned?: number;
type?: number;
sendToNewMembers?: boolean;
isShowEditCard?: number;
tipWindowType?: number;
confirmRequired?: number;
image?: string;
pinned?: number;
type?: number;
sendToNewMembers?: boolean;
isShowEditCard?: number;
tipWindowType?: number;
confirmRequired?: number;
}
function finiteNumber(value: unknown, field: string): number {
const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;
if (!Number.isFinite(parsed)) {
throw new Error(`invalid group notice response: ${field} must be a finite number`);
}
return parsed;
const parsed =
typeof value === 'number'
? value
: typeof value === 'string' && value.trim() !== ''
? Number(value)
: Number.NaN;
if (!Number.isFinite(parsed)) {
throw new Error(`invalid group notice response: ${field} must be a finite number`);
}
return parsed;
}
function collectionValues(
collection: WebApiGroupNoticeCollection | undefined,
field: 'feeds' | 'inst',
collection: WebApiGroupNoticeCollection | undefined,
field: 'feeds' | 'inst',
): WebApiGroupNoticeFeed[] {
if (collection === undefined) return [];
if (Array.isArray(collection)) return collection;
if (collection === null || typeof collection !== 'object') {
throw new Error(`invalid group notice response: ${field} must be an array or object`);
}
return Object.values(collection);
if (collection === undefined) {
return [];
}
if (Array.isArray(collection)) {
return collection;
}
if (collection === null || typeof collection !== 'object') {
throw new Error(`invalid group notice response: ${field} must be an array or object`);
}
return Object.values(collection);
}
function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boolean): WebNoticeInfo {
if (!feed || typeof feed !== 'object') {
throw new Error('invalid group notice response: feed must be an object');
}
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
}
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
}
if (feed.settings === undefined) {
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
}
const image = (feed.msg.pics ?? []).map((pic, index) => {
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`);
if (!feed || typeof feed !== 'object') {
throw new Error('invalid group notice response: feed must be an object');
}
return {
id: pic.id,
url: groupNoticeImageUrl(pic.id),
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
};
});
const responseType = feed.type === undefined
? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
return {
notice_id: feed.fid,
sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`),
publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`),
message: {
text: feed.msg.text,
image,
images: image,
},
settings: feed.settings,
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
type: responseType,
pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
};
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
}
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
}
if (feed.settings === undefined) {
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
}
const image = (feed.msg.pics ?? []).map((pic, index) => {
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
throw new Error(
`invalid group notice response: feed ${feed.fid} image ${index} is malformed`,
);
}
return {
id: pic.id,
url: groupNoticeImageUrl(pic.id),
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
};
});
const responseType =
feed.type === undefined
? sendToNewMembers
? GROUP_NOTICE_TYPE_NEW_MEMBERS
: GROUP_NOTICE_TYPE_NORMAL
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
return {
notice_id: feed.fid,
sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`),
publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`),
message: {
text: feed.msg.text,
image,
images: image,
},
settings: feed.settings,
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
type: responseType,
pinned:
feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
};
}
/** Merge QQ's regular (`feeds`) and new-member (`inst`) announcement lists. */
export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo[] {
if (ret.ec !== 0) {
throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`);
}
const notices: WebNoticeInfo[] = [];
const indexByNoticeId = new Map<string, number>();
const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => {
for (const feed of collectionValues(collection, field)) {
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
const existingIndex = indexByNoticeId.get(mapped.notice_id);
if (existingIndex === undefined) {
indexByNoticeId.set(mapped.notice_id, notices.length);
notices.push(mapped);
} else if (sendToNewMembers) {
// If QQ returns the same item in both collections, `inst` is the
// authoritative signal that it targets new members.
notices[existingIndex] = mapped;
}
if (ret.ec !== 0) {
throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`);
}
};
append(ret.feeds, false, 'feeds');
append(ret.inst, true, 'inst');
return notices;
const notices: WebNoticeInfo[] = [];
const indexByNoticeId = new Map<string, number>();
const append = (
collection: WebApiGroupNoticeCollection | undefined,
sendToNewMembers: boolean,
field: 'feeds' | 'inst',
) => {
for (const feed of collectionValues(collection, field)) {
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
const existingIndex = indexByNoticeId.get(mapped.notice_id);
if (existingIndex === undefined) {
indexByNoticeId.set(mapped.notice_id, notices.length);
notices.push(mapped);
} else if (sendToNewMembers) {
// If QQ returns the same item in both collections, `inst` is the
// authoritative signal that it targets new members.
notices[existingIndex] = mapped;
}
}
};
append(ret.feeds, false, 'feeds');
append(ret.inst, true, 'inst');
return notices;
}
// ─────────────── private helpers (cookie acquisition) ───────────────
function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
return ForceFetchClientKey.invoke(bridge);
return ForceFetchClientKey.invoke(bridge);
}
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
return GetPskey.invoke(bridge, { domainList });
function getPSkey(
bridge: Bridge,
domainList: string[],
): Promise<{ domainPskeyMap: Map<string, string> }> {
return GetPskey.invoke(bridge, { domainList });
}
async function getCookies(bridge: Bridge, domain: string): Promise<Record<string, string>> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
const ClientKeyData = await forceFetchClientKeyInner(bridge);
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl =
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' +
bridge.identity.uin +
'&clientkey=' +
ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' +
domain +
'%2F' +
bridge.identity.uin +
'%2Finfocenter&keyindex=' +
ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
const data = await RequestUtil.HttpsGetCookies(requestUrl);
if (!data['p_skey'] || data['p_skey'].length === 0) {
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
// for the same domain. Errors are swallowed so the caller can
// still proceed with whatever cookies it did get.
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
} catch {
return data;
if (!data['p_skey'] || data['p_skey'].length === 0) {
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
// for the same domain. Errors are swallowed so the caller can
// still proceed with whatever cookies it did get.
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
} catch {
return data;
}
}
}
return data;
return data;
}
async function getSKey(bridge: Bridge): Promise<string> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
const ClientKeyData = await forceFetchClientKeyInner(bridge);
if (!ClientKeyData.clientKey) {
throw new Error('getClientKey Error: clientKey is empty');
}
if (!ClientKeyData.clientKey) {
throw new Error('getClientKey Error: clientKey is empty');
}
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
const u1 = encodeURIComponent(
'https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0',
);
const requestUrl =
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' +
bridge.identity.uin +
'&clientkey=' +
ClientKeyData.clientKey +
'&u1=' +
u1 +
'&keyindex=' +
ClientKeyData.keyIndex;
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
if (!skey) {
throw new Error('SKey is Empty');
}
if (!skey) {
throw new Error('SKey is Empty');
}
return skey;
return skey;
}
/**
@@ -228,207 +290,213 @@ async function getSKey(bridge: Bridge): Promise<string> {
* skey or p_skey. djb2 hash truncated to 31 bits.
*/
function getBknFromSKey(skey: string): number {
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return hash & 2147483647;
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return hash & 2147483647;
}
export class WebApi {
constructor(private readonly ctx: BridgeContext) { }
constructor(private readonly ctx: BridgeContext) {}
// ─────────────── cookie / token primitives ───────────────
// ─────────────── cookie / token primitives ───────────────
async forceFetchClientKey(): Promise<ClientKeyInfo> {
return forceFetchClientKeyInner(asBridge(this.ctx));
}
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
* (qzone.qq.com) and by every other web helper here. */
async getCookies(domain: string): Promise<Record<string, string>> {
return getCookies(asBridge(this.ctx), domain);
}
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
async getCookiesStr(domain: string): Promise<string> {
const cookieObject = await getCookies(asBridge(this.ctx), domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
async getCsrfToken(): Promise<number> {
const skey = await getSKey(asBridge(this.ctx));
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
const cookieObject = await getCookies(asBridge(this.ctx), domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0;
return {
cookies: cookiesStr,
token,
csrf_token: token,
};
}
// ─────────────── group essence ───────────────
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
}
/** Walks every page and returns the concatenated result. */
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await getGroupEssenceMsgAll(cookieObject, groupCode);
}
// ─────────────── group honor ───────────────
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: WebHonorInfo = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
if (talkativeList.length > 0) {
honorInfo.current_talkative = talkativeList[0];
honorInfo.talkative_list = talkativeList;
}
async forceFetchClientKey(): Promise<ClientKeyInfo> {
return forceFetchClientKeyInner(asBridge(this.ctx));
}
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
* (qzone.qq.com) and by every other web helper here. */
async getCookies(domain: string): Promise<Record<string, string>> {
return getCookies(asBridge(this.ctx), domain);
}
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
async getCookiesStr(domain: string): Promise<string> {
const cookieObject = await getCookies(asBridge(this.ctx), domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
async getCsrfToken(): Promise<number> {
const skey = await getSKey(asBridge(this.ctx));
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
return honorInfo;
}
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
async getCredentials(
domain: string,
): Promise<{ cookies: string; token: number; csrf_token: number }> {
const cookieObject = await getCookies(asBridge(this.ctx), domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
// ─────────────── group sign-in (打卡) ───────────────
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0;
/** Today's group sign-in list via qun.qq.com. [] when the group has no
* sign-ins; THROWS on transport / auth failure (caller maps to failed). */
async getSignedList(groupId: number): Promise<SignedListMember[]> {
const bridge = asBridge(this.ctx);
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return getDaySignedListWebAPI(cookieObject, groupId.toString(), bridge.identity.uin.toString());
}
// ─────────────── group notice ───────────────
async sendNotice(
groupId: number,
content: string,
options?: SendNoticeOptions,
): Promise<SetNoticeRetSuccess> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
let picId = '';
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
// Route through loadBinarySource so the group-notice image download
// gets the same browser-UA + Referer-retry hardening as every other
// media fetch — and http/file/base64 source handling for free.
const loaded = await loadBinarySource(options.image, 'group-notice image');
const imageBuffer = Buffer.from(loaded.bytes);
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
return {
cookies: cookiesStr,
token,
csrf_token: token,
};
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
{
pinned: options?.pinned,
type: options?.type,
sendToNewMembers: options?.sendToNewMembers,
isShowEditCard: options?.isShowEditCard,
tipWindowType: options?.tipWindowType,
confirmRequired: options?.confirmRequired,
picId,
imgWidth,
imgHeight,
},
);
// ─────────────── group essence ───────────────
if (ret.ec !== 0) {
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
}
return ret;
}
/** Walks every page and returns the concatenated result. */
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await getGroupEssenceMsgAll(cookieObject, groupCode);
}
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
// ─────────────── group honor ───────────────
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
return mapGroupNoticeResponse(ret);
}
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
}
const honorInfo: WebHonorInfo = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
// ─────────────── friend dress (好友装扮) ───────────────
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
/** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域,
* 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/
* 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */
async getFriendDress(targetUin: number): Promise<WebFriendDress> {
const bridge = asBridge(this.ctx);
const cookieObject = await getCookies(bridge, 'vip.qq.com');
return getFriendDressWebAPI(cookieObject, targetUin.toString());
}
if (talkativeList.length > 0) {
honorInfo.current_talkative = talkativeList[0];
honorInfo.talkative_list = talkativeList;
}
}
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
}
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
}
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
}
return honorInfo;
}
// ─────────────── group sign-in (打卡) ───────────────
/** Today's group sign-in list via qun.qq.com. [] when the group has no
* sign-ins; THROWS on transport / auth failure (caller maps to failed). */
async getSignedList(groupId: number): Promise<SignedListMember[]> {
const bridge = asBridge(this.ctx);
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return getDaySignedListWebAPI(
cookieObject,
groupId.toString(),
bridge.identity.uin.toString(),
);
}
// ─────────────── group notice ───────────────
async sendNotice(
groupId: number,
content: string,
options?: SendNoticeOptions,
): Promise<SetNoticeRetSuccess> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
let picId = '';
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
// Route through loadBinarySource so the group-notice image download
// gets the same browser-UA + Referer-retry hardening as every other
// media fetch — and http/file/base64 source handling for free.
const loaded = await loadBinarySource(options.image, 'group-notice image');
const imageBuffer = Buffer.from(loaded.bytes);
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
const ret = await setGroupNoticeWebAPI(cookieObject, groupCode, content, {
pinned: options?.pinned,
type: options?.type,
sendToNewMembers: options?.sendToNewMembers,
isShowEditCard: options?.isShowEditCard,
tipWindowType: options?.tipWindowType,
confirmRequired: options?.confirmRequired,
picId,
imgWidth,
imgHeight,
});
if (ret.ec !== 0) {
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
}
return ret;
}
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
return mapGroupNoticeResponse(ret);
}
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
}
// ─────────────── friend dress (好友装扮) ───────────────
/** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域,
* 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/
* 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */
async getFriendDress(targetUin: number): Promise<WebFriendDress> {
const bridge = asBridge(this.ctx);
const cookieObject = await getCookies(bridge, 'vip.qq.com');
return getFriendDressWebAPI(cookieObject, targetUin.toString());
}
}
+1 -2
View File
@@ -2,7 +2,6 @@ import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/brid
import type { ApiHub } from './apis';
export interface BridgeContext extends BaseBridgeContext {
readonly apis: ApiHub;
readonly apis: ApiHub;
}
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
+11 -11
View File
@@ -2,18 +2,18 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
import type { BridgeContext } from './bridge-context';
export interface RosterWarmupResult {
friendsLoaded: boolean;
groupsLoaded: boolean;
friendsLoaded: boolean;
groupsLoaded: boolean;
}
export interface BridgeInterface extends BridgeContext {
readonly activePid: number | null;
/** Settles once for this Bridge session after first-login roster fetch. */
whenRosterWarmupSettled(): Promise<RosterWarmupResult>;
/** False only when every attached QQ process has a confirmed receive or
* request-path failure. An unarmed watchdog remains true for compatibility. */
readonly receiveHealthy: boolean;
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
* QQ has not emitted its cache notification since SnowLuma attached. */
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
readonly activePid: number | null;
/** Settles once for this Bridge session after first-login roster fetch. */
whenRosterWarmupSettled(): Promise<RosterWarmupResult>;
/** False only when every attached QQ process has a confirmed receive or
* request-path failure. An unarmed watchdog remains true for compatibility. */
readonly receiveHealthy: boolean;
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
* QQ has not emitted its cache notification since SnowLuma attached. */
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
}
File diff suppressed because it is too large. Load diff
+357 -334
View File
@@ -1,8 +1,4 @@
import {
createLogger,
renderTraceBytes,
runWithTraceRequest,
} from '@snowluma/common/logger';
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
@@ -13,7 +9,7 @@ export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string, bridge: Bridge) => void;
interface QQSession {
bridge: Bridge;
bridge: Bridge;
}
const log = createLogger('Bridge');
@@ -21,366 +17,393 @@ const packetLog = createLogger('Bridge.Packet');
const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private sessionStartedListeners_: SessionStartedCallback[] = [];
private sessionClosedListeners_: SessionClosedCallback[] = [];
private sessionStartedListeners_: SessionStartedCallback[] = [];
private sessionClosedListeners_: SessionClosedCallback[] = [];
/** Additive subscription: every observer (OneBotManager, NotificationManager,
* …) receives every session edge. (Was a single `set*Callback` setter —
* converted to N listeners so a second observer can't clobber the first.)
* The close edge now carries the bridge too, since callers read the last
* nickname before it is disposed. */
addSessionStartedListener(cb: SessionStartedCallback): void {
this.sessionStartedListeners_.push(cb);
}
addSessionClosedListener(cb: SessionClosedCallback): void {
this.sessionClosedListeners_.push(cb);
}
private fireSessionStarted(uin: string, bridge: Bridge): void {
for (const cb of this.sessionStartedListeners_) {
try {
cb(uin, bridge);
} catch (err) {
log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err));
}
/** Additive subscription: every observer (OneBotManager, NotificationManager,
* …) receives every session edge. (Was a single `set*Callback` setter —
* converted to N listeners so a second observer can't clobber the first.)
* The close edge now carries the bridge too, since callers read the last
* nickname before it is disposed. */
addSessionStartedListener(cb: SessionStartedCallback): void {
this.sessionStartedListeners_.push(cb);
}
}
private fireSessionClosed(uin: string, bridge: Bridge): void {
for (const cb of this.sessionClosedListeners_) {
try {
cb(uin, bridge);
} catch (err) {
log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err));
}
addSessionClosedListener(cb: SessionClosedCallback): void {
this.sessionClosedListeners_.push(cb);
}
}
onPidDisconnected(pid: number): void {
const uin = this.pidToUin_.get(pid);
if (!uin) return;
runWithTraceRequest(() => {
const startedAt = Date.now();
runtimeLog.trace(
'bridge_detach_start pid=%d uin=%j',
pid,
uin,
);
try {
const closed = this.detachPidFromSession(pid, uin);
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
if (closed) {
runtimeLog.trace(
'bridge_detach_branch pid=%d uin=%j branch=session_closed',
pid,
uin,
);
private fireSessionStarted(uin: string, bridge: Bridge): void {
for (const cb of this.sessionStartedListeners_) {
try {
cb(uin, bridge);
} catch (err) {
log.warn(
'session-started listener threw: %s',
err instanceof Error ? err.message : String(err),
);
}
}
runtimeLog.trace(
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
pid,
uin,
closed ? 'session_closed' : 'pid_detached',
activePid,
Date.now() - startedAt,
);
} catch (error) {
runtimeLog.trace(
'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d',
pid,
uin,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
const uin = this.pidToUin_.get(pid);
if (!uin) {
const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`;
log.error(message);
throw new Error(message);
}
const session = this.sessions_.get(uin);
if (!session || !session.bridge.hasPid(pid)) {
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
log.error(message);
throw new Error(message);
private fireSessionClosed(uin: string, bridge: Bridge): void {
for (const cb of this.sessionClosedListeners_) {
try {
cb(uin, bridge);
} catch (err) {
log.warn(
'session-closed listener threw: %s',
err instanceof Error ? err.message : String(err),
);
}
}
}
session.bridge.setPidReceiveHealthy(pid, healthy);
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!isRealUin(uin)) return;
onPidDisconnected(pid: number): void {
const uin = this.pidToUin_.get(pid);
runWithTraceRequest(() => {
const startedAt = Date.now();
const previousUin = this.pidToUin_.get(pid) ?? null;
runtimeLog.trace(
'bridge_binding_start pid=%d uin=%j source=login previousUin=%j',
pid,
uin,
previousUin,
);
if (!uin) {
return;
}
runWithTraceRequest(() => {
const startedAt = Date.now();
runtimeLog.trace('bridge_detach_start pid=%d uin=%j', pid, uin);
try {
const closed = this.detachPidFromSession(pid, uin);
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
if (closed) {
runtimeLog.trace(
'bridge_detach_branch pid=%d uin=%j branch=session_closed',
pid,
uin,
);
}
runtimeLog.trace(
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
pid,
uin,
closed ? 'session_closed' : 'pid_detached',
activePid,
Date.now() - startedAt,
);
} catch (error) {
runtimeLog.trace(
'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d',
pid,
uin,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
const uin = this.pidToUin_.get(pid);
if (!uin) {
const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`;
log.error(message);
throw new Error(message);
}
const session = this.sessions_.get(uin);
if (!session || !session.bridge.hasPid(pid)) {
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
log.error(message);
throw new Error(message);
}
session.bridge.setPidReceiveHealthy(pid, healthy);
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!isRealUin(uin)) {
return;
}
runWithTraceRequest(() => {
const startedAt = Date.now();
const previousUin = this.pidToUin_.get(pid) ?? null;
runtimeLog.trace(
'bridge_binding_start pid=%d uin=%j source=login previousUin=%j',
pid,
uin,
previousUin,
);
try {
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
if (previousUin && previousUin !== uin) {
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j',
pid,
uin,
previousUin,
);
const previousSession = this.sessions_.get(previousUin);
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
pid,
uin,
previousSession ? 'previous_session_retained' : 'previous_session_closed',
previousUin,
previousSession?.bridge.activePid ?? null,
);
}
if (created) {
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=session_created',
pid,
uin,
);
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
}
runtimeLog.trace(
'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d',
pid,
uin,
previousUin && previousUin !== uin ? 'rebound' : 'bound',
created,
session.bridge.activePid,
Date.now() - startedAt,
);
} catch (error) {
runtimeLog.trace(
'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d',
pid,
uin,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
onPacket(pkt: PacketInfo): void {
runWithTraceRequest(() => this.onPacketInContext(pkt));
}
private onPacketInContext(pkt: PacketInfo): void {
const startedAt = Date.now();
packetLog.trace(() => [
'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s',
pkt.serviceCmd,
pkt.seqId,
pkt.retCode,
pkt.fromClient,
pkt.pid,
pkt.uin,
pkt.body.byteLength,
renderTraceBytes(pkt.body),
]);
if (!pkt.uin || !isRealUin(pkt.uin)) {
packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
Date.now() - startedAt,
]);
return;
}
const uin = pkt.uin;
let completion: Promise<void>;
let handedToPipeline = false;
try {
// A packet may be the first trustworthy observation that a live PID moved
// to another UIN. Apply the exact same ownership transition as login so a
// PID can never remain attached to two Bridges.
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
const { session, created } = client
? this.bindPid(pkt.pid, uin, client, 'packet')
: this.ensureSession(uin);
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
}
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
// dispatch; its promise only marks completion of any async enrichment.
handedToPipeline = true;
completion = session.bridge.onPacket(pkt);
} catch (error) {
this.tracePacketFailure(
pkt,
startedAt,
handedToPipeline ? 'pipeline_failed' : 'routing_failed',
error,
);
throw error;
}
void completion.catch((error) => {
this.tracePacketFailure(pkt, startedAt, 'pipeline_failed', error);
});
}
private tracePacketFailure(
pkt: PacketInfo,
startedAt: number,
reason: 'routing_failed' | 'pipeline_failed',
error: unknown,
): void {
packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
reason,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
]);
log.error(
'packet %s failed for %s: %s',
reason === 'routing_failed' ? 'routing' : 'pipeline',
pkt.serviceCmd,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
/** Bind PID + sender as one state transition. If the PID changed accounts,
* the old Bridge is fully detached (and, when empty, closed) before the new
* Bridge is created. */
private bindPid(
pid: number,
uin: string,
packetClient: PacketSender,
source: 'login' | 'packet',
): { session: QQSession; created: boolean } {
const previousUin = this.pidToUin_.get(pid);
try {
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
if (previousUin && previousUin !== uin) {
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j',
pid,
uin,
previousUin,
);
const previousSession = this.sessions_.get(previousUin);
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
pid,
uin,
previousSession ? 'previous_session_retained' : 'previous_session_closed',
previousUin,
previousSession?.bridge.activePid ?? null,
);
log.warn(
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
pid,
previousUin,
uin,
source,
);
this.detachPidFromSession(pid, previousUin);
}
if (created) {
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=session_created',
pid,
uin,
);
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
const result = this.ensureSession(uin);
result.session.bridge.bindPid(pid, packetClient);
this.pidToUin_.set(pid, uin);
return result;
}
private packetClientForPid(pid: number): PacketSender | null {
const uin = this.pidToUin_.get(pid);
if (!uin) {
return null;
}
runtimeLog.trace(
'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d',
pid,
uin,
previousUin && previousUin !== uin ? 'rebound' : 'bound',
created,
session.bridge.activePid,
Date.now() - startedAt,
);
} catch (error) {
runtimeLog.trace(
'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d',
pid,
uin,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
onPacket(pkt: PacketInfo): void {
runWithTraceRequest(() => this.onPacketInContext(pkt));
}
const session = this.sessions_.get(uin);
private onPacketInContext(pkt: PacketInfo): void {
const startedAt = Date.now();
packetLog.trace(() => [
'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s',
pkt.serviceCmd,
pkt.seqId,
pkt.retCode,
pkt.fromClient,
pkt.pid,
pkt.uin,
pkt.body.byteLength,
renderTraceBytes(pkt.body),
]);
if (!pkt.uin || !isRealUin(pkt.uin)) {
packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
Date.now() - startedAt,
]);
return;
}
const uin = pkt.uin;
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
log.error(message);
throw new Error(message);
}
let completion: Promise<void>;
let handedToPipeline = false;
try {
// A packet may be the first trustworthy observation that a live PID moved
// to another UIN. Apply the exact same ownership transition as login so a
// PID can never remain attached to two Bridges.
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
const { session, created } = client
? this.bindPid(pkt.pid, uin, client, 'packet')
: this.ensureSession(uin);
const packetClient = session.bridge.packetClientForPid(pid);
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
}
if (packetClient) {
return packetClient;
}
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
// dispatch; its promise only marks completion of any async enrichment.
handedToPipeline = true;
completion = session.bridge.onPacket(pkt);
} catch (error) {
this.tracePacketFailure(
pkt,
startedAt,
handedToPipeline
? 'pipeline_failed'
: 'routing_failed',
error,
);
throw error;
}
void completion.catch((error) => {
this.tracePacketFailure(
pkt,
startedAt,
'pipeline_failed',
error,
);
});
}
private tracePacketFailure(
pkt: PacketInfo,
startedAt: number,
reason: 'routing_failed' | 'pipeline_failed',
error: unknown,
): void {
packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
reason,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
]);
log.error(
'packet %s failed for %s: %s',
reason === 'routing_failed'
? 'routing'
: 'pipeline',
pkt.serviceCmd,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
/** Bind PID + sender as one state transition. If the PID changed accounts,
* the old Bridge is fully detached (and, when empty, closed) before the new
* Bridge is created. */
private bindPid(
pid: number,
uin: string,
packetClient: PacketSender,
source: 'login' | 'packet',
): { session: QQSession; created: boolean } {
const previousUin = this.pidToUin_.get(pid);
if (previousUin && previousUin !== uin) {
log.warn(
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
pid,
previousUin,
uin,
source,
);
this.detachPidFromSession(pid, previousUin);
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
log.error(message);
throw new Error(message);
}
const result = this.ensureSession(uin);
result.session.bridge.bindPid(pid, packetClient);
this.pidToUin_.set(pid, uin);
return result;
}
private detachPidFromSession(pid: number, uin: string): boolean {
const mappedUin = this.pidToUin_.get(pid);
private packetClientForPid(pid: number): PacketSender | null {
const uin = this.pidToUin_.get(pid);
if (!uin) return null;
if (mappedUin !== uin) {
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
log.error(message);
throw new Error(message);
}
const session = this.sessions_.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
log.error(message);
throw new Error(message);
const session = this.sessions_.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
log.error(message);
throw new Error(message);
}
if (!session.bridge.hasPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
log.error(message);
throw new Error(message);
}
if (!session.bridge.packetClientForPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
log.error(message);
throw new Error(message);
}
// Validation is complete. Mutate both sides only after the ownership
// invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid);
session.bridge.detachPid(pid);
if (!session.bridge.empty) {
return false;
}
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge);
session.bridge.dispose();
return true;
}
const packetClient = session.bridge.packetClientForPid(pid);
if (packetClient) return packetClient;
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
log.error(message);
throw new Error(message);
}
if (session) {
return { session, created: false };
}
private detachPidFromSession(pid: number, uin: string): boolean {
const mappedUin = this.pidToUin_.get(pid);
if (mappedUin !== uin) {
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
log.error(message);
throw new Error(message);
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
}
const session = this.sessions_.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
log.error(message);
throw new Error(message);
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
if (!session.bridge.hasPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
log.error(message);
throw new Error(message);
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
}
if (!session.bridge.packetClientForPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
log.error(message);
throw new Error(message);
}
// Validation is complete. Mutate both sides only after the ownership
// invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid);
session.bridge.detachPid(pid);
if (!session.bridge.empty) return false;
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge);
session.bridge.dispose();
return true;
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
}
}