Apply formatting and fix web request utilities
Add consistent indent rule to ESLint and normalize formatting/indentation across multiple files. Refactor RequestUtil: improve cookie extraction, redirect handling, and HttpGetJson/HttpGetText request flow; fix cookie string builder formatting. Fix uploadGroupNoticeImage promise/error handling and network request flow. Also apply minor style/refactor tweaks in bridge web APIs, onebot handlers, message-store SQL alignment, and Proton AST collector utilities to improve readability and correctness.
This commit is contained in:
1 parent
aea2676c31
commit
36c3ed031b
22 files changed
+2144
-2140
No files matched your search
@@ -47,10 +47,10 @@ function convertBigIntToString(obj: any): any {
|
||||
}
|
||||
|
||||
export async function getGroupAlbumMediaList(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
attachInfo: string = ''
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
attachInfo: string = ''
|
||||
): Promise<GroupAlbumMediaResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
@@ -70,9 +70,9 @@ export async function getGroupAlbumMediaList(
|
||||
});
|
||||
|
||||
const result = await bridge.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
|
||||
body,
|
||||
15000
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
|
||||
body,
|
||||
15000
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -98,11 +98,11 @@ export async function getGroupAlbumMediaList(
|
||||
|
||||
|
||||
export async function commentGroupAlbumMedia(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
content: string
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
content: string
|
||||
): Promise<GroupAlbumCommentResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const clientKey = Date.now().toString();
|
||||
@@ -147,9 +147,9 @@ export async function commentGroupAlbumMedia(
|
||||
});
|
||||
|
||||
const result = await bridge.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
|
||||
body,
|
||||
15000
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
|
||||
body,
|
||||
15000
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -175,12 +175,12 @@ export async function commentGroupAlbumMedia(
|
||||
}
|
||||
|
||||
export async function likeGroupAlbumMedia(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
batchId: string,
|
||||
lloc: string | undefined,
|
||||
isLike: boolean
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
batchId: string,
|
||||
lloc: string | undefined,
|
||||
isLike: boolean
|
||||
): Promise<any> {
|
||||
const uin = bridge.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
@@ -224,9 +224,9 @@ export async function likeGroupAlbumMedia(
|
||||
});
|
||||
|
||||
const result = await bridge.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
|
||||
body,
|
||||
15000
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
|
||||
body,
|
||||
15000
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -244,10 +244,10 @@ export async function likeGroupAlbumMedia(
|
||||
}
|
||||
|
||||
export async function deleteGroupAlbumMedia(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
lloc: string
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
lloc: string
|
||||
): Promise<any> {
|
||||
const uin = bridge.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
@@ -266,9 +266,9 @@ export async function deleteGroupAlbumMedia(
|
||||
});
|
||||
|
||||
const result = await bridge.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
|
||||
body,
|
||||
15000
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
|
||||
body,
|
||||
15000
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
|
||||
@@ -120,8 +120,8 @@ export function getBknFromSKey(skey: string): number {
|
||||
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('; ');
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
|
||||
@@ -137,8 +137,8 @@ export async function getCsrfToken(bridge: Bridge): Promise<number> {
|
||||
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('; ');
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
const token = skey ? getBknFromSKey(skey) : 0;
|
||||
|
||||
@@ -147,13 +147,13 @@ async function createAlbumUploadSession(
|
||||
* 修复后的上传图片分片方法
|
||||
*/
|
||||
async function uploadAlbumSlice(
|
||||
session: string,
|
||||
filePath: string,
|
||||
// 移除 offset 和 chunkSize 参数,改为在内部控制
|
||||
imgMd5: string,
|
||||
skey: string,
|
||||
pskey: string,
|
||||
uin: string
|
||||
session: string,
|
||||
filePath: string,
|
||||
// 移除 offset 和 chunkSize 参数,改为在内部控制
|
||||
imgMd5: string,
|
||||
skey: string,
|
||||
pskey: string,
|
||||
uin: string
|
||||
): Promise<void> {
|
||||
const img_size = statSync(filePath).size;
|
||||
const slice_size = 16384; // 严格使用 16KB
|
||||
|
||||
@@ -19,53 +19,53 @@ export interface GroupEssenceMsgRet {
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
export async function getGroupEssenceMsg(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
pageStart: number = 0,
|
||||
pageLimit: number = 50
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
pageStart: number = 0,
|
||||
pageLimit: number = 50
|
||||
): Promise<GroupEssenceMsgRet | undefined> {
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
|
||||
bkn: bkn,
|
||||
page_start: pageStart.toString(),
|
||||
page_limit: pageLimit.toString(),
|
||||
group_code: groupCode,
|
||||
}).toString()}`;
|
||||
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
|
||||
bkn: bkn,
|
||||
page_start: pageStart.toString(),
|
||||
page_limit: pageLimit.toString(),
|
||||
group_code: groupCode,
|
||||
}).toString()}`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息 (最多循环 20 页)
|
||||
*/
|
||||
export async function getGroupEssenceMsgAll(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
): Promise<GroupEssenceMsgRet[]> {
|
||||
const ret: GroupEssenceMsgRet[] = [];
|
||||
const ret: GroupEssenceMsgRet[] = [];
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
|
||||
|
||||
if (!data) break;
|
||||
if (!data) break;
|
||||
|
||||
ret.push(data);
|
||||
ret.push(data);
|
||||
|
||||
if (data.data?.is_end) break;
|
||||
}
|
||||
if (data.data?.is_end) break;
|
||||
}
|
||||
|
||||
return ret;
|
||||
return ret;
|
||||
}
|
||||
@@ -13,41 +13,41 @@ export enum WebHonorType {
|
||||
|
||||
|
||||
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}`);
|
||||
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 [];
|
||||
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) {
|
||||
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
|
||||
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
return data.map((item: any) => ({
|
||||
user_id: item?.uin,
|
||||
nickname: item?.name,
|
||||
avatar: item?.avatar,
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
|
||||
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -37,237 +37,237 @@ export interface WebApiGroupNoticeRet {
|
||||
}
|
||||
|
||||
export function calculateBkn(key: string): string {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
const code = key.charCodeAt(i);
|
||||
hash = hash + (hash << 5) + code;
|
||||
}
|
||||
return (hash & 0x7FFFFFFF).toString();
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
const code = key.charCodeAt(i);
|
||||
hash = hash + (hash << 5) + code;
|
||||
}
|
||||
return (hash & 0x7FFFFFFF).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送群公告 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
|
||||
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 {
|
||||
// 分别获取 skey 和 p_skey
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
try {
|
||||
// 分别获取 skey 和 p_skey
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey);
|
||||
const urlBkn = calculateBkn(pskey);
|
||||
//
|
||||
// console.log(skey)
|
||||
// console.log(pskey)
|
||||
//
|
||||
// console.log(urlBkn);
|
||||
// console.log(bodyBkn)
|
||||
const bodyBkn = calculateBkn(skey);
|
||||
const urlBkn = calculateBkn(pskey);
|
||||
//
|
||||
// console.log(skey)
|
||||
// console.log(pskey)
|
||||
//
|
||||
// console.log(urlBkn);
|
||||
// console.log(bodyBkn)
|
||||
|
||||
const settings = JSON.stringify({
|
||||
is_show_edit_card: isShowEditCard,
|
||||
tip_window_type: tipWindowType,
|
||||
confirm_required: confirmRequired,
|
||||
});
|
||||
const settings = JSON.stringify({
|
||||
is_show_edit_card: isShowEditCard,
|
||||
tip_window_type: tipWindowType,
|
||||
confirm_required: confirmRequired,
|
||||
});
|
||||
|
||||
const bodyParams: Record<string, string> = {
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn,
|
||||
text: content,
|
||||
pinned: pinned.toString(),
|
||||
type: type.toString(),
|
||||
settings,
|
||||
};
|
||||
const bodyParams: Record<string, string> = {
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn,
|
||||
text: content,
|
||||
pinned: pinned.toString(),
|
||||
type: type.toString(),
|
||||
settings,
|
||||
};
|
||||
|
||||
if (picId !== '') {
|
||||
bodyParams.pic = picId;
|
||||
bodyParams.imgWidth = imgWidth.toString();
|
||||
bodyParams.imgHeight = imgHeight.toString();
|
||||
}
|
||||
|
||||
// 注意这里:URL 必须使用 skey 算出来的 bkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
|
||||
const body = new URLSearchParams(bodyParams).toString();
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
body,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
if (picId !== '') {
|
||||
bodyParams.pic = picId;
|
||||
bodyParams.imgWidth = imgWidth.toString();
|
||||
bodyParams.imgHeight = imgHeight.toString();
|
||||
}
|
||||
|
||||
// 注意这里:URL 必须使用 skey 算出来的 bkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
|
||||
const body = new URLSearchParams(bodyParams).toString();
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
body,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取群公告列表 Web API
|
||||
*/
|
||||
export async function getGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
start: number = -1, // -1 表示第一页
|
||||
count: number = 20 // 抓包中是 10,你可以根据需要调整
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
start: number = -1, // -1 表示第一页
|
||||
count: number = 20 // 抓包中是 10,你可以根据需要调整
|
||||
): Promise<WebApiGroupNoticeRet | undefined> {
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
|
||||
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
|
||||
|
||||
const bodyParams = new URLSearchParams({
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
|
||||
ft: '23',
|
||||
s: start.toString(), // 分页游标
|
||||
n: count.toString(), // 获取数量
|
||||
i: '1',
|
||||
ni: '1'
|
||||
}).toString();
|
||||
const bodyParams = new URLSearchParams({
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
|
||||
ft: '23',
|
||||
s: start.toString(), // 分页游标
|
||||
n: count.toString(), // 获取数量
|
||||
i: '1',
|
||||
ni: '1'
|
||||
}).toString();
|
||||
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
||||
url,
|
||||
'POST',
|
||||
bodyParams,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
// console.log(JSON.stringify(ret, null, 2));
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
||||
url,
|
||||
'POST',
|
||||
bodyParams,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
// console.log(JSON.stringify(ret, null, 2));
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 上传群公告图片 Web API
|
||||
*/
|
||||
export async function uploadGroupNoticeImage(
|
||||
cookieObject: Record<string, string>,
|
||||
imageBuffer: Buffer
|
||||
cookieObject: Record<string, string>,
|
||||
imageBuffer: Buffer
|
||||
): Promise<{ id: string; width: number; height: number } | undefined> {
|
||||
try {
|
||||
const bkn = calculateBkn(cookieObject['skey']);
|
||||
const boundary = `-----------------------------${Date.now()}`;
|
||||
try {
|
||||
const bkn = calculateBkn(cookieObject['skey']);
|
||||
const boundary = `-----------------------------${Date.now()}`;
|
||||
|
||||
const parts: Buffer[] = [];
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
|
||||
parts.push(imageBuffer);
|
||||
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
|
||||
const parts: Buffer[] = [];
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
|
||||
parts.push(imageBuffer);
|
||||
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
|
||||
|
||||
const body = Buffer.concat(parts);
|
||||
const body = Buffer.concat(parts);
|
||||
|
||||
const options = {
|
||||
hostname: 'web.qun.qq.com',
|
||||
path: '/cgi-bin/announce/upload_img',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
||||
'Content-Length': body.length,
|
||||
'Cookie': cookieToString(cookieObject),
|
||||
},
|
||||
};
|
||||
const options = {
|
||||
hostname: 'web.qun.qq.com',
|
||||
path: '/cgi-bin/announce/upload_img',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
||||
'Content-Length': body.length,
|
||||
'Cookie': cookieToString(cookieObject),
|
||||
},
|
||||
};
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const req = https.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const result = JSON.parse(data) as UploadImageRetSuccess;
|
||||
if (result.ec === 0 && result.id) {
|
||||
const unescapedIdStr = result.id.replace(/"/g, '"');
|
||||
return new Promise((resolve) => {
|
||||
const req = https.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const result = JSON.parse(data) as UploadImageRetSuccess;
|
||||
if (result.ec === 0 && result.id) {
|
||||
const unescapedIdStr = result.id.replace(/"/g, '"');
|
||||
|
||||
const idObj = JSON.parse(unescapedIdStr);
|
||||
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
|
||||
} else {
|
||||
resolve(undefined);
|
||||
}
|
||||
} catch {
|
||||
resolve(undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', (err) => {
|
||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
||||
const idObj = JSON.parse(unescapedIdStr);
|
||||
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
|
||||
} else {
|
||||
resolve(undefined);
|
||||
});
|
||||
req.write(body);
|
||||
req.end();
|
||||
}
|
||||
} catch {
|
||||
resolve(undefined);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
req.on('error', (err) => {
|
||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
||||
resolve(undefined);
|
||||
});
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
} catch (e) {
|
||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除群公告 Web API
|
||||
*/
|
||||
export async function deleteGroupNotice(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
fid: string
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
fid: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
|
||||
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
|
||||
|
||||
const params = new URLSearchParams({
|
||||
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
|
||||
fid: fid,
|
||||
qid: groupCode,
|
||||
}).toString();
|
||||
const params = new URLSearchParams({
|
||||
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
|
||||
fid: fid,
|
||||
qid: groupCode,
|
||||
}).toString();
|
||||
|
||||
// 注意这里:URL 拼接 urlBkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
|
||||
// 注意这里:URL 拼接 urlBkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
params,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret?.ec === 0;
|
||||
} catch (e) {
|
||||
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return false;
|
||||
}
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
params,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret?.ec === 0;
|
||||
} catch (e) {
|
||||
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2,126 +2,126 @@ 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; } = {};
|
||||
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);
|
||||
});
|
||||
res.on('data', () => { }); // 必须消耗流
|
||||
res.on('end', () => {
|
||||
this.handleRedirect(res, url, cookies)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
if (res.headers['set-cookie']) {
|
||||
this.extractCookies(res.headers['set-cookie'], cookies);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
req.on('error', (error: Error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: {
|
||||
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,
|
||||
};
|
||||
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;
|
||||
}
|
||||
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(); });
|
||||
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);
|
||||
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}`));
|
||||
}
|
||||
req.end();
|
||||
} catch (parseError: any) {
|
||||
reject(new Error(parseError.message));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
|
||||
return this.HttpGetJson<string>(url, method, data, headers, false, false);
|
||||
}
|
||||
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('; ');
|
||||
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();
|
||||
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();
|
||||
}
|
||||
@@ -1004,11 +1004,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
try {
|
||||
const data = await ctx.bridge.getMiniAppArk(
|
||||
String(type),
|
||||
String(title),
|
||||
String(desc),
|
||||
String(picUrl),
|
||||
String(jumpUrl)
|
||||
String(type),
|
||||
String(title),
|
||||
String(desc),
|
||||
String(picUrl),
|
||||
String(jumpUrl)
|
||||
);
|
||||
return okResponse(data);
|
||||
} catch (e) {
|
||||
@@ -1030,11 +1030,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
try {
|
||||
const data = await ctx.bridge.clickInlineKeyboardButton(
|
||||
groupId,
|
||||
botAppid,
|
||||
String(buttonId),
|
||||
String(callbackData),
|
||||
msgSeq
|
||||
groupId,
|
||||
botAppid,
|
||||
String(buttonId),
|
||||
String(callbackData),
|
||||
msgSeq
|
||||
);
|
||||
return okResponse(data);
|
||||
} catch (e) {
|
||||
|
||||
@@ -243,9 +243,9 @@ function collectByName<T extends { name: string }>(
|
||||
function pickAutoName(kind: keyof OneBotNetworks, used: Map<string, unknown>, counter: number): string {
|
||||
const prefix =
|
||||
kind === 'httpServers' ? 'http' :
|
||||
kind === 'httpClients' ? 'httppost' :
|
||||
kind === 'wsServers' ? 'ws' :
|
||||
'wsclient';
|
||||
kind === 'httpClients' ? 'httppost' :
|
||||
kind === 'wsServers' ? 'ws' :
|
||||
'wsclient';
|
||||
let candidate = `${prefix}-${counter}`;
|
||||
while (used.has(candidate)) {
|
||||
counter += 1;
|
||||
|
||||
@@ -130,17 +130,17 @@ export class MessageStore {
|
||||
// So for private messages, we only match by message_hash and is_group flag.
|
||||
const row = isGroup
|
||||
? this.db.prepare(
|
||||
`SELECT sequence
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(sessionId, messageId) as { sequence: number } | undefined
|
||||
).get(sessionId, messageId) as { sequence: number } | undefined
|
||||
: this.db.prepare(
|
||||
`SELECT sequence
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(messageId) as { sequence: number } | undefined;
|
||||
).get(messageId) as { sequence: number } | undefined;
|
||||
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
|
||||
return null;
|
||||
|
||||
Reference in new issue
Block a user