Merge pull request #31 from H3CoF6/feat/onebot

Implement group album action
This commit is contained in:
墨梓柒 authored and GitHub committed 2026-05-19 08:18:39 +08:00
commit 02d1848d39
12 files changed
+1068 -2

No files matched your search

@@ -0,0 +1,282 @@
// Group album actions via TRPC protocol
import type { Bridge } from '../bridge';
import { protoEncode, protoDecode } from '@/protobuf/decode';
import { GetMediaListRequestSchema,
GetMediaListResponseSchema,
DoQunCommentRequestSchema,
DoQunCommentResponseSchema,
DoQunLikeRequestSchema,
DoQunLikeResponseSchema,
DeleteMediasRequestSchema,
DeleteMediasResponseSchema
} from '../proto/oidb-action';
export interface GroupAlbumMediaResult {
mediaList: any[];
nextAttachInfo: string;
}
export interface GroupAlbumCommentResult {
id: string;
user: { uin: string };
content: Array<{ type: number; content: string }>;
time: string;
clientKey: string;
}
function convertBigIntToString(obj: any): any {
if (obj === null || obj === undefined) return obj;
if (typeof obj === 'bigint') return obj.toString();
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
if (typeof obj === 'object') {
const result: any = {};
for (const key in obj) {
result[key] = convertBigIntToString(obj[key]);
}
return result;
}
return obj;
}
export async function getGroupAlbumMediaList(
bridge: Bridge,
groupId: number,
albumId: string,
attachInfo: string = ''
): Promise<GroupAlbumMediaResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protoEncode({
field1: 0,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
reqInfo: {
groupId: groupId.toString(),
albumId: albumId,
field3: 0,
attachInfo: attachInfo,
field5: '',
},
traceId: traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
}, GetMediaListRequestSchema);
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to get album media list');
}
const resp = protoDecode(result.responseData, GetMediaListResponseSchema);
if (!resp || (resp as any).field1 !== 0) {
throw new Error(`fetch album media list error: retCode ${(resp as any)?.field1 || 'unknown'}`);
}
const data = (resp as any).data || {};
const mediaList = data.mediaList || [];
const nextAttachInfo = data.nextAttachInfo || '';
return convertBigIntToString({
mediaList,
nextAttachInfo,
});
}
export async function commentGroupAlbumMedia(
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();
const uin = bridge.identity.uin;
const body = protoEncode({
field1: 8527,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
body: {
groupId: groupId.toString(),
field3: 2,
reqBody: {
field1: { field3: 0, field4: "" },
field2: {
field1: { uin }
},
field5: {
field1: {
field2: {
field1: 0, field2: "",
lloc,
field4: "", field6: "", field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0
}
},
albumId,
field5: 0
},
},
field5: {
field2: { uin },
field3: {
field1: 0,
field2: content,
field3: "", field4: "", field5: 0, field6: ""
},
clientKey,
}
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
}, DoQunCommentRequestSchema);
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to comment on album media');
}
const resp = protoDecode(result.responseData, DoQunCommentResponseSchema);
const resCode = (resp as any)?.field1;
if (!resp || (resCode !== 0 && resCode !== 8527 && !(resp as any).comment)) {
throw new Error(`comment album media error: retCode ${resCode || 'unknown'}`);
}
const commentData = (resp as any).comment?.data || {};
return convertBigIntToString({
id: commentData.id || '',
user: { uin: commentData.user?.uin || '' },
content: commentData.content || [],
time: commentData.time || '0',
clientKey: commentData.clientKey || '',
});
}
export async function likeGroupAlbumMedia(
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)}`;
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
}
const body = protoEncode({
field1: 5495,
field2: "h5_test",
field3: "h5_test",
body: {
type,
like: { id, status },
publish: {
cellCommon: {
time: BigInt(Date.now()),
feedId: `422_0_${batchId}`
},
cellUserInfo: {
user: { uin }
},
cellMedia: {
albumId: albumId,
batchId: BigInt(batchId)
},
cellQunInfo: {
qunId: groupId.toString()
}
},
clientKey
},
extMap: [{ key: 'fc-appid', value: '100' }],
}, DoQunLikeRequestSchema);
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to like album media');
}
const resp = protoDecode(result.responseData, DoQunLikeResponseSchema);
const resCode = (resp as any)?.field1;
if (!resp || resCode !== 5495) {
throw new Error(`like album media error: retCode ${resCode || 'unknown'}`);
}
return (resp as any).body?.like || {};
}
export async function deleteGroupAlbumMedia(
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)}`;
const body = protoEncode({
field1: 8694,
field2: "h5_test",
field3: "h5_test",
body: {
groupId: groupId.toString(),
albumId: albumId,
lloc: lloc,
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
}, DeleteMediasRequestSchema);
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to delete album media');
}
const resp = protoDecode(result.responseData, DeleteMediasResponseSchema);
const resCode = (resp as any)?.field1;
const errCode = (resp as any)?.field2;
const errMsg = (resp as any)?.field3;
if (!resp || resCode !== 8694 || errCode) {
throw new Error(`delete album media error [${errCode || 'unknown'}]: ${errMsg || 'unknown'}`);
}
return { success: true };
}
@@ -91,6 +91,14 @@ export interface BridgeInterface {
renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void>;
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Group Album ───
getGroupAlbumList(groupId: number): Promise<any>;
uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void>;
getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise<any>;
commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise<any>;
deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise<any>;
likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
+31
View File
@@ -126,7 +126,14 @@ import {
getCookiesStr as getCookiesStr_,
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
getGroupAlbumListWeb as getGroupAlbumListWeb_,
uploadImageToGroupAlbumWeb as uploadImageToGroupAlbumWeb_,
} from './web-actions';
import { getGroupAlbumMediaList as getGroupAlbumMediaList_,
commentGroupAlbumMedia as commentGroupAlbumMedia_,
likeGroupAlbumMedia as likeGroupAlbumMedia_,
deleteGroupAlbumMedia as deleteGroupAlbumMedia_,
} from './actions/group-album';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus';
@@ -484,6 +491,30 @@ export class Bridge implements BridgeInterface {
return getGroupEssenceAll_(this, groupId);
}
async getGroupAlbumList(groupId: number): Promise<any> {
return getGroupAlbumListWeb_(this, groupId);
}
async uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
return uploadImageToGroupAlbumWeb_(this, groupId, albumId, albumName, filePath);
}
async getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise<any> {
return getGroupAlbumMediaList_(this, groupId, albumId, attachInfo);
}
async commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise<any> {
return commentGroupAlbumMedia_(this, groupId, albumId, lloc, content);
}
async likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any> {
return likeGroupAlbumMedia_(this, groupId, albumId, batchId, lloc, isLike);
}
async deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise<any> {
return deleteGroupAlbumMedia_(this, groupId, albumId, lloc);
}
async sendGroupNotice(groupId: number, content: string, options?: any) {
return sendGroupNotice_(this, groupId, content, options);
}
+10
View File
@@ -334,3 +334,13 @@ export const NTV2UploadRichMediaRespSchema = {
respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema },
} satisfies ProtoSchema;
// --- Group Avatar Upload Extend ---
export const GroupAvatarUploadExtSchema = {
field1: { field: 1, type: 'uint32' as const },
groupId: { field: 2, type: 'uint64' as const },
field3: { field: 3, type: 'bytes' as const },
field5: { field: 5, type: 'uint32' as const },
field6: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
+260 -1
View File
@@ -1277,4 +1277,263 @@ export const GroupAvatarExtraSchema = {
field3: { field: 3, type: 'message' as const, schema: GroupAvatarExtraField3Schema },
field5: { field: 5, type: 'uint32' as const }, // observed value: 3
field6: { field: 6, type: 'uint32' as const }, // observed value: 1
} satisfies ProtoSchema;
} satisfies ProtoSchema;
///////// --- group album
// --- Request Schemas ---
export const ExtMapEntrySchema = {
key: { field: 1, type: 'string' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const ReqInfoSchema = {
groupId: { field: 1, type: 'string' as const },
albumId: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'int32' as const },
attachInfo: { field: 4, type: 'string' as const },
field5: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const GetMediaListRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'bytes' as const },
field3: { field: 3, type: 'bytes' as const },
reqInfo: { field: 4, type: 'message' as const, schema: ReqInfoSchema },
traceId: { field: 5, type: 'string' as const },
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
// --- Response Schemas ---
export const UrlInfoSchema = {
url: { field: 1, type: 'string' as const },
width: { field: 2, type: 'uint32' as const },
height: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const PhotoUrlSchema = {
spec: { field: 1, type: 'uint32' as const },
url: { field: 2, type: 'message' as const, schema: UrlInfoSchema }
} satisfies ProtoSchema;
export const ImageInfoSchema = {
name: { field: 1, type: 'string' as const },
sloc: { field: 2, type: 'string' as const },
lloc: { field: 3, type: 'string' as const },
photoUrls: { field: 4, type: 'repeated_message' as const, schema: PhotoUrlSchema },
defaultUrl: { field: 5, type: 'message' as const, schema: UrlInfoSchema },
isGif: { field: 6, type: 'bool' as const },
hasRaw: { field: 7, type: 'bool' as const },
} satisfies ProtoSchema;
export const MediaInfoSchema = {
type: { field: 1, type: 'uint32' as const },
image: { field: 2, type: 'message' as const, schema: ImageInfoSchema },
uploader: { field: 6, type: 'string' as const },
batchId: { field: 7, type: 'uint64' as const },
uploadTime: { field: 8, type: 'uint64' as const },
} satisfies ProtoSchema;
export const GetMediaListRspDataSchema = {
albumInfo: {
field: 1,
type: 'message' as const,
schema: {
albumId: { field: 1, type: 'string' as const },
owner: { field: 2, type: 'string' as const },
name: { field: 3, type: 'string' as const },
} satisfies ProtoSchema
},
mediaList: { field: 3, type: 'repeated_message' as const, schema: MediaInfoSchema },
prevAttachInfo: { field: 4, type: 'string' as const },
nextAttachInfo: { field: 5, type: 'string' as const }, // 用于翻页拉取的 token
} satisfies ProtoSchema;
export const GetMediaListResponseSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'bytes' as const },
field3: { field: 3, type: 'bytes' as const },
data: { field: 4, type: 'message' as const, schema: GetMediaListRspDataSchema }, // 将原本的 bytes 修正为 message 解析
} satisfies ProtoSchema;
// --- DoQunComment: Comment on group album media ---
// --- DoQunComment: 严格对齐底层字节的字段定义 ---
export const CommentContentItemSchema = {
type: { field: 1, type: 'uint32' as const },
content: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const CommentUserSchema = {
uin: { field: 13, type: 'string' as const },
} satisfies ProtoSchema;
// 评论具体内容结构 (原 CommentReqContentSchema)
export const CommentReqContentSchema = {
field2: { field: 2, type: 'message' as const, schema: CommentUserSchema },
field3: { field: 3, type: 'message' as const, schema: {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'string' as const },
field4: { field: 4, type: 'string' as const },
field5: { field: 5, type: 'uint32' as const },
field6: { field: 6, type: 'string' as const },
} satisfies ProtoSchema },
clientKey: { field: 7, type: 'string' as const }, // 对应你的 clientKey
} satisfies ProtoSchema;
export const CommentReqPhotoInfoSchema = {
field1: { field: 1, type: 'message' as const, schema: {
field2: { field: 2, type: 'message' as const, schema: {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'string' as const },
lloc: { field: 3, type: 'string' as const },
field4: { field: 4, type: 'string' as const },
field6: { field: 6, type: 'string' as const },
field7: { field: 7, type: 'uint32' as const },
field8: { field: 8, type: 'uint32' as const },
field9: { field: 9, type: 'uint32' as const },
field14: { field: 14, type: 'uint32' as const },
field15: { field: 15, type: 'uint32' as const },
field17: { field: 17, type: 'uint32' as const },
} satisfies ProtoSchema },
} satisfies ProtoSchema },
albumId: { field: 3, type: 'string' as const },
field5: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const CommentReqBodySchema = {
field1: { field: 1, type: 'message' as const, schema: {
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'string' as const },
} satisfies ProtoSchema },
field2: { field: 2, type: 'message' as const, schema: {
field1: { field: 1, type: 'message' as const, schema: CommentUserSchema }
} satisfies ProtoSchema },
field5: { field: 5, type: 'message' as const, schema: CommentReqPhotoInfoSchema }, // 注意:抓包证实照片在 field 5
} satisfies ProtoSchema;
export const DoQunCommentRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'bytes' as const },
field3: { field: 3, type: 'bytes' as const },
body: { field: 4, type: 'message' as const, schema: {
groupId: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'uint32' as const },
reqBody: { field: 4, type: 'message' as const, schema: CommentReqBodySchema },
field5: { field: 5, type: 'message' as const, schema: CommentReqContentSchema }, // 注意:评论文本实际在外层的 field 5
} satisfies ProtoSchema },
traceId: { field: 5, type: 'string' as const },
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
export const CommentRespUserSchema = {
uin: { field: 13, type: 'string' as const },
} satisfies ProtoSchema;
export const CommentRespContentSchema = {
type: { field: 1, type: 'uint32' as const },
content: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const CommentRespDataSchema = {
id: { field: 1, type: 'string' as const },
user: { field: 2, type: 'message' as const, schema: CommentRespUserSchema },
content: { field: 3, type: 'repeated_message' as const, schema: CommentRespContentSchema },
time: { field: 4, type: 'uint64' as const },
clientKey: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunCommentResponseSchema = {
field1: { field: 1, type: 'int32' as const },
comment: { field: 4, type: 'message' as const, schema: {
data: { field: 2, type: 'message' as const, schema: CommentRespDataSchema },
} satisfies ProtoSchema },
} satisfies ProtoSchema;
// --- DoQunLike: Like group album media ---
export const DoQunLikeReqLikeInfoSchema = {
id: { field: 1, type: 'string' as const },
status: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqCellCommonSchema = {
time: { field: 3, type: 'uint64' as const },
feedId: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqCellUserSchema = {
uin: { field: 13, type: 'string' as const }, // 修复:抓包证实 uin 是 field 13
} satisfies ProtoSchema;
export const DoQunLikeReqCellUserInfoSchema = {
user: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellUserSchema },
} satisfies ProtoSchema;
export const DoQunLikeReqCellQunInfoSchema = {
qunId: { field: 1, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqCellMediaSchema = {
albumId: { field: 3, type: 'string' as const },
batchId: { field: 5, type: 'uint64' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqFeedPublishSchema = {
cellCommon: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellCommonSchema },
cellUserInfo: { field: 2, type: 'message' as const, schema: DoQunLikeReqCellUserInfoSchema },
cellMedia: { field: 5, type: 'message' as const, schema: DoQunLikeReqCellMediaSchema },
cellQunInfo: { field: 12, type: 'message' as const, schema: DoQunLikeReqCellQunInfoSchema },
} satisfies ProtoSchema;
export const DoQunLikeReqBodySchema = {
type: { field: 2, type: 'uint32' as const },
like: { field: 3, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema },
publish: { field: 4, type: 'message' as const, schema: DoQunLikeReqFeedPublishSchema },
clientKey: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunLikeRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'string' as const },
body: { field: 4, type: 'message' as const, schema: DoQunLikeReqBodySchema },
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
export const DoQunLikeRespBodySchema = {
like: { field: 2, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema },
} satisfies ProtoSchema;
export const DoQunLikeResponseSchema = {
field1: { field: 1, type: 'int32' as const },
body: { field: 4, type: 'message' as const, schema: DoQunLikeRespBodySchema },
} satisfies ProtoSchema;
// --- DeleteMedias: Delete group album media ---
export const DeleteMediasReqBodySchema = {
groupId: { field: 1, type: 'string' as const },
albumId: { field: 2, type: 'string' as const },
lloc: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const DeleteMediasRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'string' as const },
body: { field: 4, type: 'message' as const, schema: DeleteMediasReqBodySchema },
traceId: { field: 5, type: 'string' as const }, // <-- 把它挪到外层了!
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
export const DeleteMediasResponseSchema = {
field1: { field: 1, type: 'int32' as const }, // 8694
field2: { field: 2, type: 'int32' as const }, // 错误码 (例如: 10023)
field3: { field: 3, type: 'string' as const }, // 错误信息 (例如: "no right delete...")
} satisfies ProtoSchema;
@@ -0,0 +1,29 @@
// Group album actions via web API
import type { Bridge } from '../bridge';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '../web/group-album';
import { getCookies } from './cookies';
export async function getGroupAlbumListWeb(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
return albumData?.album || [];
}
export async function uploadImageToGroupAlbumWeb(
bridge: Bridge,
groupId: number,
albumId: string,
albumName: string,
filePath: string
): Promise<void> {
const groupCode = groupId.toString();
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
}
@@ -25,3 +25,8 @@ export {
getGroupNotice,
deleteGroupNoticeByFid,
} from './group-notice';
export {
getGroupAlbumListWeb,
uploadImageToGroupAlbumWeb,
} from './group-album';
+251
View File
@@ -0,0 +1,251 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { createHash } from 'crypto';
import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
import { basename, join } from 'path';
import { tmpdir } from 'os';
import * as console from "node:console";
// 群相册信息
export interface GroupAlbumInfo {
id: string;
name: string;
picNum: number;
createTime: number;
[key: string]: any;
}
// 获取群相册列表返回
export interface GroupAlbumListRet {
album: GroupAlbumInfo[];
[key: string]: any;
}
// 相册媒体信息
export interface AlbumMediaInfo {
photoId: string;
url: string;
uploadTime: number;
[key: string]: any;
}
/**
* 获取群相册列表
*/
export async function getGroupAlbumList(
cookieObject: Record<string, string>,
groupId: string,
uin: string
): Promise<GroupAlbumListRet | undefined> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
}
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?${new URLSearchParams({
random: '7570',
g_tk: bkn,
format: 'json',
inCharset: 'utf-8',
outCharset: 'utf-8',
qua: 'V1_IPH_SQ_6.2.0_0_HDBM_T',
cmd: 'qunGetAlbumList',
qunId: groupId,
qunid: groupId,
start: '0',
num: '1000',
uin,
getMemberRole: '0',
}).toString()}`;
const ret = await RequestUtil.HttpGetJson<{ data: GroupAlbumListRet }>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
if (!ret || typeof ret !== 'object') {
throw new Error('invalid response from qzone api');
}
return ret.data;
}
/**
* 创建群相册上传会话
*/
async function createAlbumUploadSession(
groupId: string,
albumId: string,
albumName: string,
filePath: string,
skey: string,
pskey: string,
imgMd5: string,
uin: string
): Promise<string> {
const imgSize = statSync(filePath).size;
const imgName = basename(filePath);
const bkn = getBknFromCookie({ skey });
const timestamp = Math.floor(Date.now() / 1000);
const body = {
control_req: [{
uin,
token: { type: 4, data: pskey, appid: 5 },
appid: 'qun',
checksum: imgMd5,
check_type: 0,
file_len: imgSize,
env: { refer: 'qzone', deviceInfo: 'h5' },
model: 0,
biz_req: {
sPicTitle: imgName,
sPicDesc: '',
sAlbumName: albumName,
sAlbumID: albumId,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType: 0,
iUpPicType: 0,
iBatchID: timestamp,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iNeedFeeds: 1,
iUploadTime: timestamp,
mapExt: { appid: 'qun', userid: groupId },
stExtendInfo: { mapParams: { photo_num: '1', video_num: '0', batch_num: '1' } },
},
session: '',
asy_upload: 0,
cmd: 'FileUpload',
}],
};
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`;
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>(
api,
'POST',
body,
{ Cookie: cookie, 'Content-Type': 'application/json' }
);
if (response.ret !== 0 || !response.data?.session) {
throw new Error(`创建上传会话失败: ${response.msg}`);
}
return response.data.session;
}
/**
* 修复后的上传图片分片方法
*/
async function uploadAlbumSlice(
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
const bkn = getBknFromCookie({ skey });
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const stream = createReadStream(filePath, { highWaterMark: slice_size });
let seq = 0;
let offset = 0;
for await (const chunk of stream) {
const end = Math.min(offset + chunk.length, img_size);
// 使用原生的 FormData 构建安全的 multipart 请求
const form = new FormData();
form.append('uin', uin);
form.append('appid', 'qun');
form.append('session', session);
form.append('offset', offset.toString());
form.append('data', new Blob([chunk as Buffer], { type: 'application/octet-stream' }), 'blob');
form.append('checksum', '');
form.append('check_type', '0');
form.append('retry', '0');
form.append('seq', seq.toString());
form.append('end', end.toString());
form.append('cmd', 'FileUpload');
form.append('slice_size', slice_size.toString());
form.append('biz_req.iUploadType', '0');
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${bkn}`;
// 放弃使用 HttpGetJson,改用原生 fetch,它能完美处理 FormData 和边界
const response = await fetch(api, {
method: 'POST',
headers: {
Cookie: cookie,
// 注意:不要手动设置 Content-Type,fetch 会自动加上带有正确 boundary 的 multipart/form-data
},
body: form,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json() as { ret: number, msg: string };
if (post.ret !== 0) {
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
}
offset += chunk.length;
seq++;
}
}
/**
* 上传图片到群相册
*/
export async function uploadImageToGroupAlbum(
cookieObject: Record<string, string>,
groupId: string,
albumId: string,
albumName: string,
filePath: string,
uin: string
): Promise<void> {
const { loadBinarySource } = await import('../highway/utils');
const loaded = await loadBinarySource(filePath, 'album image');
let tempFile: string | null = null;
let actualPath = filePath;
if (/^(https?:\/\/|base64:\/\/)/i.test(filePath)) {
tempFile = join(tmpdir(), `album_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`);
writeFileSync(tempFile, loaded.bytes);
actualPath = tempFile;
}
try {
const imgMd5 = createHash('md5').update(loaded.bytes).digest('hex');
// const imgSize = loaded.bytes.length;
const skey = cookieObject.skey || '';
const pskey = cookieObject.p_skey || '';
const session = await createAlbumUploadSession(groupId, albumId, albumName, actualPath, skey, pskey, imgMd5, uin);
await uploadAlbumSlice(session, actualPath, imgMd5, skey, pskey, uin);
} finally {
if (tempFile) {
try { unlinkSync(tempFile); } catch { /* ignore */ }
}
}
}
@@ -119,4 +119,4 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
}
@@ -0,0 +1,132 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_album_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
try {
const albumList = await ctx.getGroupAlbumList(groupId);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('upload_image_to_qun_album', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const albumName = asString(params.album_name);
const file = asString(params.file);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.uploadImageToGroupAlbum(groupId, albumId, albumName, file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('get_group_album_media_list', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const attachInfo = asString(params.attach_info) || '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
try {
const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId, attachInfo);
return okResponse(mediaList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('do_group_album_comment', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
const content = asString(params.content);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
try {
const comment = await ctx.commentGroupAlbumMedia(groupId, albumId, lloc, content);
return okResponse(comment);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('set_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
// 取消点赞群相册媒体
h.registerAction('cancel_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('del_group_album_media', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
if (!groupId || !albumId || !lloc) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
}
try {
const res = await ctx.deleteGroupAlbumMedia(groupId, albumId, lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
}
+31
View File
@@ -15,6 +15,10 @@ import { register as registerGroupAdmin } from './actions/group-admin';
import { register as registerGroupFile } from './actions/group-file';
import { register as registerRequest } from './actions/request';
import { register as registerExtended } from './actions/extended';
import { register as registerGroupAlbum } from './actions/group-album';
import { WebHonorType } from '@/bridge/web/group-honor';
import { ClientKeyInfo } from '@/bridge/bridge';
export interface MessageSendResult {
messageId: number;
@@ -95,7 +99,33 @@ export interface ApiActionContext {
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
// Extended NapCat-compatible
setFriendRemark: (userId: number, remark: string) => Promise<void>;
setGroupRemark: (groupId: number, remark: string) => Promise<void>;
setGroupAvatar: (groupId: number, source: string) => Promise<void>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
markGroupMsgAsRead: (groupId: number, sequence: number) => Promise<void>;
markPrivateMsgAsRead: (userId: number, sequence: number) => Promise<void>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
fetchCustomFace: (count?: number) => Promise<string[]>;
getEmojiLikes: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>;
// Web
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise<any>;
getGroupEssenceAll: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
getGroupAlbumList: (groupId: number) => Promise<any>;
uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise<void>;
getGroupAlbumMediaList: (groupId: number, albumId: string, attachInfo?: string) => Promise<any>;
commentGroupAlbumMedia: (groupId: number, albumId: string, lloc: string, content: string) => Promise<any>;
deleteGroupAlbumMedia: (groupId: number, albumId: string, lloc: string) => Promise<any>;
likeGroupAlbumMedia: (groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean) => Promise<any>;
sendGroupNotice: (groupId: number, content: string, options?: any) => Promise<any>;
getGroupNotice: (groupId: number) => Promise<any[]>;
deleteGroupNotice: (groupId: number, fid: string) => Promise<boolean>;
getCookiesStr: (domain: string) => Promise<string>;
getCsrfToken: () => Promise<number>;
getCredentials: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
forceFetchClientKey: () => Promise<ClientKeyInfo>;
// Media lookup (populated from previously dispatched message segments)
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
@@ -117,6 +147,7 @@ export class ApiHandler {
registerGroupFile(this, context);
registerRequest(this, context);
registerExtended(this, context);
registerGroupAlbum(this, context);
}
registerAction(action: string, handler: ActionHandler): void {
@@ -162,6 +162,10 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
forceFetchClientKey: () => bridge.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
// Cross-store: looks up the meta then routes through Bridge.
@@ -174,6 +178,30 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId, sequence) => bridge.markGroupMsgAsRead(groupId, sequence),
markPrivateMsgAsRead: (userId, sequence) => 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-backed actions.
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type),
getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId),
getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId),
uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath),
getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.getGroupAlbumMediaList(groupId, albumId, attachInfo),
commentGroupAlbumMedia: (groupId, albumId, lloc, content) => bridge.commentGroupAlbumMedia(groupId, albumId, lloc, content),
deleteGroupAlbumMedia: (groupId, albumId, lloc) => bridge.deleteGroupAlbumMedia(groupId, albumId, lloc),
likeGroupAlbumMedia: (groupId, albumId, batchId, lloc, isLike) => bridge.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, isLike),
sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options),
getGroupNotice: (groupId) => bridge.getGroupNotice(groupId),
deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid),
getCookiesStr: (domain) => bridge.getCookiesStr(domain),
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain) => bridge.getCredentials(domain),
// Extended
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),