71 lines
5.7 KiB
TypeScript
71 lines
5.7 KiB
TypeScript
import {serveApiDocumentation} from '@/lib/api-documentation';
|
|
import type { NextApiRequest,NextApiResponse } from "next";
|
|
import formidable,{type File} from "formidable";
|
|
import { randomUUID,createHash } from "node:crypto";
|
|
import { createReadStream } from "node:fs";
|
|
import { rm } from "node:fs/promises";
|
|
import sharp from "sharp";
|
|
import { z } from "zod";
|
|
import { transaction } from "@/lib/db";
|
|
import { putFile,removeObject } from "@/lib/storage";
|
|
import { probe } from "@/lib/probe";
|
|
import { sameOrigin,apiError } from "@/lib/api";
|
|
export const config={api:{bodyParser:false}};
|
|
export type UploadPolicy = { validateImage?: (path:string) => Promise<void>; defaultTitle?:string };
|
|
export async function upload(req:NextApiRequest,res:NextApiResponse,policy:UploadPolicy={}){
|
|
if(serveApiDocumentation(req,res,'/api/upload'))return;
|
|
if(req.method!=='POST')return res.status(405).end();
|
|
const temporary:string[]=[];const uploaded:string[]=[];
|
|
try{
|
|
sameOrigin(req);
|
|
const form=formidable({maxFileSize:250*1024*1024,maxTotalFileSize:1024*1024*1024,maxFiles:16,allowEmptyFiles:false});
|
|
// file completion events can finish out of order; preserve multipart selection order.
|
|
const items:File[]=[];
|
|
form.on('fileBegin',(_name,file)=>{temporary.push(file.filepath);items.push(file)});
|
|
const [fields]=await form.parse(req);
|
|
const assetOnly=z.enum(['true','false']).default('false').parse(fields.assetOnly?.[0])==='true';
|
|
const kind=z.enum(['image','video','audio']).parse(policy.validateImage?'image':fields.kind?.[0]);
|
|
const title=z.string().trim().min(1).max(200).parse(fields.title?.[0]||policy.defaultTitle||(assetOnly?'上传素材':undefined));
|
|
const slug=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(120).optional().parse(fields.slug?.[0]);
|
|
const description=z.string().trim().max(100000).parse(fields.description?.[0]||'');
|
|
const tagIds=z.array(z.uuid()).max(50).parse(JSON.parse(fields.tags?.[0]||'[]'));
|
|
if(!items.length) return res.status(400).json({error:'请选择文件'});
|
|
const records:{id:string;key:string;mime:string;width:number|undefined;height:number|undefined;duration:number|undefined;hasAudio:boolean|null;size:number;hash:string;filename:string}[]=[];
|
|
for(const file of items){
|
|
let mime='';let width:number|undefined,height:number|undefined,duration:number|undefined,hasAudio:boolean|null=null;
|
|
if(kind==='image'){
|
|
if(policy.validateImage)await policy.validateImage(file.filepath);
|
|
const meta=await sharp(file.filepath,{limitInputPixels:100000000}).metadata();
|
|
const formats:Record<string,string>={jpeg:'image/jpeg',png:'image/png',webp:'image/webp',gif:'image/gif',avif:'image/avif'};
|
|
mime=formats[meta.format||''];if(!mime)throw new Error('Unsupported image format');width=meta.width;height=meta.height;
|
|
}else{
|
|
const meta=await probe(file.filepath);const video=meta.streams.find(s=>s.codec_type==='video');const audio=meta.streams.some(s=>s.codec_type==='audio');
|
|
if(kind==='video'&&!video)throw new Error('File has no video stream');if(kind==='audio'&&(!audio||video))throw new Error('Select an audio file');
|
|
if(!file.mimetype?.startsWith(kind+'/'))throw new Error('Unsupported media MIME type');
|
|
mime=file.mimetype;width=video?.width;height=video?.height;duration=Number(meta.format.duration)||undefined;hasAudio=kind==='video'?audio:null;
|
|
}
|
|
const hash=createHash('sha256');for await(const chunk of createReadStream(file.filepath))hash.update(chunk);
|
|
const id=randomUUID(),key=`originals/${id}`;await putFile(key,file.filepath,mime);uploaded.push(key);
|
|
records.push({id,key,mime,width,height,duration,hasAudio,size:file.size,hash:hash.digest('hex'),filename:file.originalFilename||'未命名素材'});
|
|
}
|
|
const postId=assetOnly?null:randomUUID();
|
|
await transaction(async client=>{
|
|
if(postId)await client.query('INSERT INTO posts(id,slug,kind,title,description) VALUES($1,$2,$3,$4,$5)',[postId,slug||postId,kind,title,description.slice(0,1000)||title]);
|
|
for(const [position,a] of records.entries()){
|
|
await client.query('INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256,width,height,duration,has_audio,processing_status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)',[a.id,kind,a.filename,a.key,a.mime,a.size,a.hash,a.width,a.height,a.duration,a.hasAudio,kind==='video'?'pending':'ready']);
|
|
if(postId)await client.query('INSERT INTO post_assets(post_id,asset_id,position) VALUES($1,$2,$3)',[postId,a.id,position]);
|
|
for(const tag of new Set(tagIds))await client.query('INSERT INTO asset_tags(asset_id,tag_id) VALUES($1,$2)',[a.id,tag]);
|
|
if(kind==='video')await client.query('INSERT INTO media_jobs(id,asset_id) VALUES($1,$2)',[randomUUID(),a.id]);
|
|
}
|
|
if(postId&&description){const id=randomUUID();await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[id,description]);await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'caption')",[postId,id,records.length]);}
|
|
if(postId)for(const tag of new Set(tagIds))await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[postId,tag]);
|
|
});
|
|
uploaded.length=0;
|
|
if(assetOnly)return res.status(201).json({assets:records.map(a=>a.id),files:records.map(a=>({id:a.id,filename:a.filename,sha256:a.hash}))});
|
|
return res.status(201).json({id:postId,slug:slug||postId,url:`/p/${slug||postId}`,assets:records.map(a=>a.id)});
|
|
}catch(e){if(e instanceof Error && (/maxFileSize|maxTotalFileSize|maxFiles/.test(e.message)))return res.status(413).json({error:'最多 16 个文件,单个不超过 250 MB,总计不超过 1 GB'});return apiError(res,e);}
|
|
finally{await Promise.allSettled(temporary.map(p=>rm(p,{force:true})));await Promise.allSettled(uploaded.map(removeObject));}
|
|
}
|
|
|
|
export default upload;
|