Build PROMPT media library with masonry UI and persistent PostgreSQL S3 storage
PROMPT CI and deployment / verify-and-deploy (push) Successful in 8m18s
PROMPT CI and deployment / verify-and-deploy (push) Successful in 8m18s
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import { useEffect,useRef,useState } from "react";
|
||||
import { useRouter } from "next/router";
|
||||
import { Search,Image as ImageIcon,ArrowUpRight,AudioLines,Film,Layers,ArrowDown,Upload } from "lucide-react";
|
||||
import { Shell } from "./Shell";
|
||||
import { Heatmap } from "./Heatmap";
|
||||
import { sections,mediaUrl,type FeedData,type Post } from "@/lib/model";
|
||||
export function PostCard({post}:{post:Post}){
|
||||
const image=post.assets.find(a=>a.kind==='image');const video=post.assets.find(a=>a.kind==='video');const cover=post.cover_asset_id||image?.id;
|
||||
const label=sections.find(s=>s.kind===post.kind)?.name;const count=post.assets.filter(a=>a.kind!=='text').length;
|
||||
const source=cover?mediaUrl(cover):video?.variants.includes('poster')?mediaUrl(video.id,'poster'):null;
|
||||
return <Link className="post-card" href={`/p/${post.slug}`}><div className={`post-cover cover-${post.kind}`} style={image?.width&&image?.height?{aspectRatio:`${image.width}/${image.height}`,maxHeight:460}:undefined}>
|
||||
{source?<img src={source} alt={post.title} loading="lazy"/>:post.kind==='audio'?<div className="waveform">{Array.from({length:36},(_,i)=><i key={i} style={{height:12+((i*31)%65)}}/>)}</div>:<div className="cover-symbol">{post.kind==='video'?<Film size={42}/>:<Layers size={42}/>}<span>{label}</span></div>}
|
||||
{count>1&&<span className="cover-count"><Layers size={12}/>{count}</span>}{video&&<span className="cover-badge">{video.has_audio?'有声音':'无声音'}</span>}
|
||||
</div><h3>{post.title}</h3><div className="post-meta"><span><i className={`type-dot ${post.kind}`}/>{label}</span><time>{new Date(post.created_at).toLocaleDateString('zh-CN',{month:'2-digit',day:'2-digit',timeZone:'Asia/Shanghai'})}</time></div>{post.tags.length>0&&<div className="card-tags">{post.tags.slice(0,2).map(t=><span key={t.id}>#{t.name}</span>)}</div>}</Link>;
|
||||
}
|
||||
function Masonry({posts}:{posts:Post[]}){
|
||||
const element=useRef<HTMLDivElement>(null);const [width,setWidth]=useState(1100);
|
||||
useEffect(()=>{if(!element.current)return;const observer=new ResizeObserver(entries=>setWidth(entries[0].contentRect.width));observer.observe(element.current);return ()=>observer.disconnect();},[]);
|
||||
const count=width>1250?5:width>1000?4:width>720?3:2;
|
||||
const columns:Post[][]=Array.from({length:count},()=>[]);const heights=Array(count).fill(0);const cardWidth=(width-22*(count-1))/count;
|
||||
for(const post of posts){const image=post.assets.find(a=>a.kind==='image');const ratio=image?.width&&image.height?image.height/image.width:post.kind==='audio'?1:1.25;const index=heights.indexOf(Math.min(...heights));columns[index].push(post);heights[index]+=Math.min(cardWidth*ratio,460)+90+Math.ceil(post.title.length/15)*20;}
|
||||
return <div ref={element} className="masonry" style={{gridTemplateColumns:`repeat(${count}, minmax(0,1fr))`}}>{columns.map((items,i)=><div className="masonry-column" key={i}>{items.map(p=><PostCard post={p} key={p.id}/>)}</div>)}</div>;
|
||||
}
|
||||
export function Feed({initial,section='',tagPath=''}:{initial:FeedData;section?:string;tagPath?:string}){
|
||||
const router=useRouter();const [posts,setPosts]=useState(initial.posts);const [cursor,setCursor]=useState(initial.nextCursor);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const generation=useRef(0);
|
||||
useEffect(()=>{generation.current++;setPosts(initial.posts);setCursor(initial.nextCursor);setError('');setBusy(false);},[initial,router.query.q]);
|
||||
const current=sections.find(s=>s.path===section);const target=initial.tags.find(t=>t.path===tagPath);const children=initial.tags.filter(t=>target?t.parent_id===target.id:!t.parent_id);
|
||||
async function load(){const gen=generation.current;setBusy(true);setError('');try{const q=new URLSearchParams({section,path:tagPath,cursor:cursor||'',q:String(router.query.q||'')});const res=await fetch('/api/feed?'+q);const d=await res.json();if(!res.ok)throw new Error(d.error);if(gen===generation.current){setPosts(old=>[...old,...d.posts.filter((p:Post)=>!old.some(a=>a.id===p.id))]);setCursor(d.nextCursor);}}catch{if(gen===generation.current)setError('加载没有完成,点击重试。');}finally{if(gen===generation.current)setBusy(false);}}
|
||||
return <Shell><Head><title>{target?.name||current?.name||'灵感首页'} · PROMPT</title><meta name="description" content="自己的图文、视频与声音创作空间"/></Head>
|
||||
{current&&<header className="page-header feed-heading"><div><h1>{target?.name||current.name}</h1><p>{current.hint}</p></div></header>}
|
||||
{!section&&<Heatmap data={initial.contributions}/>}
|
||||
{tagPath&&<div className="breadcrumbs"><Link href={`/${section}`}>全部{current?.name}</Link>{tagPath.split('/').map((_,i)=>{const path=tagPath.split('/').slice(0,i+1).join('/');return <span key={path}> / <Link href={`/${section}/${path}`}>{initial.tags.find(t=>t.path===path)?.name}</Link></span>;})}</div>}
|
||||
<div className="feed-toolbar"><div className="feed-tabs">{!section?<><Link className="selected" href="/">全部</Link>{sections.map(s=><Link key={s.path} href={`/${s.path}`}>{s.name}</Link>)}</>:<><Link className={!tagPath?'selected':''} href={`/${section}`}>全部</Link>{children.map(t=><Link key={t.id} href={`/${section}/${t.path}`}>{t.name}</Link>)}</>}</div><span className="sort-label"><ArrowDown size={13}/>最近收录</span></div>
|
||||
{initial.unavailable?<div className="empty-state"><Layers/><h2>素材库暂时没有连接上</h2><p>请稍后刷新,已保存的内容不会因此丢失。</p></div>:posts.length?<Masonry posts={posts}/>:<div className="empty-state"><div className="empty-art"><span/><ImageIcon size={42} strokeWidth={1.2}/><i><AudioLines size={18}/></i><b><Film size={19}/></b></div><span className="eyebrow">A LITTLE SPACE FOR SOMETHING GOOD</span><h2>{router.query.q?'还没有找到这份灵感':'这里还没有内容'}</h2><p>{router.query.q?'换一个词试试看。':'导入图片、视频或声音,开始整理你的素材。'}</p><Link className="primary-button" href={`/library/import${current&&['image','video','audio'].includes(current.kind)?'?kind='+current.kind:''}`}><Upload size={16}/>导入素材<ArrowUpRight size={16}/></Link><small>图文和动态作品通过代码加入,自由决定每一个像素。</small></div>}
|
||||
{cursor&&<div className="load-more"><button disabled={busy} onClick={load}>{busy?'正在翻找…':error||'再看一些'}<ArrowDown size={14}/></button></div>}
|
||||
<footer className="page-footer">PROMPT <span>·</span> PROBABLY RENDERING ONE MORE PIXEL TONIGHT</footer>
|
||||
</Shell>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useState,useRef,useEffect } from "react";
|
||||
export function Heatmap({data}:{data:{day:string;total:number}[]}){
|
||||
const [hover,setHover]=useState('');const values=new Map(data.map(d=>[d.day,d.total]));
|
||||
const scroller=useRef<HTMLDivElement>(null);
|
||||
useEffect(()=>{if(scroller.current)scroller.current.scrollLeft=scroller.current.scrollWidth;},[]);
|
||||
const now=new Date();const today=new Date(now.toLocaleDateString('en-CA',{timeZone:'Asia/Shanghai'})+'T00:00:00Z');
|
||||
const start=new Date(today);start.setUTCDate(start.getUTCDate()-364-start.getUTCDay());
|
||||
const days=Array.from({length:371},(_,i)=>{const d=new Date(start);d.setUTCDate(d.getUTCDate()+i);return d;});
|
||||
const total=data.reduce((s,d)=>s+d.total,0);
|
||||
return <section className="activity-card" aria-label="创作贡献热力图"><div className="activity-top"><div><span className="eyebrow">CREATIVE RHYTHM</span><h2>创作记录<span>{total} 次贡献</span></h2></div><span className="activity-year">过去一年 <span>↗</span></span></div>
|
||||
<div className="heatmap-scroll" ref={scroller}><div className="month-row">{Array.from({length:53},(_,week)=>{const d=days[week*7];const changed=week===0||d.getUTCMonth()!==days[(week-1)*7].getUTCMonth();return <span key={week}>{changed?`${d.getUTCMonth()+1}月`:''}</span>;})}</div><div className="heatmap-body"><div className="weekdays"><span>一</span><span>三</span><span>五</span></div><div className="heatmap-grid">{days.map(d=>{const key=d.toISOString().slice(0,10);const n=values.get(key)||0;const future=d>today;const label=`${key} · ${n} 次贡献`;return <button key={key} tabIndex={n>0?0:-1} disabled={future} aria-label={label} title={label} onFocus={()=>setHover(label)} onBlur={()=>setHover('')} onMouseEnter={()=>setHover(label)} onMouseLeave={()=>setHover('')} className={`heat-cell level-${n===0?0:n<3?1:n<6?2:n<10?3:4} ${future?'future':''}`}/>;})}</div></div></div>
|
||||
<div className="activity-bottom"><span>{hover||'每日贡献汇总'}</span><div className="heat-legend">少{[0,1,2,3,4].map(n=><i key={n} className={`heat-cell level-${n}`}/>)}多</div></div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { Grid2X2,Image,Film,AudioLines,BookOpen,Clapperboard,Sparkles,ArrowUpRight,Layers,Tags,Upload,Menu,X,Search } from "lucide-react";
|
||||
import { useEffect,useState,type ReactNode } from "react";
|
||||
const groups=[
|
||||
{label:'',items:[{href:'/',label:'首页',icon:Grid2X2}]},
|
||||
{label:'素材',items:[{href:'/images',label:'图片',icon:Image},{href:'/videos',label:'视频',icon:Film},{href:'/audio',label:'声音',icon:AudioLines}]},
|
||||
{label:'作品',items:[{href:'/articles',label:'图文',icon:BookOpen},{href:'/motion',label:'动态',icon:Clapperboard}]},
|
||||
{label:'工具',items:[{href:'/library/assets',label:'素材库',icon:Layers},{href:'/library/tags',label:'分类管理',icon:Tags},{href:'/tools/doodle',label:'线条工具',icon:Sparkles}]},
|
||||
];
|
||||
export function Shell({children}:{children:ReactNode}){
|
||||
const router=useRouter();const [open,setOpen]=useState(false);const [query,setQuery]=useState(String(router.query.q||''));
|
||||
useEffect(()=>setQuery(String(router.query.q||'')),[router.query.q]);
|
||||
return <div className="app-shell"><button className="mobile-menu icon-button" aria-label="展开导航" onClick={()=>setOpen(!open)}>{open?<X size={22}/>:<Menu size={22}/>}</button>
|
||||
<aside className={`sidebar ${open?'is-open':''}`}><Link href="/" className="brand" onClick={()=>setOpen(false)}><span className="brand-mark">P</span><strong>PROMPT</strong></Link>
|
||||
<nav>{groups.map((g,i)=><div className="nav-group" key={i}>{g.label&&<p>{g.label}</p>}{g.items.map(item=>{const active=item.href==='/'?router.asPath.split('?')[0]==='/':router.asPath.split('?')[0].startsWith(item.href);return <Link key={item.href} href={item.href} title={item.label} className={`nav-item ${active?'active':''}`} onClick={()=>setOpen(false)}><item.icon size={24} strokeWidth={active?2.2:1.8}/><span>{item.label}</span></Link>;})}</div>)}</nav>
|
||||
<div className="sidebar-bottom"><Link href="/library/import" className="import-link"><Upload size={22}/><span>导入素材</span><ArrowUpRight size={17}/></Link></div>
|
||||
</aside><main className="main-content"><div className="global-topbar"><form className="global-search" role="search" onSubmit={e=>{e.preventDefault();const path=router.asPath.split('?')[0];const destination=/^\/(images|videos|audio|articles|motion)(\/|$)/.test(path)?path:'/';void router.push({pathname:destination,query:query?{q:query}:{}});}}><Search size={24}/><input aria-label="搜索素材包" placeholder="搜索素材、作品和灵感" value={query} onChange={e=>setQuery(e.target.value)}/>{query&&<button type="button" aria-label="清空搜索" onClick={()=>setQuery('')}><X size={20}/></button>}</form><span className="profile-mark" aria-label="PROMPT 个人空间">P</span></div>{children}</main>{open&&<button className="nav-scrim" aria-label="关闭导航" onClick={()=>setOpen(false)}/>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { ComponentType } from "react";
|
||||
// Register code-authored pages here, then reference their key in the posts API.
|
||||
// No page or sample post is inserted into the user's library automatically.
|
||||
export const works: Record<string, { kind: "article" | "motion"; Component: ComponentType }> = {};
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { ZodError } from "zod";
|
||||
export function sameOrigin(req: NextApiRequest) {
|
||||
const origin=req.headers.origin;
|
||||
if (origin && new URL(origin).host !== req.headers.host) throw new Error("Cross-origin request rejected");
|
||||
}
|
||||
export function apiError(res: NextApiResponse,error: unknown) {
|
||||
if(error instanceof ZodError) return res.status(400).json({error:"请检查输入内容",issues:error.issues});
|
||||
const message=error instanceof Error?error.message:"";
|
||||
const clientMessages:Record<string,string>={
|
||||
'Register the coded page before creating its post':'请先在代码中注册对应的作品页面',
|
||||
'Referenced asset does not exist':'引用的素材不存在',
|
||||
'A media post needs matching content':'素材包需要包含对应类型的素材',
|
||||
'Cover must reference an image':'封面需要引用一张图片',
|
||||
'Unsupported image format':'支持 JPG、PNG、WebP、GIF 和 AVIF 图片',
|
||||
'File has no video stream':'文件中没有可用的画面',
|
||||
'Select an audio file':'请选择独立的声音文件',
|
||||
'Unsupported media MIME type':'文件类型不受支持',
|
||||
};
|
||||
if(clientMessages[message])return res.status(400).json({error:clientMessages[message]});
|
||||
const code=(error as {code?:string})?.code;
|
||||
if(code==='23505')return res.status(409).json({error:'这个网址标识已经存在,请换一个'});
|
||||
if(code==='23503')return res.status(400).json({error:'引用的分类或素材不存在'});
|
||||
if(["Invalid cursor","Tag not found","Cross-origin request rejected"].includes(message)) return res.status(400).json({error:message});
|
||||
console.error("API failure",error instanceof Error?error.message:"Unknown error");
|
||||
return res.status(500).json({error:"操作没有完成,请稍后重试"});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Pool, type PoolClient } from "pg";
|
||||
|
||||
const globalDb = globalThis as unknown as { promptPool?: Pool };
|
||||
export function db() {
|
||||
if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required");
|
||||
return globalDb.promptPool ??= new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
|
||||
}
|
||||
export async function transaction<T>(run: (client: PoolClient) => Promise<T>): Promise<T> {
|
||||
const client = await db().connect();
|
||||
try { await client.query("BEGIN"); const result = await run(client); await client.query("COMMIT"); return result; }
|
||||
catch (error) { await client.query("ROLLBACK"); throw error; }
|
||||
finally { client.release(); }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { db } from "./db";
|
||||
import { decodeCursor, encodeCursor, type FeedData, type Post, type PostKind, type Tag } from "./model";
|
||||
import { works } from "../content/registry";
|
||||
const tagTree = `WITH RECURSIVE tree AS (SELECT *,slug::text AS path FROM tags WHERE parent_id IS NULL UNION ALL SELECT t.*,tree.path||'/'||t.slug FROM tags t JOIN tree ON t.parent_id=tree.id) SELECT * FROM tree`;
|
||||
export async function tags(): Promise<Tag[]> { return (await db().query(`${tagTree} ORDER BY path`)).rows; }
|
||||
const expand = `SELECT p.*,
|
||||
COALESCE((SELECT jsonb_agg(ae ORDER BY ae.position) FROM (SELECT a.*,pa.position,pa.role,COALESCE((SELECT jsonb_agg(v.role) FROM asset_variants v WHERE v.asset_id=a.id),'[]') AS variants FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id) ae),'[]') AS assets,
|
||||
COALESCE((SELECT jsonb_agg(t) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id),'[]') AS tags FROM posts p`;
|
||||
function serialize(posts: Post[], allTags: Tag[]): Post[] {
|
||||
return posts.map(p => ({...p, created_at: new Date(p.created_at).toISOString(), tags:p.tags.map(t=>allTags.find(a=>a.id===t.id)!).filter(Boolean)}));
|
||||
}
|
||||
export async function getPost(slug: string): Promise<Post | null> {
|
||||
const result = await db().query(`${expand} WHERE p.slug=$1`,[slug]);
|
||||
return serialize(result.rows,await tags())[0] || null;
|
||||
}
|
||||
export async function feed(options: {kind?: PostKind; path?: string; cursor?: string; q?: string} = {}): Promise<FeedData> {
|
||||
const allTags=await tags(); const target=options.path ? allTags.find(t=>t.path===options.path) : undefined;
|
||||
if(options.path&&!target) throw new Error("Tag not found");
|
||||
const cursor=decodeCursor(options.cursor); const values: unknown[]=[];
|
||||
const where=[`((p.kind IN ('article','motion') AND p.page_key=ANY($1::text[])) OR EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role='content' AND a.kind=p.kind AND a.storage_key IS NOT NULL AND a.byte_size>0))`];
|
||||
values.push(Object.keys(works));
|
||||
if(options.kind){values.push(options.kind);where.push(`p.kind=$${values.length}`);}
|
||||
if(target){values.push(allTags.filter(t=>t.path===target.path||t.path.startsWith(target.path+"/")).map(t=>t.id));where.push(`EXISTS(SELECT 1 FROM post_tags WHERE post_id=p.id AND tag_id=ANY($${values.length}::uuid[]))`);}
|
||||
if(options.q){values.push(`%${options.q.replace(/[\\%_]/g,"\\$&")}%`);where.push(`p.title ILIKE $${values.length}`);}
|
||||
if(cursor){values.push(...cursor);where.push(`(p.created_at,p.id)<($${values.length-1}::timestamptz,$${values.length}::uuid)`);}
|
||||
const rows=(await db().query(`${expand} WHERE ${where.join(' AND ')} ORDER BY p.created_at DESC,p.id DESC LIMIT 25`,values)).rows as Post[];
|
||||
const hasMore=rows.length>24; const posts=serialize(rows.slice(0,24),allTags); const last=posts.at(-1);
|
||||
const contributions=(await db().query(`SELECT to_char(occurred_at AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD') AS day,sum(amount)::integer AS total FROM contribution_events WHERE occurred_at>=now()-interval '366 days' GROUP BY day ORDER BY day`)).rows;
|
||||
return {posts,tags:allTags,contributions,nextCursor:hasMore&&last?encodeCursor(last.created_at,last.id):null};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export const sections = [
|
||||
{ path: "images", kind: "image", name: "图片素材", hint: "照片、插画与可以反复使用的画面" },
|
||||
{ path: "videos", kind: "video", name: "视频素材", hint: "片段与镜头,声音随画面一起收好" },
|
||||
{ path: "audio", kind: "audio", name: "声音素材", hint: "音乐、环境声与声音片段" },
|
||||
{ path: "articles", kind: "article", name: "图文作品", hint: "用网页编写,慢慢打磨每一页" },
|
||||
{ path: "motion", kind: "motion", name: "动态作品", hint: "让网页本身成为时间里的画面" },
|
||||
] as const;
|
||||
export type PostKind = typeof sections[number]["kind"];
|
||||
export type Asset = { id: string; kind: "image" | "video" | "audio" | "text"; filename: string | null; body: string | null; width: number | null; height: number | null; duration: number | null; has_audio: boolean | null; processing_status: string; variants: string[] };
|
||||
export type Tag = { id: string; parent_id: string | null; name: string; slug: string; path: string };
|
||||
export type Post = { id: string; slug: string; kind: PostKind; title: string; created_at: string; page_key: string | null; cover_asset_id: string | null; assets: Asset[]; tags: Tag[] };
|
||||
export type FeedData = { posts: Post[]; tags: Tag[]; contributions: { day: string; total: number }[]; nextCursor: string | null; unavailable?: boolean };
|
||||
export function validSection(path: string) { return sections.find(s => s.path === path); }
|
||||
export const mediaUrl = (id: string, variant?: string) => `/api/media/${id}${variant ? `?variant=${variant}` : ""}`;
|
||||
export function encodeCursor(date: string, id: string) { return Buffer.from(JSON.stringify([date,id])).toString("base64url"); }
|
||||
export function decodeCursor(value?: string) {
|
||||
if (!value) return null;
|
||||
try { const [date,id] = JSON.parse(Buffer.from(value,"base64url").toString());
|
||||
if (!Number.isNaN(Date.parse(date)) && /^[0-9a-f-]{36}$/.test(id)) return [date,id];
|
||||
} catch { /* invalid pagination cursor */ }
|
||||
throw new Error("Invalid cursor");
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
export const run=promisify(execFile);
|
||||
export async function probe(file:string) {
|
||||
const {stdout}=await run(process.env.FFPROBE_PATH||'ffprobe',['-v','error','-protocol_whitelist','file,pipe','-show_streams','-show_format','-of','json',file],{timeout:30000,maxBuffer:2*1024*1024});
|
||||
return JSON.parse(stdout) as {streams:{codec_type:string;width?:number;height?:number}[];format:{duration?:string;format_name?:string}};
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, HeadBucketCommand, CreateBucketCommand } from "@aws-sdk/client-s3";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
let instance: S3Client;
|
||||
export function storage() {
|
||||
return instance ??= new S3Client({
|
||||
endpoint: process.env.S3_ENDPOINT, region: "us-east-1", forcePathStyle: true,
|
||||
credentials: { accessKeyId: process.env.S3_ACCESS_KEY!, secretAccessKey: process.env.S3_SECRET_KEY! },
|
||||
requestChecksumCalculation: "WHEN_REQUIRED", responseChecksumValidation: "WHEN_REQUIRED",
|
||||
});
|
||||
}
|
||||
export const bucket = () => process.env.S3_BUCKET || "prompt";
|
||||
export async function ensureBucket() {
|
||||
try { await storage().send(new HeadBucketCommand({ Bucket: bucket() })); }
|
||||
catch (e) {
|
||||
if ((e as { $metadata?: { httpStatusCode: number } }).$metadata?.httpStatusCode !== 404) throw e;
|
||||
await storage().send(new CreateBucketCommand({ Bucket: bucket() }));
|
||||
}
|
||||
}
|
||||
export async function putFile(key: string, path: string, mime: string) {
|
||||
const size = (await stat(path)).size;
|
||||
await storage().send(new PutObjectCommand({ Bucket: bucket(), Key: key, Body: createReadStream(path), ContentLength: size, ContentType: mime }));
|
||||
return size;
|
||||
}
|
||||
export const getObject = (key: string, range?: string) => storage().send(new GetObjectCommand({ Bucket: bucket(), Key: key, Range: range }));
|
||||
export const removeObject = (key: string) => storage().send(new DeleteObjectCommand({ Bucket: bucket(), Key: key }));
|
||||
@@ -0,0 +1,27 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { transaction } from "./db";
|
||||
import { works } from "../content/registry";
|
||||
export const postInput=z.object({
|
||||
slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,119}$/).optional(),
|
||||
kind:z.enum(["image","video","audio","article","motion"]),title:z.string().trim().min(1).max(200),
|
||||
assets:z.array(z.object({id:z.uuid(),role:z.enum(["content","caption"]).default("content")})).max(100).default([]),
|
||||
text:z.string().trim().max(100000).optional(),tags:z.array(z.uuid()).max(50).default([]),
|
||||
coverAssetId:z.uuid().optional(),pageKey:z.string().max(120).optional(),
|
||||
});
|
||||
export async function createPost(input:z.infer<typeof postInput>) {
|
||||
const id=randomUUID(); const slug=input.slug||id;
|
||||
if(["article","motion"].includes(input.kind)&&(!input.pageKey||works[input.pageKey]?.kind!==input.kind)) throw new Error("Register the coded page before creating its post");
|
||||
return transaction(async client=>{
|
||||
const ids=[...new Set(input.assets.map(a=>a.id))];
|
||||
const assets=ids.length?(await client.query('SELECT id,kind FROM assets WHERE id=ANY($1::uuid[])',[ids])).rows:[];
|
||||
if(assets.length!==ids.length) throw new Error("Referenced asset does not exist");
|
||||
if(["image","video","audio"].includes(input.kind)&&!input.assets.some(link=>link.role==='content'&&assets.some(a=>a.id===link.id&&a.kind===input.kind))) throw new Error("A media post needs matching content");
|
||||
if(input.coverAssetId && !(await client.query("SELECT 1 FROM assets WHERE id=$1 AND kind='image'",[input.coverAssetId])).rowCount) throw new Error("Cover must reference an image");
|
||||
await client.query('INSERT INTO posts(id,slug,kind,title,page_key,cover_asset_id) VALUES($1,$2,$3,$4,$5,$6)',[id,slug,input.kind,input.title,input.pageKey||null,input.coverAssetId||null]);
|
||||
for(const [position,a] of input.assets.entries()) await client.query('INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,$4)',[id,a.id,position,a.role]);
|
||||
if(input.text){const textId=randomUUID();await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[textId,input.text]);await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'caption')",[id,textId,input.assets.length]);}
|
||||
for(const tag of new Set(input.tags)) await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[id,tag]);
|
||||
return {id,slug};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { GetServerSideProps } from "next";
|
||||
import { Feed } from "@/components/Feed";
|
||||
import { feed } from "@/lib/library";
|
||||
import { validSection } from "@/lib/model";
|
||||
export default Feed;
|
||||
export const getServerSideProps:GetServerSideProps=async({params,query})=>{
|
||||
const section=String(params?.section||'');const item=validSection(section);if(!item)return {notFound:true};
|
||||
const tagPath=Array.isArray(params?.taxonomy)?params.taxonomy.join('/'):'';
|
||||
try{return {props:{initial:await feed({kind:item.kind,path:tagPath,q:String(query.q||'').slice(0,200)}),section,tagPath}};}
|
||||
catch(e){if(e instanceof Error&&e.message==='Tag not found')return {notFound:true};return {props:{initial:{posts:[],tags:[],contributions:[],nextCursor:null,unavailable:true},section,tagPath}};}
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { NextApiRequest,NextApiResponse } from "next";
|
||||
import { feed } from "@/lib/library";
|
||||
import { validSection } from "@/lib/model";
|
||||
import { apiError } from "@/lib/api";
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
if(req.method!=='GET')return res.status(405).end();
|
||||
try {const section=String(req.query.section||'');if(section&&!validSection(section))return res.status(400).json({error:'未知分类'});
|
||||
res.setHeader('Cache-Control','no-store');return res.json(await feed({kind:validSection(section)?.kind,path:String(req.query.path||''),cursor:String(req.query.cursor||''),q:String(req.query.q||'').slice(0,200)}));
|
||||
}catch(e){return apiError(res,e);}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { NextApiRequest,NextApiResponse } from "next";
|
||||
import type { Readable } from "node:stream";
|
||||
import { db } from "@/lib/db";
|
||||
import { getObject } from "@/lib/storage";
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
if(!['GET','HEAD'].includes(req.method||''))return res.status(405).end();
|
||||
if(!/^[0-9a-f-]{36}$/.test(String(req.query.id)))return res.status(404).end();
|
||||
try{
|
||||
const variant=String(req.query.variant||'');
|
||||
if(variant&&!['poster','silent_video','audio_track'].includes(variant))return res.status(404).end();
|
||||
const result=variant?await db().query('SELECT storage_key,mime_type FROM asset_variants WHERE asset_id=$1 AND role=$2',[req.query.id,variant]):await db().query('SELECT storage_key,mime_type FROM assets WHERE id=$1',[req.query.id]);
|
||||
if(!result.rows[0]?.storage_key)return res.status(404).end();
|
||||
const object=await getObject(result.rows[0].storage_key,req.headers.range);
|
||||
res.status(object.ContentRange?206:200);
|
||||
res.setHeader('Content-Type',object.ContentType||'application/octet-stream');res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('Accept-Ranges','bytes');
|
||||
if(object.ContentLength!==undefined)res.setHeader('Content-Length',object.ContentLength);
|
||||
if(object.ContentRange)res.setHeader('Content-Range',object.ContentRange);
|
||||
res.setHeader('Cache-Control','private, max-age=3600');
|
||||
const stream=object.Body as Readable;
|
||||
if(req.method==='HEAD'){stream.destroy();return res.end();}
|
||||
res.on('close',()=>stream.destroy());stream.on('error',()=>res.destroy());return stream.pipe(res);
|
||||
}catch(e){const code=(e as {$metadata?:{httpStatusCode:number}}).$metadata?.httpStatusCode;return res.status(code===416?416:404).end();}
|
||||
}
|
||||
export const config={api:{responseLimit:false}};
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { NextApiRequest,NextApiResponse } from "next";
|
||||
import { createPost,postInput } from "@/lib/write";
|
||||
import { sameOrigin,apiError } from "@/lib/api";
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
if(req.method!=='POST')return res.status(405).end();
|
||||
try{sameOrigin(req);return res.status(201).json(await createPost(postInput.parse(req.body)));}catch(e){return apiError(res,e);}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { NextApiRequest,NextApiResponse } from 'next';
|
||||
import { db } from '@/lib/db';
|
||||
import { storage,bucket } from '@/lib/storage';
|
||||
import { HeadBucketCommand } from '@aws-sdk/client-s3';
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
if(req.method!=='GET')return res.status(405).end();
|
||||
res.setHeader('Cache-Control','no-store');
|
||||
try{await db().query('SELECT 1 FROM schema_migrations LIMIT 1');await storage().send(new HeadBucketCommand({Bucket:bucket()}));return res.json({status:'ok',database:'ready',objects:'ready'});}catch{return res.status(503).json({status:'unavailable'});}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { NextApiRequest,NextApiResponse } from "next";
|
||||
import { z } from "zod";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { db } from "@/lib/db";
|
||||
import { tags } from "@/lib/library";
|
||||
import { sameOrigin,apiError } from "@/lib/api";
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
try{
|
||||
if(req.method==='GET')return res.json(await tags());
|
||||
if(req.method!=='POST')return res.status(405).end();
|
||||
sameOrigin(req);
|
||||
const data=z.object({name:z.string().trim().min(1).max(60),slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,59}$/),parentId:z.uuid().nullable().default(null)}).parse(req.body);
|
||||
const id=randomUUID(); await db().query('INSERT INTO tags(id,name,slug,parent_id) VALUES($1,$2,$3,$4)',[id,data.name,data.slug,data.parentId]);return res.status(201).json({id});
|
||||
}catch(e){return apiError(res,e);}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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 default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
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});
|
||||
form.on('fileBegin',(_name,file)=>temporary.push(file.filepath));
|
||||
const [fields,files]=await form.parse(req);
|
||||
const kind=z.enum(['image','video','audio']).parse(fields.kind?.[0]);
|
||||
const title=z.string().trim().min(1).max(200).parse(fields.title?.[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]||'[]'));
|
||||
const items=Object.values(files).flat().filter(Boolean) as File[];
|
||||
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'){
|
||||
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=randomUUID();
|
||||
await transaction(async client=>{
|
||||
await client.query('INSERT INTO posts(id,slug,kind,title) VALUES($1,$2,$3,$4)',[postId,postId,kind,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']);
|
||||
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(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]);}
|
||||
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;return res.status(201).json({id:postId,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));}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { GetServerSideProps } from "next";
|
||||
import { Feed } from "@/components/Feed";
|
||||
import { feed } from "@/lib/library";
|
||||
export default Feed;
|
||||
export const getServerSideProps:GetServerSideProps=async({query})=>{
|
||||
try{return {props:{initial:await feed({q:String(query.q||'').slice(0,200)})}};}
|
||||
catch{return {props:{initial:{posts:[],tags:[],contributions:[],nextCursor:null,unavailable:true}}};}
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { GetServerSideProps } from "next";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { Layers,Copy,Upload } from "lucide-react";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { db } from "@/lib/db";
|
||||
import { mediaUrl,type Asset } from "@/lib/model";
|
||||
type Row=Asset&{uses:number};
|
||||
export default function Assets({assets,next}:{assets:Row[];next:string|null}){
|
||||
const [copied,setCopied]=useState('');
|
||||
return <Shell><Head><title>原始素材 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">ONE ASSET, MANY POSSIBILITIES</span><h1>素材库</h1><p>查看全部原始文件和文字,复用已收录的素材。</p></div><Link className="secondary-button" href="/library/import"><Upload size={15}/>导入素材</Link></header>
|
||||
{assets.length?<div className="asset-grid">{assets.map(a=><article className="asset-tile" key={a.id}><div className="asset-preview">{a.kind==='image'?<img src={mediaUrl(a.id)} alt={a.filename||''} loading="lazy"/>:a.kind==='audio'?<audio controls preload="none" src={mediaUrl(a.id)}/>:a.kind==='video'?<video controls preload="metadata" src={mediaUrl(a.id)}/>:<p>{a.body?.slice(0,300)}</p>}</div><div className="asset-tile-info"><h3>{a.filename||'文字片段'}</h3><span>{a.uses} 个素材包正在引用</span><button aria-label="复制素材 ID" onClick={async()=>{await navigator.clipboard.writeText(a.id);setCopied(a.id);}}><Copy size={14}/>{copied===a.id?'已复制':'复制 ID'}</button></div></article>)}</div>:<div className="empty-state"><Layers size={38}/><h2>素材架还是空的</h2><p>导入的图片、视频、声音,以及素材包中的文字都会保存在这里。</p></div>}
|
||||
{next&&<Link className="secondary-button" href={'/library/assets?before='+encodeURIComponent(next)}>下一页素材</Link>}
|
||||
</Shell>;
|
||||
}
|
||||
export const getServerSideProps:GetServerSideProps=async({query})=>{
|
||||
const before=String(query.before||'');const valid=/^[0-9a-f-]{36}$/.test(before);
|
||||
const result=await db().query(`SELECT a.*,(SELECT count(DISTINCT post_id)::integer FROM post_assets WHERE asset_id=a.id) AS uses,'[]'::json AS variants FROM assets a ${valid?'WHERE (a.created_at,a.id)<(SELECT created_at,id FROM assets WHERE id=$1)':''} ORDER BY a.created_at DESC,a.id DESC LIMIT 49`,valid?[before]:[]);
|
||||
const rows=result.rows.slice(0,48).map(({created_at,...a})=>a);return {props:{assets:rows,next:result.rows.length>48?rows.at(-1).id:null}};
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { GetServerSideProps } from "next";
|
||||
import Head from "next/head";
|
||||
import { useState,type FormEvent } from "react";
|
||||
import { useRouter } from "next/router";
|
||||
import { Upload,Image,Film,AudioLines,ArrowUpRight,X,Check } from "lucide-react";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { tags } from "@/lib/library";
|
||||
import type { Tag } from "@/lib/model";
|
||||
export default function Import({allTags}:{allTags:Tag[]}){
|
||||
const router=useRouter();const [kind,setKind]=useState(['image','video','audio'].includes(String(router.query.kind))?String(router.query.kind):'image');
|
||||
const [files,setFiles]=useState<File[]>([]);const [title,setTitle]=useState('');const [description,setDescription]=useState('');const [selected,setSelected]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');
|
||||
function choose(list:FileList|null){if(!list)return;const items=Array.from(list);setFiles(items);if(!title&&items[0])setTitle(items[0].name.replace(/\.[^.]+$/,''));}
|
||||
async function submit(e:FormEvent){e.preventDefault();setError('');setBusy(true);try{const data=new FormData();data.set('kind',kind);data.set('title',title);data.set('description',description);data.set('tags',JSON.stringify(selected));files.forEach(f=>data.append('files',f));const res=await fetch('/api/upload',{method:'POST',body:data});const result=await res.json();if(!res.ok)throw new Error(result.error);await router.push('/p/'+result.slug);}catch(e){setError(e instanceof Error?e.message:'上传失败');}finally{setBusy(false);}}
|
||||
return <Shell><Head><title>素材入库 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">MAKE ROOM FOR INSPIRATION</span><h1>导入素材</h1><p>支持多文件导入。同一组素材收录为一个素材包,每份文件都可以再次引用。</p></div></header><form className="editor-panel" onSubmit={submit}>
|
||||
<div className="kind-picker">{[{id:'image',name:'图片',Icon:Image},{id:'video',name:'视频',Icon:Film},{id:'audio',name:'声音',Icon:AudioLines}].map(t=><button type="button" key={t.id} disabled={busy} className={kind===t.id?'selected':''} onClick={()=>{setKind(t.id);setFiles([]);}}><t.Icon size={19}/>{t.name}</button>)}</div>
|
||||
<label className="drop-zone" onDragOver={e=>e.preventDefault()} onDrop={e=>{e.preventDefault();if(!busy)choose(e.dataTransfer.files);}}><input type="file" multiple disabled={busy} accept={kind==='image'?'image/jpeg,image/png,image/webp,image/gif,image/avif':kind+'/*'} onChange={e=>choose(e.target.files)}/><span className="upload-circle"><Upload size={24}/></span><strong>选择文件或拖放到这里</strong><span>最多 16 个文件,单个不超过 250 MB</span></label>
|
||||
{files.length>0&&<ul className="file-list">{files.map((f,i)=><li key={i}><Check size={15}/><span>{f.name}</span><small>{(f.size/1024/1024).toFixed(1)} MB</small><button type="button" aria-label={`移除 ${f.name}`} disabled={busy} onClick={()=>setFiles(a=>a.filter((_,j)=>i!==j))}><X size={14}/></button></li>)}</ul>}
|
||||
<div className="form-field"><label htmlFor="title">标题</label><input id="title" required maxLength={200} value={title} onChange={e=>setTitle(e.target.value)} placeholder="添加标题"/></div>
|
||||
<div className="form-field"><label htmlFor="description">描述 <small>选填</small></label><textarea id="description" maxLength={100000} rows={4} value={description} onChange={e=>setDescription(e.target.value)} placeholder="拍摄场景、灵感、下次想怎么用…"/></div>
|
||||
{allTags.length>0&&<div className="form-field"><label>放进哪些分类 <small>可多选</small></label><div className="tag-picker">{allTags.map(t=><label key={t.id}><input type="checkbox" checked={selected.includes(t.id)} onChange={e=>setSelected(s=>e.target.checked?[...s,t.id]:s.filter(id=>id!==t.id))}/>{allTags.filter(a=>t.path.startsWith(a.path+'/')).map(a=>a.name+' / ')}{t.name}</label>)}</div></div>}
|
||||
{kind==='video'&&<p className="form-note">视频入库后会自动分离画面和声音。有声、无声都会标记;分离出的音轨始终跟随原视频。</p>}
|
||||
{error&&<p role="alert" className="error-message">{error}</p>}<div className="form-actions"><span>原文件独立保存,素材包只记录引用。</span><button className="primary-button" disabled={!files.length||busy}>{busy?'正在入库,请稍候…':'导入素材'}<ArrowUpRight size={16}/></button></div>
|
||||
</form></Shell>;
|
||||
}
|
||||
export const getServerSideProps:GetServerSideProps=async()=>({props:{allTags:await tags()}});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { GetServerSideProps } from "next";
|
||||
import Head from "next/head";
|
||||
import { useState,type FormEvent } from "react";
|
||||
import { useRouter } from "next/router";
|
||||
import { Hash,CornerDownRight } from "lucide-react";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { tags } from "@/lib/library";
|
||||
import type { Tag } from "@/lib/model";
|
||||
export default function TagsPage({allTags}:{allTags:Tag[]}){
|
||||
const router=useRouter();const [error,setError]=useState('');const [busy,setBusy]=useState(false);
|
||||
async function submit(e:FormEvent<HTMLFormElement>){e.preventDefault();const form=e.currentTarget;const data=new FormData(form);setBusy(true);setError('');try{const r=await fetch('/api/tags',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:data.get('name'),slug:data.get('slug'),parentId:data.get('parentId')||null})});if(!r.ok)throw new Error((await r.json()).error);form.reset();await router.replace(router.asPath);}catch(e){setError(e instanceof Error?e.message:'保存失败');}finally{setBusy(false);}}
|
||||
return <Shell><Head><title>分类标签 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">A PLACE FOR EVERY IDEA</span><h1>分类管理</h1><p>按层级整理标签。同一个素材包可以同时归入多个分类。</p></div></header><div className="management-grid"><section className="surface"><h2>分类树 <small>{allTags.length} 个分类</small></h2>{allTags.length?allTags.map(t=><div className="taxonomy-row" key={t.id} style={{paddingLeft:18+t.path.split('/').length*18}}>{t.parent_id?<CornerDownRight size={16}/>:<Hash size={16}/>}<strong>{t.name}</strong><code>/{t.path}</code></div>):<div className="quiet-empty">还没有分类。先从一个大方向开始。</div>}</section><form className="surface compact-form" onSubmit={submit}><h2>新建分类</h2><label>分类名称<input required name="name" maxLength={60} placeholder="比如:手绘线条"/></label><label>网址标识<input required name="slug" pattern="[a-z0-9][a-z0-9-]*" maxLength={60} placeholder="hand-drawn"/><small>使用小写字母、数字和连字符。</small></label><label>上级分类<select name="parentId"><option value="">作为一级分类</option>{allTags.map(t=><option key={t.id} value={t.id}>{t.path.split('/').map((_,i)=>allTags.find(a=>a.path===t.path.split('/').slice(0,i+1).join('/'))?.name).join(' / ')}</option>)}</select></label>{error&&<p className="error-message" role="alert">{error}</p>}<button className="primary-button" disabled={busy}>{busy?'保存中…':'保存分类'}</button></form></div></Shell>;
|
||||
}
|
||||
export const getServerSideProps:GetServerSideProps=async()=>({props:{allTags:await tags()}});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { GetServerSideProps } from "next";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import { useEffect,useState } from "react";
|
||||
import { useRouter } from "next/router";
|
||||
import { ArrowLeft,ChevronLeft,ChevronRight,Volume2,VolumeX,Download,Copy,Layers } from "lucide-react";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { getPost } from "@/lib/library";
|
||||
import { mediaUrl,sections,type Post } from "@/lib/model";
|
||||
import { works } from "@/content/registry";
|
||||
export default function PostDetail({post}:{post:Post}){
|
||||
const [index,setIndex]=useState(0);const [copied,setCopied]=useState(false);const router=useRouter();
|
||||
const media=post.assets.filter(a=>a.kind!=='text');const selected=media[index];const section=sections.find(s=>s.kind===post.kind)!;
|
||||
useEffect(()=>{if(post.assets.some(a=>['pending','processing'].includes(a.processing_status))){const timer=setTimeout(()=>{void router.replace(router.asPath,undefined,{scroll:false});},3000);return ()=>clearTimeout(timer);}},[post,router]);
|
||||
const Work=post.page_key?works[post.page_key]?.Component:undefined;
|
||||
return <Shell><Head><title>{post.title} · PROMPT</title></Head><div className="detail-top"><Link href={`/${section.path}`}><ArrowLeft size={17}/>返回{section.name}</Link><span>{section.name}</span></div>
|
||||
<div className={`detail-layout ${Work?'coded-detail':''}`}><section className="detail-media">
|
||||
{Work?<Work/>:selected?<><div className={`media-stage stage-${selected.kind}`}>
|
||||
{selected.kind==='image'&&<img src={mediaUrl(selected.id)} alt={selected.filename||post.title}/>}
|
||||
{selected.kind==='video'&&<video key={selected.id} controls playsInline preload="metadata" poster={selected.variants.includes('poster')?mediaUrl(selected.id,'poster'):undefined} src={mediaUrl(selected.id,selected.variants.includes('silent_video')?'silent_video':undefined)}/>}
|
||||
{selected.kind==='audio'&&<div className="audio-stage"><div className="vinyl"><span/></div><h3>{selected.filename}</h3><audio key={selected.id} controls preload="metadata" src={mediaUrl(selected.id)}/></div>}
|
||||
{media.length>1&&<><button className="gallery-prev icon-button" disabled={index===0} aria-label="上一个素材" onClick={()=>setIndex(i=>i-1)}><ChevronLeft/></button><button className="gallery-next icon-button" disabled={index===media.length-1} aria-label="下一个素材" onClick={()=>setIndex(i=>i+1)}><ChevronRight/></button><span className="gallery-position">{index+1} / {media.length}</span></>}
|
||||
</div>
|
||||
{selected.kind==='video'&&<div className="video-companion"><div><span className="pill">{selected.has_audio?<><Volume2 size={14}/>原视频有声音</>:<><VolumeX size={14}/>原视频无声音</>}</span><small>{selected.processing_status==='ready'?'画面已分离,可独立预览与复用':selected.processing_status==='failed'?'音画分离未完成,原文件仍可使用':'正在后台拆分画面与声音…'}</small></div>{selected.variants.includes('audio_track')&&<div className="bound-audio"><span><Volume2 size={16}/>这段视频的声音</span><audio controls preload="metadata" src={mediaUrl(selected.id,'audio_track')}/><small>音轨随视频保存,不属于独立声音素材。</small></div>}</div>}
|
||||
{media.length>1&&<div className="thumbnail-strip">{media.map((a,i)=><button key={a.id} className={i===index?'selected':''} onClick={()=>setIndex(i)} aria-label={`查看第 ${i+1} 个素材`}>{a.kind==='image'?<img src={mediaUrl(a.id)} alt=""/>:a.variants.includes('poster')?<img src={mediaUrl(a.id,'poster')} alt=""/>:<span>{a.kind==='audio'?'声音':'视频'} {i+1}</span>}</button>)}</div>}</>:<div className="empty-state"><Layers/><p>这个素材包还没有可展示的内容。</p></div>}
|
||||
</section><aside className="detail-info"><span className="eyebrow">A PIECE OF YOUR COLLECTION</span><h1>{post.title}</h1><div className="detail-date">{new Date(post.created_at).toLocaleString('zh-CN',{timeZone:'Asia/Shanghai'})}<span>· {media.length} 份素材</span></div>
|
||||
<div className="description">{post.assets.filter(a=>a.kind==='text').map(a=><p key={a.id}>{a.body}</p>)}</div>
|
||||
<div className="tag-list">{post.tags.map(t=><Link key={t.id} href={`/${section.path}/${t.path}`}># {t.name}</Link>)}</div>
|
||||
{selected&&<div className="asset-facts"><h3>素材信息</h3><dl><dt>原文件</dt><dd>{selected.filename}</dd>{selected.width&&<><dt>尺寸</dt><dd>{selected.width} × {selected.height}</dd></>}{selected.duration&&<><dt>时长</dt><dd>{selected.duration.toFixed(1)} 秒</dd></>}<dt>复用方式</dt><dd>引用同一素材,无需再次上传</dd></dl><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(selected.id);setCopied(true);setTimeout(()=>setCopied(false),2000);}}><Copy size={14}/>{copied?'已复制素材 ID':'复制素材 ID'}</button><a className="text-link" href={mediaUrl(selected.id)} download><Download size={14}/>打开原文件</a></div>}
|
||||
</aside></div>
|
||||
</Shell>;
|
||||
}
|
||||
export const getServerSideProps:GetServerSideProps=async({params})=>{
|
||||
const post=await getPost(String(params?.slug||''));return post?{props:{post}}:{notFound:true};
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import Head from "next/head";
|
||||
import { useState } from "react";
|
||||
import { Download,Copy,Sparkles } from "lucide-react";
|
||||
import { Shell } from "@/components/Shell";
|
||||
const strokes=[
|
||||
{name:'睡眼',hint:'让石头和面包打一个盹',path:'M22 54 Q38 72 54 54 M74 54 Q90 72 106 54 M39 65 l-3 8 M89 65 l3 8'},
|
||||
{name:'弯弯箭头',hint:'把目光引向一个小细节',path:'M20 87 Q15 26 92 37 M77 22 L100 37 L80 53'},
|
||||
{name:'一朵小云',hint:'给天空加一点想象',path:'M30 82 C3 83 10 52 31 55 C26 22 71 20 75 47 C100 33 120 64 101 80 M32 82 L99 82'},
|
||||
{name:'一点心动',hint:'给喜欢的东西圈个重点',path:'M65 99 C-4 57 35 15 64 45 C92 11 133 57 65 99'},
|
||||
{name:'闪一下',hint:'把光画成一个小小的惊喜',path:'M64 20 Q61 59 28 64 Q60 67 64 106 Q69 68 102 64 Q69 60 64 20 M103 17 L103 35 M94 26 L112 26'},
|
||||
{name:'草在长',hint:'沿着画面边缘悄悄长出来',path:'M24 101 Q25 73 10 64 M24 101 Q38 71 39 51 M60 101 Q49 74 48 66 M60 101 Q75 65 72 35 M96 101 Q87 71 86 62 M96 101 Q105 76 116 72'},
|
||||
{name:'松松的圈',hint:'不必画得很圆',path:'M93 30 C44 8 11 40 21 79 C32 118 110 110 110 61 C109 26 76 18 45 25'},
|
||||
{name:'波浪下划线',hint:'留给一句想记住的话',path:'M13 67 Q23 48 33 67 T53 67 T73 67 T93 67 T113 67'},
|
||||
];
|
||||
export default function Doodle(){
|
||||
const [selected,setSelected]=useState(0);const [color,setColor]=useState('#fffaf0');const [copied,setCopied]=useState(false);
|
||||
const svg=()=>`<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><path d="${strokes[selected].path}" fill="none" stroke="${color}" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
|
||||
function download(){const url=URL.createObjectURL(new Blob([svg()],{type:'image/svg+xml'}));const a=document.createElement('a');a.href=url;a.download=`prompt-doodle-${selected+1}.svg`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
|
||||
return <Shell><Head><title>线条灵感 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">SMALL LINES, LITTLE STORIES</span><h1>线条工具</h1><p>选择图形、调整颜色,下载后用于照片涂鸦。</p></div><span className="pill"><Sparkles size={14}/>照片涂鸦工具箱</span></header><div className="doodle-layout"><section className="doodle-catalog">{strokes.map((s,i)=><button key={s.name} onClick={()=>{setSelected(i);setCopied(false);}} className={`doodle-card ${i===selected?'selected':''}`}><div><svg viewBox="0 0 128 128"><path d={s.path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><strong>{s.name}</strong><small>{s.hint}</small></button>)}</section><aside className="surface doodle-inspector"><span className="eyebrow">A LITTLE MARK</span><div className="doodle-large"><svg viewBox="0 0 128 128"><path d={strokes[selected].path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><h2>{strokes[selected].name}</h2><p>{strokes[selected].hint}</p><div className="swatches">{['#fffaf0','#332c28','#ef6954','#ecc75b'].map(c=><button aria-label={`线条颜色 ${c}`} key={c} style={{background:c}} className={c===color?'selected':''} onClick={()=>setColor(c)}/>)}</div><button className="primary-button" onClick={download}><Download size={16}/>下载透明底 SVG</button><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(svg());setCopied(true);}}><Copy size={16}/>{copied?'已复制':'复制线条'}</button><p className="form-note">小图用来挑选造型与记录想法。正式画进照片时,位置、比例与笔触仍需要顺着画面调整。</p></aside></div></Shell>;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,44 @@
|
||||
import { mkdtemp,rm } from "node:fs/promises";
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import type { Readable } from "node:stream";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
import { db,transaction } from "./lib/db";
|
||||
import { getObject,putFile } from "./lib/storage";
|
||||
import { probe,run } from "./lib/probe";
|
||||
let stopping=false;
|
||||
process.on('SIGTERM',()=>{stopping=true;});process.on('SIGINT',()=>{stopping=true;});
|
||||
async function processOne(){
|
||||
const job=await transaction(async client=>(await client.query(`UPDATE media_jobs SET status='processing',attempts=attempts+1,locked_at=now() WHERE id=(SELECT id FROM media_jobs WHERE (status='pending' AND available_at<=now()) OR (status='processing' AND locked_at<now()-interval '15 minutes') ORDER BY available_at FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *`)).rows[0]);
|
||||
if(!job)return false;
|
||||
const dir=await mkdtemp(join(tmpdir(),'prompt-video-'));
|
||||
try{
|
||||
await db().query("UPDATE assets SET processing_status='processing',processing_error=NULL WHERE id=$1",[job.asset_id]);
|
||||
const asset=(await db().query('SELECT * FROM assets WHERE id=$1',[job.asset_id])).rows[0];
|
||||
const input=join(dir,'input');const object=await getObject(asset.storage_key);
|
||||
await pipeline(object.Body as Readable,createWriteStream(input));
|
||||
const metadata=await probe(input);const hasAudio=metadata.streams.some(s=>s.codec_type==='audio');
|
||||
const variants=[{role:'silent_video',mime:'video/mp4',file:'silent.mp4',args:['-map','0:v:0','-an','-c:v','libx264','-preset','veryfast','-crf','22','-pix_fmt','yuv420p','-vf','scale=trunc(iw/2)*2:trunc(ih/2)*2','-movflags','+faststart']},
|
||||
{role:'poster',mime:'image/jpeg',file:'poster.jpg',args:['-map','0:v:0','-frames:v','1','-vf','scale=min(1200\\,iw):-2']}];
|
||||
if(hasAudio)variants.push({role:'audio_track',mime:'audio/mp4',file:'audio.m4a',args:['-map','0:a:0','-vn','-c:a','aac','-b:a','192k']});
|
||||
const outputs:{role:string;mime:string;file:string;args:string[];key:string;size:number}[]=[];
|
||||
for(const v of variants){const path=join(dir,v.file);await run(process.env.FFMPEG_PATH||'ffmpeg',['-nostdin','-y','-v','error','-protocol_whitelist','file,pipe','-i',input,...v.args,path],{timeout:10*60*1000,maxBuffer:2*1024*1024});const key=`derived/${asset.id}/${v.file}`;const size=await putFile(key,path,v.mime);outputs.push({...v,key,size});}
|
||||
await transaction(async client=>{
|
||||
for(const v of outputs)await client.query('INSERT INTO asset_variants(asset_id,role,storage_key,mime_type,byte_size) VALUES($1,$2,$3,$4,$5) ON CONFLICT(asset_id,role) DO UPDATE SET storage_key=excluded.storage_key,mime_type=excluded.mime_type,byte_size=excluded.byte_size',[asset.id,v.role,v.key,v.mime,v.size]);
|
||||
await client.query("UPDATE assets SET has_audio=$2,processing_status='ready',processing_error=NULL WHERE id=$1",[asset.id,hasAudio]);
|
||||
await client.query("UPDATE media_jobs SET status='ready',last_error=NULL WHERE id=$1",[job.id]);
|
||||
});
|
||||
}catch(error){
|
||||
const message=(error instanceof Error?error.message:'Processing failed').slice(0,2000);const final=job.attempts>=3;
|
||||
await transaction(async client=>{
|
||||
await client.query("UPDATE media_jobs SET status=$2,last_error=$3,available_at=now()+interval '30 seconds' WHERE id=$1",[job.id,final?'failed':'pending',message]);
|
||||
await client.query('UPDATE assets SET processing_status=$2,processing_error=$3 WHERE id=$1',[job.asset_id,final?'failed':'pending',message]);
|
||||
});
|
||||
console.error(`Video processing failed for ${job.asset_id}; retry=${!final}`);
|
||||
}finally{await rm(dir,{recursive:true,force:true});}
|
||||
return true;
|
||||
}
|
||||
async function main(){while(!stopping){try{if(!await processOne())await setTimeout(2000);}catch{console.error('Worker connection error; retrying');await setTimeout(5000);}}await db().end();}
|
||||
main().catch(()=>process.exit(1));
|
||||
Reference in New Issue
Block a user