feat: add api files caching, update audioplayer ui

This commit is contained in:
2024-03-25 06:59:40 +07:00
parent 33c91ac0a7
commit 339969baa8
16 changed files with 320 additions and 140 deletions
+64
View File
@@ -0,0 +1,64 @@
import type { Context } from "hono";
import { getFilePath } from "./utils";
import { HTTPException } from "hono/http-exception";
import ID3 from "node-id3";
import cache from "../../middlewares/cache";
export const getId3Tags = async (c: Context) => {
const url = new URL(c.req.url);
const pathname = decodeURI(url.pathname).split("/");
const uri = pathname.slice(pathname.indexOf("id3-tags") + 1).join("/");
const { path } = getFilePath("/" + uri);
const cached = cache.key("id3-tags", path);
if (cached.data != null) {
return c.json(cached.data || {});
}
let tags: any = false;
try {
const id3Tags = await ID3.Promise.read(path, { noRaw: true });
const data: any = { ...id3Tags };
if (data.image) {
const imgUrl = new URL(url);
imgUrl.pathname = imgUrl.pathname.replace("/id3-tags", "/id3-img");
data.image = imgUrl.toString();
}
tags = id3Tags;
} catch (err) {}
cached.set(tags);
return c.json(tags || {});
};
export const getId3Image = async (c: Context) => {
const url = new URL(c.req.url);
const pathname = decodeURI(url.pathname).split("/");
const uri = pathname.slice(pathname.indexOf("id3-img") + 1).join("/");
const { path } = getFilePath("/" + uri);
const cached = cache.key("id3-img", path);
if (cached.data) {
c.header("Content-Type", cached.data.mime);
const buffer = Buffer.from(cached.data.imageBuffer);
return c.body(buffer);
}
try {
const tags = await ID3.Promise.read(path, { noRaw: true });
const image = tags.image;
if (!image || typeof image === "string") {
throw new Error("No image found!");
}
cached.set(image);
c.header("Content-Type", image.mime);
return c.body(image.imageBuffer);
} catch (err) {
throw new HTTPException(400, { message: "cannot get tags!" });
}
};
+7 -1
View File
@@ -4,12 +4,18 @@ import { getFilesSchema, ytdlSchema } from "./schema";
import { getFiles } from "./get";
import { download } from "./download";
import { getYtdl, ytdl } from "./ytdl";
import cache from "../../middlewares/cache";
import { getId3Tags, getId3Image } from "./id3Tags";
const cacheFile = cache({ ttl: 86400 });
const route = new Hono()
.get("/", zValidator("query", getFilesSchema), getFiles)
.post("/upload")
.post("/ytdl", zValidator("json", ytdlSchema), ytdl)
.get("/ytdl/:id", getYtdl)
.get("/download/*", download);
.get("/download/*", cacheFile, download)
.get("/id3-tags/*", cacheFile, getId3Tags)
.get("/id3-img/*", cacheFile, getId3Image);
export default route;