simple-fs-server/routes/dir/[...path].tsx

88 lines
2.3 KiB
TypeScript
Raw Normal View History

2023-01-06 18:24:27 +09:00
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
import { asset, Head } from "$fresh/runtime.ts";
import { removePrefixFromPathname } from "../../util/util.ts";
2023-01-05 18:18:07 +09:00
import { join } from "path/posix.ts";
import DirList, { EntryInfo } from "../../islands/DirList.tsx";
import FileViewer from "../../islands/FileViewer.tsx";
type DirProps = {
type: "dir";
path: string;
stat: Deno.FileInfo;
files: EntryInfo[];
2023-01-06 18:24:27 +09:00
};
2023-01-05 18:18:07 +09:00
type FileProps = {
type: "file";
path: string;
stat: Deno.FileInfo;
2023-01-06 18:24:27 +09:00
};
2023-01-05 18:18:07 +09:00
type DirOrFileProps = DirProps | FileProps;
2023-01-06 18:24:27 +09:00
async function GET(req: Request, ctx: HandlerContext): Promise<Response> {
2023-01-05 18:18:07 +09:00
const authRequired = Deno.env.get("AUTH_REQUIRED") === "true";
2023-01-06 18:24:27 +09:00
if (authRequired) {
const login = ctx.state["login"];
if (!login) {
return new Response(null, {
status: 302,
headers: {
"Location": "/login",
"content-type": "text/plain",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"Access-Control-Allow-Headers":
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
},
});
2023-01-05 18:18:07 +09:00
}
2023-01-06 18:24:27 +09:00
}
2023-01-05 18:18:07 +09:00
const url = new URL(req.url);
2023-01-06 18:20:26 +09:00
const path = removePrefixFromPathname(decodeURI(url.pathname), "/dir");
2023-01-05 18:18:07 +09:00
const stat = await Deno.stat(path);
2023-01-06 18:24:27 +09:00
if (stat.isDirectory) {
2023-01-05 18:18:07 +09:00
const filesIter = await Deno.readDir(path);
2023-01-06 18:24:27 +09:00
const files: EntryInfo[] = [];
for await (const file of filesIter) {
2023-01-05 18:18:07 +09:00
const fileStat = await Deno.stat(join(path, file.name));
files.push({
...file,
lastModified: fileStat.mtime ? new Date(fileStat.mtime) : undefined,
2023-01-06 18:24:27 +09:00
size: fileStat.size,
2023-01-05 18:18:07 +09:00
});
}
return await ctx.render({
type: "dir",
2023-01-06 18:24:27 +09:00
stat,
files,
path,
});
} else {
2023-01-05 18:18:07 +09:00
return await ctx.render({
type: "file",
2023-01-06 18:24:27 +09:00
stat,
path,
2023-01-05 18:18:07 +09:00
});
}
2023-01-06 18:24:27 +09:00
}
2023-01-05 18:18:07 +09:00
export const handler: Handlers = {
2023-01-06 18:24:27 +09:00
GET,
};
2023-01-05 18:18:07 +09:00
export default function DirLists(props: PageProps<DirOrFileProps>) {
const data = props.data;
2023-01-06 18:24:27 +09:00
return (
<>
<Head>
<title>Simple file server : {data.path}</title>
</Head>
<div class="p-4 mx-auto max-w-screen-md">
{data.type === "dir"
? <DirList path={data.path} files={data.files}></DirList>
: <FileViewer path={data.path}></FileViewer>}
</div>
</>
2023-01-05 18:18:07 +09:00
);
}