-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-server.ts
More file actions
393 lines (335 loc) · 10.5 KB
/
api-server.ts
File metadata and controls
393 lines (335 loc) · 10.5 KB
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
#!/usr/bin/env bun
/**
* api-server.ts
* HTTP API server for Sora 2 video generation with authentication
*
* Usage:
* AUTH_TOKEN=your-secret-token bun run api-server.ts
*
* Environment variables:
* OPENAI_API_KEY=sk-...
* AUTH_TOKEN=your-auth-token
* PORT=3000 (optional, defaults to 3000)
*/
import path from "node:path";
import fs from "node:fs/promises";
interface VideoRequest {
prompt: string;
duration?: number;
orientation?: "portrait" | "landscape";
image?: string; // base64 encoded image
seed?: number;
model?: string;
}
interface VideoJob {
id: string;
status: "queued" | "processing" | "completed" | "failed";
progress?: number;
videoUrl?: string;
error?: string;
createdAt: Date;
completedAt?: Date;
request: VideoRequest;
}
// In-memory job storage (in production, use a database)
const jobs = new Map<string, VideoJob>();
// Configuration
const API_KEY = process.env.OPENAI_API_KEY;
const AUTH_TOKEN = process.env.AUTH_TOKEN || "default-token-change-me";
const PORT = process.env.PORT || 3000;
if (!API_KEY) {
console.error("❌ Missing OPENAI_API_KEY in environment.");
process.exit(1);
}
if (AUTH_TOKEN === "default-token-change-me") {
console.warn("⚠️ Using default AUTH_TOKEN. Set a secure token in production!");
}
// Helper functions
function validateAuthToken(req: Request): boolean {
const authHeader = req.headers.get("Authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return false;
}
const token = authHeader.slice(7);
return token === AUTH_TOKEN;
}
function generateJobId(): string {
return `job_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
}
async function createSoraVideo(jobId: string, request: VideoRequest) {
const job = jobs.get(jobId)!;
try {
// Update job status
job.status = "processing";
job.progress = 0;
// Map parameters
const orientation = (request.orientation || "landscape").toLowerCase();
const size = orientation === "portrait" ? "720x1280" : "1280x720";
const duration = request.duration || 8;
const seconds = duration.toString();
const model = request.model || "sora-2";
// Build payload
const payload: Record<string, unknown> = {
model,
prompt: request.prompt,
size,
seconds,
};
if (request.seed !== undefined) {
payload.seed = request.seed;
}
if (request.image) {
payload.input_reference = request.image;
}
// Create video job with OpenAI
const createRes = await fetch("https://api.openai.com/v1/videos", {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!createRes.ok) {
throw new Error(`OpenAI API error: ${await createRes.text()}`);
}
const created = await createRes.json() as any;
const openaiJobId = created.id || created.video_id;
if (!openaiJobId) {
throw new Error("No job ID returned from OpenAI");
}
// Poll for completion
while (true) {
const statusRes = await fetch(`https://api.openai.com/v1/videos/${openaiJobId}`, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (!statusRes.ok) {
throw new Error(`Failed to check status: ${await statusRes.text()}`);
}
const state = await statusRes.json() as any;
const status = state.status;
// Update progress
if (typeof state.progress === "number") {
job.progress = state.progress;
}
// Check for completion
if (["completed", "succeeded", "complete"].includes(status)) {
// Get video content
const contentRes = await fetch(`https://api.openai.com/v1/videos/${openaiJobId}/content`, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (contentRes.ok) {
// Save video to output directory
const outdir = path.resolve(process.cwd(), "out");
await fs.mkdir(outdir, { recursive: true });
const videoPath = path.join(outdir, `${jobId}.mp4`);
await Bun.write(videoPath, contentRes);
job.videoUrl = `/videos/${jobId}.mp4`;
job.status = "completed";
job.completedAt = new Date();
job.progress = 100;
} else {
throw new Error("Failed to download video content");
}
break;
}
// Check for failure
if (["failed", "error", "cancelled", "canceled"].includes(status)) {
throw new Error(state.error?.message || "Video generation failed");
}
// Wait before next poll
await Bun.sleep(5000);
}
} catch (error: any) {
job.status = "failed";
job.error = error.message;
job.completedAt = new Date();
}
}
// API Routes
Bun.serve({
port: PORT,
async fetch(req: Request) {
const url = new URL(req.url);
const method = req.method;
const path = url.pathname;
// CORS headers
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
// Handle preflight
if (method === "OPTIONS") {
return new Response(null, { status: 204, headers: corsHeaders });
}
// Health check (no auth required)
if (path === "/health" && method === "GET") {
return Response.json({ status: "ok", timestamp: new Date() }, {
headers: corsHeaders,
});
}
// All other endpoints require authentication
if (!validateAuthToken(req)) {
return Response.json(
{ error: "Unauthorized. Include 'Authorization: Bearer <token>' header" },
{ status: 401, headers: corsHeaders }
);
}
// POST /api/videos - Create a new video generation job
if (path === "/api/videos" && method === "POST") {
try {
const body = await req.json() as VideoRequest;
// Validate required fields
if (!body.prompt) {
return Response.json(
{ error: "Missing required field: prompt" },
{ status: 400, headers: corsHeaders }
);
}
// Validate duration
if (body.duration && ![4, 8, 12].includes(body.duration)) {
return Response.json(
{ error: "Duration must be 4, 8, or 12 seconds" },
{ status: 400, headers: corsHeaders }
);
}
// Create job
const jobId = generateJobId();
const job: VideoJob = {
id: jobId,
status: "queued",
createdAt: new Date(),
request: body,
};
jobs.set(jobId, job);
// Start async video generation
createSoraVideo(jobId, body);
return Response.json(
{
jobId,
status: "queued",
message: "Video generation started",
},
{ status: 202, headers: corsHeaders }
);
} catch (error: any) {
return Response.json(
{ error: error.message || "Invalid request" },
{ status: 400, headers: corsHeaders }
);
}
}
// GET /api/videos/:id - Get job status
if (path.startsWith("/api/videos/") && method === "GET") {
const jobId = path.slice(12);
const job = jobs.get(jobId);
if (!job) {
return Response.json(
{ error: "Job not found" },
{ status: 404, headers: corsHeaders }
);
}
return Response.json(
{
id: job.id,
status: job.status,
progress: job.progress,
videoUrl: job.videoUrl,
error: job.error,
createdAt: job.createdAt,
completedAt: job.completedAt,
request: job.request,
},
{ headers: corsHeaders }
);
}
// GET /api/videos - List all jobs
if (path === "/api/videos" && method === "GET") {
const jobList = Array.from(jobs.values()).map(job => ({
id: job.id,
status: job.status,
progress: job.progress,
createdAt: job.createdAt,
completedAt: job.completedAt,
prompt: job.request.prompt,
}));
return Response.json(
{
jobs: jobList,
total: jobList.length,
},
{ headers: corsHeaders }
);
}
// GET /videos/:filename - Serve video files
if (path.startsWith("/videos/") && method === "GET") {
const filename = path.slice(8);
const videoPath = path.join(process.cwd(), "out", filename);
try {
const file = Bun.file(videoPath);
if (await file.exists()) {
return new Response(file, {
headers: {
...corsHeaders,
"Content-Type": "video/mp4",
"Content-Disposition": `inline; filename="${filename}"`,
},
});
}
} catch (error) {
// File not found
}
return Response.json(
{ error: "Video not found" },
{ status: 404, headers: corsHeaders }
);
}
// DELETE /api/videos/:id - Cancel/delete a job
if (path.startsWith("/api/videos/") && method === "DELETE") {
const jobId = path.slice(12);
const job = jobs.get(jobId);
if (!job) {
return Response.json(
{ error: "Job not found" },
{ status: 404, headers: corsHeaders }
);
}
// Delete video file if it exists
if (job.videoUrl) {
const videoPath = path.join(process.cwd(), "out", `${jobId}.mp4`);
try {
await fs.unlink(videoPath);
} catch (error) {
// File might not exist
}
}
jobs.delete(jobId);
return Response.json(
{ message: "Job deleted successfully" },
{ headers: corsHeaders }
);
}
// 404 for unknown routes
return Response.json(
{ error: "Not found" },
{ status: 404, headers: corsHeaders }
);
},
});
console.log(`
🚀 Sora 2 API Server running on http://localhost:${PORT}
Authentication: Bearer ${AUTH_TOKEN.slice(0, 8)}...
Endpoints:
GET /health - Health check (no auth)
POST /api/videos - Create video generation job
GET /api/videos/:id - Get job status
GET /api/videos - List all jobs
DELETE /api/videos/:id - Delete job
GET /videos/:filename.mp4 - Download video
Example:
curl -X POST http://localhost:${PORT}/api/videos \\
-H "Authorization: Bearer ${AUTH_TOKEN}" \\
-H "Content-Type: application/json" \\
-d '{"prompt": "A beautiful sunset over the ocean"}'
`);