KKiosapi.id

← Tutorial

Bagian 8: Video: job asinkron

Buat klip video promo pendek: kirim job, periksa status, putar hasilnya.

Di halaman ini

Yang akan Anda bangun

Ingin melihat hasilnya dulu? Buka demo jadi (rekaman, tanpa API key) →

Langkah 1: Server: kirim job, periksa status, alirkan berkas

Video asinkron: POST /v1/videos/generations langsung membalas 202 + job_id; klien memeriksa GET /v1/jobs/:id sampai succeeded. Kiosapi hanya menagih jika berhasil. Berkas video butuh header Authorization, jadi Worker mengalirkannya ke browser.

Berkas: src/modul/video.ts

src/modul/video.ts
/**
 * Video bersifat ASINKRON: POST /v1/videos/generations langsung membalas 202 + `job_id`; klien
 * memeriksa GET /v1/jobs/:id sampai `succeeded`, lalu mengunduh videonya. Kiosapi hanya menagih jika
 * berhasil. Berkas video membutuhkan header Authorization, jadi Worker mengalirkannya ke browser.
 */
async function tangani({ request, kiosapi, sub }: Konteks): Promise<Response> {
  try {
    const [id, aksi] = sub;
    if (!id && request.method === 'POST') {
      const body = await bacaJson<{ prompt?: unknown }>(request);
      const prompt = typeof body?.prompt === 'string' ? body.prompt.trim().slice(0, 1000) : '';
      if (!prompt) return json({ error: 'Field "prompt" wajib diisi.' }, 400);
      const job = await kiosapi.post<JobBaru>('/videos/generations', {
        model: MODEL_VIDEO,
        prompt,
        option: OPSI_VIDEO,
      });
      return json({ jobId: job.job_id, estimasiRupiah: job.estimate_rupiah ?? null }, 202);
    }
    if (id && ID_JOB.test(id) && !aksi && request.method === 'GET') {
      const job = await kiosapi.get<Job>(`/jobs/${id}`);
      return json({
        status: job.status,
        biayaRupiah: job.cost_rupiah ?? null,
        error: job.error ?? null,
      });
    }
    if (id && ID_JOB.test(id) && aksi === 'berkas' && request.method === 'GET') {
      const res = await kiosapi.getMentah(`/jobs/${id}/video`);
      return new Response(res.body, {
        headers: {
          'content-type': res.headers.get('content-type') ?? 'video/mp4',
          'cache-control': 'no-store',
        },
      });
    }
    return json({ error: 'Tidak ditemukan.' }, 404);
  } catch (err) {
    return galat(err);
  }
}

Langkah 2: Browser: polling dengan progres

Halaman mengirim job lalu memeriksa status tiap beberapa detik. Saat succeeded, berkas diambil lewat fetch (dengan header kunci), dijadikan blob URL, dan diputar.

Berkas: public/app/modul/video.js

public/app/modul/video.js
/**
 * Video asinkron: kirim job → periksa status tiap beberapa detik → saat `succeeded`, ambil berkasnya.
 * Kiosapi hanya menagih jika berhasil; render biasanya 1–3 menit.
 */
async function buat(contohId) {
  tombol.disabled = true;
  dibatalkan = false;
  isi(hasil);
  bar.style.display = '';
  const progres = bar.firstChild;
  try {
    const job = await json('video', { method: 'POST', body: { prompt: prompt.value }, contohId });
    status.textContent = `Job ${job.jobId} dikirim${job.estimasiRupiah ? ` · perkiraan biaya ${uang(job.estimasiRupiah)}` : ''}…`;
    const mulai = Date.now();
    for (;;) {
      await tidur(adaKunci() ? 5000 : 1200); // mode rekaman memutar ulang lebih cepat
      if (dibatalkan) return;
      const detik = Math.round((Date.now() - mulai) / 1000);
      const j = await json(`video/${job.jobId}`, { contohId });
      progres.style.width = `${Math.min(95, 8 + detik / 1.5)}%`;
      status.textContent = `Status: ${j.status} · ${detik} detik`;
      if (j.status === 'succeeded') {
        progres.style.width = '100%';
        const src = await berkasVideo(job.jobId, contohId);
        isi(
          hasil,
          h('video', { controls: true, src, autoplay: true, loop: true }),
          h(
            'div',
            { class: 'baris' },
            h(
              'button',
              { class: 'kecil', onclick: () => unduh(src, 'video-promo.mp4') },
              'Unduh',
            ),
            h(
              'span',
              { class: 'kecil-muted' },
              `Biaya: ${j.biayaRupiah ? uang(j.biayaRupiah) : '—'}`,
            ),
          ),
        );
        status.textContent = 'Selesai.';
        return;
      }
      if (j.status === 'failed') throw new Error(`Video gagal: ${JSON.stringify(j.error)}`);
      if (Date.now() - mulai > MAKS_MENIT * 60_000)
        throw new Error('Waktu tunggu habis. Coba lagi nanti.');
    }
  } catch (err) {
    toast(pesanGalat(err), 'error');
    status.textContent = pesanGalat(err);
  } finally {
    tombol.disabled = false;
  }
}
Berkas lengkap: src/modul/video.ts · 66 baris
import { bacaJson, galat, json } from '../lib/http.js';
import type { Konteks, Modul } from './tipe.js';

const MODEL_VIDEO = 'minimax/hailuo-2.3'; // dihitung PER KLIP; opsi menentukan resolusi + durasi
const OPSI_VIDEO = '768p-6s';

type JobBaru = { job_id: string; status: string; estimate_rupiah?: number };
type Job = {
  status: 'running' | 'succeeded' | 'failed' | string;
  cost_rupiah?: number;
  error?: unknown;
};

const ID_JOB = /^[A-Za-z0-9_-]{6,100}$/;

/**
 * Video bersifat ASINKRON: POST /v1/videos/generations langsung membalas 202 + `job_id`; klien
 * memeriksa GET /v1/jobs/:id sampai `succeeded`, lalu mengunduh videonya. Kiosapi hanya menagih jika
 * berhasil. Berkas video membutuhkan header Authorization, jadi Worker mengalirkannya ke browser.
 */
async function tangani({ request, kiosapi, sub }: Konteks): Promise<Response> {
  try {
    const [id, aksi] = sub;
    if (!id && request.method === 'POST') {
      const body = await bacaJson<{ prompt?: unknown }>(request);
      const prompt = typeof body?.prompt === 'string' ? body.prompt.trim().slice(0, 1000) : '';
      if (!prompt) return json({ error: 'Field "prompt" wajib diisi.' }, 400);
      const job = await kiosapi.post<JobBaru>('/videos/generations', {
        model: MODEL_VIDEO,
        prompt,
        option: OPSI_VIDEO,
      });
      return json({ jobId: job.job_id, estimasiRupiah: job.estimate_rupiah ?? null }, 202);
    }
    if (id && ID_JOB.test(id) && !aksi && request.method === 'GET') {
      const job = await kiosapi.get<Job>(`/jobs/${id}`);
      return json({
        status: job.status,
        biayaRupiah: job.cost_rupiah ?? null,
        error: job.error ?? null,
      });
    }
    if (id && ID_JOB.test(id) && aksi === 'berkas' && request.method === 'GET') {
      const res = await kiosapi.getMentah(`/jobs/${id}/video`);
      return new Response(res.body, {
        headers: {
          'content-type': res.headers.get('content-type') ?? 'video/mp4',
          'cache-control': 'no-store',
        },
      });
    }
    return json({ error: 'Tidak ditemukan.' }, 404);
  } catch (err) {
    return galat(err);
  }
}

export const video: Modul = {
  id: 'video',
  judul: 'Video',
  ringkas: 'Buat klip video promo pendek (job asinkron: kirim → polling → putar).',
  berbayar: true,
  catatan: 'Berbayar per klip (± beberapa ribu Rupiah) dan hanya jika berhasil; render 1–3 menit.',
  tangani,
};
Berkas lengkap: public/app/modul/video.js · 103 baris
import { adaKunci, berkasVideo, json } from '../api.js';
import { barContoh, kepala, pesanGalat } from '../komponen.js';
import { h, isi, tidur, toast, uang, unduh } from '../ui.js';

const MAKS_MENIT = 8;

export async function render(root, app, modul) {
  const prompt = h('textarea', {
    value:
      'Close-up of fresh white rice grains pouring from a sack in a warm small Indonesian grocery store, cinematic, soft light',
  });
  const status = h('div', { class: 'kecil-muted' });
  const bar = h(
    'div',
    { class: 'progres', style: { display: 'none' } },
    h('div', { style: { width: '0%' } }),
  );
  const hasil = h('div', { class: 'medi' });
  const tombol = h('button', { class: 'utama' }, 'Buat video (6 detik)');
  let dibatalkan = false;

  /**
   * Video asinkron: kirim job → periksa status tiap beberapa detik → saat `succeeded`, ambil berkasnya.
   * Kiosapi hanya menagih jika berhasil; render biasanya 1–3 menit.
   */
  async function buat(contohId) {
    tombol.disabled = true;
    dibatalkan = false;
    isi(hasil);
    bar.style.display = '';
    const progres = bar.firstChild;
    try {
      const job = await json('video', { method: 'POST', body: { prompt: prompt.value }, contohId });
      status.textContent = `Job ${job.jobId} dikirim${job.estimasiRupiah ? ` · perkiraan biaya ${uang(job.estimasiRupiah)}` : ''}…`;
      const mulai = Date.now();
      for (;;) {
        await tidur(adaKunci() ? 5000 : 1200); // mode rekaman memutar ulang lebih cepat
        if (dibatalkan) return;
        const detik = Math.round((Date.now() - mulai) / 1000);
        const j = await json(`video/${job.jobId}`, { contohId });
        progres.style.width = `${Math.min(95, 8 + detik / 1.5)}%`;
        status.textContent = `Status: ${j.status} · ${detik} detik`;
        if (j.status === 'succeeded') {
          progres.style.width = '100%';
          const src = await berkasVideo(job.jobId, contohId);
          isi(
            hasil,
            h('video', { controls: true, src, autoplay: true, loop: true }),
            h(
              'div',
              { class: 'baris' },
              h(
                'button',
                { class: 'kecil', onclick: () => unduh(src, 'video-promo.mp4') },
                'Unduh',
              ),
              h(
                'span',
                { class: 'kecil-muted' },
                `Biaya: ${j.biayaRupiah ? uang(j.biayaRupiah) : '—'}`,
              ),
            ),
          );
          status.textContent = 'Selesai.';
          return;
        }
        if (j.status === 'failed') throw new Error(`Video gagal: ${JSON.stringify(j.error)}`);
        if (Date.now() - mulai > MAKS_MENIT * 60_000)
          throw new Error('Waktu tunggu habis. Coba lagi nanti.');
      }
    } catch (err) {
      toast(pesanGalat(err), 'error');
      status.textContent = pesanGalat(err);
    } finally {
      tombol.disabled = false;
    }
  }

  tombol.onclick = () => buat('video-beras');
  root.append(
    kepala(modul),
    h(
      'div',
      { class: 'kartu' },
      barContoh('video', (c) => buat(c.id)),
      h('h3', {}, '🎬 Klip video promo'),
      prompt,
      h('div', { class: 'baris' }, tombol),
      bar,
      status,
      hasil,
      h(
        'p',
        { class: 'kecil-muted' },
        'Tip: tulis prompt dalam bahasa Inggris untuk hasil terbaik. Halaman ini tetap bisa ditinggalkan; job berjalan di server Kiosapi.',
      ),
    ),
  );
  return () => {
    dibatalkan = true;
  };
}

Langkah 3: Daftarkan modul

Modul baru cukup didaftarkan di dua tempat (urutan baris = urutan menu): daftar server dan daftar halaman. Setelah itu menu Video muncul otomatis; tidak ada kode lain yang berubah.

src/modul/index.ts
import { akun } from './akun.js';
import { stokModul } from './stok.js';
import { beranda } from './beranda.js';
import { hargaPasar } from './harga-pasar.js';
import { sop } from './sop.js';
import { promo } from './promo.js';
import { musik } from './musik.js';
import { video } from './video.js';
import type { Modul } from './tipe.js';

export const MODUL: Modul[] = [akun, stokModul, beranda, hargaPasar, sop, promo, musik, video];
public/app/modul/index.js (id harus sama dengan id modul di server)
export const HALAMAN = {
  akun: () => import('./akun.js'),
  stok: () => import('./stok.js'),
  beranda: () => import('./beranda.js'),
  'harga-pasar': () => import('./harga-pasar.js'),
  sop: () => import('./sop.js'),
  promo: () => import('./promo.js'),
  musik: () => import('./musik.js'),
  video: () => import('./video.js'),
};

Hasilnya

Di bawah ini hasil nyata yang direkam dari Kiosapi ketika kode modul ini dijalankan (bukan ilustrasi). Putar ulang di demo →

Contoh: Klip beras dituang di warung (6 detik)

Status job: running → succeeded

Pada rekaman, render dipercepat; di mode langsung biasanya 1–3 menit dan halaman boleh ditinggalkan (job berjalan di server Kiosapi).

Biaya & endpoint

Biaya: Berbayar per klip (± Rp8.500) dan hanya jika berhasil; render 1–3 menit.

Endpoint yang dipakai: Studio API (video)