mirror of
https://github.com/khairul169/home-lab.git
synced 2026-10-02 17:13:57 +07:00
feat: add file manager app
This commit is contained in:
@@ -7,3 +7,4 @@ AUTH_PASSWORD=
|
||||
# Apps
|
||||
PC_MAC_ADDR=
|
||||
TERMINAL_SHELL=
|
||||
FILE_DIRS="/some/path;/another/path"
|
||||
|
||||
+36
-1
@@ -1,3 +1,5 @@
|
||||
import type { Context, Next } from "hono";
|
||||
import { HTTPException } from "hono/http-exception";
|
||||
import * as jwt from "hono/jwt";
|
||||
|
||||
const JWT_SECRET =
|
||||
@@ -11,4 +13,37 @@ export const verifyToken = async (token: string) => {
|
||||
return jwt.verify(token, JWT_SECRET);
|
||||
};
|
||||
|
||||
export const authMiddleware = jwt.jwt({ secret: JWT_SECRET });
|
||||
export const authMiddleware = async (ctx: Context, next: Next) => {
|
||||
const authHeader = ctx.req.raw.headers.get("Authorization");
|
||||
const queryToken = ctx.req.query("token");
|
||||
let token;
|
||||
|
||||
if (authHeader) {
|
||||
const parts = authHeader.split(/\s+/);
|
||||
if (parts.length !== 2) {
|
||||
throw new HTTPException(401, { message: "Unauthorized!" });
|
||||
} else {
|
||||
token = parts[1];
|
||||
}
|
||||
}
|
||||
|
||||
if (queryToken) {
|
||||
token = queryToken;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new HTTPException(401, { message: "Unauthorized!" });
|
||||
}
|
||||
|
||||
let payload;
|
||||
try {
|
||||
payload = await jwt.verify(token, JWT_SECRET);
|
||||
} catch (e) {}
|
||||
|
||||
if (!payload) {
|
||||
throw new HTTPException(401, { message: "Unauthorized!" });
|
||||
}
|
||||
|
||||
ctx.set("jwtPayload", payload);
|
||||
await next();
|
||||
};
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"@hono/zod-validator": "^0.2.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"hono": "^4.1.0",
|
||||
"mime": "^4.0.1",
|
||||
"nanoid": "^5.0.6",
|
||||
"node-pty": "^1.0.0",
|
||||
"systeminformation": "^5.22.2",
|
||||
|
||||
@@ -3,6 +3,7 @@ import auth from "./auth";
|
||||
import system from "./system";
|
||||
import _process from "./process";
|
||||
import apps from "./apps";
|
||||
import files from "./files";
|
||||
import { authMiddleware } from "../lib/jwt";
|
||||
|
||||
const routes = new Hono()
|
||||
@@ -10,7 +11,8 @@ const routes = new Hono()
|
||||
.use(authMiddleware)
|
||||
.route("/system", system)
|
||||
.route("/process", _process)
|
||||
.route("/apps", apps);
|
||||
.route("/apps", apps)
|
||||
.route("/files", files);
|
||||
|
||||
export type AppType = typeof routes;
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { Hono } from "hono";
|
||||
import { z } from "zod";
|
||||
import fs from "node:fs/promises";
|
||||
import { HTTPException } from "hono/http-exception";
|
||||
import { ReadStream, createReadStream } from "node:fs";
|
||||
import { ReadableStream } from "stream/web";
|
||||
import mime from "mime";
|
||||
|
||||
const getFilesSchema = z
|
||||
.object({
|
||||
path: z.string(),
|
||||
})
|
||||
.partial()
|
||||
.optional();
|
||||
|
||||
const filesDirList = process.env.FILE_DIRS
|
||||
? process.env.FILE_DIRS.split(";").map((i) => ({
|
||||
name: i.split("/").at(-1),
|
||||
path: i,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const route = new Hono()
|
||||
.get("/", zValidator("query", getFilesSchema), async (c) => {
|
||||
const input: z.infer<typeof getFilesSchema> = c.req.query();
|
||||
const pathname = (input.path || "").split("/");
|
||||
const path = pathname.slice(2).join("/");
|
||||
const baseName = pathname[1];
|
||||
|
||||
if (!baseName?.length) {
|
||||
return c.json(
|
||||
filesDirList.map((i) => ({
|
||||
name: i.name,
|
||||
path: "/" + i.name,
|
||||
isDirectory: true,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
const baseDir = filesDirList.find((i) => i.name === baseName)?.path;
|
||||
if (!baseDir) {
|
||||
return c.json([]);
|
||||
}
|
||||
|
||||
try {
|
||||
const cwd = baseDir + "/" + path;
|
||||
const entities = await fs.readdir(cwd, { withFileTypes: true });
|
||||
|
||||
const files = entities
|
||||
.filter((e) => !e.name.startsWith("."))
|
||||
.map((e) => ({
|
||||
name: e.name,
|
||||
path: "/" + [baseName, path, e.name].filter(Boolean).join("/"),
|
||||
isDirectory: e.isDirectory(),
|
||||
}))
|
||||
.sort((a, b) => {
|
||||
if (a.isDirectory && !b.isDirectory) {
|
||||
return -1;
|
||||
} else if (!a.isDirectory && b.isDirectory) {
|
||||
return 1;
|
||||
} else {
|
||||
return a.name.localeCompare(b.name);
|
||||
}
|
||||
});
|
||||
|
||||
return c.json(files);
|
||||
} catch (err) {}
|
||||
|
||||
return c.json([]);
|
||||
})
|
||||
.get(
|
||||
"/download",
|
||||
zValidator("query", z.object({ path: z.string().min(1) })),
|
||||
async (c) => {
|
||||
const pathname = (c.req.query("path") || "").split("/");
|
||||
const path = "/" + pathname.slice(2).join("/");
|
||||
const baseName = pathname[1];
|
||||
|
||||
try {
|
||||
if (!baseName?.length) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
const baseDir = filesDirList.find((i) => i.name === baseName)?.path;
|
||||
if (!baseDir) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
const filepath = baseDir + path;
|
||||
const stat = await fs.stat(filepath);
|
||||
const size = stat.size;
|
||||
|
||||
// c.header("Content-Type", "application/octet-stream");
|
||||
// c.header("Content-Disposition", `attachment; filename="${path}"`);
|
||||
|
||||
c.header(
|
||||
"Content-Type",
|
||||
mime.getType(filepath) || "application/octet-stream"
|
||||
);
|
||||
|
||||
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
|
||||
c.header("Content-Length", size.toString());
|
||||
c.status(200);
|
||||
return c.body(null);
|
||||
}
|
||||
|
||||
const range = c.req.header("range") || "";
|
||||
|
||||
if (!range) {
|
||||
c.header("Content-Length", size.toString());
|
||||
return c.body(createStreamBody(createReadStream(filepath)), 200);
|
||||
}
|
||||
|
||||
c.header("Accept-Ranges", "bytes");
|
||||
c.header("Date", stat.birthtime.toUTCString());
|
||||
|
||||
const parts = range.replace(/bytes=/, "").split("-", 2);
|
||||
const start = parts[0] ? parseInt(parts[0], 10) : 0;
|
||||
let end = parts[1] ? parseInt(parts[1], 10) : stat.size - 1;
|
||||
if (size < end - start + 1) {
|
||||
end = size - 1;
|
||||
}
|
||||
|
||||
const chunksize = end - start + 1;
|
||||
const stream = createReadStream(filepath, { start, end });
|
||||
|
||||
c.header("Content-Length", chunksize.toString());
|
||||
c.header("Content-Range", `bytes ${start}-${end}/${stat.size}`);
|
||||
|
||||
return c.body(createStreamBody(stream), 206);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
throw new HTTPException(404, { message: "Not Found!" });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const createStreamBody = (stream: ReadStream) => {
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
stream.on("data", (chunk) => {
|
||||
controller.enqueue(chunk);
|
||||
});
|
||||
stream.on("end", () => {
|
||||
controller.close();
|
||||
});
|
||||
},
|
||||
|
||||
cancel() {
|
||||
stream.destroy();
|
||||
},
|
||||
});
|
||||
return body;
|
||||
};
|
||||
|
||||
export default route;
|
||||
@@ -199,6 +199,11 @@ hono@^4.1.0:
|
||||
resolved "https://registry.yarnpkg.com/hono/-/hono-4.1.0.tgz#62cef81df0dbf731643155e1e5c1b9dffb230dc4"
|
||||
integrity sha512-9no6DCHb4ijB1tWdFXU6JnrnFgzwVZ1cnIcS1BjAFnMcjbtBTOMsQrDrPH3GXbkNEEEkj8kWqcYBy8Qc0bBkJQ==
|
||||
|
||||
mime@^4.0.1:
|
||||
version "4.0.1"
|
||||
resolved "https://registry.yarnpkg.com/mime/-/mime-4.0.1.tgz#ad7563d1bfe30253ad97dedfae2b1009d01b9470"
|
||||
integrity sha512-5lZ5tyrIfliMXzFtkYyekWbtRXObT9OWa8IwQ5uxTBDHucNNwniRqo0yInflj+iYi5CBa6qxadGzGarDfuEOxA==
|
||||
|
||||
nan@^2.17.0:
|
||||
version "2.19.0"
|
||||
resolved "https://registry.yarnpkg.com/nan/-/nan-2.19.0.tgz#bb58122ad55a6c5bc973303908d5b16cfdd5a8c0"
|
||||
|
||||
Reference in New Issue
Block a user