Add a persistent clip library with folders, optional password, and hidden-thumbnail glow.
Generated videos save into a chosen folder, sensitive clips skip thumbnails until played, and Docker writes the catalog to a Coolify volume. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -34,9 +34,31 @@ export default defineEventHandler(async (event) => {
|
||||
? Number(fields.seed)
|
||||
: Math.floor(Math.random() * 2_147_483_647)
|
||||
const length = frameLength(Number(fields.duration || 5))
|
||||
const hideThumbnail = fields.hideThumbnail === 'true'
|
||||
assertLibraryAccess(event)
|
||||
const library = publicLibrary(event)
|
||||
const folderId = library.folders.some(folder => folder.id === fields.folderId)
|
||||
? fields.folderId
|
||||
: library.folders[0]?.id
|
||||
if (!folderId) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Create a library folder before generating' })
|
||||
}
|
||||
|
||||
const job = createJob()
|
||||
job.maxStep = steps
|
||||
job.hideThumbnail = hideThumbnail
|
||||
job.library = {
|
||||
folderId,
|
||||
hideThumbnail,
|
||||
prompt,
|
||||
aspect: fields.aspect || 'auto',
|
||||
width,
|
||||
height,
|
||||
steps,
|
||||
turbo,
|
||||
seed,
|
||||
thumb: image.data
|
||||
}
|
||||
emitJob(job, { type: 'status', message: 'Uploading image...', progress: 2 })
|
||||
|
||||
void runGeneration(job, { prompt, image, width, height, steps, seed, turbo, length }).catch((error) => {
|
||||
@@ -54,7 +76,9 @@ export default defineEventHandler(async (event) => {
|
||||
height,
|
||||
aspect: fields.aspect || 'auto',
|
||||
steps,
|
||||
turbo
|
||||
turbo,
|
||||
folderId,
|
||||
hideThumbnail
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
assertLibraryAccess(event)
|
||||
const id = getRouterParam(event, 'id')
|
||||
await deleteClip(String(id))
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
assertLibraryAccess(event)
|
||||
const id = String(getRouterParam(event, 'id') || '')
|
||||
const clip = getClip(id)
|
||||
if (clip.hideThumbnail) {
|
||||
throw createError({ statusCode: 404, statusMessage: 'Thumbnail hidden' })
|
||||
}
|
||||
const path = clipThumbPath(clip.id)
|
||||
if (!existsSync(path)) {
|
||||
throw createError({ statusCode: 404, statusMessage: 'Thumbnail not found' })
|
||||
}
|
||||
const buf = readFileSync(path)
|
||||
const png = buf[0] === 0x89 && buf[1] === 0x50
|
||||
setHeader(event, 'Content-Type', png ? 'image/png' : 'image/jpeg')
|
||||
setHeader(event, 'Cache-Control', 'private, max-age=3600')
|
||||
return buf
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
assertLibraryAccess(event)
|
||||
const id = String(getRouterParam(event, 'id') || '')
|
||||
const clip = getClip(id)
|
||||
const path = clipVideoPath(clip.id)
|
||||
if (!existsSync(path)) {
|
||||
throw createError({ statusCode: 404, statusMessage: 'Video file is missing' })
|
||||
}
|
||||
setHeader(event, 'Content-Type', 'video/mp4')
|
||||
setHeader(event, 'Content-Disposition', `inline; filename="${clip.id}.mp4"`)
|
||||
setHeader(event, 'Cache-Control', 'private, max-age=3600')
|
||||
return readFileSync(path)
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
assertLibraryAccess(event)
|
||||
const body = await readBody<{ name?: string }>(event)
|
||||
const folder = await createFolder(String(body?.name || ''))
|
||||
return folder
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
assertLibraryAccess(event)
|
||||
const id = getRouterParam(event, 'id')
|
||||
return await deleteFolder(String(id))
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
assertLibraryAccess(event)
|
||||
const id = getRouterParam(event, 'id')
|
||||
const body = await readBody<{ name?: string }>(event)
|
||||
return await renameFolder(String(id), String(body?.name || ''))
|
||||
})
|
||||
@@ -0,0 +1,3 @@
|
||||
export default defineEventHandler((event) => {
|
||||
return publicLibrary(event)
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
export default defineEventHandler((event) => {
|
||||
clearLibraryUnlock(event)
|
||||
return publicLibrary(event)
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody<{ password?: string; currentPassword?: string }>(event)
|
||||
if (isLibraryLocked() && !(await verifyLibraryPassword(String(body?.currentPassword || '')))) {
|
||||
throw createError({ statusCode: 401, statusMessage: 'Current library password is incorrect' })
|
||||
}
|
||||
const next = String(body?.password || '').trim()
|
||||
if (next && next.length < 4) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Use at least 4 characters, or leave blank to remove the password' })
|
||||
}
|
||||
const version = await setLibraryPassword(next || null)
|
||||
if (next) setLibraryUnlock(event, version)
|
||||
else clearLibraryUnlock(event)
|
||||
return publicLibrary(event)
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody<{ password?: string }>(event)
|
||||
const password = String(body?.password || '')
|
||||
if (!password) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Password is required' })
|
||||
}
|
||||
if (!(await verifyLibraryPassword(password))) {
|
||||
throw createError({ statusCode: 401, statusMessage: 'Incorrect library password' })
|
||||
}
|
||||
setLibraryUnlock(event, currentPasswordVersion())
|
||||
return publicLibrary(event)
|
||||
})
|
||||
@@ -10,6 +10,8 @@ export interface JobEvent {
|
||||
filename?: string
|
||||
subfolder?: string
|
||||
mediaType?: string
|
||||
clipId?: string
|
||||
hideThumbnail?: boolean
|
||||
error?: string
|
||||
elapsedMs?: number
|
||||
}
|
||||
@@ -25,6 +27,20 @@ export interface Job {
|
||||
maxStep: number
|
||||
startedAt: number
|
||||
video?: { filename: string; subfolder: string; type: string }
|
||||
clipId?: string
|
||||
hideThumbnail?: boolean
|
||||
library?: {
|
||||
folderId: string
|
||||
hideThumbnail: boolean
|
||||
prompt: string
|
||||
aspect: string
|
||||
width: number
|
||||
height: number
|
||||
steps: number
|
||||
turbo: boolean
|
||||
seed: number
|
||||
thumb?: Buffer
|
||||
}
|
||||
error?: string
|
||||
events: JobEvent[]
|
||||
listeners: Set<(event: JobEvent) => void>
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
|
||||
import { promisify } from 'node:util'
|
||||
import type { H3Event } from 'h3'
|
||||
|
||||
const scryptAsync = promisify(scrypt)
|
||||
|
||||
export interface LibraryFolder {
|
||||
id: string
|
||||
name: string
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export interface LibraryClip {
|
||||
id: string
|
||||
folderId: string
|
||||
prompt: string
|
||||
aspect: string
|
||||
width: number
|
||||
height: number
|
||||
steps: number
|
||||
turbo: boolean
|
||||
seed: number
|
||||
hideThumbnail: boolean
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
interface Catalog {
|
||||
passwordHash: string | null
|
||||
folders: LibraryFolder[]
|
||||
clips: LibraryClip[]
|
||||
}
|
||||
|
||||
function libraryRoot() {
|
||||
const config = useRuntimeConfig()
|
||||
return (config.libraryDir || process.env.LIBRARY_DIR || '/data/library').replace(/\/$/, '')
|
||||
}
|
||||
|
||||
function catalogPath() {
|
||||
return join(libraryRoot(), 'catalog.json')
|
||||
}
|
||||
|
||||
function ensureRoot() {
|
||||
const root = libraryRoot()
|
||||
mkdirSync(join(root, 'files'), { recursive: true })
|
||||
return root
|
||||
}
|
||||
|
||||
function emptyCatalog(): Catalog {
|
||||
return {
|
||||
passwordHash: null,
|
||||
folders: [{ id: 'inbox', name: 'Inbox', createdAt: Date.now() }],
|
||||
clips: []
|
||||
}
|
||||
}
|
||||
|
||||
let writeChain = Promise.resolve()
|
||||
|
||||
function readCatalog(): Catalog {
|
||||
ensureRoot()
|
||||
if (!existsSync(catalogPath())) {
|
||||
const created = emptyCatalog()
|
||||
writeFileSync(catalogPath(), JSON.stringify(created, null, 2))
|
||||
return created
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(catalogPath(), 'utf8')) as Catalog
|
||||
if (!Array.isArray(parsed.folders) || !parsed.folders.length) {
|
||||
parsed.folders = emptyCatalog().folders
|
||||
}
|
||||
parsed.clips = Array.isArray(parsed.clips) ? parsed.clips : []
|
||||
parsed.passwordHash = parsed.passwordHash || null
|
||||
return parsed
|
||||
} catch {
|
||||
return emptyCatalog()
|
||||
}
|
||||
}
|
||||
|
||||
function writeCatalog(catalog: Catalog) {
|
||||
ensureRoot()
|
||||
const tmp = catalogPath() + '.tmp'
|
||||
writeFileSync(tmp, JSON.stringify(catalog, null, 2))
|
||||
renameSync(tmp, catalogPath())
|
||||
}
|
||||
|
||||
function mutate<T>(fn: (catalog: Catalog) => T): Promise<T> {
|
||||
const run = writeChain.then(() => {
|
||||
const catalog = readCatalog()
|
||||
const result = fn(catalog)
|
||||
writeCatalog(catalog)
|
||||
return result
|
||||
})
|
||||
writeChain = run.then(() => undefined, () => undefined)
|
||||
return run
|
||||
}
|
||||
|
||||
export function passwordVersion(hash: string | null) {
|
||||
return hash ? hash.slice(-24) : 'open'
|
||||
}
|
||||
|
||||
export function currentPasswordVersion() {
|
||||
return passwordVersion(readCatalog().passwordHash)
|
||||
}
|
||||
|
||||
export function isLibraryLocked() {
|
||||
return Boolean(readCatalog().passwordHash)
|
||||
}
|
||||
|
||||
export function libraryUnlocked(event: H3Event) {
|
||||
const catalog = readCatalog()
|
||||
if (!catalog.passwordHash) return true
|
||||
return getLibraryUnlockVersion(event) === passwordVersion(catalog.passwordHash)
|
||||
}
|
||||
|
||||
export function assertLibraryAccess(event: H3Event) {
|
||||
if (libraryUnlocked(event)) return readCatalog()
|
||||
throw createError({ statusCode: 403, statusMessage: 'Library is locked' })
|
||||
}
|
||||
|
||||
export async function hashLibraryPassword(password: string) {
|
||||
const salt = randomBytes(16)
|
||||
const hash = await scryptAsync(password, salt, 64) as Buffer
|
||||
return `scrypt:${salt.toString('hex')}:${hash.toString('hex')}`
|
||||
}
|
||||
|
||||
export async function verifyLibraryPassword(password: string) {
|
||||
const stored = readCatalog().passwordHash
|
||||
if (!stored) return true
|
||||
const parts = stored.split(':')
|
||||
if (parts.length !== 3 || parts[0] !== 'scrypt') return false
|
||||
const salt = Buffer.from(parts[1], 'hex')
|
||||
const expected = Buffer.from(parts[2], 'hex')
|
||||
const actual = await scryptAsync(password, salt, 64) as Buffer
|
||||
return actual.length === expected.length && timingSafeEqual(actual, expected)
|
||||
}
|
||||
|
||||
export function publicLibrary(event: H3Event) {
|
||||
const catalog = readCatalog()
|
||||
const locked = Boolean(catalog.passwordHash)
|
||||
const unlocked = libraryUnlocked(event)
|
||||
if (locked && !unlocked) {
|
||||
return { locked: true, unlocked: false, folders: [] as LibraryFolder[], clips: [] as LibraryClip[] }
|
||||
}
|
||||
return {
|
||||
locked,
|
||||
unlocked: true,
|
||||
folders: catalog.folders,
|
||||
clips: catalog.clips
|
||||
}
|
||||
}
|
||||
|
||||
export function createFolder(name: string) {
|
||||
const trimmed = name.trim().slice(0, 80)
|
||||
if (!trimmed) throw createError({ statusCode: 400, statusMessage: 'Folder name is required' })
|
||||
return mutate((catalog) => {
|
||||
if (catalog.folders.some(folder => folder.name.toLowerCase() === trimmed.toLowerCase())) {
|
||||
throw createError({ statusCode: 409, statusMessage: 'A folder with that name already exists' })
|
||||
}
|
||||
const folder: LibraryFolder = { id: crypto.randomUUID(), name: trimmed, createdAt: Date.now() }
|
||||
catalog.folders.push(folder)
|
||||
return folder
|
||||
})
|
||||
}
|
||||
|
||||
export function renameFolder(id: string, name: string) {
|
||||
const trimmed = name.trim().slice(0, 80)
|
||||
if (!trimmed) throw createError({ statusCode: 400, statusMessage: 'Folder name is required' })
|
||||
return mutate((catalog) => {
|
||||
const folder = catalog.folders.find(item => item.id === id)
|
||||
if (!folder) throw createError({ statusCode: 404, statusMessage: 'Folder not found' })
|
||||
folder.name = trimmed
|
||||
return folder
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteFolder(id: string) {
|
||||
return mutate((catalog) => {
|
||||
if (catalog.folders.length <= 1) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Keep at least one library folder' })
|
||||
}
|
||||
const folder = catalog.folders.find(item => item.id === id)
|
||||
if (!folder) throw createError({ statusCode: 404, statusMessage: 'Folder not found' })
|
||||
const clips = catalog.clips.filter(clip => clip.folderId === id)
|
||||
catalog.folders = catalog.folders.filter(item => item.id !== id)
|
||||
catalog.clips = catalog.clips.filter(clip => clip.folderId !== id)
|
||||
const fallback = catalog.folders[0].id
|
||||
for (const clip of clips) {
|
||||
rmSync(clipDir(clip.id), { recursive: true, force: true })
|
||||
}
|
||||
return { fallbackFolderId: fallback }
|
||||
})
|
||||
}
|
||||
|
||||
export async function setLibraryPassword(password: string | null) {
|
||||
const hash = password && password.length ? await hashLibraryPassword(password) : null
|
||||
return mutate((catalog) => {
|
||||
catalog.passwordHash = hash
|
||||
return passwordVersion(hash)
|
||||
})
|
||||
}
|
||||
|
||||
function clipDir(id: string) {
|
||||
return join(libraryRoot(), 'files', id)
|
||||
}
|
||||
|
||||
export function clipVideoPath(id: string) {
|
||||
return join(clipDir(id), 'video.mp4')
|
||||
}
|
||||
|
||||
export function clipThumbPath(id: string) {
|
||||
return join(clipDir(id), 'thumb')
|
||||
}
|
||||
|
||||
export async function saveClip(params: {
|
||||
folderId: string
|
||||
prompt: string
|
||||
aspect: string
|
||||
width: number
|
||||
height: number
|
||||
steps: number
|
||||
turbo: boolean
|
||||
seed: number
|
||||
hideThumbnail: boolean
|
||||
video: Buffer
|
||||
thumb?: Buffer | null
|
||||
}) {
|
||||
const catalog = readCatalog()
|
||||
const folder = catalog.folders.find(item => item.id === params.folderId) || catalog.folders[0]
|
||||
if (!folder) throw createError({ statusCode: 400, statusMessage: 'No library folder available' })
|
||||
const clip: LibraryClip = {
|
||||
id: crypto.randomUUID(),
|
||||
folderId: folder.id,
|
||||
prompt: params.prompt,
|
||||
aspect: params.aspect,
|
||||
width: params.width,
|
||||
height: params.height,
|
||||
steps: params.steps,
|
||||
turbo: params.turbo,
|
||||
seed: params.seed,
|
||||
hideThumbnail: params.hideThumbnail,
|
||||
createdAt: Date.now()
|
||||
}
|
||||
mkdirSync(clipDir(clip.id), { recursive: true })
|
||||
writeFileSync(clipVideoPath(clip.id), params.video)
|
||||
if (!params.hideThumbnail && params.thumb?.length) {
|
||||
writeFileSync(clipThumbPath(clip.id), params.thumb)
|
||||
}
|
||||
await mutate((next) => {
|
||||
next.clips.unshift(clip)
|
||||
})
|
||||
return clip
|
||||
}
|
||||
|
||||
export function getClip(id: string) {
|
||||
const clip = readCatalog().clips.find(item => item.id === id)
|
||||
if (!clip) throw createError({ statusCode: 404, statusMessage: 'Clip not found' })
|
||||
return clip
|
||||
}
|
||||
|
||||
export function deleteClip(id: string) {
|
||||
return mutate((catalog) => {
|
||||
const clip = catalog.clips.find(item => item.id === id)
|
||||
if (!clip) throw createError({ statusCode: 404, statusMessage: 'Clip not found' })
|
||||
catalog.clips = catalog.clips.filter(item => item.id !== id)
|
||||
rmSync(clipDir(id), { recursive: true, force: true })
|
||||
return clip
|
||||
})
|
||||
}
|
||||
|
||||
export async function downloadComfyVideo(video: { filename: string; subfolder: string; type: string }) {
|
||||
const params = new URLSearchParams({
|
||||
filename: video.filename,
|
||||
subfolder: video.subfolder,
|
||||
type: video.type
|
||||
})
|
||||
const res = await comfyFetch(`/view?${params.toString()}`)
|
||||
if (!res.ok) throw new Error('Failed to fetch completed video from ComfyUI')
|
||||
return Buffer.from(await res.arrayBuffer())
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export interface SessionUser {
|
||||
|
||||
const COOKIE = 'aigen_session'
|
||||
const STATE_COOKIE = 'aigen_oauth_state'
|
||||
const LIBRARY_COOKIE = 'aigen_library'
|
||||
|
||||
function secret() {
|
||||
const config = useRuntimeConfig()
|
||||
@@ -78,6 +79,18 @@ export function authEnabled() {
|
||||
return Boolean(config.public.authEnabled && config.oidcClientId && config.oidcClientSecret)
|
||||
}
|
||||
|
||||
export function setLibraryUnlock(event: H3Event, version: string) {
|
||||
setCookie(event, LIBRARY_COOKIE, seal({ version }), cookieOpts(event))
|
||||
}
|
||||
|
||||
export function getLibraryUnlockVersion(event: H3Event) {
|
||||
return unseal<{ version?: string }>(getCookie(event, LIBRARY_COOKIE))?.version || null
|
||||
}
|
||||
|
||||
export function clearLibraryUnlock(event: H3Event) {
|
||||
deleteCookie(event, LIBRARY_COOKIE, { path: '/' })
|
||||
}
|
||||
|
||||
export function publicBaseUrl(event: H3Event) {
|
||||
const proto = getRequestHeader(event, 'x-forwarded-proto') || getRequestProtocol(event)
|
||||
const host = getRequestHeader(event, 'x-forwarded-host') || getRequestHost(event)
|
||||
|
||||
+33
-3
@@ -1,4 +1,4 @@
|
||||
import { NODE_LABELS } from '~/server/utils/workflow'
|
||||
import { NODE_LABELS, isEncodingNode } from '~/server/utils/workflow'
|
||||
import type { Job } from '~/server/utils/jobs'
|
||||
|
||||
function classifyError(message: string) {
|
||||
@@ -39,6 +39,34 @@ export async function watchComfyJob(job: Job) {
|
||||
return
|
||||
}
|
||||
job.video = video
|
||||
if (job.library) {
|
||||
emitJob(job, { type: 'status', message: 'Saving to library...', progress: 98 })
|
||||
try {
|
||||
const buffer = await downloadComfyVideo(video)
|
||||
const clip = await saveClip({
|
||||
folderId: job.library.folderId,
|
||||
prompt: job.library.prompt,
|
||||
aspect: job.library.aspect,
|
||||
width: job.library.width,
|
||||
height: job.library.height,
|
||||
steps: job.library.steps,
|
||||
turbo: job.library.turbo,
|
||||
seed: job.library.seed,
|
||||
hideThumbnail: job.library.hideThumbnail,
|
||||
video: buffer,
|
||||
thumb: job.library.hideThumbnail ? null : job.library.thumb
|
||||
})
|
||||
job.clipId = clip.id
|
||||
job.hideThumbnail = clip.hideThumbnail
|
||||
job.library.thumb = undefined
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
job.status = 'error'
|
||||
job.error = `Video generated but library save failed: ${message}`
|
||||
emitJob(job, { type: 'error', error: job.error, message: job.error })
|
||||
return
|
||||
}
|
||||
}
|
||||
job.status = 'complete'
|
||||
emitJob(job, {
|
||||
type: 'complete',
|
||||
@@ -46,7 +74,9 @@ export async function watchComfyJob(job: Job) {
|
||||
progress: 100,
|
||||
filename: video.filename,
|
||||
subfolder: video.subfolder,
|
||||
mediaType: video.type
|
||||
mediaType: video.type,
|
||||
clipId: job.clipId,
|
||||
hideThumbnail: job.hideThumbnail
|
||||
})
|
||||
}
|
||||
|
||||
@@ -109,7 +139,7 @@ export async function watchComfyJob(job: Job) {
|
||||
return
|
||||
}
|
||||
const label = NODE_LABELS[node] || `Running node ${node}`
|
||||
const encoding = node === '16' || node === '17'
|
||||
const encoding = isEncodingNode(node)
|
||||
emitJob(job, {
|
||||
type: 'executing',
|
||||
node,
|
||||
|
||||
Reference in New Issue
Block a user