/** * ArchNemix Shorts Generator API - Node.js v5.1.0 * ════════════════════════════════════════════════════════════════════════════ * Exact mirror of Python FFmpeg backend (ffmpeg_main.py v5.1.0) * Uses native FFmpeg CLI tool via child_process.spawn * Endpoints, request/response formats, and video cleanup match Python version */ const express = require('express'); const cors = require('cors'); const crypto = require('crypto'); const fs = require('fs').promises; const fsSync = require('fs'); const path = require('path'); const { spawn } = require('child_process'); const { v4: uuidv4 } = require('uuid'); // ============================================================================= // CONFIG // ============================================================================= const HF_DATASET = process.env.HF_DATASET || 'YTShortMakerArchx/BG_VIDS_ARCHX_YT'; const HF_TOKEN = process.env.HF_TOKEN; const APP_KEY = process.env.APP_KEY; const UI_ORIGIN = process.env.UI_ORIGIN || 'https://shortgenx.pages.dev'; const PORT = process.env.PORT || 7860; const BASE_DIR = '/tmp'; const AUDIO_DIR = path.join(BASE_DIR, 'audio'); const OUTPUT_DIR = path.join(BASE_DIR, 'out'); const JOBS_DIR = path.join(BASE_DIR, 'jobs'); const CLIENT_DIR = path.join(BASE_DIR, 'clients'); const HF_CACHE_DIR = '/tmp/hf_cache'; // Create directories for (const dir of [AUDIO_DIR, OUTPUT_DIR, JOBS_DIR, CLIENT_DIR, HF_CACHE_DIR]) { if (!fsSync.existsSync(dir)) { fsSync.mkdirSync(dir, { recursive: true }); } } // Rate limiting const RATE_LIMITS = new Map(); const GENERATE_LIMIT = 3; // per hour per client const STATUS_LIMIT = 1000; // per hour per job // Job timeout const JOBS = new Map(); const JOB_TIMEOUT = 900; // 15 min hard cap // Video listing cache const VIDEO_CACHE = new Map(); const CACHE_TIMEOUT = 300; // 5 minutes // ============================================================================= // QUEUE SYSTEM // ============================================================================= const MAX_CONCURRENT = 1; const AVG_JOB_DURATION_S = 360; // 6 minutes per job const JOB_QUEUE = []; const RUNNING_JOBS = new Set(); // ============================================================================= // CLIENT ID SYSTEM // ============================================================================= const CLIENT_TOKENS = new Map(); function clientFile(token) { return path.join(CLIENT_DIR, `${token.slice(0, 8)}.json`); } function loadClient(token) { if (CLIENT_TOKENS.has(token)) { return CLIENT_TOKENS.get(token); } const filePath = clientFile(token); if (fsSync.existsSync(filePath)) { try { const data = JSON.parse(fsSync.readFileSync(filePath, 'utf8')); data.created_at = new Date(data.created_at); data.last_seen = new Date(data.last_seen); CLIENT_TOKENS.set(token, data); return data; } catch (e) { // ignore } } return null; } function saveClient(rec) { const token = rec.token; CLIENT_TOKENS.set(token, rec); try { const recCopy = { ...rec, created_at: rec.created_at.toISOString(), last_seen: rec.last_seen.toISOString(), }; fsSync.writeFileSync(clientFile(token), JSON.stringify(recCopy)); } catch (e) { console.warn(`Failed to persist client ${token.slice(0, 8)}: ${e.message}`); } } function createClient(fingerprint) { const rec = { token: crypto.randomBytes(24).toString('hex'), fingerprint, created_at: new Date(), last_seen: new Date(), job_count: 0, jobs: [], }; saveClient(rec); console.log(`New client ${rec.token.slice(0, 8)}...`); return rec; } function fingerprint(req) { const data = `${req.ip}:${req.get('user-agent') || ''}:${req.get('accept') || ''}`; return crypto.createHash('sha256').update(data).digest('hex'); } function resolveClient(req) { let token = (req.get('X-Client-ID') || '').trim(); if (token) { let rec = loadClient(token); if (rec) { rec.last_seen = new Date(); saveClient(rec); return rec; } const fp = fingerprint(req); rec = { token, fingerprint: fp, created_at: new Date(), last_seen: new Date(), job_count: 0, jobs: [], }; saveClient(rec); console.log(`Restored client ${token.slice(0, 8)}... from header`); return rec; } const fp = fingerprint(req); for (const rec of CLIENT_TOKENS.values()) { if (rec.fingerprint === fp) { rec.last_seen = new Date(); saveClient(rec); return rec; } } return createClient(fp); } // ============================================================================= // EXPRESS APP // ============================================================================= const app = express(); // Allowed origins - strict list const ALLOWED_ORIGINS = [ 'https://shortgenx.pages.dev', // Your frontend 'https://ytshortmakerarchx-archnemix-controller.hf.space', // Your controller space 'http://localhost:3000', // Local development ONLY port 3000 'http://127.0.0.1:3000', // Local development ONLY port 3000 ]; app.use(cors({ origin: (origin, callback) => { // Allow requests with no origin (like server-to-server) if (!origin) { return callback(null, true); } // Check if origin is allowed if (ALLOWED_ORIGINS.indexOf(origin) !== -1) { return callback(null, true); } console.warn(`[CORS] Rejected origin: ${origin}`); callback(new Error(`Origin ${origin} not allowed by CORS`)); }, credentials: true, methods: ['GET', 'POST', 'DELETE', 'OPTIONS', 'HEAD'], allowedHeaders: ['*'], exposedHeaders: ['X-Client-ID'], maxAge: 600, })); app.use(express.json({ limit: '50mb' })); // ============================================================================= // SECURITY // ============================================================================= function validateAppKey(req) { if (!APP_KEY || APP_KEY === 'archnemix-secret-key-change-in-production') { return true; } const key = req.get('X-APP-KEY') || req.get('Authorization')?.replace('Bearer ', '') || ''; return key === APP_KEY; } function validateOrigin(req) { const origin = req.get('origin') || req.get('referer') || ''; // Allow requests with no origin (server-to-server) if (!origin) return true; // Strict allowed origins (exact match only) const ALLOWED_ORIGINS_EXACT = [ 'https://shortgenx.pages.dev', 'https://ytshortmakerarchx-archnemix-controller.hf.space', 'http://localhost:3000', 'http://127.0.0.1:3000', ]; // Exact match check if (ALLOWED_ORIGINS_EXACT.includes(origin)) { return true; } console.warn(`[SECURITY] Rejected request from origin: ${origin}`); return false; } function rateLimit(key, limit, window = 3600) { const now = Date.now() / 1000; if (!RATE_LIMITS.has(key)) { RATE_LIMITS.set(key, []); } const timestamps = RATE_LIMITS.get(key).filter(t => now - t < window); RATE_LIMITS.set(key, timestamps); if (timestamps.length >= limit) { return false; } timestamps.push(now); return true; } // ============================================================================= // HUGGINGFACE HELPERS // ============================================================================= async function listVideosFromDataset(category = 'minecraft') { // Map category aliases to dataset folder names const categoryMap = { 'minecraft': 'minecraft', 'subwaysurfers': 'subwaysurfers', 'ss': 'subwaysurfers' }; const datasetCategory = categoryMap[category] || category; const cacheKey = `videos_${datasetCategory}`; if (VIDEO_CACHE.has(cacheKey)) { const { ts, data } = VIDEO_CACHE.get(cacheKey); if (Date.now() / 1000 - ts < CACHE_TIMEOUT) { return data; } } // Default fallback based on category const defaults = datasetCategory === 'subwaysurfers' ? ['ss1', 'ss2', 'ss3', 'ss4', 'ss5'] // 5 videos : Array.from({ length: 6 }, (_, i) => `mc${i + 1}`); try { const fetch = (await import('node-fetch')).default; const url = `https://huggingface.co/api/datasets/${HF_DATASET}/tree/main/${datasetCategory}`; const headers = HF_TOKEN ? { 'Authorization': `Bearer ${HF_TOKEN}` } : {}; const response = await fetch(url, { headers }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const files = await response.json(); const result = files .filter(f => f.type === 'file' && f.path.endsWith('.mp4')) .map(f => path.basename(f.path, '.mp4')); VIDEO_CACHE.set(cacheKey, { ts: Date.now() / 1000, data: result }); return result; } catch (e) { console.error(`list_videos failed: ${e.message}`); return defaults; } } async function downloadVideoFromDataset(videoName, category = 'minecraft') { videoName = videoName.replace('.mp4', ''); const paths = [`${category}/${videoName}.mp4`, `${videoName}.mp4`]; for (const filePath of paths) { try { const url = `https://huggingface.co/datasets/${HF_DATASET}/resolve/main/${filePath}`; const localPath = path.join(HF_CACHE_DIR, `${videoName}.mp4`); // Check if already cached if (fsSync.existsSync(localPath)) { return localPath; } const fetch = (await import('node-fetch')).default; const headers = HF_TOKEN ? { 'Authorization': `Bearer ${HF_TOKEN}` } : {}; const response = await fetch(url, { headers }); if (response.ok) { const buffer = await response.buffer(); await fs.writeFile(localPath, buffer); return localPath; } } catch (e) { continue; } } const available = await listVideosFromDataset(category); throw new Error(`Video '${videoName}' not found. Available: ${available.join(', ')}`); } // ============================================================================= // FILE HELPERS // ============================================================================= async function saveBase64Audio(data, filePath) { if (data.startsWith('data:audio/')) { data = data.split(',')[1]; } const audioBuffer = Buffer.from(data, 'base64'); if (audioBuffer.length > 15 * 1024 * 1024) { throw new Error('Audio too large (max 15 MB)'); } await fs.writeFile(filePath, audioBuffer); return audioBuffer.length; } async function saveSubtitles(ass, filePath) { if (!ass.includes('[Script Info]') || !ass.includes('[Events]')) { throw new Error('Invalid ASS subtitle format'); } if (Buffer.byteLength(ass) > 500 * 1024) { throw new Error('Subtitles too large (max 500 KB)'); } await fs.writeFile(filePath, ass, 'utf8'); } function getMediaDuration(filePath) { return new Promise((resolve) => { const proc = spawn('ffprobe', [ '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', filePath, ]); let output = ''; proc.stdout.on('data', data => output += data.toString()); proc.on('close', (code) => { if (code === 0 && output.trim()) { resolve(parseFloat(output.trim())); } else { // Fallback estimate try { const size = fsSync.statSync(filePath).size; resolve(Math.max(1.0, Math.min(180.0, size / 16000))); } catch { resolve(30.0); } } }); setTimeout(() => { proc.kill(); resolve(30.0); }, 10000); }); } // ============================================================================= // JOB MANAGEMENT // ============================================================================= function makeJob(jobId, clientToken) { return { id: jobId, client_token: clientToken, status: 'queued', queue_position: null, progress: 0, message: 'Waiting in queue...', created_at: new Date(), updated_at: new Date(), error: null, output_path: null, audio_path: null, subs_path: null, ffmpeg_frame: 0, ffmpeg_fps: 0.0, ffmpeg_out_time: 0.0, ffmpeg_speed: 0.0, total_duration: 0.0, }; } function createJob(jobId, clientToken) { const job = makeJob(jobId, clientToken); JOBS.set(jobId, job); persistJob(jobId); return job; } function updateJob(jobId, updates) { if (!JOBS.has(jobId)) return; const job = JOBS.get(jobId); Object.assign(job, updates); job.updated_at = new Date(); persistJob(jobId); } function persistJob(jobId) { if (!JOBS.has(jobId)) return; try { const job = JOBS.get(jobId); const data = { ...job, created_at: job.created_at.toISOString(), updated_at: job.updated_at.toISOString(), }; fsSync.writeFileSync(path.join(JOBS_DIR, `${jobId}.json`), JSON.stringify(data)); } catch (e) { console.error(`persist_job failed: ${e.message}`); } } function cleanupOldJobs() { const now = new Date(); for (const [jobId, job] of JOBS.entries()) { const age = (now - job.updated_at) / 1000; if (age > 3600) { JOBS.delete(jobId); RUNNING_JOBS.delete(jobId); const idx = JOB_QUEUE.indexOf(jobId); if (idx !== -1) JOB_QUEUE.splice(idx, 1); // Cleanup files for (const file of [ path.join(JOBS_DIR, `${jobId}.json`), path.join(AUDIO_DIR, `${jobId}.mp3`), path.join(AUDIO_DIR, `${jobId}.ass`), path.join(OUTPUT_DIR, `${jobId}.mp4`), ]) { try { fsSync.unlinkSync(file); } catch (e) { // ignore } } } } } // ============================================================================= // QUEUE HELPERS // ============================================================================= function queuePosition(jobId) { const idx = JOB_QUEUE.indexOf(jobId); return idx !== -1 ? idx + 1 : null; } function queueEta(position, jobDuration = null) { let runningRemaining = AVG_JOB_DURATION_S; for (const jid of RUNNING_JOBS) { const j = JOBS.get(jid); if (!j) continue; const total = j.total_duration || AVG_JOB_DURATION_S; const out = j.ffmpeg_out_time || 0; const remaining = Math.max(0, total - out); runningRemaining = Math.min(runningRemaining, remaining); } const queuedAhead = Math.max(0, position - 1); const totalWaitS = runningRemaining + queuedAhead * AVG_JOB_DURATION_S; const ownDuration = jobDuration || AVG_JOB_DURATION_S; const totalS = totalWaitS + ownDuration; const lowS = Math.floor(totalWaitS * 0.75); const highS = Math.floor(totalWaitS * 1.2); const fmt = (s) => { if (s < 60) return `${s}s`; const m = Math.floor(s / 60); const sec = s % 60; return sec ? `${m}m ${sec.toString().padStart(2, '0')}s` : `${m}m`; }; return { queue_position: position, jobs_ahead: position, wait_low_s: lowS, wait_high_s: highS, wait_low_human: fmt(lowS), wait_high_human: fmt(highS), total_with_own_s: Math.floor(totalS), message: `Position ${position} in queue — roughly ${fmt(lowS)}–${fmt(highS)} wait, likely less`, }; } function refreshQueuePositions() { JOB_QUEUE.forEach((jid, i) => { if (JOBS.has(jid)) { const pos = i + 1; updateJob(jid, { queue_position: pos, message: queueEta(pos).message, }); } }); } // ============================================================================= // FFMPEG PROCESS MANAGEMENT // ============================================================================= const FFMPEG_PROCS = new Map(); function killFfmpegForJob(jobId) { const proc = FFMPEG_PROCS.get(jobId); if (proc && !proc.killed) { try { proc.kill('SIGKILL'); console.log(`Killed FFmpeg for job ${jobId}`); } catch (e) { // ignore } } FFMPEG_PROCS.delete(jobId); } function parseFfmpegKv(line) { const parts = line.trim().split('='); if (parts.length !== 2) return {}; return { [parts[0].trim()]: parts[1].trim() }; } async function streamFfmpegProgress(proc, jobId, totalDuration, progressStart = 50, progressEnd = 95) { let frame = 0, fps = 0, speed = 0; let outTimeS = 0.0; let lastUpdateTime = Date.now(); return new Promise((resolve, reject) => { proc.stderr.on('data', (data) => { const lines = data.toString().split('\n'); for (const line of lines) { if (!line.trim()) continue; const kv = parseFfmpegKv(line); if (Object.keys(kv).length === 0) continue; const [key, val] = Object.entries(kv)[0]; if (key === 'frame') { frame = parseInt(val) || frame; } else if (key === 'fps') { fps = parseFloat(val) || fps; } else if (key === 'out_time_ms') { outTimeS = parseInt(val) / 1_000_000 || outTimeS; } else if (key === 'out_time') { const parts = val.split(':'); if (parts.length === 3) { const [h, m, s] = parts; outTimeS = parseInt(h) * 3600 + parseInt(m) * 60 + parseFloat(s); } } else if (key === 'speed') { speed = parseFloat(val.replace('x', '')) || speed; } else if (key === 'progress') { const now = Date.now(); if (val === 'end' || now - lastUpdateTime >= 500) { lastUpdateTime = now; const ratio = totalDuration > 0 ? Math.min(1.0, outTimeS / totalDuration) : 0; const mapped = Math.floor(progressStart + ratio * (progressEnd - progressStart)); updateJob(jobId, { progress: mapped, ffmpeg_frame: frame, ffmpeg_fps: fps, ffmpeg_out_time: Math.round(outTimeS * 100) / 100, ffmpeg_speed: speed, total_duration: totalDuration, message: totalDuration > 0 && speed > 0 ? `Encoding ${outTimeS.toFixed(1)}s / ${totalDuration.toFixed(1)}s (${speed.toFixed(1)}x speed)` : 'Encoding...', }); } if (val === 'end') { resolve(); return; } if (JOBS.get(jobId)?.status === 'failed') { proc.kill(); reject(new Error('Job marked as failed')); return; } } } }); proc.on('close', (code) => { if (code === 0) { resolve(); } else { reject(new Error(`FFmpeg exited with code ${code}`)); } }); proc.on('error', reject); }); } // ============================================================================= // CORE VIDEO PROCESSING // ============================================================================= async function processVideoTask(jobId, audioPath, subsPath, background, duration) { try { console.log(`Job ${jobId}: starting encode`); updateJob(jobId, { status: 'processing', progress: 10, message: 'Downloading background video...', queue_position: null, }); // Auto-detect category from video name // ss1, ss2, ss3, ss4, ss5 → subwaysurfers // mc1, mc2, etc. → minecraft let category = 'minecraft'; // default fallback if (background.startsWith('ss')) { category = 'subwaysurfers'; } else if (background.startsWith('mc')) { category = 'minecraft'; } let bgPath; try { bgPath = await downloadVideoFromDataset(background, category); } catch (e) { updateJob(jobId, { status: 'failed', error: e.message }); return; } updateJob(jobId, { progress: 20, message: 'Analysing media...' }); const audioDur = duration || await getMediaDuration(audioPath); const videoDur = await getMediaDuration(bgPath); if (audioDur < 1 || audioDur > 180) { updateJob(jobId, { status: 'failed', error: 'Audio duration out of range (1-180 s)' }); return; } console.log(`Job ${jobId}: audio=${audioDur.toFixed(2)}s bg=${videoDur.toFixed(2)}s`); let bgInputArgs; if (videoDur > audioDur) { const maxStart = videoDur - audioDur; const start = Math.random() * maxStart; bgInputArgs = [ '-ss', start.toFixed(3), '-t', audioDur.toFixed(3), '-i', bgPath, ]; console.log(`Job ${jobId}: trim start=${start.toFixed(2)}s`); } else { const loopN = Math.floor(audioDur / videoDur) + 2; bgInputArgs = [ '-stream_loop', loopN.toString(), '-i', bgPath, ]; console.log(`Job ${jobId}: loop x${loopN}`); } const subsStr = subsPath.replace(/\\/g, '/').replace(/:/g, '\\:'); const vf = `[0:v]ass='${subsStr}',scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1[v]`; const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`); const finalCmd = [ '-y', '-hide_banner', '-loglevel', 'error', ...bgInputArgs, '-i', audioPath, '-filter_complex', vf, '-map', '[v]', '-map', '1:a', '-c:v', 'libx264', '-preset', 'medium', '-crf', '16', '-minrate', '8M', '-maxrate', '16M', '-bufsize', '16M', '-profile:v', 'high', '-level:v', '4.2', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '192k', '-shortest', '-movflags', '+faststart', '-threads', '0', '-progress', 'pipe:2', '-t', audioDur.toFixed(3), outputPath, ]; updateJob(jobId, { progress: 40, message: 'Encoding... (single-pass)', total_duration: audioDur }); const timeout = Math.max(480, Math.floor(audioDur * 5) + 120) * 1000; const encodeProc = spawn('ffmpeg', finalCmd); FFMPEG_PROCS.set(jobId, encodeProc); const progressPromise = streamFfmpegProgress(encodeProc, jobId, audioDur, 40, 95); const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout) ); try { await Promise.race([progressPromise, timeoutPromise]); } catch (e) { killFfmpegForJob(jobId); if (e.message === 'timeout') { updateJob(jobId, { status: 'failed', error: 'Encoding timed out — try a shorter script' }); return; } if (JOBS.get(jobId)?.status === 'failed') { return; } updateJob(jobId, { status: 'failed', error: `Encoding failed: ${e.message.slice(0, 200)}` }); return; } FFMPEG_PROCS.delete(jobId); if (!fsSync.existsSync(outputPath) || fsSync.statSync(outputPath).size === 0) { updateJob(jobId, { status: 'failed', error: 'Output file missing after encode' }); return; } const sizeMb = fsSync.statSync(outputPath).size / 1024 / 1024; console.log(`Job ${jobId}: done ${sizeMb.toFixed(2)} MB`); // Cleanup input files for (const p of [audioPath, subsPath]) { try { await fs.unlink(p); } catch (e) { // ignore } } updateJob(jobId, { status: 'completed', progress: 100, message: `Done! ${sizeMb.toFixed(1)} MB`, output_path: outputPath, }); } catch (e) { console.error(`process_video_task unhandled for ${jobId}:`, e); updateJob(jobId, { status: 'failed', error: 'Unexpected server error' }); } } // ============================================================================= // VIDEO CLEANUP (1-hour TTL) // ============================================================================= async function cleanupOldVideos() { setInterval(async () => { try { const cutoffTime = Date.now() / 1000 - 3600; // 1 hour ago let cleanedCount = 0; let cleanedSizeMb = 0; const files = await fs.readdir(OUTPUT_DIR); for (const file of files) { if (!file.endsWith('.mp4')) continue; const filePath = path.join(OUTPUT_DIR, file); try { const stats = await fs.stat(filePath); if (stats.mtimeMs / 1000 < cutoffTime) { const sizeMb = stats.size / 1024 / 1024; await fs.unlink(filePath); cleanedCount++; cleanedSizeMb += sizeMb; console.log(`Cleaned up ${file} (${sizeMb.toFixed(1)}MB)`); } } catch (e) { console.warn(`Cleanup failed ${file}: ${e.message}`); } } if (cleanedCount > 0) { console.log(`Cleaned ${cleanedCount} videos, freed ${cleanedSizeMb.toFixed(1)}MB`); } } catch (e) { console.error(`Cleanup error: ${e.message}`); } }, 600_000); // 10 minutes } // ============================================================================= // QUEUE WORKER // ============================================================================= async function queueWorker() { setInterval(async () => { if (RUNNING_JOBS.size >= MAX_CONCURRENT) return; if (JOB_QUEUE.length === 0) return; const jobId = JOB_QUEUE[0]; const job = JOBS.get(jobId); if (!job || job.status === 'failed' || job.status === 'completed') { JOB_QUEUE.shift(); return; } JOB_QUEUE.shift(); RUNNING_JOBS.add(jobId); refreshQueuePositions(); const audioPath = job.audio_path; const subsPath = job.subs_path; const background = job.background || 'mc1'; const duration = job.requested_duration; processVideoTask(jobId, audioPath, subsPath, background, duration) .finally(() => { RUNNING_JOBS.delete(jobId); refreshQueuePositions(); }); }, 2000); } // ============================================================================= // FILE CLEANUP HELPER // ============================================================================= function deleteOutputFile(jobId, outputPath) { setTimeout(async () => { try { await fs.unlink(outputPath); if (JOBS.has(jobId)) { updateJob(jobId, { output_path: null, message: 'Downloaded and cleaned up', }); } console.log(`Cleaned up ${jobId} after download`); } catch (e) { console.warn(`Cleanup failed for ${jobId}: ${e.message}`); } }, 5000); // 5 second delay } // ============================================================================= // API ENDPOINTS // ============================================================================= app.get('/', (req, res) => { res.json({ name: 'ArchNemix Shorts Generator API', version: '5.1.0', queue: { max_concurrent: MAX_CONCURRENT, avg_job_duration_s: AVG_JOB_DURATION_S, }, endpoints: { register: 'GET /register', generate: 'POST /generate', cancel: 'DELETE /job/{id}', job_status: 'GET /job/{id}', queue: 'GET /queue', stream: 'GET /stream/{id} — inline video playback', download: 'GET /download/{id} — file download (deletes after)', delete: 'DELETE /video/{id}', videos: 'GET /videos/{category}', health: 'GET /health', }, }); }); app.get('/register', (req, res) => { const client = resolveClient(req); res.set('X-Client-ID', client.token); res.json({ client_token: client.token, is_new: client.job_count === 0, job_count: client.job_count, instructions: "Store client_token in localStorage as 'archx_client_id'. Send it as the X-Client-ID header on every request.", }); }); app.get('/health', async (req, res) => { try { const videos = await listVideosFromDataset('minecraft'); res.json({ status: 'healthy', timestamp: new Date().toISOString(), videos: videos.length, running: RUNNING_JOBS.size, queued: JOB_QUEUE.length, active_jobs: Array.from(JOBS.values()).filter(j => j.status === 'processing').length, }); } catch (e) { res.status(503).json({ status: 'degraded', error: e.message }); } }); app.get('/queue', (req, res) => { const running = RUNNING_JOBS.size; const waiting = JOB_QUEUE.length; res.json({ running, waiting, total_active: running + waiting, avg_job_s: AVG_JOB_DURATION_S, estimated_wait_s: running === 0 ? waiting * AVG_JOB_DURATION_S : (waiting + 1) * AVG_JOB_DURATION_S, message: (running + waiting) === 0 ? 'No jobs running — submit yours now!' : `${running} running, ${waiting} in queue`, }); }); app.get('/videos/:category', async (req, res) => { const category = req.params.category || 'minecraft'; try { const videos = await listVideosFromDataset(category) || Array.from({ length: 6 }, (_, i) => `mc${i + 1}`); res.json({ category, videos, count: videos.length }); } catch (e) { res.json({ category, videos: Array.from({ length: 6 }, (_, i) => `mc${i + 1}`), count: 6, error: e.message, }); } }); app.post('/generate', async (req, res) => { if (!validateAppKey(req)) { return res.status(403).json({ error: 'Invalid API key' }); } if (!validateOrigin(req)) { return res.status(403).json({ error: 'Invalid origin' }); } const client = resolveClient(req); const token = client.token; if (!rateLimit(`generate:${token}`, GENERATE_LIMIT)) { return res.status(429).json({ error: `Rate limit: max ${GENERATE_LIMIT} requests/hour` }); } cleanupOldJobs(); const activeForClient = Array.from(JOBS.values()).filter( j => j.client_token === token && (j.status === 'queued' || j.status === 'processing') ); if (activeForClient.length > 0) { const existingId = activeForClient[0].id; return res.status(409).json({ error: `You already have an active job (${existingId}). Wait for it to finish or cancel it first.`, }); } const { audio_base64, subtitles_ass, background, duration } = req.body; if (!audio_base64 || audio_base64.length < 10) { return res.status(400).json({ error: 'audio_base64 is required and must be at least 10 characters' }); } if (!subtitles_ass || subtitles_ass.length < 10) { return res.status(400).json({ error: 'subtitles_ass is required and must be at least 10 characters' }); } if (!background) { return res.status(400).json({ error: 'background is required' }); } const jobId = uuidv4(); const audioPath = path.join(AUDIO_DIR, `${jobId}.mp3`); const subsPath = path.join(AUDIO_DIR, `${jobId}.ass`); createJob(jobId, token); try { await saveBase64Audio(audio_base64, audioPath); await saveSubtitles(subtitles_ass, subsPath); } catch (e) { updateJob(jobId, { status: 'failed', error: e.message }); return res.status(400).json({ error: e.message }); } updateJob(jobId, { audio_path: audioPath, subs_path: subsPath, background, requested_duration: duration, }); client.job_count++; client.jobs.push(jobId); if (client.jobs.length > 50) { client.jobs = client.jobs.slice(-50); } saveClient(client); const position = RUNNING_JOBS.size === 0 ? 0 : JOB_QUEUE.length + 1; JOB_QUEUE.push(jobId); refreshQueuePositions(); const eta = position === 0 ? { message: 'Starting very soon...', wait_low_s: 0, wait_high_s: 30 } : queueEta(position, duration); res.set('X-Client-ID', token); res.json({ job_id: jobId, client_token: token, status: 'queued', queue_position: position > 0 ? position : 1, queue: eta, check_status: `/job/${jobId}`, }); }); app.get('/job/:job_id', (req, res) => { const jobId = req.params.job_id; if (!rateLimit(`status:${jobId}`, STATUS_LIMIT)) { return res.json({ job_id: jobId, status: 'rate_limited' }); } if (!JOBS.has(jobId)) { const jobFile = path.join(JOBS_DIR, `${jobId}.json`); if (fsSync.existsSync(jobFile)) { try { const data = JSON.parse(fsSync.readFileSync(jobFile, 'utf8')); return res.json(data); } catch (e) { // ignore } } return res.status(404).json({ error: 'Job not found' }); } const job = JOBS.get(jobId); const now = new Date(); if ((now - job.updated_at) / 1000 > JOB_TIMEOUT) { if (job.status !== 'completed' && job.status !== 'failed') { updateJob(jobId, { status: 'failed', error: 'Job timed out' }); } } const pos = queuePosition(jobId); const resp = { job_id: job.id, status: job.status, progress: job.progress, message: job.message, queue_position: pos, queue: pos ? queueEta(pos) : null, created_at: job.created_at.toISOString(), updated_at: job.updated_at.toISOString(), encode_stats: { frame: job.ffmpeg_frame || 0, fps: job.ffmpeg_fps || 0.0, out_time_s: job.ffmpeg_out_time || 0.0, total_s: job.total_duration || 0.0, speed: job.ffmpeg_speed || 0.0, }, }; // Return both URLs when completed — controller stores these directly if (job.status === 'completed' && job.output_path) { resp.download_url = `/download/${jobId}`; resp.stream_url = `/stream/${jobId}`; } if (job.error) { resp.error = job.error; } res.json(resp); }); app.get('/stream/:job_id', (req, res) => { const jobId = req.params.job_id; const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`); if (!fsSync.existsSync(outputPath)) { return res.status(404).json({ error: 'Video not found or not ready' }); } if (JOBS.has(jobId) && JOBS.get(jobId).status !== 'completed') { return res.status(400).json({ error: 'Video not ready yet' }); } res.set({ 'Cache-Control': 'no-cache', 'Accept-Ranges': 'bytes', }); res.sendFile(outputPath); }); app.get('/download/:job_id', (req, res) => { const jobId = req.params.job_id; const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`); if (!fsSync.existsSync(outputPath)) { return res.status(404).json({ error: 'Video not found or not ready' }); } if (JOBS.has(jobId) && JOBS.get(jobId).status !== 'completed') { return res.status(400).json({ error: 'Video not ready yet' }); } // Delete file from /tmp after response is sent res.on('finish', () => deleteOutputFile(jobId, outputPath)); res.set({ 'Content-Disposition': `attachment; filename="archnemix-short-${jobId.slice(0, 8)}.mp4"`, 'Cache-Control': 'no-cache', }); res.sendFile(outputPath); }); app.delete('/video/:job_id', async (req, res) => { if (!validateAppKey(req)) { return res.status(403).json({ error: 'Invalid API key' }); } const jobId = req.params.job_id; const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`); let removed = false; if (fsSync.existsSync(outputPath)) { try { await fs.unlink(outputPath); removed = true; console.log(`Deleted ${jobId}`); } catch (e) { return res.status(500).json({ error: `Delete failed: ${e.message}` }); } } if (JOBS.has(jobId)) { updateJob(jobId, { output_path: null, message: 'Video deleted by user', }); } res.json({ job_id: jobId, deleted: removed }); }); app.delete('/job/:job_id', (req, res) => { if (!validateAppKey(req)) { return res.status(403).json({ error: 'Invalid API key' }); } const jobId = req.params.job_id; if (!JOBS.has(jobId)) { return res.json({ job_id: jobId, cancelled: false, reason: 'not found' }); } const job = JOBS.get(jobId); if (job.status === 'completed' || job.status === 'failed') { return res.json({ job_id: jobId, cancelled: false, reason: job.status }); } killFfmpegForJob(jobId); RUNNING_JOBS.delete(jobId); const idx = JOB_QUEUE.indexOf(jobId); if (idx !== -1) { JOB_QUEUE.splice(idx, 1); } // Clean up output file if it exists const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`); try { fsSync.unlinkSync(outputPath); } catch (e) { // ignore } updateJob(jobId, { status: 'failed', error: 'Cancelled by controller — client disconnected', }); refreshQueuePositions(); console.log(`Job ${jobId} cancelled via controller request`); res.json({ job_id: jobId, cancelled: true }); }); app.get('/debug/dataset', async (req, res) => { try { const fetch = (await import('node-fetch')).default; const url = `https://huggingface.co/api/datasets/${HF_DATASET}/tree/main`; const headers = HF_TOKEN ? { 'Authorization': `Bearer ${HF_TOKEN}` } : {}; const response = await fetch(url, { headers }); const files = await response.json(); const mc = files.filter(f => f.path.toLowerCase().includes('minecraft') && f.path.endsWith('.mp4')); res.json({ dataset: HF_DATASET, total_files: files.length, minecraft: mc.map(f => f.path), }); } catch (e) { res.status(500).json({ status: 'error', error: e.message }); } }); // ============================================================================= // STARTUP // ============================================================================= app.listen(PORT, async () => { console.log('='.repeat(60)); console.log('ArchNemix Shorts Generator API v5.1.0 (Node.js)'); console.log(`Dataset : ${HF_DATASET}`); console.log(`Concurrent : ${MAX_CONCURRENT}`); console.log(`Avg job : ${AVG_JOB_DURATION_S}s (${Math.floor(AVG_JOB_DURATION_S / 60)}m)`); console.log('Quality : CRF 16 · medium · 8-16 Mbps · AAC 192k'); console.log('Video path : stream from /tmp, delete on download'); console.log('='.repeat(60)); queueWorker(); cleanupOldVideos(); try { const vids = await listVideosFromDataset('minecraft'); console.log(`${vids.length} videos cached`); } catch (e) { console.warn(`Video cache warm-up: ${e.message}`); } cleanupOldJobs(); console.log(`Ready on port ${PORT}`); }); // Graceful shutdown process.on('SIGTERM', () => { console.log('Shutdown — cleaning jobs'); cleanupOldJobs(); process.exit(0); });