feat(onebot): add upload_video_to_qun_album
Group albums already list videos, but upload only accepted images. Add a dedicated video action that extracts a cover and returns the new video id. Fixed #331
This commit is contained in:
6 files changed
+769
-6
No files matched your search
@@ -17,7 +17,7 @@ import type {
|
||||
MediaInfo,
|
||||
UrlInfo,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import { uploadImageToGroupAlbum } from '@snowluma/protocol/web/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';
|
||||
|
||||
@@ -262,6 +262,13 @@ export class GroupAlbumApi {
|
||||
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<GroupAlbumMediaResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
|
||||
@@ -12881,6 +12881,105 @@
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群文件"
|
||||
},
|
||||
{
|
||||
"name": "upload_video_to_qun_album",
|
||||
"aliases": [],
|
||||
"summary": "上传视频到群相册",
|
||||
"returns": "{ id: string }",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "视频 id"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_id",
|
||||
"type": "uint",
|
||||
"required": true,
|
||||
"role": "group_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "群号"
|
||||
},
|
||||
{
|
||||
"name": "album_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "相册 id"
|
||||
},
|
||||
{
|
||||
"name": "album_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "相册名称"
|
||||
},
|
||||
{
|
||||
"name": "file",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"role": "video",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "视频文件"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "群号",
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"album_id": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "相册 id"
|
||||
},
|
||||
"album_name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "相册名称"
|
||||
},
|
||||
"file": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "视频文件",
|
||||
"x-role": "video"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_id",
|
||||
"album_id",
|
||||
"album_name",
|
||||
"file"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群相册"
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
@@ -12918,7 +13017,7 @@
|
||||
},
|
||||
{
|
||||
"category": "群相册",
|
||||
"count": 8
|
||||
"count": 9
|
||||
},
|
||||
{
|
||||
"category": "空间",
|
||||
|
||||
@@ -12884,6 +12884,105 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群文件"
|
||||
},
|
||||
{
|
||||
"name": "upload_video_to_qun_album",
|
||||
"aliases": [],
|
||||
"summary": "上传视频到群相册",
|
||||
"returns": "{ id: string }",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "视频 id"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_id",
|
||||
"type": "uint",
|
||||
"required": true,
|
||||
"role": "group_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "群号"
|
||||
},
|
||||
{
|
||||
"name": "album_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "相册 id"
|
||||
},
|
||||
{
|
||||
"name": "album_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "相册名称"
|
||||
},
|
||||
{
|
||||
"name": "file",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"role": "video",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "视频文件"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "群号",
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"album_id": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "相册 id"
|
||||
},
|
||||
"album_name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "相册名称"
|
||||
},
|
||||
"file": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "视频文件",
|
||||
"x-role": "video"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_id",
|
||||
"album_id",
|
||||
"album_name",
|
||||
"file"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群相册"
|
||||
}
|
||||
];
|
||||
|
||||
@@ -12922,7 +13021,7 @@ export const CATEGORIES: CatalogCategory[] = [
|
||||
},
|
||||
{
|
||||
"category": "群相册",
|
||||
"count": 8
|
||||
"count": 9
|
||||
},
|
||||
{
|
||||
"category": "空间",
|
||||
|
||||
@@ -155,6 +155,28 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'upload_video_to_qun_album',
|
||||
summary: '上传视频到群相册',
|
||||
returns: '{ id: string }',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string', description: '视频 id' },
|
||||
},
|
||||
required: ['id'],
|
||||
},
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }).describe('相册 id'),
|
||||
album_name: f.string({ allowEmpty: false }).describe('相册名称'),
|
||||
file: f.video().describe('视频文件'),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.bridge.apis.groupAlbum.uploadVideo(p.group_id, p.album_id, p.album_name, p.file);
|
||||
return okResponse(result);
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'get_group_album_media_list',
|
||||
readOnly: true,
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import type { JsonValue } from '@snowluma/common/json';
|
||||
import { createHash } from 'crypto';
|
||||
import { createReadStream, statSync, unlinkSync, writeFileSync } from 'fs';
|
||||
import { closeSync, createReadStream, openSync, readSync, statSync, unlinkSync, writeFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { basename, join } from 'path';
|
||||
import { hashFileStreaming } from '../highway/hash-file';
|
||||
import { stageSourceToDisk } from '../highway/stage';
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
|
||||
/** Same ceiling as highway video upload (`MAX_VIDEO_SIZE`). */
|
||||
const ALBUM_VIDEO_MAX_BYTES = 1536 * 1024 * 1024;
|
||||
const DEFAULT_ALBUM_SLICE_SIZE = 16384;
|
||||
|
||||
// 群相册信息
|
||||
export interface GroupAlbumInfo {
|
||||
id: string;
|
||||
@@ -256,3 +262,376 @@ export async function uploadImageToGroupAlbum(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface AlbumVideoProbe {
|
||||
/** ffmpeg `getVideoInfo` duration, in seconds. */
|
||||
duration: number;
|
||||
cover: Uint8Array;
|
||||
}
|
||||
|
||||
export interface GroupAlbumVideoUploadResult {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface GroupAlbumVideoUploadDeps {
|
||||
probe?: (videoPath: string) => Promise<AlbumVideoProbe>;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
interface AlbumSliceSession {
|
||||
session: string;
|
||||
sliceSize: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface AlbumSliceBiz {
|
||||
vid?: string;
|
||||
photoId?: string;
|
||||
photoUrl?: string;
|
||||
}
|
||||
|
||||
interface AlbumSliceUploadResponse {
|
||||
ret: number;
|
||||
msg?: string;
|
||||
data?: {
|
||||
session?: string;
|
||||
slice_size?: number;
|
||||
biz?: {
|
||||
sVid?: string;
|
||||
sPhotoID?: string;
|
||||
sBURL?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
function albumUploadCookie(uin: string, skey: string, pskey: string): string {
|
||||
return `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
}
|
||||
|
||||
function albumUploadGtk(skey: string, pskey: string): string {
|
||||
return getBknFromCookie({ p_skey: pskey, skey });
|
||||
}
|
||||
|
||||
function readFileHead(filePath: string, size: number): Buffer {
|
||||
const fd = openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(size);
|
||||
const got = readSync(fd, buf, 0, size, 0);
|
||||
return buf.subarray(0, got);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function isKnownImageHead(bytes: Uint8Array): boolean {
|
||||
if (bytes.length >= 2 && bytes[0] === 0xFF && bytes[1] === 0xD8) return true;
|
||||
if (bytes.length >= 8
|
||||
&& bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||
return true;
|
||||
}
|
||||
if (bytes.length >= 6
|
||||
&& bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) {
|
||||
return true;
|
||||
}
|
||||
if (bytes.length >= 2 && bytes[0] === 0x42 && bytes[1] === 0x4D) return true;
|
||||
return bytes.length >= 12
|
||||
&& bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46
|
||||
&& bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50;
|
||||
}
|
||||
|
||||
function isIsoBmffHead(bytes: Uint8Array): boolean {
|
||||
return bytes.length >= 8
|
||||
&& bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70;
|
||||
}
|
||||
|
||||
function unlinkQuiet(filePath: string): void {
|
||||
try { unlinkSync(filePath); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
function normalizeAlbumSliceSize(sliceSize: number | undefined): number {
|
||||
return sliceSize && sliceSize > 0 ? sliceSize : DEFAULT_ALBUM_SLICE_SIZE;
|
||||
}
|
||||
|
||||
async function defaultAlbumVideoProbe(videoPath: string): Promise<AlbumVideoProbe> {
|
||||
const { getFFmpegAddon } = await import('../highway/ffmpeg-addon');
|
||||
const info = await getFFmpegAddon().getVideoInfo(videoPath);
|
||||
const cover = info.image && info.image.length > 0 ? new Uint8Array(info.image) : new Uint8Array();
|
||||
if (cover.length === 0) {
|
||||
throw new Error('无法从视频提取封面');
|
||||
}
|
||||
return { duration: info.duration || 0, cover };
|
||||
}
|
||||
|
||||
async function createAlbumMediaSession(
|
||||
checksum: string,
|
||||
skey: string,
|
||||
pskey: string,
|
||||
uin: string,
|
||||
timestamp: number,
|
||||
controlReq: Record<string, unknown>,
|
||||
): Promise<AlbumSliceSession> {
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${checksum}?g_tk=${albumUploadGtk(skey, pskey)}`;
|
||||
const response = await RequestUtil.HttpGetJson<AlbumSliceUploadResponse>(
|
||||
api,
|
||||
'POST',
|
||||
{ control_req: [controlReq] },
|
||||
{ Cookie: albumUploadCookie(uin, skey, pskey), 'Content-Type': 'application/json' },
|
||||
);
|
||||
|
||||
if (response.ret !== 0 || !response.data?.session) {
|
||||
throw new Error(`创建上传会话失败: ${response.msg ?? ''}`);
|
||||
}
|
||||
|
||||
return {
|
||||
session: response.data.session,
|
||||
sliceSize: normalizeAlbumSliceSize(response.data.slice_size),
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
async function uploadAlbumFileSlices(opts: {
|
||||
session: string;
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
sliceSize: number;
|
||||
appid: string;
|
||||
checkType: number;
|
||||
uploadCmd: 'FileUpload' | 'FileUploadVideo';
|
||||
skey: string;
|
||||
pskey: string;
|
||||
uin: string;
|
||||
}): Promise<AlbumSliceBiz> {
|
||||
const { session, filePath, fileSize, sliceSize, appid, checkType, uploadCmd, skey, pskey, uin } = opts;
|
||||
const bkn = albumUploadGtk(skey, pskey);
|
||||
const cookie = albumUploadCookie(uin, skey, pskey);
|
||||
const stream = createReadStream(filePath, { highWaterMark: sliceSize });
|
||||
let seq = 0;
|
||||
let offset = 0;
|
||||
let lastBiz: AlbumSliceBiz = {};
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const chunkBytes = chunk as Buffer;
|
||||
const end = offset + chunkBytes.length;
|
||||
const form = new FormData();
|
||||
form.append('uin', uin);
|
||||
form.append('appid', appid);
|
||||
form.append('session', session);
|
||||
form.append('offset', offset.toString());
|
||||
form.append('data', new Blob([chunkBytes], { type: 'application/octet-stream' }), 'blob');
|
||||
form.append('checksum', '');
|
||||
form.append('check_type', String(checkType));
|
||||
form.append('retry', '0');
|
||||
form.append('seq', seq.toString());
|
||||
form.append('end', end.toString());
|
||||
form.append('cmd', 'FileUpload');
|
||||
form.append('slice_size', String(chunkBytes.length));
|
||||
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/${uploadCmd}?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${fileSize}&type=form&g_tk=${bkn}`;
|
||||
const response = await fetch(api, { method: 'POST', headers: { Cookie: cookie }, body: form });
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const post = await response.json() as AlbumSliceUploadResponse;
|
||||
if (post.ret !== 0) {
|
||||
throw new Error(`分片 ${seq} 上传失败: ${post.msg ?? ''}`);
|
||||
}
|
||||
|
||||
lastBiz = {
|
||||
vid: post.data?.biz?.sVid || lastBiz.vid,
|
||||
photoId: post.data?.biz?.sPhotoID || lastBiz.photoId,
|
||||
photoUrl: post.data?.biz?.sBURL || lastBiz.photoUrl,
|
||||
};
|
||||
offset = end;
|
||||
seq++;
|
||||
}
|
||||
|
||||
if (fileSize === 0 || offset !== fileSize) {
|
||||
throw new Error('视频分片上传不完整');
|
||||
}
|
||||
|
||||
return lastBiz;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传视频到群相册:先传视频拿到 vid,再传客户端封面。
|
||||
*/
|
||||
export async function uploadVideoToGroupAlbum(
|
||||
cookieObject: Record<string, string>,
|
||||
groupId: string,
|
||||
albumId: string,
|
||||
albumName: string,
|
||||
filePath: string,
|
||||
uin: string,
|
||||
deps: GroupAlbumVideoUploadDeps = {},
|
||||
): Promise<GroupAlbumVideoUploadResult> {
|
||||
const skey = cookieObject.skey || '';
|
||||
const pskey = cookieObject.p_skey || '';
|
||||
const now = deps.now ?? (() => Math.floor(Date.now() / 1000));
|
||||
const probe = deps.probe ?? defaultAlbumVideoProbe;
|
||||
|
||||
const staged = await stageSourceToDisk(filePath, ALBUM_VIDEO_MAX_BYTES);
|
||||
let coverPath: string | null = null;
|
||||
|
||||
try {
|
||||
const head = readFileHead(staged.filePath, 16);
|
||||
if (isKnownImageHead(head) || !isIsoBmffHead(head)) {
|
||||
throw new Error('群相册视频上传仅支持 MP4 等 ISO BMFF 视频');
|
||||
}
|
||||
|
||||
const hashes = await hashFileStreaming(staged.filePath);
|
||||
const fileName = staged.fileName || 'video.mp4';
|
||||
const info = await probe(staged.filePath);
|
||||
if (info.cover.length === 0) {
|
||||
throw new Error('无法从视频提取封面');
|
||||
}
|
||||
|
||||
coverPath = join(tmpdir(), `album_video_cover_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`);
|
||||
writeFileSync(coverPath, Buffer.from(info.cover));
|
||||
const coverMd5 = createHash('md5').update(Buffer.from(info.cover)).digest('hex');
|
||||
const coverSize = info.cover.length;
|
||||
const videoTimestamp = now();
|
||||
const playTime = info.duration * 1000;
|
||||
|
||||
const videoSession = await createAlbumMediaSession(
|
||||
hashes.sha1Hex,
|
||||
skey,
|
||||
pskey,
|
||||
uin,
|
||||
videoTimestamp,
|
||||
{
|
||||
uin,
|
||||
token: { type: 4, data: pskey, appid: 5 },
|
||||
appid: 'video_qun',
|
||||
checksum: hashes.sha1Hex,
|
||||
check_type: 1,
|
||||
file_len: staged.fileSize,
|
||||
env: { refer: 'qzone', deviceInfo: 'h5' },
|
||||
model: 0,
|
||||
biz_req: {
|
||||
sPicTitle: fileName,
|
||||
sPicDesc: '',
|
||||
sAlbumName: '',
|
||||
sAlbumID: '',
|
||||
iAlbumTypeID: 0,
|
||||
iBitmap: 0,
|
||||
iUploadType: 3,
|
||||
iUpPicType: 0,
|
||||
iBatchID: 0,
|
||||
sPicPath: '',
|
||||
iPicWidth: 0,
|
||||
iPicHight: 0,
|
||||
iWaterType: 0,
|
||||
iDistinctUse: 0,
|
||||
sTitle: fileName,
|
||||
sDesc: '',
|
||||
iFlag: 0,
|
||||
iUploadTime: videoTimestamp,
|
||||
iPlayTime: playTime,
|
||||
sCoverUrl: '',
|
||||
iIsNew: 111,
|
||||
iIsOriginalVideo: 0,
|
||||
iIsFormatF20: 0,
|
||||
extend_info: {
|
||||
video_type: '3',
|
||||
domainid: '5',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
qun_id: groupId,
|
||||
},
|
||||
},
|
||||
session: '',
|
||||
asy_upload: 0,
|
||||
cmd: 'FileUploadVideo',
|
||||
},
|
||||
);
|
||||
|
||||
const videoBiz = await uploadAlbumFileSlices({
|
||||
session: videoSession.session,
|
||||
filePath: staged.filePath,
|
||||
fileSize: staged.fileSize,
|
||||
sliceSize: videoSession.sliceSize,
|
||||
appid: 'video_qun',
|
||||
checkType: 1,
|
||||
uploadCmd: 'FileUploadVideo',
|
||||
skey,
|
||||
pskey,
|
||||
uin,
|
||||
});
|
||||
if (!videoBiz.vid) {
|
||||
throw new Error('视频上传未返回视频 id');
|
||||
}
|
||||
|
||||
const coverTimestamp = now();
|
||||
const coverSession = await createAlbumMediaSession(
|
||||
coverMd5,
|
||||
skey,
|
||||
pskey,
|
||||
uin,
|
||||
coverTimestamp,
|
||||
{
|
||||
uin,
|
||||
token: { type: 4, data: pskey, appid: 5 },
|
||||
appid: 'qun',
|
||||
checksum: coverMd5,
|
||||
check_type: 0,
|
||||
file_len: coverSize,
|
||||
env: { refer: 'huodong', deviceInfo: 'h5' },
|
||||
model: 0,
|
||||
biz_req: {
|
||||
sPicTitle: fileName,
|
||||
sPicDesc: '',
|
||||
sAlbumName: albumName,
|
||||
sAlbumID: albumId,
|
||||
iAlbumTypeID: 0,
|
||||
iBitmap: 0,
|
||||
iUploadType: 2,
|
||||
iUpPicType: 0,
|
||||
iBatchID: videoTimestamp,
|
||||
sPicPath: '',
|
||||
iPicWidth: 0,
|
||||
iPicHight: 0,
|
||||
iWaterType: 0,
|
||||
iDistinctUse: 0,
|
||||
iNeedFeeds: 1,
|
||||
iUploadTime: coverTimestamp,
|
||||
mapExt: { appid: 'qun', userid: groupId },
|
||||
mutliPicInfo: { iBatUploadNum: 1, iCurUpload: 0, iSuccNum: 0, iFailNum: 0 },
|
||||
stExtendInfo: { mapParams: { vid: videoBiz.vid, photo_num: '0', video_num: '1' } },
|
||||
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: '',
|
||||
},
|
||||
session: '',
|
||||
asy_upload: 0,
|
||||
cmd: '',
|
||||
},
|
||||
);
|
||||
|
||||
const coverBiz = await uploadAlbumFileSlices({
|
||||
session: coverSession.session,
|
||||
filePath: coverPath,
|
||||
fileSize: coverSize,
|
||||
sliceSize: coverSession.sliceSize,
|
||||
appid: 'qun',
|
||||
checkType: 0,
|
||||
uploadCmd: 'FileUpload',
|
||||
skey,
|
||||
pskey,
|
||||
uin,
|
||||
});
|
||||
if (!coverBiz.photoId || !coverBiz.photoUrl) {
|
||||
throw new Error('视频封面上传未返回图片 id');
|
||||
}
|
||||
|
||||
return { id: videoBiz.vid };
|
||||
} finally {
|
||||
if (coverPath) unlinkQuiet(coverPath);
|
||||
await staged.cleanup();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,21 @@
|
||||
import { createHash } from 'crypto';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { uploadImageToGroupAlbum } from '../../src/web/group-album';
|
||||
import { uploadImageToGroupAlbum, uploadVideoToGroupAlbum } from '../../src/web/group-album';
|
||||
import { RequestUtil } from '../../src/web/request-util';
|
||||
|
||||
const MP4_BASE64 = 'AAAAGGZ0eXBtcDQyAAAAAG1wNDJpc29t';
|
||||
const MP4_SOURCE = `base64://${MP4_BASE64}`;
|
||||
const MP4_BYTES = Buffer.from(MP4_BASE64, 'base64');
|
||||
const JPEG_SOURCE = 'base64:///9j/4AAQSkZJRgABAQAAAQABAAD/2wAAAA==';
|
||||
const COVER = Buffer.from('album-cover');
|
||||
|
||||
function controlReq(body: unknown): Record<string, unknown> {
|
||||
const req = (body as { control_req: Array<Record<string, unknown>> }).control_req[0];
|
||||
expect(req).toBeTruthy();
|
||||
return req;
|
||||
}
|
||||
|
||||
describe('group album image upload', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
@@ -20,7 +33,7 @@ describe('group album image upload', () => {
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
'base64://AAAAGGZ0eXBtcDQyAAAAAG1wNDJpc29t',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
)).rejects.toThrow('群相册上传仅支持 JPEG、PNG、GIF、WebP 或 BMP 图片');
|
||||
|
||||
@@ -28,3 +41,147 @@ describe('group album image upload', () => {
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('group album video upload', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('rejects a JPEG before starting a remote upload', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockRejectedValue(new Error('unexpected remote upload'));
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
const probe = vi.fn();
|
||||
|
||||
await expect(uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
JPEG_SOURCE,
|
||||
'10000',
|
||||
{ probe },
|
||||
)).rejects.toThrow('群相册视频上传仅支持 MP4 等 ISO BMFF 视频');
|
||||
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(probe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads the video with SHA1 then the cover bound to the returned vid', async () => {
|
||||
const sha1 = createHash('sha1').update(MP4_BYTES).digest('hex');
|
||||
const coverMd5 = createHash('md5').update(COVER).digest('hex');
|
||||
const bodies: unknown[] = [];
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockImplementation(async (_url, _method, body) => {
|
||||
bodies.push(body);
|
||||
const appid = controlReq(body).appid;
|
||||
if (appid === 'video_qun') {
|
||||
return { ret: 0, msg: '', data: { session: 'video-session', slice_size: 16384 } };
|
||||
}
|
||||
return { ret: 0, msg: '', data: { session: 'cover-session', slice_size: 16384 } };
|
||||
});
|
||||
|
||||
const fetch = vi.fn(async (url: string) => ({
|
||||
ok: true,
|
||||
json: async () => {
|
||||
if (url.includes('FileUploadVideo')) {
|
||||
return { ret: 0, msg: '', data: { biz: { sVid: 'VID123' } } };
|
||||
}
|
||||
return { ret: 0, msg: '', data: { biz: { sPhotoID: 'PID', sBURL: 'https://example.test/v.jpg' } } };
|
||||
},
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
const result = await uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
{
|
||||
now: () => 1700000000,
|
||||
probe: async () => ({ duration: 6.077, cover: new Uint8Array(COVER) }),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toEqual({ id: 'VID123' });
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
expect(String(request.mock.calls[0]![0])).toContain(`FileBatchControl/${sha1}`);
|
||||
expect(String(request.mock.calls[1]![0])).toContain(`FileBatchControl/${coverMd5}`);
|
||||
|
||||
const videoReq = controlReq(bodies[0]);
|
||||
expect(videoReq).toMatchObject({
|
||||
appid: 'video_qun',
|
||||
checksum: sha1,
|
||||
check_type: 1,
|
||||
cmd: 'FileUploadVideo',
|
||||
env: { refer: 'qzone', deviceInfo: 'h5' },
|
||||
});
|
||||
expect(videoReq.biz_req).toMatchObject({
|
||||
iUploadType: 3,
|
||||
iPlayTime: 6077,
|
||||
iIsNew: 111,
|
||||
sTitle: 'video.mp4',
|
||||
extend_info: {
|
||||
video_type: '3',
|
||||
domainid: '5',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
qun_id: '12345',
|
||||
},
|
||||
});
|
||||
|
||||
const coverReq = controlReq(bodies[1]);
|
||||
expect(coverReq).toMatchObject({
|
||||
appid: 'qun',
|
||||
checksum: coverMd5,
|
||||
check_type: 0,
|
||||
cmd: '',
|
||||
env: { refer: 'huodong', deviceInfo: 'h5' },
|
||||
});
|
||||
expect(coverReq.biz_req).toMatchObject({
|
||||
iUploadType: 2,
|
||||
iBatchID: 1700000000,
|
||||
sAlbumID: 'album-id',
|
||||
sAlbumName: 'album-name',
|
||||
mutliPicInfo: { iBatUploadNum: 1 },
|
||||
stExtendInfo: { mapParams: { vid: 'VID123', photo_num: '0', video_num: '1' } },
|
||||
stExternalMapExt: { is_client_upload_cover: '1', is_pic_video_mix_feeds: '1' },
|
||||
});
|
||||
|
||||
const sliceUrls = fetch.mock.calls.map((call) => String(call[0]));
|
||||
expect(sliceUrls.some((url) => url.includes('/sliceUpload/FileUploadVideo?'))).toBe(true);
|
||||
expect(sliceUrls.some((url) => url.includes('/sliceUpload/FileUpload?'))).toBe(true);
|
||||
});
|
||||
|
||||
it('fails when the video slices do not return a vid', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
ret: 0,
|
||||
msg: '',
|
||||
data: { session: 'video-session', slice_size: 16384 },
|
||||
});
|
||||
const fetch = vi.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ ret: 0, msg: '', data: { biz: {} } }),
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
await expect(uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
{
|
||||
now: () => 1700000000,
|
||||
probe: async () => ({ duration: 6, cover: new Uint8Array(COVER) }),
|
||||
},
|
||||
)).rejects.toThrow('视频上传未返回视频 id');
|
||||
|
||||
expect(RequestUtil.HttpGetJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user