Merge pull request #9 from H3CoF6/feat/onebot
implement some onebot api
This commit is contained in:
@@ -7,6 +7,10 @@ node_modules/
|
||||
dist/
|
||||
**/dist/
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
/config/
|
||||
/data/
|
||||
|
||||
# macOS metadata
|
||||
.DS_Store
|
||||
|
||||
@@ -43,6 +43,10 @@ import {
|
||||
NTV2RichMediaRespSchema,
|
||||
GroupRecallRequestSchema,
|
||||
C2CRecallRequestSchema,
|
||||
SsoReadedReportReqSchema,
|
||||
SetStatusReqSchema,
|
||||
SetStatusRespSchema,
|
||||
OidbSetProfileSchema,
|
||||
} from './proto/oidb-action';
|
||||
import { FileUploadExtSchema } from './proto/highway';
|
||||
import {
|
||||
@@ -1242,3 +1246,116 @@ export async function recallPrivateMessage(
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
|
||||
}
|
||||
|
||||
// --- Mark message as read ---
|
||||
|
||||
export async function markPrivateMessageRead(
|
||||
bridge: Bridge,
|
||||
userId: number,
|
||||
msgSeq: number,
|
||||
timestamp: number = Math.floor(Date.now() / 1000)
|
||||
): Promise<void> {
|
||||
const uid = await resolveUserUid(bridge, userId);
|
||||
|
||||
const request = protoEncode({
|
||||
c2cList: [
|
||||
{
|
||||
uid,
|
||||
lastReadTime: BigInt(timestamp),
|
||||
lastReadSeq: BigInt(msgSeq),
|
||||
}
|
||||
]
|
||||
}, SsoReadedReportReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark private message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function markGroupMessageRead(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
msgSeq: number
|
||||
): Promise<void> {
|
||||
const request = protoEncode({
|
||||
groupList: [
|
||||
{
|
||||
groupUin: BigInt(groupId),
|
||||
lastReadSeq: BigInt(msgSeq),
|
||||
}
|
||||
]
|
||||
}, SsoReadedReportReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark group message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function setOnlineStatus(
|
||||
bridge: Bridge,
|
||||
status: number,
|
||||
extStatus: number = 0,
|
||||
batteryStatus: number = 100
|
||||
): Promise<void> {
|
||||
const request = protoEncode({
|
||||
status,
|
||||
extStatus,
|
||||
batteryStatus,
|
||||
}, SetStatusReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const resp = protoDecode(result.responseData, SetStatusRespSchema);
|
||||
if (!resp) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
if (resp.errCode !== undefined && resp.errCode !== 0) {
|
||||
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function setProfile(
|
||||
bridge: Bridge,
|
||||
nickname?: string,
|
||||
personalNote?: string
|
||||
): Promise<void> {
|
||||
const uin = BigInt(bridge.qqInfo.uin);
|
||||
const stringProfiles: any[] = [];
|
||||
const intProfiles: any[] = [];
|
||||
|
||||
if (nickname !== undefined) {
|
||||
stringProfiles.push({ fieldId: 20002, value: nickname });
|
||||
}
|
||||
|
||||
if (personalNote !== undefined) {
|
||||
stringProfiles.push({ fieldId: 102, value: personalNote });
|
||||
}
|
||||
|
||||
if (stringProfiles.length === 0 && intProfiles.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const req = {
|
||||
uin,
|
||||
stringProfiles,
|
||||
};
|
||||
|
||||
await sendOidbAndCheck(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x112a_2',
|
||||
0x112A,
|
||||
2,
|
||||
req,
|
||||
OidbSetProfileSchema
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
fetchGroupRequests as fetchGroupRequests_,
|
||||
fetchDownloadRKeys as fetchDownloadRKeys_,
|
||||
} from './bridge-contacts';
|
||||
import type { WebHonorType } from './web/group-honor';
|
||||
import {
|
||||
muteGroupMember as muteGroupMember_,
|
||||
muteGroupAll as muteGroupAll_,
|
||||
@@ -60,9 +61,24 @@ import {
|
||||
setGroupReaction as setGroupReaction_,
|
||||
recallGroupMessage as recallGroupMessage_,
|
||||
recallPrivateMessage as recallPrivateMessage_,
|
||||
markPrivateMessageRead as markGroupMsgAsRead_,
|
||||
markGroupMessageRead as markPrivateMsgAsRead_,
|
||||
setFriendRemark as setFriendRemark_,
|
||||
fetchGroupFileCount as fetchGroupFileCount_,
|
||||
setOnlineStatus as setOnlineStatus_,
|
||||
setProfile as setProfile_,
|
||||
} from './bridge-actions';
|
||||
import {
|
||||
getGroupHonorInfo as getGroupHonorInfo_,
|
||||
forceFetchClientKey as forceFetchClientKey_,
|
||||
getGroupEssence as getGroupEssence_,
|
||||
getGroupEssenceAll as getGroupEssenceAll_,
|
||||
sendGroupNotice as sendGroupNotice_,
|
||||
getGroupNotice as getGroupNotice_,
|
||||
getCookiesStr as getCookiesStr_,
|
||||
getCsrfToken as getCsrfToken_,
|
||||
getCredentials as getCredentials_,
|
||||
} from './web-actions';
|
||||
import type { GroupFilesResult } from './bridge-actions';
|
||||
import type { MediaIndexNode } from './bridge-actions';
|
||||
|
||||
@@ -86,6 +102,12 @@ export interface DownloadRKeyInfo {
|
||||
type: number;
|
||||
}
|
||||
|
||||
export interface ClientKeyInfo {
|
||||
clientKey: string;
|
||||
expireTime: string;
|
||||
keyIndex: string
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const eventLog = createLogger('Event');
|
||||
|
||||
@@ -445,8 +467,42 @@ export class Bridge {
|
||||
async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> { return setGroupReaction_(this, groupId, sequence, code, isSet); }
|
||||
async recallGroupMessage(groupId: number, sequence: number): Promise<void> { return recallGroupMessage_(this, groupId, sequence); }
|
||||
async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void> { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); }
|
||||
async markGroupMsgAsRead(groupId: number, sequence: number): Promise<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
|
||||
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
|
||||
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
|
||||
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
|
||||
return getGroupHonorInfo_(this, groupId, type);
|
||||
}
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> { return forceFetchClientKey_(this)}
|
||||
async getGroupEssence(groupId: number, pageStart: number = 0, pageLimit: number = 50): Promise<any> {
|
||||
return getGroupEssence_(this, groupId, pageStart, pageLimit);
|
||||
}
|
||||
|
||||
async getGroupEssenceAll(groupId: number): Promise<any> {
|
||||
return getGroupEssenceAll_(this, groupId);
|
||||
}
|
||||
|
||||
async sendGroupNotice(groupId: number, content: string, options?: any) {
|
||||
return sendGroupNotice_(this, groupId, content, options);
|
||||
}
|
||||
|
||||
async getGroupNotice(groupId: number) {
|
||||
return getGroupNotice_(this, groupId);
|
||||
}
|
||||
|
||||
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
|
||||
|
||||
// extend
|
||||
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
|
||||
return setOnlineStatus_(this, status, extStatus, batteryStatus);
|
||||
}
|
||||
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
|
||||
return setProfile_(this, nickname, personalNote);
|
||||
}
|
||||
async getCookiesStr(domain: string): Promise<string> { return getCookiesStr_(this, domain); }
|
||||
async getCsrfToken(): Promise<number> { return getCsrfToken_(this); }
|
||||
async getCredentials(domain: string) { return getCredentials_(this, domain); }
|
||||
|
||||
}
|
||||
|
||||
// --- Module-level helper functions ---
|
||||
|
||||
@@ -786,3 +786,80 @@ export const OidbGroupFileCountViewReqSchema = {
|
||||
export const OidbGroupFileCountViewRespSchema = {
|
||||
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- trpc.msg.msg_svc.MsgService.SsoReadedReport ---
|
||||
|
||||
export const GroupReadedReportItemSchema = {
|
||||
groupUin: { field: 1, type: 'uint64' as const },
|
||||
lastReadSeq: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const C2CReadedReportItemSchema = {
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
lastReadTime: { field: 3, type: 'uint64' as const },
|
||||
lastReadSeq: { field: 4, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SsoReadedReportReqSchema = {
|
||||
groupList: { field: 1, type: 'repeated_message' as const, schema: GroupReadedReportItemSchema },
|
||||
c2cList: { field: 2, type: 'repeated_message' as const, schema: C2CReadedReportItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- 0x102A_1: Get Client Key ---
|
||||
|
||||
export const OidbClientKeyReqSchema = {
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbClientKeyRespSchema = {
|
||||
keyIndex: { field: 2, type: 'uint32' as const },
|
||||
clientKey: { field: 3, type: 'string' as const },
|
||||
expireTime: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- 0x102A_0: Get PSKey ---
|
||||
|
||||
export const OidbGetPskeyReqSchema = {
|
||||
domainList: { field: 1, type: 'repeated_string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPskeyItemSchema = {
|
||||
domain: { field: 1, type: 'string' as const },
|
||||
pskey: { field: 2, type: 'string' as const },
|
||||
expireTime: { field: 3, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGetPskeyRespSchema = {
|
||||
pskeyItems: { field: 1, type: 'repeated_message' as const, schema: OidbPskeyItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
export const SetStatusReqSchema = {
|
||||
status: { field: 1, type: 'int32' as const },
|
||||
extStatus: { field: 2, type: 'int32' as const },
|
||||
batteryStatus: { field: 3, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SetStatusRespSchema = {
|
||||
errCode: { field: 1, type: 'int32' as const }, // 盲猜字段 1 是错误码(虽然成功时没下发,默认 0)
|
||||
errMsg: { field: 2, type: 'string' as const }, // 返回的 "set status success"
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
export const OidbProfileStringItemSchema = {
|
||||
fieldId: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbProfileIntItemSchema = {
|
||||
fieldId: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSetProfileSchema = {
|
||||
uin: { field: 1, type: 'uint64' as const },
|
||||
stringProfiles: { field: 2, type: 'repeated_message' as const, schema: OidbProfileStringItemSchema },
|
||||
intProfiles: { field: 3, type: 'repeated_message' as const, schema: OidbProfileIntItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -0,0 +1,315 @@
|
||||
// Web API operations extracted from Bridge.
|
||||
|
||||
import type { Bridge } from './bridge';
|
||||
import { sendOidbAndDecode } from './bridge-oidb';
|
||||
import { resolveUserUid } from './bridge-oidb';
|
||||
import {
|
||||
OidbClientKeyRespSchema,
|
||||
OidbClientKeyReqSchema,
|
||||
OidbGetPskeyReqSchema,
|
||||
OidbGetPskeyRespSchema
|
||||
} from './proto/oidb-action';
|
||||
import { RequestUtil } from './web/request-util';
|
||||
import { getHonorListWebAPI, WebHonorType } from './web/group-honor';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from './web/group-essence';
|
||||
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI } from './web/group-notice';
|
||||
|
||||
export async function forceFetchClientKey(bridge: Bridge) {
|
||||
const resp = await sendOidbAndDecode<any>(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x102a_1',
|
||||
0x102A,
|
||||
1,
|
||||
{},
|
||||
OidbClientKeyReqSchema,
|
||||
OidbClientKeyRespSchema
|
||||
);
|
||||
|
||||
const clientKey = resp?.clientKey || '';
|
||||
const keyIndex = String(resp?.keyIndex || '19'); // 不知道是什么
|
||||
|
||||
return {
|
||||
clientKey,
|
||||
keyIndex,
|
||||
expireTime: String(resp?.expireTime || '1800')
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPSkey(bridge: Bridge, domainList: string[]) {
|
||||
const resp = await sendOidbAndDecode<any>(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x102a_0',
|
||||
0x102A,
|
||||
0,
|
||||
{ domainList },
|
||||
OidbGetPskeyReqSchema,
|
||||
OidbGetPskeyRespSchema
|
||||
);
|
||||
|
||||
const domainPskeyMap = new Map<string, string>();
|
||||
|
||||
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
|
||||
for (const item of resp.pskeyItems) {
|
||||
if (item.domain && item.pskey) {
|
||||
domainPskeyMap.set(item.domain, item.pskey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
domainPskeyMap,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCookies(bridge: Bridge, domain: string) {
|
||||
const ClientKeyData = await forceFetchClientKey(bridge);
|
||||
|
||||
// 构造 ptlogin2 跳转 URL
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
if (!data['p_skey'] || data['p_skey'].length === 0) {
|
||||
try {
|
||||
const pskeyData = await getPSkey(bridge, [domain]);
|
||||
const pskey = pskeyData.domainPskeyMap.get(domain);
|
||||
if (pskey) {
|
||||
data['p_skey'] = pskey;
|
||||
}
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const honorInfo: any = {
|
||||
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;
|
||||
}
|
||||
|
||||
export async function getSKey(bridge: Bridge): Promise<string> {
|
||||
const ClientKeyData = await forceFetchClientKey(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.qqInfo.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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
export async function getGroupEssence(bridge: Bridge, groupId: number, pageStart: number = 0, pageLimit: number = 50) {
|
||||
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: [] } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息
|
||||
*/
|
||||
export async function getGroupEssenceAll(bridge: Bridge, groupId: number) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const essenceDataAll = await getGroupEssenceMsgAll(cookieObject, groupCode);
|
||||
|
||||
return essenceDataAll;
|
||||
}
|
||||
|
||||
export async function sendGroupNotice(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: {
|
||||
image?: string; // 未来如果要发图片,传路径进来
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
confirm_required?: number;
|
||||
}
|
||||
) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
let picId = '';
|
||||
let imgWidth = 540;
|
||||
let imgHeight = 300;
|
||||
|
||||
|
||||
// 暂时不知道怎么实现,后面有空再看看
|
||||
|
||||
// if (options?.image) {
|
||||
// const picInfo = await bridge.uploadGroupBulletinPic(groupCode, options.image);
|
||||
// picId = picInfo.id;
|
||||
// imgWidth = picInfo.width;
|
||||
// imgHeight = picInfo.height;
|
||||
// }
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
options?.pinned ?? 0,
|
||||
options?.type ?? 1,
|
||||
1,
|
||||
1,
|
||||
options?.confirm_required ?? 1,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight
|
||||
);
|
||||
|
||||
if (!ret || ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
export async function getGroupNotice(bridge: Bridge, groupId: number) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||
if (!ret) {
|
||||
throw new Error('获取公告失败');
|
||||
}
|
||||
|
||||
const retNotices: any[] = [];
|
||||
|
||||
if (ret.feeds) {
|
||||
for (const key in ret.feeds) {
|
||||
const feed = ret.feeds[key];
|
||||
if (!feed) continue;
|
||||
|
||||
const image = feed.msg?.pics?.map((pic) => ({
|
||||
id: pic.id,
|
||||
height: pic.h,
|
||||
width: pic.w,
|
||||
})) || [];
|
||||
|
||||
retNotices.push({
|
||||
notice_id: feed.fid,
|
||||
sender_id: feed.u,
|
||||
publish_time: feed.pubt,
|
||||
message: {
|
||||
text: feed.msg?.text || '',
|
||||
image: image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: feed.read_num,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retNotices;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取的公共算法:根据 skey/p_skey 计算 bkn (也就是 token / csrf_token)
|
||||
*/
|
||||
export 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Cookies (字符串格式)
|
||||
*/
|
||||
export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> {
|
||||
const cookieObject = await getCookies(bridge, domain);
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 CSRF Token (即 BKN)
|
||||
*/
|
||||
export async function getCsrfToken(bridge: Bridge): Promise<number> {
|
||||
|
||||
const skey = await getSKey(bridge);
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取凭证 (Cookies 字符串 + Token)
|
||||
*/
|
||||
export async function getCredentials(bridge: Bridge, domain: string) {
|
||||
const cookieObject = await getCookies(bridge, 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: token,
|
||||
csrf_token: token
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
|
||||
// 定义接口返回类型
|
||||
export interface GroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
data: {
|
||||
is_end: boolean;
|
||||
msg_list: any[]; // 具体结构视需要补充
|
||||
[key: string]: any;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
export async function getGroupEssenceMsg(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
pageStart: number = 0,
|
||||
pageLimit: number = 50
|
||||
): Promise<GroupEssenceMsgRet | undefined> {
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
|
||||
bkn: bkn,
|
||||
page_start: pageStart.toString(),
|
||||
page_limit: pageLimit.toString(),
|
||||
group_code: groupCode,
|
||||
}).toString()}`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息 (最多循环 20 页)
|
||||
*/
|
||||
export async function getGroupEssenceMsgAll(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
): Promise<GroupEssenceMsgRet[]> {
|
||||
const ret: GroupEssenceMsgRet[] = [];
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
|
||||
|
||||
if (!data) break;
|
||||
|
||||
ret.push(data);
|
||||
|
||||
if (data.data?.is_end) break;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
|
||||
export enum WebHonorType {
|
||||
TALKATIVE = 'talkative',
|
||||
PERFORMER = 'performer',
|
||||
LEGEND = 'legend',
|
||||
EMOTION = 'emotion',
|
||||
ALL = 'all',
|
||||
}
|
||||
|
||||
|
||||
async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
let resJson;
|
||||
try {
|
||||
const res = await RequestUtil.HttpGetText(
|
||||
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
|
||||
gc: groupCode,
|
||||
type: type.toString(),
|
||||
}).toString()}`,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
|
||||
if (match?.[1]) {
|
||||
resJson = JSON.parse(match[1].trim());
|
||||
}
|
||||
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
|
||||
} catch (e) {
|
||||
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
try {
|
||||
const data = await fetchHonorData(cookieObject, groupCode, type);
|
||||
if (!data) return [];
|
||||
|
||||
return data.map((item: any) => ({
|
||||
user_id: item?.uin,
|
||||
nickname: item?.name,
|
||||
avatar: item?.avatar,
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
// console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec?: number;
|
||||
em?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeFeed {
|
||||
fid: string;
|
||||
u: number;
|
||||
pubt: number;
|
||||
msg: {
|
||||
text: string;
|
||||
pics?: Array<{ id: string; w: number; h: number }>;
|
||||
};
|
||||
settings: any;
|
||||
read_num: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeRet {
|
||||
ec: number;
|
||||
em?: string;
|
||||
feeds?: Record<string, WebApiGroupNoticeFeed>;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送群公告 Web API
|
||||
*/
|
||||
export async function setGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
content: string,
|
||||
pinned: number = 0,
|
||||
type: number = 1,
|
||||
isShowEditCard: number = 1,
|
||||
tipWindowType: number = 1,
|
||||
confirmRequired: number = 1,
|
||||
picId: string = '',
|
||||
imgWidth: number = 540,
|
||||
imgHeight: number = 300
|
||||
): Promise<SetNoticeRetSuccess | undefined> {
|
||||
try {
|
||||
const settings = JSON.stringify({
|
||||
is_show_edit_card: isShowEditCard,
|
||||
tip_window_type: tipWindowType,
|
||||
confirm_required: confirmRequired,
|
||||
});
|
||||
|
||||
const externalParam = {
|
||||
pic: picId,
|
||||
imgWidth: imgWidth.toString(),
|
||||
imgHeight: imgHeight.toString(),
|
||||
};
|
||||
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?${new URLSearchParams({
|
||||
bkn: getBknFromCookie(cookieObject),
|
||||
qid: groupCode,
|
||||
text: content,
|
||||
pinned: pinned.toString(),
|
||||
type: type.toString(),
|
||||
settings,
|
||||
...(picId === '' ? {} : externalParam),
|
||||
}).toString()}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST', // 注意这里必须是 POST
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
): Promise<WebApiGroupNoticeRet | undefined> {
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
|
||||
const params = new URLSearchParams({
|
||||
bkn: bkn,
|
||||
qid: groupCode,
|
||||
ft: '23',
|
||||
ni: '1',
|
||||
i: '1',
|
||||
log_read: '1',
|
||||
platform: '1',
|
||||
s: '-1',
|
||||
}).toString();
|
||||
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/get_t_list?${params}&n=20`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import https from 'node:https';
|
||||
import http from 'node:http';
|
||||
|
||||
export class RequestUtil {
|
||||
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
|
||||
const client = url.startsWith('https') ? https : http;
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = client.get(url, (res) => {
|
||||
const cookies: { [key: string]: string; } = {};
|
||||
|
||||
res.on('data', () => { }); // 必须消耗流
|
||||
res.on('end', () => {
|
||||
this.handleRedirect(res, url, cookies)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
|
||||
if (res.headers['set-cookie']) {
|
||||
this.extractCookies(res.headers['set-cookie'], cookies);
|
||||
}
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
|
||||
if (res.statusCode === 301 || res.statusCode === 302) {
|
||||
if (res.headers.location) {
|
||||
const redirectUrl = new URL(res.headers.location, url);
|
||||
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
|
||||
return { ...cookies, ...redirectCookies };
|
||||
}
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
|
||||
setCookieHeaders.forEach((cookie) => {
|
||||
const parts = cookie.split(';')[0]?.split('=');
|
||||
if (parts) {
|
||||
const key = parts[0];
|
||||
const value = parts[1];
|
||||
if (key && value && key.length > 0 && value.length > 0) {
|
||||
cookies[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: {
|
||||
[key: string]: string;
|
||||
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
|
||||
const option = new URL(url);
|
||||
const protocol = url.startsWith('https://') ? https : http;
|
||||
const options = {
|
||||
hostname: option.hostname,
|
||||
port: option.port,
|
||||
path: option.pathname + option.search,
|
||||
method,
|
||||
headers,
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = protocol.request(options, (res: http.IncomingMessage) => {
|
||||
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
|
||||
if (maxRedirects <= 0) {
|
||||
reject(new Error('Too many redirects'));
|
||||
return;
|
||||
}
|
||||
const redirectUrl = new URL(res.headers.location, url).href;
|
||||
this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
let responseBody = '';
|
||||
res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
|
||||
|
||||
res.on('end', () => {
|
||||
try {
|
||||
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
|
||||
if (isJsonRet) {
|
||||
resolve(JSON.parse(responseBody) as T);
|
||||
} else {
|
||||
resolve(responseBody as T);
|
||||
}
|
||||
} else {
|
||||
reject(new Error(`Unexpected status code: ${res.statusCode}`));
|
||||
}
|
||||
} catch (parseError: any) {
|
||||
reject(new Error(parseError.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => reject(error));
|
||||
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
|
||||
req.write(isArgJson ? JSON.stringify(data) : data);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
|
||||
return this.HttpGetJson<string>(url, method, data, headers, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
export function cookieToString(cookieObject: Record<string, string>): string {
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
|
||||
export function getBknFromCookie(cookieObject: Record<string, string>): string {
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return (hash & 2147483647).toString();
|
||||
}
|
||||
@@ -71,9 +71,20 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_essence_msg_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
// Essence list fetch requires web ticket/cookie flow not wired yet.
|
||||
// Keep API-compatible output shape for callers.
|
||||
return okResponse([]);
|
||||
|
||||
if (!ctx.getGroupEssenceAll) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
const essenceDataAll = await ctx.getGroupEssenceAll(groupId);
|
||||
|
||||
const allMsgs = essenceDataAll.flatMap(res => res.data?.msg_list || []);
|
||||
|
||||
return okResponse(allMsgs);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `获取精华消息失败: ${e}`);
|
||||
}
|
||||
});
|
||||
|
||||
// --- Reactions ---
|
||||
@@ -124,10 +135,80 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
h.registerAction('mark_msg_as_read', async () => {
|
||||
h.registerAction('mark_group_msg_as_read', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const groupId = asNumber(params.group_id);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message');
|
||||
}
|
||||
|
||||
if (groupId && groupId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
|
||||
}
|
||||
|
||||
if (!ctx.markGroupMsgAsRead) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
await ctx.markGroupMsgAsRead(groupId, meta.sequence);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_private_msg_as_read', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
if (!meta || meta.isGroup) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message');
|
||||
}
|
||||
|
||||
if (userId && userId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session');
|
||||
}
|
||||
|
||||
if (!ctx.markPrivateMsgAsRead) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
await ctx.markPrivateMsgAsRead(userId, meta.sequence);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_msg_as_read', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const targetId = asNumber(params.target_id);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
|
||||
if (targetId && targetId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session');
|
||||
}
|
||||
|
||||
if (!(ctx.markPrivateMsgAsRead && ctx.markGroupMsgAsRead)) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
if (meta.isGroup) {
|
||||
await ctx.markGroupMsgAsRead(targetId, meta.sequence);
|
||||
} else {
|
||||
await ctx.markPrivateMsgAsRead(targetId, meta.sequence);
|
||||
}
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
|
||||
// --- RKey ---
|
||||
|
||||
h.registerAction('get_rkey', async () => {
|
||||
@@ -149,12 +230,51 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
// --- Group notice stubs ---
|
||||
|
||||
h.registerAction('_send_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('_send_group_notice', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const content = asString(params.content);
|
||||
const image = asString(params.image);
|
||||
|
||||
if (!groupId || !content) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and content are required');
|
||||
}
|
||||
|
||||
if (image) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented: image upload for group notice is not supported yet');
|
||||
}
|
||||
|
||||
if (!ctx.sendGroupNotice) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
const options = {
|
||||
pinned: params.pinned !== undefined ? Number(params.pinned) : 0,
|
||||
type: params.type !== undefined ? Number(params.type) : 1,
|
||||
confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1,
|
||||
};
|
||||
|
||||
await ctx.sendGroupNotice(groupId, content, options);
|
||||
return okResponse();
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('_get_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('_get_group_notice', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
|
||||
if (!ctx.getGroupNotice) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
const notices = await ctx.getGroupNotice(groupId);
|
||||
return okResponse(notices);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('_del_group_notice', async () => {
|
||||
@@ -293,18 +413,42 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
// --- Credentials ---
|
||||
|
||||
h.registerAction('get_cookies', async () => {
|
||||
return okResponse({ cookies: '' });
|
||||
h.registerAction('get_cookies', async (params) => {
|
||||
const domain = asString(params.domain) || 'qun.qq.com';
|
||||
|
||||
if (!ctx.getCookiesStr) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
try {
|
||||
const cookies = await ctx.getCookiesStr(domain);
|
||||
return okResponse({ cookies });
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_csrf_token', async () => {
|
||||
return okResponse({ token: 0 });
|
||||
if (!ctx.getCsrfToken) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
try {
|
||||
const token = await ctx.getCsrfToken();
|
||||
return okResponse({ token });
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_credentials', async () => {
|
||||
return okResponse({ cookies: '', csrf_token: 0 });
|
||||
});
|
||||
h.registerAction('get_credentials', async (params) => {
|
||||
const domain = asString(params.domain) || 'qun.qq.com';
|
||||
|
||||
if (!ctx.getCredentials) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
try {
|
||||
const creds = await ctx.getCredentials(domain);
|
||||
return okResponse(creds);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
// --- Utility ---
|
||||
|
||||
h.registerAction('set_restart', async () => {
|
||||
@@ -347,13 +491,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_private_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_group_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('_mark_all_as_read', async () => {
|
||||
return okResponse();
|
||||
@@ -414,12 +551,44 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse({ file: pathMod.resolve(filePath) });
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_profile', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('set_qq_profile', async (params) => {
|
||||
|
||||
const nickname = params.nickname !== undefined ? asString(params.nickname) : undefined;
|
||||
const personalNote = params.personal_note !== undefined ? asString(params.personal_note) : undefined;
|
||||
|
||||
if (!ctx.setProfile) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.setProfile(nickname, personalNote);
|
||||
return okResponse();
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('set_online_status', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('set_online_status', async (params) => {
|
||||
// 按 OneBot/NapCat 习惯提取参数,状态码默认为 11
|
||||
const status = asNumber(params.status);
|
||||
const extStatus = asNumber(params.ext_status) || 0;
|
||||
const batteryStatus = asNumber(params.battery_status) || 100;
|
||||
|
||||
// 参数校验
|
||||
if (status === undefined || status === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'status is required');
|
||||
}
|
||||
|
||||
if (!ctx.setOnlineStatus) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.setOnlineStatus(status, extStatus, batteryStatus);
|
||||
return okResponse();
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_ignored_notifies', async () => {
|
||||
@@ -504,7 +673,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
});
|
||||
|
||||
h.registerAction('get_clientkey', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
if (!ctx.forceFetchClientKey) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
}
|
||||
const clientKeyInfo = await ctx.forceFetchClientKey();
|
||||
if (!clientKeyInfo.clientKey) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error');
|
||||
}
|
||||
return okResponse(clientKeyInfo);
|
||||
});
|
||||
|
||||
h.registerAction('get_mini_app_ark', async () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean } from '../api-handler';
|
||||
import { asNumber, asBoolean, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { WebHonorType } from '@/bridge/web/group-honor';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_list', async (params) => {
|
||||
@@ -54,11 +55,27 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
h.registerAction('get_group_honor_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
return okResponse({
|
||||
group_id: groupId, current_talkative: null, talkative_list: [],
|
||||
performer_list: [], legend_list: [], strong_newbie_list: [], emotion_list: [],
|
||||
});
|
||||
const typeStr = asString(params.type) || 'all';
|
||||
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
|
||||
if (!ctx.getGroupHonorInfo) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
}
|
||||
|
||||
const typeValues = Object.values(WebHonorType) as string[];
|
||||
if (!typeValues.includes(typeStr)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const honorInfo = await ctx.getGroupHonorInfo(groupId, typeStr as WebHonorType);
|
||||
return okResponse(honorInfo);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_system_msg', async () => {
|
||||
|
||||
@@ -10,12 +10,25 @@ import { register as registerGroupFile } from './actions/group-file';
|
||||
import { register as registerRequest } from './actions/request';
|
||||
import { register as registerExtended } from './actions/extended';
|
||||
|
||||
import { WebHonorType } from '@/bridge/web/group-honor';
|
||||
// import {ClientKeyInfo} from "@/bridge/bridge";
|
||||
|
||||
export interface MessageSendResult {
|
||||
messageId: number;
|
||||
meta?: MessageMeta;
|
||||
echoEvent?: JsonObject;
|
||||
}
|
||||
|
||||
export interface GroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
data: {
|
||||
is_end: boolean;
|
||||
msg_list: any[];
|
||||
[key: string]: any;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface ApiActionContext {
|
||||
getLoginInfo: () => { userId: number; nickname: string };
|
||||
isOnline: () => boolean;
|
||||
@@ -62,6 +75,9 @@ export interface ApiActionContext {
|
||||
sendGroupPoke?: (groupId: number, userId: number) => Promise<void>;
|
||||
setEssenceMsg?: (messageId: number) => Promise<void>;
|
||||
deleteEssenceMsg?: (messageId: number) => Promise<void>;
|
||||
forceFetchClientKey? : () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
|
||||
setOnlineStatus?: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
|
||||
setProfile?: (nickname?: string, personalNote?: string) => Promise<void>;
|
||||
// New context methods
|
||||
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
|
||||
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
|
||||
@@ -78,6 +94,17 @@ export interface ApiActionContext {
|
||||
setFriendRemark?: (userId: number, remark: string) => Promise<void>;
|
||||
getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
|
||||
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
|
||||
markGroupMsgAsRead?: (groupId: number, sequence: number) => Promise<void>;
|
||||
markPrivateMsgAsRead?: (userId: number, sequence: number) => Promise<void>;
|
||||
// Web
|
||||
getGroupHonorInfo?: (groupId: number, type: WebHonorType | string) => Promise<any>;
|
||||
getGroupEssence?: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
|
||||
getGroupEssenceAll?: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
|
||||
sendGroupNotice?: (groupId: number, content: string, options?: any) => Promise<any>;
|
||||
getGroupNotice?: (groupId: number) => Promise<any[]>;
|
||||
getCookiesStr?: (domain: string) => Promise<string>;
|
||||
getCsrfToken?: () => Promise<number>;
|
||||
getCredentials?: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
|
||||
}
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
@@ -8,6 +8,7 @@ import { parseMessage } from './message-parser';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import {WebHonorType} from "@/bridge/web/group-honor";
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
@@ -111,6 +112,8 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||
getForwardMsg: async (resId) => {
|
||||
return handleGetForward(ref, resId);
|
||||
},
|
||||
forceFetchClientKey: async () => bridge.forceFetchClientKey(),
|
||||
|
||||
// Extended NapCat-compatible
|
||||
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
|
||||
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
|
||||
@@ -119,6 +122,19 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
|
||||
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
|
||||
},
|
||||
markGroupMsgAsRead: (groupId: number, sequence: number) => bridge.markGroupMsgAsRead(groupId, sequence),
|
||||
markPrivateMsgAsRead: (userId: number, sequence: number) => bridge.markPrivateMsgAsRead(userId, sequence),
|
||||
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
|
||||
setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote),
|
||||
// web
|
||||
getGroupHonorInfo: (groupId: number, type: WebHonorType | string)=> bridge.getGroupHonorInfo(groupId, type),
|
||||
getGroupEssence: (groupId: number, pageStart: number = 0, pageLimit: number = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
|
||||
getGroupEssenceAll: (groupId: number) => bridge.getGroupEssenceAll(groupId),
|
||||
sendGroupNotice: (groupId: number, content: string, options?: any) => bridge.sendGroupNotice(groupId, content, options),
|
||||
getGroupNotice: (groupId: number) => bridge.getGroupNotice(groupId),
|
||||
getCookiesStr: (domain: string) => bridge.getCookiesStr(domain),
|
||||
getCsrfToken: () => bridge.getCsrfToken(),
|
||||
getCredentials: (domain: string) => bridge.getCredentials(domain),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -43,8 +43,8 @@ export const PASSWORD_RULES: PasswordRule[] = [
|
||||
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
|
||||
];
|
||||
|
||||
export function evaluatePasswordRules(password: string): { id: string; label: string; met: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, met: r.test(password) }));
|
||||
export function evaluatePasswordRules(password: string): { id: string; label: string; ok: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
|
||||
}
|
||||
|
||||
export function isStrongPassword(password: string): boolean {
|
||||
|
||||
Reference in New Issue
Block a user