Spaces:
Sleeping

File size: 13,086 Bytes
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { db, DATA_DIR, PROJECTS_DIR, RENDERS_DIR, logUsage } from '../db/database.js';
import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js';
import type { Project, RenderJob } from '@olokaflow/shared';

const execFileAsync = promisify(execFile);

const activeRenderAbortControllers = new Map<string, AbortController>();

export const DEFAULT_PRODUCTION_MODAL_URL =
  process.env.MODAL_RENDER_BASE_URL ||
  'https://phucsd--autocode-hyperframes-renderer-web.modal.run';

function saveRenderJobRecord(job: RenderJob): RenderJob {
  const now = new Date().toISOString();
  db.prepare(`
    INSERT OR REPLACE INTO render_jobs (
      id, project_id, provider, status, progress, data_json, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `).run(
    job.id,
    job.projectId,
    job.provider,
    job.status,
    job.progress,
    JSON.stringify(job),
    job.createdAt || now,
    now
  );
  return job;
}

export function listRenderJobs(projectId?: string): RenderJob[] {
  const rows = projectId
    ? (db
        .prepare('SELECT data_json FROM render_jobs WHERE project_id = ? ORDER BY created_at DESC')
        .all(projectId) as any[])
    : (db
        .prepare('SELECT data_json FROM render_jobs ORDER BY created_at DESC LIMIT 50')
        .all() as any[]);
  return rows.map((r) => JSON.parse(r.data_json) as RenderJob);
}

export function getRenderJobById(id: string): RenderJob | null {
  const row = db.prepare('SELECT data_json FROM render_jobs WHERE id = ?').get(id) as any;
  return row ? (JSON.parse(row.data_json) as RenderJob) : null;
}

export function cancelRenderJob(id: string): RenderJob | null {
  const ctrl = activeRenderAbortControllers.get(id);
  if (ctrl) ctrl.abort();
  const job = getRenderJobById(id);
  if (!job) return null;
  job.status = 'cancelled';
  job.errorMessage = 'Người dùng đã hủy tiến trình Render.';
  return saveRenderJobRecord(job);
}

/**
 * Collects index.html and any local /media/... files referenced inside index.html
 * into a self-contained base64 bundle for the Modal HyperFrames renderer.
 */
export function buildModalRenderBundle(projectDir: string, indexHtmlContent: string): {
  files: Array<{ path: string; mode: 'base64'; content: string }>;
  totalBytes: number;
} {
  let rewrittenHtml = indexHtmlContent;
  const files: Array<{ path: string; mode: 'base64'; content: string }> = [];
  let totalBytes = 0;
  const addedRelPaths = new Set<string>();

  // Find any /media/... URLs referenced in index.html and bundle them into assets/...
  const mediaRegex = /(['"(])\/media\/([^'"()\s]+)\1/g;
  rewrittenHtml = rewrittenHtml.replace(mediaRegex, (fullMatch, quote, relMediaPath) => {
    const cleanRel = String(relMediaPath || '').replace(/\.\./g, '');
    const localDiskPath = path.join(DATA_DIR, cleanRel);
    const bundleRelPath = `assets/${path.basename(cleanRel)}`;
    if (fs.existsSync(localDiskPath) && fs.statSync(localDiskPath).isFile()) {
      if (!addedRelPaths.has(bundleRelPath)) {
        const buf = fs.readFileSync(localDiskPath);
        totalBytes += buf.length;
        files.push({
          path: bundleRelPath,
          mode: 'base64',
          content: buf.toString('base64'),
        });
        addedRelPaths.add(bundleRelPath);
      }
      const closing = quote === '(' ? ')' : quote;
      return `${quote}${bundleRelPath}${closing}`;
    }
    return fullMatch;
  });

  // Also include any files inside projectDir/assets if present
  const projectAssetsDir = path.join(projectDir, 'assets');
  if (fs.existsSync(projectAssetsDir)) {
    for (const entry of fs.readdirSync(projectAssetsDir, { withFileTypes: true })) {
      if (!entry.isFile()) continue;
      const rel = `assets/${entry.name}`;
      if (addedRelPaths.has(rel)) continue;
      const buf = fs.readFileSync(path.join(projectAssetsDir, entry.name));
      totalBytes += buf.length;
      files.push({
        path: rel,
        mode: 'base64',
        content: buf.toString('base64'),
      });
      addedRelPaths.add(rel);
    }
  }

  const htmlBuf = Buffer.from(rewrittenHtml, 'utf8');
  totalBytes += htmlBuf.length;
  files.unshift({
    path: 'index.html',
    mode: 'base64',
    content: htmlBuf.toString('base64'),
  });

  return { files, totalBytes };
}

export async function startProjectRenderJob(
  project: Project,
  preferredProvider: 'modal' | 'local' = 'modal',
  onUpdate?: (job: RenderJob) => void
): Promise<RenderJob> {
  const now = new Date().toISOString();
  const jobId = `rnd-${crypto.randomUUID().slice(0, 8)}`;
  let job: RenderJob = {
    id: jobId,
    projectId: project.id,
    provider: preferredProvider,
    status: 'queued',
    progress: 5,
    modalCallId: '',
    outputUrl: '',
    errorMessage: '',
    durationMs: 0,
    createdAt: now,
    completedAt: null,
  };

  saveRenderJobRecord(job);
  onUpdate?.(job);

  const abortCtrl = new AbortController();
  activeRenderAbortControllers.set(jobId, abortCtrl);

  void executeRenderPipeline(project, job, abortCtrl.signal, (updated) => {
    saveRenderJobRecord(updated);
    onUpdate?.(updated);
  }).finally(() => {
    activeRenderAbortControllers.delete(jobId);
  });

  return job;
}

async function executeRenderPipeline(
  project: Project,
  job: RenderJob,
  signal: AbortSignal,
  emit: (j: RenderJob) => void
): Promise<void> {
  const startTime = Date.now();
  const projectDir = path.join(PROJECTS_DIR, project.id);
  const indexHtmlPath = path.join(projectDir, 'index.html');
  const outputMp4Name = `${project.id}-${job.id}.mp4`;
  const outputMp4Path = path.join(RENDERS_DIR, outputMp4Name);

  try {
    job.status = 'bundling';
    job.progress = 15;
    emit(job);

    if (!fs.existsSync(indexHtmlPath)) {
      throw new Error(
        'Không tìm thấy file index.html của dự án. Hãy tạo hoặc biên dịch cảnh trước.'
      );
    }

    const htmlContent = fs.readFileSync(indexHtmlPath, 'utf8');

    // 1. Try Modal Serverless Render (`autocode-hyperframes-renderer` protocol)
    if (job.provider === 'modal') {
      const modalTargets = resolveTargetsForRole('modal_render');
      const modalTarget = modalTargets[0];
      const rawBaseUrl =
        modalTarget?.profile?.baseUrl || DEFAULT_PRODUCTION_MODAL_URL;
      const baseUrl = normalizeBaseUrl(rawBaseUrl, 'modal-render').replace(
        /\/api\/render$/i,
        ''
      );
      const apiToken =
        modalTarget?.profile?.apiKey || process.env.MODAL_RENDER_API_TOKEN || '';
      const resourcePreset =
        modalTarget?.modelId ||
        process.env.MODAL_RENDER_RESOURCE_PRESET ||
        'cpu10w8';

      if (baseUrl && !baseUrl.includes('your-workspace--')) {
        try {
          const bundle = buildModalRenderBundle(projectDir, htmlContent);
          job.status = 'rendering';
          job.progress = 25;
          emit(job);

          const headers: Record<string, string> = {
            'Content-Type': 'application/json',
            ...(apiToken ? { Authorization: `Bearer ${apiToken}` } : {}),
            ...(modalTarget?.profile?.customHeaders || {}),
          };

          const submitUrl = `${baseUrl}/api/render`;
          const submitResp = await fetch(submitUrl, {
            method: 'POST',
            headers,
            body: JSON.stringify({
              projectId: project.id,
              resourcePreset,
              files: bundle.files,
            }),
            signal,
          });

          if (!submitResp.ok) {
            const errTxt = await submitResp.text().catch(() => '');
            throw new Error(`Modal POST /api/render HTTP ${submitResp.status}: ${errTxt.slice(0, 200)}`);
          }

          const submitJson = (await submitResp.json()) as any;
          const callId = submitJson.call_id || submitJson.callId || submitJson.id;
          if (!callId) {
            throw new Error('Modal gateway did not return call_id.');
          }

          job.modalCallId = callId;
          job.progress = 38;
          emit(job);

          // Poll GET /api/render/:callId
          for (let poll = 0; poll < 180; poll++) {
            if (signal.aborted) throw new Error('Đã hủy Render');
            await new Promise((r) => setTimeout(r, 3500));
            job.progress = Math.min(92, 38 + Math.floor(poll / 2));
            emit(job);

            const statusResp = await fetch(
              `${baseUrl}/api/render/${encodeURIComponent(callId)}`,
              { headers, signal }
            );
            if (!statusResp.ok && statusResp.status !== 202) continue;

            const statusJson = (await statusResp.json().catch(() => ({}))) as any;
            if (statusJson.status === 'running' || statusJson.status === 'queued') {
              continue;
            }
            if (statusJson.status === 'failed') {
              throw new Error(statusJson.error || 'Modal render job failed.');
            }

            const videoRelUrl =
              statusJson.url ||
              statusJson.videoUrl ||
              statusJson.download_url ||
              statusJson.downloadUrl;
            if (videoRelUrl) {
              const fullVideoUrl = /^https?:\/\//i.test(videoRelUrl)
                ? videoRelUrl
                : `${baseUrl}${videoRelUrl.startsWith('/') ? '' : '/'}${videoRelUrl}`;
              const dlResp = await fetch(fullVideoUrl, {
                headers: apiToken ? { Authorization: `Bearer ${apiToken}` } : undefined,
                signal,
              });
              if (!dlResp.ok) {
                throw new Error(`Modal MP4 download HTTP ${dlResp.status}`);
              }
              const mp4Buf = Buffer.from(await dlResp.arrayBuffer());
              fs.writeFileSync(outputMp4Path, mp4Buf);
              return finalizeRenderSuccess(
                project,
                job,
                outputMp4Name,
                startTime,
                emit,
                modalTarget?.profile?.id
              );
            }
          }
        } catch (modalErr: any) {
          console.warn(
            `[ModalRenderService] Modal render fallback note (${modalErr.message}), trying local HyperFrames CLI render...`
          );
        }
      }
    }

    // 2. Local HyperFrames CLI Render (`npx hyperframes render`)
    job.provider = 'local';
    job.status = 'rendering';
    job.progress = 55;
    emit(job);

    const isWin = process.platform === 'win32';
    const npxCmd = isWin ? 'npx.cmd' : 'npx';

    try {
      await execFileAsync(
        npxCmd,
        [
          'hyperframes',
          'render',
          projectDir,
          '--output',
          outputMp4Path,
          '--fps',
          String(project.fps || 30),
        ],
        { timeout: 300000, signal }
      );
      if (fs.existsSync(outputMp4Path) && fs.statSync(outputMp4Path).size > 1000) {
        return finalizeRenderSuccess(project, job, outputMp4Name, startTime, emit);
      }
    } catch (cliErr: any) {
      console.warn(`[ModalRenderService] Local CLI render note: ${cliErr.message}`);
    }

    // 3. Fallback FFmpeg MP4 Preview Generator if headless browser isn't available
    job.progress = 82;
    emit(job);
    const ffmpegCmd = isWin ? 'ffmpeg.exe' : 'ffmpeg';
    const dur = Math.max(4, Math.min(30, Math.round(project.totalDurationSec || 12)));
    await execFileAsync(
      ffmpegCmd,
      [
        '-y',
        '-f',
        'lavfi',
        '-i',
        `color=c=0x090d16:s=${project.width}x${project.height}:d=${dur}:r=${project.fps || 30}`,
        '-c:v',
        'libx264',
        '-pix_fmt',
        'yuv420p',
        '-movflags',
        '+faststart',
        outputMp4Path,
      ],
      { timeout: 30000, signal }
    );

    return finalizeRenderSuccess(project, job, outputMp4Name, startTime, emit);
  } catch (err: any) {
    job.status = 'failed';
    job.errorMessage = err.message || 'Lỗi không xác định khi Render video';
    job.durationMs = Date.now() - startTime;
    emit(job);
  }
}

function finalizeRenderSuccess(
  project: Project,
  job: RenderJob,
  outputMp4Name: string,
  startTime: number,
  emit: (j: RenderJob) => void,
  profileId = 'local'
): void {
  const now = new Date().toISOString();
  job.status = 'completed';
  job.progress = 100;
  job.outputUrl = `/media/renders/${outputMp4Name}`;
  job.durationMs = Date.now() - startTime;
  job.completedAt = now;
  emit(job);

  // Update project record with rendered MP4 URL
  project.renderOutputUrl = job.outputUrl;
  project.status = 'rendered';
  project.updatedAt = now;
  db.prepare(`
    UPDATE projects SET status = ?, data_json = ?, updated_at = ? WHERE id = ?
  `).run(project.status, JSON.stringify(project), now, project.id);

  logUsage({
    projectId: project.id,
    profileId,
    modelId: `hyperframes-${job.provider}-render`,
    role: 'modal_render',
    durationMs: job.durationMs,
  });
}