Files
SnowLuma/packages/bridge/src/web/group-album.ts
T
DrSmoothl f7a03ca05a refactor(bridge): extract protocol layer into @snowluma/bridge package
Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files —
events / event-bus / identity-service / packet-pipeline / element-
builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* +
the bridge-side formatters — out of `packages/core/src/bridge/`
into the new `@snowluma/bridge` workspace package. Everything that
translates QQ wire bytes ↔ typed events/elements now lives there.

Why
---
- `packages/core/src/bridge/` was actually two layers: a low-level
  "protocol decoder + I/O" set (msg-push, highway, packet-pipeline,
  identity, element-builder) AND the Api-class host (bridge.ts +
  apis/*). The Api layer can't move without the protocol layer
  moving first, but the two had grown into one directory.
- Bridge-internal consumers (highway uploaders, OIDB envelope
  helper, element-builder, msg-push parsers) only ever needed
  `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata
  cache. Splitting them out lets that minimal surface live in the
  bridge package as `BridgeContext` while the api-layer's extended
  context (with `apis: ApiHub`) stays in @snowluma/core.

What stays in @snowluma/core (apis layer):
  - bridge.ts          ── the god-class that composes the protocol
                          building blocks + mounts apis
  - bridge-interface.ts ── public façade for OneBot consumers
  - manager.ts          ── per-uin BridgeManager hub
  - apis/*              ── the 13 typed Api classes
  - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim
                              BridgeContext with `apis: ApiHub` so
                              the 13 Api classes keep their typed
                              `this.ctx.apis.X.method()` access.

Layout
------
Moved via `git mv` (history preserved):
  events / event-bus / identity-service / packet-pipeline /
  element-builder / bridge-oidb / qq-info / msg-push/* /
  highway/* / web/*           → @snowluma/bridge/<sub>
  utils/event-format.ts        → @snowluma/bridge/format.ts

  (the last one renamed because the destination directory only has
  bridge-related files; `format.ts` reads cleaner than `event-format`.
  Listed as a rename in git's `RM` output — content unchanged.)

Layering fixes (functionality preserved, just type signatures)
--------------------------------------------------------------
- `element-builder.SendContext.bridge` → typed as `BridgeContext`
  instead of `Bridge`. Reads only `bridge.identity` and the
  upload-cache (both on BridgeContext); the concrete `Bridge`
  instance still passes via free upcast.
- `bridge-oidb.runOidb` signature widened from `Bridge` to
  `BridgeContext` — same reason.
- `highway/{highway-client,pipeline,image-upload,ptt-upload,
  video-upload}.ts` — same.
- `format.ts::formatReply` parameter typed as a new local
  `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject |
  null }`) instead of `MessageStore` from @snowluma/onebot. The
  OneBot `MessageStore` is a structural superset; consumers pass
  it through unchanged.
- JSON value types moved to a new `@snowluma/common/json` subpath
  (consumed by format.ts) — `onebot/types.ts` re-exports them so
  external `import { JsonValue } from '<…>/onebot/types'` paths
  keep working.
- `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts`
  into `@snowluma/bridge/bridge-context.ts` — element-builder + the
  forward-builder both read the upload cache through BridgeContext,
  so the type has to live in @snowluma/bridge. `bridge.ts` keeps
  its re-export for back-compat.

Changes
-------
- New package `packages/bridge/` (package.json with per-file subpath
  exports mirroring legacy `core/src/bridge/<x>` layout 1:1,
  tsconfig.json, typecheck script).
- 35 `.ts` files moved via `git mv` (3 files counted by git as
  RM — rename + modify because Bridge → BridgeContext type swap).
- 150+ import sites rewritten across `packages/core/src` and
  `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`,
  `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest
  `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`.
- `@snowluma/core` depends on `@snowluma/bridge` (workspace:*).
- `@snowluma/bridge` depends on `@snowluma/common`,
  `@snowluma/proto-defs`, `@snowluma/proton`.
- `packages/core/src/utils/` directory removed (empty).

Verification
------------
- Full workspace `pnpm -r typecheck`: all 10 projects clean.
- core test suite: 552 passed / 552 total (pre-existing
  websocket-darwin-arm64.node addon failure unchanged — same
  baseline as the previous refactor commits).
- Vite build (with stubbed native binary): clean — 143 modules,
  2.84 MB bundle / 224 KB gzip, identical envelope to the
  pre-split build.

Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The
runnable `index.ts` stays in @snowluma/core as the application
entry, importing `OneBotManager` from `@snowluma/onebot`.
2026-05-21 08:41:34 +08:00

251 lines
6.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { createHash } from 'crypto';
import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
import { basename, join } from 'path';
import { tmpdir } from 'os';
// 群相册信息
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 */ }
}
}
}