Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

8.2 KB
Raw Blame
// REST cho "Tạo mẫu từ video" (THIET-KE gói mẫu §5.1). server/server.mjs gọi handleDraftRoute trước các route khác.
//   POST   /api/drafts                 multipart: video=<file mp4/mov/webm ≤ 200 MB, 4 s – 3 phút>, kind=template, consent=1,
//                                      name?, from?, note?, category?, skipTest? → 202 + nháp (chạy nền)
//   GET    /api/drafts                 danh sách nháp (không gồm nháp đã bỏ) · GET /api/drafts/:id (kèm guidance + log)
//   PUT    /api/drafts/:id/text        {text} người dùng sửa tay guidance → kết quả kiểm
//   POST   /api/drafts/:id/retest      dựng thử lại guidance hiện tại
//   POST   /api/drafts/:id/save        {slug, name} → vào gói local.mine ("Của tôi")
//   DELETE /api/drafts/:id             bỏ nháp (xoá video tham khảo)
//   GET    /drafts/:id/(ref.<ext>|sheet.jpg|test-sheet.jpg|thumb.webp)    file xem nháp
//   GET    /pack-thumbs/<packId>/<kind>-<slug>.webp                        ảnh đại diện mẫu của gói đã cài
// Lệnh ghi chặn Origin lạ (như route Edit). Id nháp chỉ nhận dạng d<12 số>-<4 hex>.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { parseMultipart, originOk, sendAndClose } from '../edit/http.mjs';
import { draftsDir, DRAFT_ID_RE, validPackId, validSlug, thumbFile, KINDS } from './registry.mjs';
import * as D from './drafts.mjs';

const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
let uploading = false;

export function initDrafts() { D.markStaleDrafts(); }

/** Chạy nháp nền. runTest: hàm (jobId) → Promise<job> đưa job dựng thử qua hàng đợi chung của server. */
function startDraft(id, runTest, fn = D.runDraft) {
  fn(id, { runTest, log: (l) => console.log(`[draft ${id}] ${l}`) }).catch((e) => console.error('[draft]', id, e.message));
}

/** Trả true nếu đã xử lý route. ctx: {send, readBody, serveFile, allowedHosts, runTest} */
export async function handleDraftRoute(req, res, p, { send, readBody, serveFile, allowedHosts, runTest }) {
  // ảnh đại diện mẫu của gói (mẫu "Của tôi" lấy từ bản dựng thử)
  const pt = /^\/pack-thumbs\/([a-z0-9.-]{5,49})\/(template|edit-style)-([a-z0-9-]{2,32})\.webp$/.exec(p);
  if (pt && ['GET', 'HEAD'].includes(req.method)) {
    const f = validPackId(pt[1]) && validSlug(pt[3]) && KINDS[pt[2]] ? thumbFile(pt[1], pt[2], pt[3]) : null;
    if (!f) send(res, 404, { error: 'không thấy ảnh' }); else serveFile(req, res, path.dirname(f), path.basename(f));
    return true;
  }
  const pf = /^\/drafts\/([^/]+)\/([\w.-]{1,24})$/.exec(p);
  if (pf && ['GET', 'HEAD'].includes(req.method)) {
    const f = DRAFT_ID_RE.test(pf[1]) ? D.draftFilePath(pf[1], pf[2]) : null;
    if (!f) send(res, 404, { error: 'không thấy file' }); else serveFile(req, res, path.dirname(f), path.basename(f));
    return true;
  }
  if (p !== '/api/drafts' && !p.startsWith('/api/drafts/')) return false;
  if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method) && !originOk(req, allowedHosts)) { sendAndClose(res, req, send, 403, { error: 'origin không hợp lệ' }); return true; }
  try {
    if (p === '/api/drafts') {
      if (req.method === 'GET') {
        send(res, 200, { drafts: D.listDrafts().filter((d) => d.status !== 'discarded').map((d) => D.draftView(d)), active: D.activeDraft(), limits: { ...D.LIMITS, consent: D.CONSENT_TEXT }, engine: D.learnEngine() });
        return true;
      }
      if (req.method === 'POST') { await createFromUpload(req, res, send, runTest); return true; }
      send(res, 405, { error: 'method' });
      return true;
    }
    const m = /^\/api\/drafts\/([^/]+)(?:\/(text|retest|save))?$/.exec(p);
    if (!m || !DRAFT_ID_RE.test(m[1])) throw httpErr(400, 'id nháp không hợp lệ');
    const id = m[1];
    const d = D.readDraft(id);
    if (!d) throw httpErr(404, 'không thấy nháp');
    if (!m[2] && req.method === 'GET') { send(res, 200, D.draftView(d, { withText: true, withLog: true })); return true; }
    if (!m[2] && req.method === 'DELETE') { send(res, 200, D.discardDraft(id)); return true; }
    if (m[2] === 'text' && req.method === 'PUT') {
      const body = await readBody(req, 80 * 1024);
      const r = D.setDraftText(id, body.text);
      send(res, 200, { ...r, draft: D.draftView(D.readDraft(id), { withText: true }) });
      return true;
    }
    if (m[2] === 'retest' && req.method === 'POST') {
      if (D.activeDraft()) throw httpErr(429, 'Đang tạo 1 mẫu khác, chờ xong rồi thử tiếp');
      if (!['ready', 'error'].includes(d.status)) throw httpErr(409, 'nháp đang chạy hoặc đã lưu/bỏ');
      startDraft(id, runTest, D.retestDraft);
      send(res, 202, D.draftView(D.readDraft(id)));
      return true;
    }
    if (m[2] === 'save' && req.method === 'POST') {
      const body = await readBody(req, 8 * 1024);
      send(res, 200, { ...D.saveDraft(id, { slug: body.slug, name: body.name }), draft: D.draftView(D.readDraft(id)) });
      return true;
    }
    send(res, 405, { error: 'method' });
  } catch (e) {
    send(res, Number.isInteger(e.code) ? e.code : 400, { error: e.message });
  }
  return true;
}

async function createFromUpload(req, res, send, runTest) {
  const ct = String(req.headers['content-type'] || '');
  if (!/^multipart\/form-data/i.test(ct)) { sendAndClose(res, req, send, 415, { error: 'cần multipart/form-data (trường video + consent)' }); return; }
  const len = Number(req.headers['content-length']);
  const maxBody = D.LIMITS.maxBytes + 256 * 1024;
  if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length (trình duyệt tự gửi)' }); return; }
  if (len > maxBody) { sendAndClose(res, req, send, 413, { error: 'Video quá nặng (tối đa 200 MB)' }); return; }
  if (D.activeDraft()) { sendAndClose(res, req, send, 429, { error: 'Đang tạo 1 mẫu khác, chờ xong rồi thử tiếp' }); return; }
  if (!D.learnEngine()) { sendAndClose(res, req, send, 503, { error: 'Chưa có AI để viết guidance (cài Claude Code hoặc đặt ANTHROPIC_API_KEY)' }); return; }
  if (uploading) { sendAndClose(res, req, send, 429, { error: 'Đang nhận 1 video khác, chờ xong rồi gửi tiếp' }); return; }
  uploading = true;
  const tmp = path.join(draftsDir(), '_upload-' + crypto.randomBytes(4).toString('hex'));
  try {
    fs.mkdirSync(tmp, { recursive: true });
    const { fields, files } = await parseMultipart(req, {
      maxBytes: maxBody,
      tooBig: 'Video quá nặng (tối đa 200 MB)',
      fileTarget: (field, filename, early) => {
        if (field !== 'video') return null;
        // trường chữ gửi trước file → kiểm luôn, khỏi nhận cả file mới báo lỗi
        if (early.consent !== undefined && !['1', 'true', 'on'].includes(early.consent)) throw httpErr(400, 'Cần tick xác nhận: video này của bạn, hoặc bạn chỉ dùng để học phong cách dựng');
        if (early.kind !== undefined && early.kind !== 'template') throw httpErr(400, 'Bản này chỉ tạo được mẫu dựng');
        const ext = path.extname(filename).toLowerCase();
        if (!D.LIMITS.ext.includes(ext)) throw httpErr(415, `Định dạng ${ext || '?'} chưa hỗ trợ (mp4, mov, webm)`);
        return path.join(tmp, 'upload' + ext);
      },
    });
    if (!files.video?.size) throw httpErr(400, 'Thiếu file video');
    await files.video.done;
    const d = await D.prepareDraft({
      src: files.video.path, filename: files.video.filename, consent: fields.consent, kind: fields.kind || 'template',
      name: fields.name, from: fields.from, note: fields.note, category: fields.category, skipTest: ['1', 'true', 'on'].includes(fields.skipTest), move: true,
    });
    uploading = false;
    startDraft(d.id, runTest);
    send(res, 202, D.draftView(D.readDraft(d.id)));
  } catch (e) {
    uploading = false;
    const code = Number.isInteger(e.code) ? e.code : 422;
    if (!res.headersSent) { if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message }); }
  } finally {
    uploading = false;
    fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
  }
}