import type { JsonObject, JsonValue } from '@snowluma/common/json'; import { createLogger } from '@snowluma/common/logger'; import type { AlbumCreator, CommentRespData, DeleteMediasRequest, DeleteMediasResponse, DoQunCommentRequest, DoQunCommentResponse, DoQunLikeRequest, DoQunLikeResponse, GetAlbumListRequest, GetAlbumListResponse, GroupAlbumInfo as GroupAlbumInfoWire, GetMediaListRequest, GetMediaListResponse, MediaInfo, UrlInfo, } from '@snowluma/proto-defs/oidb-actions/group-album'; import { uploadImageToGroupAlbum, uploadVideoToGroupAlbum } from '@snowluma/protocol/web/group-album'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; const log = createLogger('Bridge.GroupAlbum'); const GET_ALBUM_LIST_CMD = 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList'; const GET_ALBUM_LIST_SEQ = 3331; const DO_QUN_COMMENT_CMD = 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment'; const DO_QUN_COMMENT_SEQ = 8527; function uint64ToString(value: bigint | undefined): string { return (value ?? 0n).toString(); } function uint64ToSafeNumber(value: bigint | undefined, fieldName: string): number { const normalized = value ?? 0n; if (normalized > BigInt(Number.MAX_SAFE_INTEGER)) { throw new Error(`group album ${fieldName} exceeds Number.MAX_SAFE_INTEGER: ${normalized}`); } return Number(normalized); } function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreator | undefined { if (!creator) return undefined; return { uid: creator.uid ?? '', nick: creator.nick ?? '', is_sweet: creator.isSweet ?? false, is_special: creator.isSpecial ?? false, is_super_like: creator.isSuperLike ?? false, custom_id: creator.customId ?? '', poly_id: creator.polyId ?? '', portrait: creator.portrait ?? '', can_follow: creator.canFollow ?? 0, isfollowed: creator.isFollowed ?? 0, uin: creator.uin ?? '', ditto_uin: creator.dittoUin ?? '', }; } function normalizeCoverUrl(url: UrlInfo | null | undefined): QunAlbumCoverUrl | null { if (!url) return null; return { url: url.url ?? '', width: url.width ?? 0, height: url.height ?? 0, }; } function normalizeAlbumCover(cover: MediaInfo | undefined): QunAlbumCover | null { if (!cover) return null; const image = cover.image; return { type: cover.type ?? 0, image: image ? { name: image.name ?? '', sloc: image.sloc ?? '', lloc: image.lloc ?? '', photoUrls: (image.photoUrls ?? []).map((photoUrl) => ({ spec: photoUrl.spec ?? 0, url: normalizeCoverUrl(photoUrl.url), })), defaultUrl: normalizeCoverUrl(image.defaultUrl), isGif: image.isGif ?? false, hasRaw: image.hasRaw ?? false, } : null, }; } function normalizeQunAlbum(album: GroupAlbumInfoWire): QunAlbumInfo { const normalized: QunAlbumInfo = { album_id: album.albumId ?? '', owner: album.owner ?? '', name: album.name ?? '', desc: album.description ?? '', create_time: uint64ToString(album.createTime), modify_time: uint64ToString(album.modifyTime), last_upload_time: uint64ToString(album.lastUploadTime), upload_number: uint64ToString(album.uploadNumber), cover: normalizeAlbumCover(album.cover), top_flag: uint64ToString(album.topFlag), busi_type: album.busiType ?? 0, status: album.status ?? 0, allow_share: album.allowShare ?? false, is_subscribe: album.isSubscribe ?? false, bitmap: album.bitmap ?? '', is_share_album: album.isShareAlbum ?? false, qz_album_type: album.qzAlbumType ?? 0, cover_type: album.coverType ?? 0, default_desc: album.defaultDesc ?? '', sort_type: album.sortType ?? 0, }; const creator = normalizeAlbumCreator(album.creator); if (creator) normalized.creator = creator; return normalized; } function toLegacyAlbum(album: GroupAlbumInfoWire): GroupAlbumInfo { const creator = normalizeAlbumCreator(album.creator); return { id: album.albumId ?? '', name: album.name ?? '', picNum: uint64ToSafeNumber(album.uploadNumber, 'upload_number'), createTime: uint64ToSafeNumber(album.createTime, 'create_time'), desc: album.description ?? '', owner: album.owner ?? '', createuin: creator?.uin || album.owner || creator?.uid || '', // QQ NT's AlbumService returns this as a normal UTF-8 protobuf string. // Unlike the legacy Qzone HTTP endpoint, it does not rewrite Unicode // emoji into ambiguous [em]...[/em] tags. createnickname: creator?.nick ?? '', last_upload_time: uint64ToSafeNumber(album.lastUploadTime, 'last_upload_time'), cover: normalizeAlbumCover(album.cover), }; } function convertBigIntToString(obj: unknown): JsonValue { if (obj === null || obj === undefined) return null; if (typeof obj === 'bigint') return obj.toString(); if (Array.isArray(obj)) return obj.map(convertBigIntToString); if (typeof obj === 'object') { const result: JsonObject = {}; for (const [key, value] of Object.entries(obj)) { result[key] = convertBigIntToString(value); } return result; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj; return null; } export class GroupAlbumApi { constructor(private readonly ctx: BridgeContext) { } private async fetchAlbumList(groupId: number, attachInfo: string): Promise { const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const body = protobuf_encode({ seq: GET_ALBUM_LIST_SEQ, field2: new Uint8Array(0), field3: new Uint8Array(0), data: { groupId: groupId.toString(), attachInfo, }, traceId, extMap: [{ key: 'fc-appid', value: '100' }], }); log.debug( 'get album list request: group=%d cursorChars=%d requestBytes=%d', groupId, attachInfo.length, body.length, ); const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error( `get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`, ); } const response = protobuf_decode(result.responseData); const resultCode = response.result ?? 0; if (resultCode !== 0) { throw new Error( `get group album list failed: result=${resultCode}, error=${response.errorText || 'unknown'}`, ); } const normalized: GroupAlbumWireResult = { albumList: response.data?.albumList ?? [], attachInfo: response.data?.attachInfo ?? '', hasMore: response.data?.hasMore ?? false, }; log.debug( 'get album list response: group=%d albums=%d hasMore=%s cursorChars=%d responseBytes=%d', groupId, normalized.albumList.length, String(normalized.hasMore), normalized.attachInfo.length, result.responseData.length, ); return normalized; } /** QQ NT AlbumService-backed list, including its pagination cursor. */ async listQun(groupId: number, attachInfo = ''): Promise { const result = await this.fetchAlbumList(groupId, attachInfo); return { albumList: result.albumList.map(normalizeQunAlbum), attachInfo: result.attachInfo, hasMore: result.hasMore, }; } // OneBot compatibility shape used by get_group_album_list. async list(groupId: number): Promise { const albumList: GroupAlbumList = []; const seenCursors = new Set(); let attachInfo = ''; let page = 0; while (true) { const result = await this.fetchAlbumList(groupId, attachInfo); page += 1; albumList.push(...result.albumList.map(toLegacyAlbum)); if (!result.hasMore) { log.debug( 'get complete album list: group=%d pages=%d albums=%d', groupId, page, albumList.length, ); return albumList; } const nextAttachInfo = result.attachInfo; if (!nextAttachInfo) { throw new Error( `get group album list pagination failed: group=${groupId} page=${page} ` + 'hasMore=true but cursor is empty', ); } if (seenCursors.has(nextAttachInfo)) { throw new Error( `get group album list pagination failed: group=${groupId} repeated cursor at page ${page}`, ); } seenCursors.add(nextAttachInfo); attachInfo = nextAttachInfo; } } // 上传图片到现有相册(HTTP 分片上传)。 async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise { const groupCode = groupId.toString(); const uin = this.ctx.identity.uin; const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); } async uploadVideo(groupId: number, albumId: string, albumName: string, filePath: string): Promise<{ id: string }> { const groupCode = groupId.toString(); const uin = this.ctx.identity.uin; const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); return uploadVideoToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); } async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise { const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const body = protobuf_encode({ field1: 0, field2: new Uint8Array(0), field3: new Uint8Array(0), reqInfo: { groupId: groupId.toString(), albumId, field3: 0, field4: '', pageInfo: attachInfo, }, traceId, extMap: [{ key: 'fc-appid', value: '100' }], }); const result = await this.ctx.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 = protobuf_decode(result.responseData); const retCode = resp.field1 ?? 0; if (retCode !== 0) { throw new Error(`fetch album media list error: retCode ${retCode}`); } const data = resp.data ?? {}; const mediaList = data.mediaList ?? []; const nextAttachInfo = data.nextAttachInfo ?? ''; return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult; } async comment(groupId: number, albumId: string, lloc: string, content: string): Promise { const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const clientKey = Date.now().toString(); const uin = this.ctx.identity.uin; const resolved = await this.resolveCommentMedia(groupId, albumId, lloc); const media = mediaInfoForComment(resolved, lloc); const batchId = media.batchId ?? optionalBatchId(resolved?.batchId); const body = protobuf_encode({ field1: DO_QUN_COMMENT_SEQ, field2: new Uint8Array(0), field3: new Uint8Array(0), body: { groupId: groupId.toString(), field3: 2, reqBody: { field2: { field1: { uin }, }, field5: { medias: [media], albumId, ...(batchId !== undefined ? { batchId } : {}), }, }, field5: { user: { uin }, contents: [{ type: 0, content }], clientKey, }, }, traceId, extMap: [{ key: 'fc-appid', value: '100' }], }); const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, 15000); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(result.errorMessage || 'failed to comment on album media'); } const resp = protobuf_decode(result.responseData); const resultCode = resp.result ?? 0; if (resultCode !== 0) { throw new Error( `comment album media error: retCode ${resultCode}` + (resp.errorText ? `, ${resp.errorText}` : ''), ); } const commentData = commentFromResponse(resp); if (!commentData.id) { throw new Error('comment album media error: empty comment'); } return convertBigIntToString({ id: commentData.id, user: { uin: commentData.user?.uin || uin }, content: (commentData.content ?? [{ type: 0, content }]).map((item) => ({ type: item.type ?? 0, content: item.content ?? '', })), time: commentData.time ?? '0', clientKey: commentData.clientKey || clientKey, }) as unknown as GroupAlbumCommentResult; } async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise { const uin = this.ctx.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 = protobuf_encode({ 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, batchId: BigInt(batchId), }, cellQunInfo: { qunId: groupId.toString(), }, }, clientKey, }, extMap: [{ key: 'fc-appid', value: '100' }], }); const result = await this.ctx.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 = protobuf_decode(result.responseData); const resCode = resp.field1; if (resCode !== 5495) { throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`); } return convertBigIntToString(resp.body?.like ?? {}); } async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> { const target = await this.resolveDeleteTarget(groupId, albumId, lloc); const uin = this.ctx.identity.uin; const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const body = protobuf_encode({ field1: 8694, field2: 'h5_test', field3: 'h5_test', body: { groupId: groupId.toString(), albumId, mediaIds: [target.mediaId], ...(target.batchId ? { batchIds: [target.batchId] } : {}), }, traceId: clientKey, extMap: [{ key: 'fc-appid', value: '100' }], }); const result = await this.ctx.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 = protobuf_decode(result.responseData); const resCode = resp.field1; const errCode = resp.field2; const errMsg = resp.field3; if (resCode !== 8694 || errCode) { throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`); } return { success: true }; } /** * Official delete uses a photo lloc, or a video's cover lloc plus batch id. * Callers may pass either an image lloc or a video id; resolve the latter. */ private async resolveDeleteTarget( groupId: number, albumId: string, mediaKey: string, ): Promise<{ mediaId: string; batchId?: string }> { try { const seenCursors = new Set(); let attachInfo = ''; while (true) { const page = await this.getMediaList(groupId, albumId, attachInfo); const hit = findDeleteTarget(page.mediaList, mediaKey); if (hit) return hit; const next = page.nextAttachInfo ?? ''; if (!next || seenCursors.has(next)) { return { mediaId: mediaKey }; } seenCursors.add(next); attachInfo = next; } } catch (err) { log.debug( 'resolve album delete target failed, using raw id: group=%d album=%s err=%s', groupId, albumId, err instanceof Error ? err.message : String(err), ); return { mediaId: mediaKey }; } } /** * Official DoQunComment attaches the GetMediaList MediaInfo cell plus batch id. * Page the album when the caller only has a lloc / video id. */ private async resolveCommentMedia( groupId: number, albumId: string, mediaKey: string, ): Promise { try { const seenCursors = new Set(); let attachInfo = ''; while (true) { const page = await this.getMediaList(groupId, albumId, attachInfo); const hit = findCommentMedia(page.mediaList, mediaKey); if (hit) return hit; const next = page.nextAttachInfo ?? ''; if (!next || seenCursors.has(next)) return undefined; seenCursors.add(next); attachInfo = next; } } catch (err) { log.debug( 'resolve album comment media failed, using lloc only: group=%d album=%s err=%s', groupId, albumId, err instanceof Error ? err.message : String(err), ); return undefined; } } } interface AlbumDeleteMediaItem { image?: { lloc?: string } | null; video?: { id?: string; cover?: { lloc?: string } | null } | null; batchId?: string | number; } function findDeleteTarget( mediaList: ReadonlyArray, mediaKey: string, ): { mediaId: string; batchId?: string } | undefined { for (const raw of mediaList) { if (!raw || typeof raw !== 'object') continue; const item = raw as AlbumDeleteMediaItem; const batchId = item.batchId === undefined || item.batchId === '' ? undefined : String(item.batchId); if (item.image?.lloc === mediaKey) { return { mediaId: mediaKey, batchId }; } const coverLloc = item.video?.cover?.lloc; if (item.video?.id === mediaKey || coverLloc === mediaKey) { return { mediaId: coverLloc || mediaKey, batchId }; } } return undefined; } interface AlbumCommentMediaItem { type?: number; image?: { name?: string; sloc?: string; lloc?: string; isGif?: boolean; hasRaw?: boolean; } | null; video?: { id?: string; cover?: { name?: string; sloc?: string; lloc?: string; } | null; } | null; uploader?: string; batchId?: string | number | bigint; } function optionalBatchId(value: unknown): bigint | undefined { if (value === undefined || value === null || value === '') return undefined; try { const batchId = BigInt(value as string | number | bigint); return batchId === 0n ? undefined : batchId; } catch { return undefined; } } function mediaInfoForComment(item: AlbumCommentMediaItem | undefined, lloc: string): MediaInfo { if (!item) return { type: 1, image: { lloc } }; const info: MediaInfo = { type: item.type ?? (item.video ? 2 : 1), }; if (item.image) { info.image = { name: item.image.name ?? '', sloc: item.image.sloc ?? '', lloc: item.image.lloc ?? '', isGif: item.image.isGif ?? false, hasRaw: item.image.hasRaw ?? false, }; } if (item.video) { info.video = { id: item.video.id ?? '', ...(item.video.cover ? { cover: { name: item.video.cover.name ?? '', sloc: item.video.cover.sloc ?? '', lloc: item.video.cover.lloc ?? '', }, } : {}), }; } if (item.uploader) info.uploader = String(item.uploader); const batchId = optionalBatchId(item.batchId); if (batchId !== undefined) info.batchId = batchId; return info; } function findCommentMedia( mediaList: ReadonlyArray, mediaKey: string, ): AlbumCommentMediaItem | undefined { for (const raw of mediaList) { if (!raw || typeof raw !== 'object') continue; const item = raw as AlbumCommentMediaItem; if (item.image?.lloc === mediaKey) return item; if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) return item; } return undefined; } function commentFromResponse(resp: DoQunCommentResponse): CommentRespData { const wrapped = resp.comment; if (!wrapped) return {}; if (wrapped.data?.id) return wrapped.data; if (wrapped.id) { return { id: wrapped.id, content: wrapped.content, time: wrapped.time, clientKey: wrapped.clientKey, user: wrapped.data?.user, }; } return wrapped.data ?? {}; } export interface GroupAlbumMediaResult { mediaList: Array>; nextAttachInfo: string; } interface GroupAlbumWireResult { albumList: GroupAlbumInfoWire[]; attachInfo: string; hasMore: boolean; } export interface GroupAlbumInfo { id: string; name: string; picNum: number; createTime: number; desc: string; owner: string; createuin: string; createnickname: string; last_upload_time: number; cover: QunAlbumCover | null; [key: string]: JsonValue; } export type GroupAlbumList = GroupAlbumInfo[]; export interface QunAlbumCreator { uid: string; nick: string; is_sweet: boolean; is_special: boolean; is_super_like: boolean; custom_id: string; poly_id: string; portrait: string; can_follow: number; isfollowed: number; uin: string; ditto_uin: string; } export interface QunAlbumCoverUrl extends JsonObject { url: string; width: number; height: number; } export interface QunAlbumCoverPhotoUrl extends JsonObject { spec: number; url: QunAlbumCoverUrl | null; } export interface QunAlbumCoverImage extends JsonObject { name: string; sloc: string; lloc: string; photoUrls: QunAlbumCoverPhotoUrl[]; defaultUrl: QunAlbumCoverUrl | null; isGif: boolean; hasRaw: boolean; } export interface QunAlbumCover extends JsonObject { type: number; image: QunAlbumCoverImage | null; } export interface QunAlbumInfo { album_id: string; owner: string; name: string; desc: string; create_time: string; modify_time: string; last_upload_time: string; upload_number: string; cover: QunAlbumCover | null; creator?: QunAlbumCreator; top_flag: string; busi_type: number; status: number; allow_share: boolean; is_subscribe: boolean; bitmap: string; is_share_album: boolean; qz_album_type: number; cover_type: number; default_desc: string; sort_type: number; } export interface QunAlbumListResult { albumList: QunAlbumInfo[]; attachInfo: string; hasMore: boolean; } export interface GroupAlbumCommentResult { id: string; user: { uin: string }; content: Array<{ type: number; content: string }>; time: string; clientKey: string; }