-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.ts
65 lines (56 loc) · 1.7 KB
/
server.ts
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
import { Hono, Context } from "hono";
import { cuid } from "cuid";
import config from "./utils/config.ts";
import { uploadToTelegram, fetchFromTelegram } from "./utils/telegram.ts";
import { errorResponse } from "./utils/messages.ts";
const app = new Hono();
app.post("/upload", async (c: Context) => {
const body = await c.req.parseBody();
const file = body["file"];
if (!(file instanceof File)) {
return errorResponse(c, "Missing or invalid file");
}
if (!(file.size && file.size <= 2000000000)) {
return errorResponse(c, "File size is too large or empty");
}
try {
const fileId = await uploadToTelegram(file);
return c.json(
{
message: "File uploaded successfully",
fileId,
file: {
size: file.size,
name: file.name,
},
},
200
);
} catch (error) {
console.error(error);
return errorResponse(c, "Failed to upload the file");
}
});
app.get("/fetch", async (c: Context) => {
const fileId = c.req.query("fileId");
const mainFileName = c.req.query("mainFileName");
const tempName = cuid();
if (!(fileId && typeof fileId == "string")) {
return errorResponse(c, "FileId is missing");
}
try {
const fileData = await fetchFromTelegram(fileId);
const contentLength = fileData.length;
return c.body(fileData, 200, {
"Content-Type": "application/octet-stream",
"Content-Length": contentLength.toString(),
"Content-Disposition": `attachment; filename="${
mainFileName || tempName
}"`,
});
} catch (error) {
console.error(error);
return errorResponse(c, "Failed to download the file");
}
});
Deno.serve({ port: config["serverPort"] }, app.fetch);