feat: 群相册支持多图同批次上传与视频上传,分片上传改为并发 (#2081)
- 新增 upload_images_to_qun_album:多张图片共用一个批次,相册里显示为同一条 - 新增 upload_video_to_qun_album:上传视频并自动抽取首帧作为封面 - 分片大小改用服务端返回的 slice_size,分片并发上传,最后一片等其它分片传完再发 - 摘要改为流式计算,分片按需读取,不再把整个文件读进内存 - 批次号同一秒内递增,避免两次上传被并成一条
This commit is contained in:
1 parent
c0fd089539
commit
a8f6a57311
12 files changed
+913
-87
No files matched your search
@@ -8,11 +8,14 @@ import {
|
||||
WebHonorType, NapCatCore,
|
||||
} from '@/napcat-core/index';
|
||||
|
||||
import { createReadStream, readFileSync, statSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { basename } from 'node:path';
|
||||
import { qunAlbumControl } from '../data/webapi';
|
||||
import { createReadStream, existsSync, statSync } from 'node:fs';
|
||||
import { open, unlink, writeFile, type FileHandle } from 'node:fs/promises';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { basename, join } from 'node:path';
|
||||
import { qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl, QunAlbumBatch, nextQunAlbumBatchId } from '../data/webapi';
|
||||
import { createAlbumCommentRequest, createAlbumFeedPublish, createAlbumMediaFeed } from '../data/album';
|
||||
import { FFmpegService } from '../helper/ffmpeg/ffmpeg';
|
||||
import { defaultVideoThumbB64 } from '../helper/ffmpeg/video';
|
||||
import {
|
||||
buildQzoneDeleteBody,
|
||||
buildQzonePublishBody,
|
||||
@@ -35,6 +38,34 @@ export interface SetNoticeRetSuccess {
|
||||
srv_code: number;
|
||||
}
|
||||
|
||||
// 群相册分片上传的并发数
|
||||
const QUN_ALBUM_SLICE_CONCURRENCY = 8;
|
||||
// 服务端没给分片大小时的下限,以及防止异常值的上限
|
||||
const QUN_ALBUM_SLICE_MIN = 16384;
|
||||
const QUN_ALBUM_SLICE_MAX = 4 * 1024 * 1024;
|
||||
|
||||
// 流式计算文件摘要,避免为了算 MD5/SHA1 把整个文件读进内存(视频可能有几十上百 MB)
|
||||
function hashFile (path: string, algorithm: 'md5' | 'sha1'): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = createHash(algorithm);
|
||||
createReadStream(path)
|
||||
.on('data', chunk => hash.update(chunk))
|
||||
.on('end', () => resolve(hash.digest('hex')))
|
||||
.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
// 按需读取单个分片:并发上传时的内存占用只有「并发数 × 分片大小」
|
||||
async function readSlice (handle: FileHandle, offset: number, length: number): Promise<Buffer> {
|
||||
const buffer = Buffer.alloc(length);
|
||||
const { bytesRead } = await handle.read(buffer, 0, length, offset);
|
||||
// 读不满说明文件在上传过程中被改短了,继续传只会传上去一段补零的数据
|
||||
if (bytesRead !== length) {
|
||||
throw new Error(`读取分片失败: offset=${offset} 预期 ${length} 字节,实际 ${bytesRead} 字节`);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
export class NTQQWebApi {
|
||||
context: InstanceContext;
|
||||
core: NapCatCore;
|
||||
@@ -382,9 +413,11 @@ export class NTQQWebApi {
|
||||
return response.data.album;
|
||||
}
|
||||
|
||||
async createQunAlbumSession (gc: string, sAlbumID: string, sAlbumName: string, path: string, skey: string, pskey: string, img_md5: string, uin: string) {
|
||||
const img = readFileSync(path);
|
||||
const img_size = img.length;
|
||||
async createQunAlbumSession (
|
||||
gc: string, sAlbumID: string, sAlbumName: string, path: string,
|
||||
skey: string, pskey: string, img_md5: string, uin: string, batch?: QunAlbumBatch
|
||||
) {
|
||||
const img_size = statSync(path).size;
|
||||
const img_name = basename(path);
|
||||
const GTK = this.getBknFromSKey(skey);
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
@@ -397,42 +430,76 @@ export class NTQQWebApi {
|
||||
img_name,
|
||||
sAlbumName,
|
||||
sAlbumID,
|
||||
// 同批多图共用 batchId,并按「第几张 / 共几张」上报,相册里才会合并成同一条
|
||||
batchId: batch?.batchId,
|
||||
batchIndex: batch?.index,
|
||||
photo_num: batch?.count,
|
||||
batch_num: batch?.count,
|
||||
});
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${img_md5}?g_tk=${GTK}`;
|
||||
const post = await RequestUtil.HttpGetJson<{ data: { session: string; }, ret: number, msg: string; }>(api, 'POST', body, {
|
||||
const post = await RequestUtil.HttpGetJson<{
|
||||
data: { session: string; slice_size?: number | string; },
|
||||
ret: number,
|
||||
msg: string;
|
||||
}>(api, 'POST', body, {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
return post;
|
||||
}
|
||||
|
||||
async uploadQunAlbumSlice (path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number) {
|
||||
// 服务端会在会话响应里给出建议的分片大小;取不到或异常时退回 16384。
|
||||
private resolveQunAlbumSliceSize (raw: unknown) {
|
||||
const value = Number(raw);
|
||||
if (!Number.isFinite(value) || value < QUN_ALBUM_SLICE_MIN) return QUN_ALBUM_SLICE_MIN;
|
||||
return Math.min(value, QUN_ALBUM_SLICE_MAX);
|
||||
}
|
||||
|
||||
async uploadQunAlbumSlice (
|
||||
path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number,
|
||||
options: { appid?: string, cmd?: string; } = {}
|
||||
) {
|
||||
const appid = options.appid ?? 'qun';
|
||||
const cmd = options.cmd ?? 'FileUpload';
|
||||
const img_size = statSync(path).size;
|
||||
let seq = 0;
|
||||
let offset = 0;
|
||||
const GTK = this.getBknFromSKey(skey);
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
|
||||
const stream = createReadStream(path, { highWaterMark: slice_size });
|
||||
// 只记分片位置,不预先读内容;再并发上传(串行上传在几 MB 的图上要几十秒)
|
||||
const slices: { seq: number, offset: number, end: number; }[] = [];
|
||||
let seq = 0;
|
||||
let offset = 0;
|
||||
while (offset < img_size) {
|
||||
const end = Math.min(offset + slice_size, img_size);
|
||||
slices.push({ seq, offset, end });
|
||||
offset = end;
|
||||
seq++;
|
||||
}
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const end = Math.min(offset + chunk.length, img_size);
|
||||
// 视频分片响应里会带 sVid,封面二段上传要靠它把封面挂到视频上
|
||||
let sVid: string | undefined;
|
||||
|
||||
const handle = await open(path, 'r');
|
||||
const uploadSlice = async (slice: { seq: number, offset: number, end: number; }) => {
|
||||
const chunk = await readSlice(handle, slice.offset, slice.end - slice.offset);
|
||||
const form = new FormData();
|
||||
form.append('uin', uin);
|
||||
form.append('appid', 'qun');
|
||||
form.append('appid', appid);
|
||||
form.append('session', session);
|
||||
form.append('offset', offset.toString());
|
||||
form.append('offset', slice.offset.toString());
|
||||
form.append('data', new Blob([chunk], { 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('seq', slice.seq.toString());
|
||||
form.append('end', slice.end.toString());
|
||||
form.append('cmd', cmd);
|
||||
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=${GTK}`;
|
||||
// 分片路径必须与 cmd 一致:视频走 /sliceUpload/FileUploadVideo,
|
||||
// 否则服务端按图片处理,分片会「成功」但响应里没有 sVid
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/${cmd}?seq=${slice.seq}&retry=0&offset=${slice.offset}&end=${slice.end}&total=${img_size}&type=form&g_tk=${GTK}`;
|
||||
const response = await fetch(api, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -445,24 +512,153 @@ export class NTQQWebApi {
|
||||
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}`);
|
||||
const post = await response.json() as { ret: number, msg: string, data?: { biz?: { sVid?: string; }; }; };
|
||||
if (post.ret !== 0) {
|
||||
throw new Error(`分片 ${slice.seq} 上传失败: ${post.msg}`);
|
||||
}
|
||||
offset += chunk.length;
|
||||
seq++;
|
||||
if (!sVid && typeof post.data?.biz?.sVid === 'string' && post.data.biz.sVid) {
|
||||
sVid = post.data.biz.sVid;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
// 最后一片要等前面的全部传完再发:服务端收到最后一片就认为文件传完了,
|
||||
// 并发时它可能比前面的分片先到
|
||||
const lastSlice = slices.pop();
|
||||
let next = 0;
|
||||
let failure: { error: unknown; } | undefined;
|
||||
// 固定数量的 worker 各自领下一片,慢的分片不会拖住整批
|
||||
const worker = async () => {
|
||||
while (!failure) {
|
||||
const slice = slices[next++];
|
||||
if (!slice) break;
|
||||
try {
|
||||
await uploadSlice(slice);
|
||||
} catch (error) {
|
||||
if (!failure) failure = { error };
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(QUN_ALBUM_SLICE_CONCURRENCY, slices.length) }, worker));
|
||||
if (failure) throw failure.error;
|
||||
if (lastSlice) await uploadSlice(lastSlice);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
|
||||
return { success: true, message: '上传完成' };
|
||||
return { success: true, message: '上传完成', sVid };
|
||||
}
|
||||
|
||||
// 多张图片一次上传:共用同一个 batchId,相册里显示为同一条
|
||||
async uploadImagesToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, paths: string[]) {
|
||||
if (!paths.length) throw new Error('上传列表为空');
|
||||
const skey = await this.core.apis.UserApi.getSKey() || '';
|
||||
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
const batchId = nextQunAlbumBatchId();
|
||||
const count = paths.length.toString();
|
||||
|
||||
for (const [index, path] of paths.entries()) {
|
||||
const img_md5 = await hashFile(path, 'md5');
|
||||
const post = await this.createQunAlbumSession(
|
||||
gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin,
|
||||
{ batchId, count, index: index.toString() }
|
||||
);
|
||||
if (!post.data?.session) throw new Error(`创建群相册会话失败: ${post.msg || post.ret}`);
|
||||
await this.uploadQunAlbumSlice(path, post.data.session, skey, pskey, uin, this.resolveQunAlbumSliceSize(post.data.slice_size));
|
||||
}
|
||||
}
|
||||
|
||||
async uploadImageToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
|
||||
await this.uploadImagesToQunAlbum(gc, sAlbumID, sAlbumName, [path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传视频到群相册。
|
||||
*
|
||||
* 分三步:
|
||||
* 1. 建视频会话:appid=video_qun / cmd=FileUploadVideo / SHA1 校验,此时不带相册
|
||||
* 2. 分片上传视频,从分片响应里拿 sVid
|
||||
* 3. 按图片上传封面并用 vid 关联视频,相册和批次号在这一步带上,视频随封面进相册
|
||||
*/
|
||||
async uploadVideoToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
|
||||
const skey = await this.core.apis.UserApi.getSKey() || '';
|
||||
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
|
||||
const img_md5 = createHash('md5').update(readFileSync(path)).digest('hex');
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
const session = (await this.createQunAlbumSession(gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin)).data.session;
|
||||
if (!session) throw new Error('创建群相册会话失败');
|
||||
await this.uploadQunAlbumSlice(path, session, skey, pskey, uin, 16384);
|
||||
const GTK = this.getBknFromSKey(skey);
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
const video_sha1 = await hashFile(path, 'sha1');
|
||||
|
||||
// 时长:ffmpeg 不可用时上报 0
|
||||
let playTime = 0;
|
||||
try {
|
||||
playTime = Math.max(0, Math.round(await FFmpegService.getDuration(path)));
|
||||
} catch (e) {
|
||||
this.context.logger.logWarn('获取视频时长失败,iPlayTime 上报 0', e);
|
||||
}
|
||||
|
||||
// 1) 视频主体(不带相册,只传成素材)
|
||||
const videoSession = await RequestUtil.HttpGetJson<{
|
||||
data: { session: string; slice_size?: number | string; },
|
||||
ret: number,
|
||||
msg: string;
|
||||
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${video_sha1}?g_tk=${GTK}`, 'POST', qunAlbumVideoControl({
|
||||
uin,
|
||||
group_id: gc,
|
||||
pskey,
|
||||
video_sha1,
|
||||
video_size: statSync(path).size,
|
||||
play_time: playTime,
|
||||
}), {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
if (!videoSession.data?.session) throw new Error(`创建群相册视频会话失败: ${videoSession.msg || videoSession.ret}`);
|
||||
|
||||
const uploaded = await this.uploadQunAlbumSlice(path, videoSession.data.session, skey, pskey, uin,
|
||||
this.resolveQunAlbumSliceSize(videoSession.data.slice_size), { appid: 'video_qun', cmd: 'FileUploadVideo' });
|
||||
if (!uploaded.sVid) throw new Error('视频上传完成但未取得 sVid,无法挂进相册');
|
||||
|
||||
// 2) 封面:抽首帧,失败(含 ffmpeg 不可用)回落内置默认封面
|
||||
// 用 .png:Native Addon 路径产出的就是 png(日志里可见 Detected format: png),
|
||||
// 而命令行路径会按扩展名编码,两条路都能得到真正的 PNG
|
||||
const coverPath = join(this.core.NapCatTempPath, `${randomUUID()}.png`);
|
||||
try {
|
||||
try {
|
||||
await FFmpegService.extractThumbnail(path, coverPath);
|
||||
} catch (e) {
|
||||
this.context.logger.logWarn('提取视频封面失败,使用默认封面', e);
|
||||
await writeFile(coverPath, Buffer.from(defaultVideoThumbB64, 'base64'));
|
||||
}
|
||||
|
||||
// 3) 封面二段上传:这一步才带相册和批次号,视频靠它进相册
|
||||
const cover_md5 = await hashFile(coverPath, 'md5');
|
||||
const coverSession = await RequestUtil.HttpGetJson<{
|
||||
data: { session: string; slice_size?: number | string; },
|
||||
ret: number,
|
||||
msg: string;
|
||||
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${cover_md5}?g_tk=${GTK}`, 'POST', qunAlbumVideoCoverControl({
|
||||
uin,
|
||||
group_id: gc,
|
||||
pskey,
|
||||
sAlbumName,
|
||||
sAlbumID,
|
||||
cover_md5,
|
||||
cover_size: statSync(coverPath).size,
|
||||
vid: uploaded.sVid,
|
||||
}), {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
if (!coverSession.data?.session) throw new Error(`创建群相册视频封面会话失败: ${coverSession.msg || coverSession.ret}`);
|
||||
|
||||
await this.uploadQunAlbumSlice(coverPath, coverSession.data.session, skey, pskey, uin,
|
||||
this.resolveQunAlbumSliceSize(coverSession.data.slice_size));
|
||||
} finally {
|
||||
if (existsSync(coverPath)) {
|
||||
await unlink(coverPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getAlbumMediaListByNTQQ (gc: string, albumId: string, attach_info: string = '') {
|
||||
|
||||
@@ -18,20 +18,64 @@ export interface BizReq {
|
||||
iBatchID: number;
|
||||
iBitmap: number;
|
||||
iDistinctUse: number;
|
||||
iNeedFeeds: number;
|
||||
iNeedFeeds?: number;
|
||||
iPicHight: number;
|
||||
iPicWidth: number;
|
||||
iUploadTime: number;
|
||||
iUploadType: number;
|
||||
iUpPicType: number;
|
||||
iWaterType: number;
|
||||
mapExt: MapExt;
|
||||
mapExt?: MapExt;
|
||||
mutliPicInfo?: MutliPicInfo;
|
||||
sAlbumID: string;
|
||||
sAlbumName: string;
|
||||
sPicDesc: string;
|
||||
sPicPath: string;
|
||||
sPicTitle: string;
|
||||
stExtendInfo: StExtendInfo;
|
||||
stExtendInfo?: StExtendInfo;
|
||||
// 视频主体上传专用
|
||||
extend_info?: VideoExtendInfo;
|
||||
iFlag?: number;
|
||||
iIsFormatF20?: number;
|
||||
iIsNew?: number;
|
||||
iIsOriginalVideo?: number;
|
||||
iPlayTime?: number;
|
||||
sCoverUrl?: string;
|
||||
sDesc?: string;
|
||||
sTitle?: string;
|
||||
// 视频封面二段上传专用
|
||||
stExternalMapExt?: StExternalMapExt;
|
||||
sExif_CameraMaker?: string;
|
||||
sExif_CameraModel?: string;
|
||||
sExif_Latitude?: string;
|
||||
sExif_LatitudeRef?: string;
|
||||
sExif_Longitude?: string;
|
||||
sExif_LongitudeRef?: string;
|
||||
sExif_Time?: string;
|
||||
}
|
||||
|
||||
// 多图同批上传时描述「本批共几张 / 当前第几张」,相册里据此合并成同一条
|
||||
export interface MutliPicInfo {
|
||||
iBatUploadNum: string;
|
||||
iCurUpload: string;
|
||||
iSuccNum: number;
|
||||
iFailNum: number;
|
||||
}
|
||||
|
||||
// 视频主体上传用(视频不走 stExtendInfo.mapParams,而是这段扩展信息)
|
||||
export interface VideoExtendInfo {
|
||||
video_type: string;
|
||||
domainid: string;
|
||||
photo_num: string;
|
||||
video_num: string;
|
||||
batch_num: string;
|
||||
qun_id: string;
|
||||
}
|
||||
|
||||
// 视频封面二段上传用:声明这是客户端上传的封面,且与图片混合在同一条动态里
|
||||
export interface StExternalMapExt {
|
||||
is_client_upload_cover: string;
|
||||
is_pic_video_mix_feeds: string;
|
||||
}
|
||||
|
||||
export interface MapExt {
|
||||
@@ -47,6 +91,8 @@ export interface MapParams {
|
||||
batch_num: string;
|
||||
photo_num: string;
|
||||
video_num: string;
|
||||
// 视频封面二段上传时用它把封面挂到已上传的视频上
|
||||
vid?: string;
|
||||
}
|
||||
|
||||
export interface Env {
|
||||
@@ -60,6 +106,96 @@ export interface Token {
|
||||
type: number;
|
||||
}
|
||||
|
||||
// 一次上传的批次信息:同批的多张图必须共用 batchId,相册里才会显示成同一条。
|
||||
export interface QunAlbumBatch {
|
||||
batchId: number,
|
||||
count: string,
|
||||
index: string
|
||||
}
|
||||
|
||||
let lastQunAlbumBatchId = 0;
|
||||
|
||||
// 批次号取秒级时间戳。同一秒里发起的两次上传要错开,不然会被相册并成同一条
|
||||
export function nextQunAlbumBatchId () {
|
||||
lastQunAlbumBatchId = Math.max(Math.floor(Date.now() / 1000), lastQunAlbumBatchId + 1);
|
||||
return lastQunAlbumBatchId;
|
||||
}
|
||||
|
||||
// control_req 的外层(鉴权、来源、会话),图片、视频、封面都一样
|
||||
function buildQunAlbumControlReq (
|
||||
{ uin, pskey, appid, checksum, check_type, file_len, refer = 'qzone', cmd }: {
|
||||
uin: string,
|
||||
pskey: string,
|
||||
appid: string,
|
||||
checksum: string,
|
||||
check_type: number,
|
||||
file_len: number,
|
||||
refer?: string,
|
||||
cmd?: string
|
||||
},
|
||||
biz_req: BizReq
|
||||
): ControlReq {
|
||||
const req: ControlReq = {
|
||||
uin,
|
||||
token: { type: 4, data: pskey, appid: 5 },
|
||||
appid,
|
||||
checksum,
|
||||
check_type,
|
||||
file_len,
|
||||
env: { refer, deviceInfo: 'h5' },
|
||||
model: 0,
|
||||
biz_req,
|
||||
session: '',
|
||||
asy_upload: 0,
|
||||
};
|
||||
if (cmd) req.cmd = cmd;
|
||||
return req;
|
||||
}
|
||||
|
||||
// biz_req 里三种上传都要带的基础字段
|
||||
function buildQunAlbumBizBase (
|
||||
{ iUploadType, sAlbumName = '', sAlbumID = '', iBatchID = 0, sPicTitle = '' }: {
|
||||
iUploadType: number,
|
||||
sAlbumName?: string,
|
||||
sAlbumID?: string,
|
||||
iBatchID?: number,
|
||||
sPicTitle?: string
|
||||
}
|
||||
): BizReq {
|
||||
return {
|
||||
sPicTitle,
|
||||
sPicDesc: '',
|
||||
sAlbumName,
|
||||
sAlbumID,
|
||||
iAlbumTypeID: 0,
|
||||
iBitmap: 0,
|
||||
iUploadType,
|
||||
iUpPicType: 0,
|
||||
iBatchID,
|
||||
sPicPath: '',
|
||||
iPicWidth: 0,
|
||||
iPicHight: 0,
|
||||
iWaterType: 0,
|
||||
iDistinctUse: 0,
|
||||
iUploadTime: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
}
|
||||
|
||||
// 进相册的那一步(图片、视频封面)要带的群与批次信息
|
||||
function buildQunAlbumFeedFields (group_id: string, mapParams: MapParams, batchIndex: string) {
|
||||
return {
|
||||
iNeedFeeds: 1,
|
||||
mapExt: { appid: 'qun', userid: group_id },
|
||||
stExtendInfo: { mapParams },
|
||||
mutliPicInfo: {
|
||||
iBatUploadNum: mapParams.batch_num,
|
||||
iCurUpload: batchIndex,
|
||||
iSuccNum: 0,
|
||||
iFailNum: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function qunAlbumControl ({
|
||||
uin,
|
||||
group_id,
|
||||
@@ -72,6 +208,8 @@ export function qunAlbumControl ({
|
||||
photo_num = '1',
|
||||
video_num = '0',
|
||||
batch_num = '1',
|
||||
batchId = nextQunAlbumBatchId(),
|
||||
batchIndex = '0',
|
||||
}: {
|
||||
uin: string,
|
||||
group_id: string,
|
||||
@@ -83,64 +221,21 @@ export function qunAlbumControl ({
|
||||
sAlbumID: string,
|
||||
photo_num?: string,
|
||||
video_num?: string,
|
||||
batch_num?: string
|
||||
batch_num?: string,
|
||||
batchId?: number,
|
||||
batchIndex?: string
|
||||
}
|
||||
): {
|
||||
control_req: ControlReq[]
|
||||
} {
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
|
||||
return {
|
||||
control_req: [
|
||||
control_req: [buildQunAlbumControlReq(
|
||||
{ uin, pskey, appid: 'qun', checksum: pic_md5, check_type: 0, file_len: img_size, cmd: 'FileUpload' },
|
||||
{
|
||||
uin,
|
||||
token: {
|
||||
type: 4,
|
||||
data: pskey,
|
||||
appid: 5,
|
||||
},
|
||||
appid: 'qun',
|
||||
checksum: pic_md5,
|
||||
check_type: 0,
|
||||
file_len: img_size,
|
||||
env: {
|
||||
refer: 'qzone',
|
||||
deviceInfo: 'h5',
|
||||
},
|
||||
model: 0,
|
||||
biz_req: {
|
||||
sPicTitle: img_name,
|
||||
sPicDesc: '',
|
||||
sAlbumName,
|
||||
sAlbumID,
|
||||
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: group_id,
|
||||
},
|
||||
stExtendInfo: {
|
||||
mapParams: {
|
||||
photo_num,
|
||||
video_num,
|
||||
batch_num,
|
||||
},
|
||||
},
|
||||
},
|
||||
session: '',
|
||||
asy_upload: 0,
|
||||
cmd: 'FileUpload',
|
||||
}],
|
||||
...buildQunAlbumBizBase({ iUploadType: 0, sAlbumName, sAlbumID, iBatchID: batchId, sPicTitle: img_name }),
|
||||
...buildQunAlbumFeedFields(group_id, { photo_num, video_num, batch_num }, batchIndex),
|
||||
}
|
||||
)],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -174,3 +269,118 @@ export function createStreamUpload (
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 视频主体上传的控制体。
|
||||
*
|
||||
* 视频这一步不进相册(相册留空,iBatchID 为 0),只是先把视频传成素材;
|
||||
* 分片响应里拿到 sVid 后,再由封面上传(qunAlbumVideoCoverControl)把视频挂进相册。
|
||||
*/
|
||||
export function qunAlbumVideoControl ({
|
||||
uin,
|
||||
group_id,
|
||||
pskey,
|
||||
video_sha1,
|
||||
video_size,
|
||||
play_time = 0,
|
||||
photo_num = '0',
|
||||
video_num = '1',
|
||||
batch_num = '1',
|
||||
}: {
|
||||
uin: string,
|
||||
group_id: string,
|
||||
pskey: string,
|
||||
video_sha1: string,
|
||||
video_size: number,
|
||||
play_time?: number,
|
||||
photo_num?: string,
|
||||
video_num?: string,
|
||||
batch_num?: string
|
||||
}): {
|
||||
control_req: ControlReq[]
|
||||
} {
|
||||
return {
|
||||
control_req: [buildQunAlbumControlReq(
|
||||
{ uin, pskey, appid: 'video_qun', checksum: video_sha1, check_type: 1, file_len: video_size, cmd: 'FileUploadVideo' },
|
||||
{
|
||||
...buildQunAlbumBizBase({ iUploadType: 3 }),
|
||||
sTitle: '',
|
||||
sDesc: '',
|
||||
sCoverUrl: '',
|
||||
iFlag: 0,
|
||||
iPlayTime: play_time,
|
||||
iIsNew: 111,
|
||||
iIsOriginalVideo: 0,
|
||||
iIsFormatF20: 0,
|
||||
extend_info: {
|
||||
video_type: '3',
|
||||
domainid: '5',
|
||||
photo_num,
|
||||
video_num,
|
||||
batch_num,
|
||||
qun_id: group_id,
|
||||
},
|
||||
}
|
||||
)],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 视频封面上传的控制体。
|
||||
*
|
||||
* 按图片上传,但 iUploadType 为 2,并用 mapParams.vid 指向已上传的视频。
|
||||
* 相册和批次号只在这一步出现,视频是靠封面进的相册。
|
||||
*/
|
||||
export function qunAlbumVideoCoverControl ({
|
||||
uin,
|
||||
group_id,
|
||||
pskey,
|
||||
sAlbumName,
|
||||
sAlbumID,
|
||||
cover_md5,
|
||||
cover_size,
|
||||
vid,
|
||||
batchId = nextQunAlbumBatchId(),
|
||||
batchIndex = '0',
|
||||
photo_num = '0',
|
||||
video_num = '1',
|
||||
batch_num = '1',
|
||||
}: {
|
||||
uin: string,
|
||||
group_id: string,
|
||||
pskey: string,
|
||||
sAlbumName: string,
|
||||
sAlbumID: string,
|
||||
cover_md5: string,
|
||||
cover_size: number,
|
||||
vid: string,
|
||||
batchId?: number,
|
||||
batchIndex?: string,
|
||||
photo_num?: string,
|
||||
video_num?: string,
|
||||
batch_num?: string
|
||||
}): {
|
||||
control_req: ControlReq[]
|
||||
} {
|
||||
return {
|
||||
control_req: [buildQunAlbumControlReq(
|
||||
{ uin, pskey, appid: 'qun', checksum: cover_md5, check_type: 0, file_len: cover_size, refer: 'huodong' },
|
||||
{
|
||||
...buildQunAlbumBizBase({ iUploadType: 2, sAlbumName, sAlbumID, iBatchID: batchId }),
|
||||
...buildQunAlbumFeedFields(group_id, { vid, photo_num, video_num, batch_num }, batchIndex),
|
||||
// 标明封面由客户端上传,且允许和图片出现在同一条动态里
|
||||
stExternalMapExt: {
|
||||
is_client_upload_cover: '1',
|
||||
is_pic_video_mix_feeds: '1',
|
||||
},
|
||||
sExif_CameraMaker: '',
|
||||
sExif_CameraModel: '',
|
||||
sExif_Time: '',
|
||||
sExif_LatitudeRef: '',
|
||||
sExif_Latitude: '',
|
||||
sExif_LongitudeRef: '',
|
||||
sExif_Longitude: '',
|
||||
}
|
||||
)],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { uriToLocalFile } from 'napcat-common/src/file';
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { unlink } from 'node:fs/promises';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
album_id: Type.String({ description: '相册ID' }),
|
||||
album_name: Type.String({ description: '相册名称' }),
|
||||
files: Type.Array(Type.String(), { description: '图片路径、URL或Base64 数组,一次上传多张' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Any({ description: '上传结果' });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class UploadImagesToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.UploadImagesToQunAlbum;
|
||||
override actionSummary = '上传多张图片到群相册';
|
||||
override actionDescription = '一次上传多张图片,这些图片在群相册里显示为同一条上传';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
album_name: '相册1',
|
||||
files: ['/path/to/1.jpg', '/path/to/2.jpg'],
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: null,
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
if (!payload.files.length) throw new Error('files 不能为空');
|
||||
const localPaths: string[] = [];
|
||||
const tempPaths: string[] = [];
|
||||
try {
|
||||
for (const file of payload.files) {
|
||||
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, file);
|
||||
localPaths.push(downloadResult.path);
|
||||
if (!downloadResult.isLocal && downloadResult.path) {
|
||||
tempPaths.push(downloadResult.path);
|
||||
}
|
||||
}
|
||||
return await this.core.apis.WebApi.uploadImagesToQunAlbum(
|
||||
payload.group_id,
|
||||
payload.album_id,
|
||||
payload.album_name,
|
||||
localPaths
|
||||
);
|
||||
} finally {
|
||||
for (const path of tempPaths) {
|
||||
if (existsSync(path)) {
|
||||
await unlink(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { uriToLocalFile } from 'napcat-common/src/file';
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { unlink } from 'node:fs/promises';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
album_id: Type.String({ description: '相册ID' }),
|
||||
album_name: Type.String({ description: '相册名称' }),
|
||||
file: Type.String({ description: '视频路径、URL或Base64' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Any({ description: '上传结果' });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class UploadVideoToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.UploadVideoToQunAlbum;
|
||||
override actionSummary = '上传视频到群相册';
|
||||
override actionDescription = '上传视频到群相册,封面自动抽取首帧(失败时使用内置默认封面)';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
album_name: '相册1',
|
||||
file: '/path/to/video.mp4',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: null,
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
|
||||
try {
|
||||
return await this.core.apis.WebApi.uploadVideoToQunAlbum(
|
||||
payload.group_id,
|
||||
payload.album_id,
|
||||
payload.album_name,
|
||||
downloadResult.path
|
||||
);
|
||||
} finally {
|
||||
if (!downloadResult.isLocal && downloadResult.path && existsSync(downloadResult.path)) {
|
||||
await unlink(downloadResult.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,8 @@ import { CancelGroupTodo } from './packet/CancelGroupTodo';
|
||||
import { SetGroupTodo } from './packet/SetGroupTodo';
|
||||
import { GetQunAlbumList } from './extends/GetQunAlbumList';
|
||||
import { UploadImageToQunAlbum } from './extends/UploadImageToQunAlbum';
|
||||
import { UploadImagesToQunAlbum } from './extends/UploadImagesToQunAlbum';
|
||||
import { UploadVideoToQunAlbum } from './extends/UploadVideoToQunAlbum';
|
||||
import { DoGroupAlbumComment } from './extends/DoGroupAlbumComment';
|
||||
import { GetGroupAlbumMediaList } from './extends/GetGroupAlbumMediaList';
|
||||
import { SetGroupAlbumMediaLike, CancelGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
|
||||
@@ -182,6 +184,8 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetGroupAlbumMediaList(obContext, core),
|
||||
new GetQunAlbumList(obContext, core),
|
||||
new UploadImageToQunAlbum(obContext, core),
|
||||
new UploadImagesToQunAlbum(obContext, core),
|
||||
new UploadVideoToQunAlbum(obContext, core),
|
||||
new SetGroupTodo(obContext, core),
|
||||
new CompleteGroupTodo(obContext, core),
|
||||
new CancelGroupTodo(obContext, core),
|
||||
|
||||
@@ -28,6 +28,8 @@ export const ActionName = {
|
||||
DoGroupAlbumComment: 'do_group_album_comment',
|
||||
GetGroupAlbumMediaList: 'get_group_album_media_list',
|
||||
UploadImageToQunAlbum: 'upload_image_to_qun_album',
|
||||
UploadImagesToQunAlbum: 'upload_images_to_qun_album',
|
||||
UploadVideoToQunAlbum: 'upload_video_to_qun_album',
|
||||
GetQunAlbumList: 'get_qun_album_list',
|
||||
SetGroupTodo: 'set_group_todo',
|
||||
CompleteGroupTodo: 'complete_group_todo',
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"napcat-vite": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1",
|
||||
"tsx": "^4.7.1",
|
||||
"vite": "^6.0.0"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { NTQQWebApi } from '@/napcat-core/apis/webapi';
|
||||
import { nextQunAlbumBatchId, qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl } from '@/napcat-core/data/webapi';
|
||||
|
||||
const GROUP_ID = '2161015335';
|
||||
const ALBUM_ID = 'V624Oe3c1Dk7pX4et6lh4703uM49iGAR';
|
||||
const ALBUM_NAME = '水哥';
|
||||
const UIN = '2965296625';
|
||||
|
||||
// control_req 在严格模式(noUncheckedIndexedAccess)下是可选元素,这里统一收敛掉
|
||||
const firstReq = (body: { control_req: unknown[] }) => {
|
||||
const req = body.control_req[0];
|
||||
if (!req) throw new Error('control_req 为空');
|
||||
return req as NonNullable<ReturnType<typeof qunAlbumControl>['control_req'][0]>;
|
||||
};
|
||||
|
||||
const imageReq = (overrides: Record<string, unknown> = {}) => firstReq(qunAlbumControl({
|
||||
uin: UIN,
|
||||
group_id: GROUP_ID,
|
||||
pskey: 'PSKEY',
|
||||
pic_md5: 'MD5A',
|
||||
img_size: 12345,
|
||||
img_name: 'a.jpg',
|
||||
sAlbumName: ALBUM_NAME,
|
||||
sAlbumID: ALBUM_ID,
|
||||
...overrides,
|
||||
}));
|
||||
|
||||
describe('群相册图片组包', () => {
|
||||
it('单图:字段与改动前一致,批次号为秒级时间戳', () => {
|
||||
const req = imageReq();
|
||||
|
||||
expect(req.appid).toBe('qun');
|
||||
expect(req.cmd).toBe('FileUpload');
|
||||
expect(req.check_type).toBe(0);
|
||||
expect(req.checksum).toBe('MD5A');
|
||||
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
|
||||
expect(req.biz_req?.sPicTitle).toBe('a.jpg');
|
||||
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
|
||||
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
|
||||
expect(req.biz_req?.iUploadType).toBe(0);
|
||||
expect(req.biz_req?.iNeedFeeds).toBe(1);
|
||||
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: '1', video_num: '0', batch_num: '1' });
|
||||
// 每张图各自成批时,批次号仍是 10 位秒级时间戳
|
||||
expect(String(req.biz_req?.iBatchID)).toHaveLength(10);
|
||||
});
|
||||
|
||||
it('同一秒内的两次上传批次号不同,不会被相册并成一条', () => {
|
||||
const first = imageReq().biz_req?.iBatchID;
|
||||
const second = imageReq().biz_req?.iBatchID;
|
||||
expect(second).toBeGreaterThan(first ?? Infinity);
|
||||
expect(nextQunAlbumBatchId()).toBeGreaterThan(second ?? Infinity);
|
||||
});
|
||||
|
||||
it('多图同批:共用批次号,张数与序号按批上报', () => {
|
||||
const batchId = 1791038000;
|
||||
const total = '3';
|
||||
const reqs = [0, 1, 2].map(i => imageReq({
|
||||
pic_md5: `MD5${i}`,
|
||||
batchId,
|
||||
batchIndex: String(i),
|
||||
photo_num: total,
|
||||
batch_num: total,
|
||||
}));
|
||||
|
||||
expect(new Set(reqs.map(r => r.biz_req?.iBatchID)).size).toBe(1);
|
||||
expect(reqs[0]?.biz_req?.iBatchID).toBe(batchId);
|
||||
reqs.forEach((req, i) => {
|
||||
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({ photo_num: total, video_num: '0', batch_num: total });
|
||||
expect(req.biz_req?.mutliPicInfo).toEqual({
|
||||
iBatUploadNum: total,
|
||||
iCurUpload: String(i),
|
||||
iSuccNum: 0,
|
||||
iFailNum: 0,
|
||||
});
|
||||
expect(req.checksum).toBe(`MD5${i}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('群相册视频组包', () => {
|
||||
it('视频主体:video_qun / FileUploadVideo / SHA1,且不带相册与批次号', () => {
|
||||
const req = firstReq(qunAlbumVideoControl({
|
||||
uin: UIN,
|
||||
group_id: GROUP_ID,
|
||||
pskey: 'PSKEY',
|
||||
video_sha1: 'SHA1A',
|
||||
video_size: 1048576,
|
||||
play_time: 37,
|
||||
}));
|
||||
|
||||
expect(req.appid).toBe('video_qun');
|
||||
expect(req.cmd).toBe('FileUploadVideo');
|
||||
expect(req.check_type).toBe(1);
|
||||
expect(req.checksum).toBe('SHA1A');
|
||||
expect(req.file_len).toBe(1048576);
|
||||
expect(req.env).toEqual({ refer: 'qzone', deviceInfo: 'h5' });
|
||||
|
||||
expect(req.biz_req?.iUploadType).toBe(3);
|
||||
expect(req.biz_req?.iPlayTime).toBe(37);
|
||||
expect(req.biz_req?.iIsNew).toBe(111);
|
||||
// 视频主体不参与批次:iBatchID 固定 0,相册留空,也没有 mutliPicInfo
|
||||
expect(req.biz_req?.iBatchID).toBe(0);
|
||||
expect(req.biz_req?.sAlbumID).toBe('');
|
||||
expect(req.biz_req?.sAlbumName).toBe('');
|
||||
expect(req.biz_req?.mutliPicInfo).toBeUndefined();
|
||||
expect(req.biz_req?.stExtendInfo).toBeUndefined();
|
||||
expect(req.biz_req?.mapExt).toBeUndefined();
|
||||
expect(req.biz_req?.extend_info).toEqual({
|
||||
video_type: '3',
|
||||
domainid: '5',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
batch_num: '1',
|
||||
qun_id: GROUP_ID,
|
||||
});
|
||||
});
|
||||
|
||||
it('封面二段:走图片口径带相册与批次号,并用 vid 绑定视频', () => {
|
||||
const batchId = 1791038000;
|
||||
const req = firstReq(qunAlbumVideoCoverControl({
|
||||
uin: UIN,
|
||||
group_id: GROUP_ID,
|
||||
pskey: 'PSKEY',
|
||||
sAlbumName: ALBUM_NAME,
|
||||
sAlbumID: ALBUM_ID,
|
||||
cover_md5: 'COVERMD5',
|
||||
cover_size: 20000,
|
||||
vid: 'SV123',
|
||||
batchId,
|
||||
}));
|
||||
|
||||
expect(req.appid).toBe('qun');
|
||||
expect(req.cmd).toBeUndefined();
|
||||
expect(req.check_type).toBe(0);
|
||||
expect(req.checksum).toBe('COVERMD5');
|
||||
// 封面这一步才带相册和批次号——视频靠它进相册
|
||||
expect(req.env).toEqual({ refer: 'huodong', deviceInfo: 'h5' });
|
||||
expect(req.biz_req?.iUploadType).toBe(2);
|
||||
expect(req.biz_req?.iBatchID).toBe(batchId);
|
||||
expect(req.biz_req?.sAlbumID).toBe(ALBUM_ID);
|
||||
expect(req.biz_req?.sAlbumName).toBe(ALBUM_NAME);
|
||||
expect(req.biz_req?.iNeedFeeds).toBe(1);
|
||||
expect(req.biz_req?.stExtendInfo?.mapParams).toEqual({
|
||||
vid: 'SV123',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
batch_num: '1',
|
||||
});
|
||||
expect(req.biz_req?.stExternalMapExt).toEqual({
|
||||
is_client_upload_cover: '1',
|
||||
is_pic_video_mix_feeds: '1',
|
||||
});
|
||||
expect(req.biz_req?.mutliPicInfo).toEqual({
|
||||
iBatUploadNum: '1',
|
||||
iCurUpload: '0',
|
||||
iSuccNum: 0,
|
||||
iFailNum: 0,
|
||||
});
|
||||
expect(req.biz_req?.mapExt).toEqual({ appid: 'qun', userid: GROUP_ID });
|
||||
});
|
||||
});
|
||||
|
||||
describe('群相册分片上传', () => {
|
||||
let tempDir: string;
|
||||
let sliceFile: string;
|
||||
|
||||
const createApi = () => new NTQQWebApi(
|
||||
{ logger: { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn(), logDebug: vi.fn() } } as never,
|
||||
{ NapCatTempPath: tempDir } as never
|
||||
);
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(path.join(tmpdir(), 'napcat-album-slice-'));
|
||||
sliceFile = path.join(tempDir, 'payload.bin');
|
||||
// 40000 字节 / 16384 分片 = 3 片
|
||||
await writeFile(sliceFile, Buffer.alloc(40000, 7));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('按分片大小切片,把 appid/cmd 透传到每个分片请求,并回收 sVid', async () => {
|
||||
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({
|
||||
ret: 0,
|
||||
msg: '',
|
||||
data: { biz: { sVid: 'SV123' } },
|
||||
}), { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const result = await createApi().uploadQunAlbumSlice(
|
||||
sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384,
|
||||
{ appid: 'video_qun', cmd: 'FileUploadVideo' }
|
||||
);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
expect(result).toMatchObject({ success: true, sVid: 'SV123' });
|
||||
|
||||
// 分片是并发发出的,调用顺序不确定,按 seq 建索引再断言
|
||||
const forms = new Map(fetchMock.mock.calls.map((call) => {
|
||||
const form = call[1]?.body as unknown as FormData;
|
||||
return [form.get('seq'), form] as const;
|
||||
}));
|
||||
const first = forms.get('0');
|
||||
expect(first).toBeDefined();
|
||||
expect(first?.get('appid')).toBe('video_qun');
|
||||
expect(first?.get('cmd')).toBe('FileUploadVideo');
|
||||
expect(first?.get('session')).toBe('SESSION');
|
||||
expect(first?.get('offset')).toBe('0');
|
||||
expect(first?.get('end')).toBe('16384');
|
||||
expect(first?.get('slice_size')).toBe('16384');
|
||||
|
||||
const urls = fetchMock.mock.calls.map(call => String(call[0]));
|
||||
expect(urls.some(url => url.includes('seq=0&retry=0&offset=0&end=16384&total=40000'))).toBe(true);
|
||||
expect(urls.some(url => url.includes('seq=2&retry=0&offset=32768&end=40000&total=40000'))).toBe(true);
|
||||
// 路径必须跟随 cmd:视频走 /sliceUpload/FileUploadVideo,否则服务端不返回 sVid
|
||||
expect(urls.every(url => url.includes('/webapp/json/sliceUpload/FileUploadVideo?'))).toBe(true);
|
||||
});
|
||||
|
||||
it('不传 appid/cmd 时退回图片口径(路径也是 FileUpload)', async () => {
|
||||
const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const result = await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
|
||||
|
||||
const form = fetchMock.mock.calls[0]?.[1]?.body as unknown as FormData;
|
||||
expect(form.get('appid')).toBe('qun');
|
||||
expect(form.get('cmd')).toBe('FileUpload');
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toContain('/webapp/json/sliceUpload/FileUpload?');
|
||||
expect(result.sVid).toBeUndefined();
|
||||
});
|
||||
|
||||
it('最后一片等其它分片全部传完才发', async () => {
|
||||
// 100000 字节 / 16384 = 7 片(seq 0~6)
|
||||
await writeFile(sliceFile, Buffer.alloc(100000, 7));
|
||||
let finished = 0;
|
||||
let finishedWhenLastSent = -1;
|
||||
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
|
||||
const seq = Number((init.body as unknown as FormData).get('seq'));
|
||||
if (seq === 6) {
|
||||
finishedWhenLastSent = finished;
|
||||
} else {
|
||||
// 前面的分片故意慢一点、倒序完成
|
||||
await new Promise(resolve => setTimeout(resolve, (6 - seq) * 5));
|
||||
finished++;
|
||||
}
|
||||
return new Response(JSON.stringify({ ret: 0, msg: '' }), { status: 200 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(7);
|
||||
expect(finishedWhenLastSent).toBe(6);
|
||||
});
|
||||
|
||||
it('前面的分片失败时不再发最后一片', async () => {
|
||||
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
|
||||
const seq = (init.body as unknown as FormData).get('seq');
|
||||
return new Response(JSON.stringify(seq === '1' ? { ret: -1, msg: 'boom' } : { ret: 0, msg: '' }), { status: 200 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
|
||||
.rejects.toThrow('分片 1 上传失败: boom');
|
||||
const seqs = fetchMock.mock.calls.map(call => (call[1]?.body as unknown as FormData).get('seq'));
|
||||
expect(seqs).not.toContain('2');
|
||||
});
|
||||
|
||||
it('分片失败时抛出带序号与原因的错误', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ ret: -1, msg: 'boom' }), { status: 200 })));
|
||||
|
||||
// 分片是并发上传的,Promise.all 抛出的是最先失败的那一片,序号不确定
|
||||
await expect(createApi().uploadQunAlbumSlice(sliceFile, 'SESSION', 'SKEY', 'PSKEY', UIN, 16384))
|
||||
.rejects.toThrow(/分片 \d+ 上传失败: boom/);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { GeneralCallResultStatus } from '../napcat-core/services/common';
|
||||
import {
|
||||
applyGroupManagementSettings,
|
||||
createGroupDetailInfoV2Param,
|
||||
@@ -10,7 +11,8 @@ describe('NTQQ group operations', () => {
|
||||
test('reports the exact native setting that failed', () => {
|
||||
expect(() => assertGroupManagementResults('设置群成员功能权限', [{
|
||||
setting: 'allow_member_create_group',
|
||||
result: { result: 1006, errMsg: '未知错误' },
|
||||
// 枚举里只有 OK/ERROR,这里刻意用一个任意的原生错误码
|
||||
result: { result: 1006 as GeneralCallResultStatus, errMsg: '未知错误' },
|
||||
}])).toThrow(/allow_member_create_group.*1006.*未知错误/);
|
||||
expect(() => assertGroupManagementResults('设置群成员功能权限', []))
|
||||
.not.toThrow();
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "vitest",
|
||||
"test:ui": "vitest --ui"
|
||||
"test:ui": "vitest --ui",
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1",
|
||||
"vitest": "^4.0.9"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -10,7 +10,7 @@ describe('QQ AppID lookup', () => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'arch', { ...archDescriptor, value: 'x64' });
|
||||
info = Object.create(QQBasicInfoWrapper.prototype);
|
||||
info.context = { logger: { log: vi.fn() } } as QQBasicInfoWrapper['context'];
|
||||
info.context = { logger: { log: vi.fn() } } as unknown as QQBasicInfoWrapper['context'];
|
||||
vi.spyOn(info, 'getFullQQVersion');
|
||||
vi.spyOn(info, 'getAppidV2ByMajor').mockReturnValue('537999999');
|
||||
});
|
||||
|
||||
Generated
+6
@@ -332,6 +332,9 @@ importers:
|
||||
specifier: workspace:*
|
||||
version: link:../napcat-vite
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.1
|
||||
version: 22.19.1
|
||||
tsx:
|
||||
specifier: ^4.7.1
|
||||
version: 4.21.0
|
||||
@@ -394,6 +397,9 @@ importers:
|
||||
specifier: workspace:*
|
||||
version: link:../napcat-rpc
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.1
|
||||
version: 22.19.1
|
||||
vitest:
|
||||
specifier: ^4.0.9
|
||||
version: 4.0.9(@types/debug@4.1.12)(@types/node@22.19.1)(@vitest/ui@4.0.9)(jiti@1.21.7)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
Reference in new issue
Block a user