Add a read-only action for querying QQ profile decorations from the authenticated web page. Validate and classify page responses, expose structured errors, and cover parsing with a sanitized fixture.
433 lines
16 KiB
TypeScript
433 lines
16 KiB
TypeScript
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||
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 { getFriendDressWebAPI, type WebFriendDress } from '@snowluma/protocol/web/friend-dress';
|
||
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,
|
||
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; }
|
||
|
||
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[];
|
||
}
|
||
|
||
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; height: number; width: number }>;
|
||
images: Array<{ id: 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;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
function collectionValues(
|
||
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);
|
||
}
|
||
|
||
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`);
|
||
}
|
||
return {
|
||
id: 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;
|
||
}
|
||
}
|
||
};
|
||
|
||
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);
|
||
}
|
||
|
||
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);
|
||
|
||
// 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);
|
||
|
||
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;
|
||
}
|
||
|
||
async function getSKey(bridge: Bridge): Promise<string> {
|
||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||
|
||
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 cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||
const skey = cookies['skey'];
|
||
|
||
if (!skey) {
|
||
throw new Error('SKey is Empty');
|
||
}
|
||
|
||
return skey;
|
||
}
|
||
|
||
/**
|
||
* Standard QQ bkn hash (also known as token / csrf_token) derived from
|
||
* 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;
|
||
}
|
||
|
||
export class WebApi {
|
||
constructor(private readonly ctx: BridgeContext) { }
|
||
|
||
// ─────────────── 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;
|
||
}
|
||
}
|
||
|
||
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());
|
||
}
|
||
}
|