MoooVeee
/**
 * ============================================================
 * BUS-W-VOICE2 WORKER — AI Voice video generation via OpenRouter
 * (Own Voice / lip-sync stays on the original bus-w-voice worker)
 * ============================================================
 *
 * SETUP:
 *   1. Create a Worker named bus-w-voice2, paste this file, deploy.
 *   2. Variables and Secrets → add OPENROUTER_API_KEY (encrypted).
 *   3. Optional: ALLOWED_ORIGIN (default *), OPENROUTER_BASE_URL (default
 *      https://openrouter.ai/api/v1), PUBLIC_BASE_URL if served from a
 *      custom domain instead of the workers.dev URL.
 *   No KV bindings needed — this worker holds no state; OpenRouter tracks
 *   job status by ID, and video bytes are proxied live on every request.
 *
 * ACTIONS
 *   create  { imageUrl, prompt, duration, resolution, aspectRatio, useBackup }
 *           → { data: { taskId, model } }
 *   check   { taskId }
 *           → { data: { state: 'processing' } }
 *           → { data: { state: 'completed', videoUrl } }
 *           → { data: { state: 'failed', failMsg } }
 *   GET /or-video/<taskId>  → proxies the finished MP4 (auth injected here)
 *
 * MODEL ROUTING
 *   720p : kwaivgi/kling-v3.0-std  (primary)  → alibaba/wan-3.0 (fallback)
 *   1080p: alibaba/wan-3.0 (only option on OpenRouter today; useBackup
 *          just retries the same model — no true 1080p fallback yet)
 * ============================================================
 */
const OPENROUTER_VIDEO_TIMEOUT_MS = 30000;
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (request.method === 'OPTIONS') {
      return new Response(null, { status: 204, headers: buildCorsHeaders(env, request) });
    }
    if (request.method === 'GET' && url.pathname.startsWith('/or-video/')) {
      return handleServeVideo(url, env, request);
    }
    if (request.method !== 'POST') {
      return textResponse('Not found.', 404, env, request);
    }
    let body;
    try {
      body = await request.json();
    } catch {
      return textResponse('Could not parse request body as JSON.', 400, env, request);
    }
    switch (body.action) {
      case 'create': return handleCreate(body, env, request);
      case 'check':  return handleCheck(body, env, request);
      default:       return textResponse(`Unknown action "${body.action}".`, 400, env, request);
    }
  },
};
// ============================================================
// CREATE
// ============================================================
async function handleCreate(body, env, request) {
  const {
    imageUrl,
    prompt,
    duration,
    resolution = '720p',
    aspectRatio = '16:9',
    useBackup = false,
  } = body;
  if (!imageUrl) return textResponse('Missing imageUrl.', 400, env, request);
  if (!prompt) return textResponse('Missing prompt.', 400, env, request);
  if (!duration) return textResponse('Missing duration.', 400, env, request);
  const primaryModel = resolution === '1080p'
    ? 'alibaba/wan-3.0'
    : (useBackup ? 'alibaba/wan-3.0' : 'kwaivgi/kling-v3.0-std');
  const params = { imageUrl, prompt, duration, resolution, aspectRatio, env };
  try {
    const job = await submitVideoJob(primaryModel, params);
    return jsonResponse({ data: { taskId: job.id, model: primaryModel } }, env, request);
  } catch (err) {
    // Automatic fallback: only meaningful for 720p, and only if we didn't
    // already land on Wan 3.0 as the primary.
    if (resolution !== '1080p' && primaryModel !== 'alibaba/wan-3.0') {
      try {
        const job2 = await submitVideoJob('alibaba/wan-3.0', params);
        return jsonResponse({ data: { taskId: job2.id, model: 'alibaba/wan-3.0' } }, env, request);
      } catch (err2) {
        return textResponse(
          `Video generation failed on both models. ${primaryModel}: ${err.message} | alibaba/wan-3.0: ${err2.message}`,
          502, env, request
        );
      }
    }
    return textResponse(`Video generation failed: ${err.message}`, 502, env, request);
  }
}
async function submitVideoJob(model, { imageUrl, prompt, duration, resolution, aspectRatio, env }) {
  const url = baseUrl(env.OPENROUTER_BASE_URL, 'https://openrouter.ai/api/v1') + '/videos';
  const payload = {
    model,
    prompt,
    duration: parseInt(duration, 10),
    resolution,
    aspect_ratio: aspectRatio,
    generate_audio: true, // the model speaks the script — this is the "AI Voice" behavior
    frame_images: [
      { type: 'image_url', image_url: { url: imageUrl }, frame_type: 'first_frame' },
    ],
  };
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), OPENROUTER_VIDEO_TIMEOUT_MS);
  let res;
  try {
    res = await fetch(url, {
      method: 'POST',
      signal: controller.signal,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${env.OPENROUTER_API_KEY}`,
      },
      body: JSON.stringify(payload),
    });
  } catch (err) {
    if (err.name === 'AbortError') throw new Error(`${model} timed out submitting job`);
    throw err;
  } finally {
    clearTimeout(timer);
  }
  if (!res.ok) {
    const txt = await res.text();
    throw new Error(`${model} HTTP ${res.status}: ${txt.slice(0, 250)}`);
  }
  const data = await res.json();
  if (!data?.id) throw new Error(`${model}: no job id in response. Raw: ` + JSON.stringify(data).slice(0, 200));
  return data;
}
// ============================================================
// CHECK
// ============================================================
async function handleCheck(body, env, request) {
  const { taskId } = body;
  if (!taskId) return textResponse('Missing taskId.', 400, env, request);
  const url = baseUrl(env.OPENROUTER_BASE_URL, 'https://openrouter.ai/api/v1') + '/videos/' + encodeURIComponent(taskId);
  let res;
  try {
    res = await fetch(url, { headers: { 'Authorization': `Bearer ${env.OPENROUTER_API_KEY}` } });
  } catch (err) {
    return textResponse('Status check failed: ' + err.message, 502, env, request);
  }
  if (!res.ok) {
    const txt = await res.text().catch(() => String(res.status));
    return textResponse(`Status check HTTP ${res.status}: ${txt.slice(0, 200)}`, 502, env, request);
  }
  const data = await res.json();
  const status = data.status;
  if (status === 'completed') {
    const origin = env.PUBLIC_BASE_URL ? baseUrl(env.PUBLIC_BASE_URL, '') : new URL(request.url).origin;
    return jsonResponse({ data: { state: 'completed', videoUrl: `${origin}/or-video/${encodeURIComponent(taskId)}` } }, env, request);
  }
  if (status === 'failed' || status === 'cancelled' || status === 'expired') {
    return jsonResponse({ data: { state: 'failed', failMsg: data.error || `Video ${status}` } }, env, request);
  }
  return jsonResponse({ data: { state: 'processing' } }, env, request);
}
// ============================================================
// GET /or-video/<taskId> — proxy the finished MP4, auth injected here
// ============================================================
async function handleServeVideo(url, env, request) {
  const m = url.pathname.match(/^\/or-video\/([A-Za-z0-9_-]+)$/);
  if (!m) return textResponse('Not found.', 404, env, request);
  const taskId = m[1];
  const contentUrl = baseUrl(env.OPENROUTER_BASE_URL, 'https://openrouter.ai/api/v1')
    + '/videos/' + encodeURIComponent(taskId) + '/content?index=0';
  let res;
  try {
    res = await fetch(contentUrl, { headers: { 'Authorization': `Bearer ${env.OPENROUTER_API_KEY}` } });
  } catch (err) {
    return textResponse('Video fetch failed: ' + err.message, 502, env, request);
  }
  if (!res.ok) {
    return new Response('Video not available yet or expired.', {
      status: 404,
      headers: { ...buildCorsHeaders(env, request), 'Cache-Control': 'no-store' },
    });
  }
  return new Response(res.body, {
    status: 200,
    headers: {
      ...buildCorsHeaders(env, request),
      'Content-Type': res.headers.get('Content-Type') || 'video/mp4',
      'Cache-Control': 'public, max-age=3600',
    },
  });
}
// ============================================================
// UTILITIES
// ============================================================
function baseUrl(envVal, fallback) {
  return (envVal || fallback).replace(/\/$/, '');
}
function buildCorsHeaders(env, request) {
  const origin = request.headers.get('Origin') || '';
  const allowed = env.ALLOWED_ORIGIN || '*';
  const isAllowed = allowed === '*' || origin === allowed || origin === '';
  return {
    'Access-Control-Allow-Origin': isAllowed ? (origin || '*') : allowed,
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    'Access-Control-Max-Age': '86400',
  };
}
function jsonResponse(data, env, request) {
  return new Response(JSON.stringify(data), {
    status: 200,
    headers: { 'Content-Type': 'application/json', ...buildCorsHeaders(env, request) },
  });
}
function textResponse(message, status, env, request) {
  return new Response(message, {
    status,
    headers: { 'Content-Type': 'text/plain', ...buildCorsHeaders(env, request) },
  });
}
Ready to launch? Start Machine — Keys Please?
Need support? Open support ticket
Have questions? 678.425.8298
Email

© PCS, LLC  ·  MoooVeee  ·  All rights reserved
Home About Privacy Policy Terms of Use