-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
99 lines (83 loc) · 2.89 KB
/
Copy pathserver.ts
File metadata and controls
99 lines (83 loc) · 2.89 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
import Bao, { Context } from "baojs";
import { randomBytes } from "crypto";
import { DEFAULT_CONFIG, type Config } from "./types/config";
import { entities } from "./entities";
const app = new Bao();
app.get("/", (ctx) => {
return ctx.sendText("Am i alive?");
});
app.get("/image", async (ctx) => {
const url = new URL(ctx.req.url);
const config: Config = {
...DEFAULT_CONFIG,
photoOnly: true,
seed: url.searchParams.get("seed") || randomBytes(16).toString('hex'),
};
const generator = entities.get(url.searchParams.get("type") || "tree");
if (!generator) {
return ctx.sendText("Generator not found", {status: 404});
}
const result = await generator.generate(ctx,undefined, config);
if (!result.imageBuffer) {
return ctx.sendText("Image generation failed", {status: 500});
}
return ctx.sendRaw(new Response(result.imageBuffer, { headers: { 'Content-Type': 'image/png', } }));
});
app.get("/video", async (ctx) => {
const url = new URL(ctx.req.url);
const config: Config = {
...DEFAULT_CONFIG,
photoOnly: false,
seed: url.searchParams.get("seed") || randomBytes(16).toString('hex'),
};
const generator = entities.get(url.searchParams.get("type") || "tree");
if (!generator) {
return ctx.sendText("Generator not found", {status: 404});
}
const readableStream = new ReadableStream({
start(controller) {
generator.generate.generate(ctx,(process, videoStream) =>
{
videoStream.on('data', (chunk: Buffer) => {
controller.enqueue(chunk);
});
videoStream.on('end', () => {
controller.close();
});
videoStream.on('error', (err) => {
controller.error(err);
});
},
config).catch((err) => {
controller.error(err);
});
}
});
return ctx.sendRaw(new Response(readableStream, {
headers: {
"Content-Type": "video/webm",
"Transfer-Encoding": "chunked"
}
}));
});
app.get("/treeInfo", async (ctx) => {
const url = new URL(ctx.req.url);
const config: Config = {
...DEFAULT_CONFIG,
photoOnly: true,
seed: url.searchParams.get("seed") || randomBytes(16).toString('hex'),
};
const generator = entities.get("tree");
if (!generator) {
return ctx.sendText("Generator not found", {status: 404});
}
const result = await generator.generate.getInfo(config);
if (!result.trunkStartPosition) {
return ctx.sendText("Tree info generation failed", {status: 500});
}
return ctx.sendJson({
trunkStartPosition: result.trunkStartPosition
});
});
const server = app.listen({ port: 3000 });
console.log(`Server listening on http://localhost:${server.port}`);