Compare commits

..

No commits in common. "312964f22c2281ec6414847cc8d4c83b0945640f" and "d959076d284f6208dc46239cea065a3e4aa0d3cb" have entirely different histories.

34 changed files with 1038 additions and 1185 deletions

View File

@ -23,4 +23,4 @@ Start the project:
deno task start deno task start
``` ```
This will watch the project directory and restart as necessary. This will watch the project directory and restart as necessary.

View File

@ -3,67 +3,63 @@ import MarkdownRenderer from "./MarkdownRenderer.tsx";
import { useEffect, useState } from "preact/hooks"; import { useEffect, useState } from "preact/hooks";
const TypeToExt = { const TypeToExt = {
"image": new Set([".png", ".jpg", ".jpeg", ".gif", ".svg"]), "image": new Set([".png", ".jpg", ".jpeg", ".gif", ".svg"]),
"video": new Set([".mp4", ".webm", ".ogg"]), "video": new Set([".mp4", ".webm", ".ogg"]),
"audio": new Set([".mp3", ".wav", ".flac"]), "audio": new Set([".mp3", ".wav", ".flac"]),
"md": new Set([".md"]), "md": new Set([".md"]),
"text": new Set([".txt"]), "text": new Set([".txt"]),
"code": new Set([".json", ".js", ".ts", ".css", ".tsx", ".jsx"]), "code": new Set([".json", ".js", ".ts", ".css", ".tsx", ".jsx"]),
}; }
function extToType(ext: string) { function extToType(ext: string) {
for (const [type, exts] of Object.entries(TypeToExt)) { for (const [type, exts] of Object.entries(TypeToExt)) {
if (exts.has(ext)) { if (exts.has(ext)) {
return type; return type;
}
} }
} return "unknown";
return "unknown";
} }
function FetchAndRender(props: { src: string; type: string }) { function FetchAndRender(props: {src: string, type: string}){
const src = props.src; const src = props.src;
const ext = extname(src); const ext = extname(src);
const [content, setContent] = useState(""); const [content, setContent] = useState("");
useEffect(() => { useEffect(() => {
fetch(src).then((res) => res.text()).then(setContent); fetch(src).then(res => res.text()).then(setContent);
}, [src]); }, [src]);
switch (props.type) { switch (props.type) {
case "text": case "text":
return <div style={{ whiteSpace: "pre-wrap" }}>{content}</div>; return <div style={{ whiteSpace: "pre-wrap" }}>{content}</div>;
case "md": case "md":
return <MarkdownRenderer text={content} />; return <MarkdownRenderer text={content} />;
case "code": case "code":
return ( return <pre style={{ whiteSpace: "pre-wrap" }}><code lang={ext.slice(1)}>{content}</code></pre>;
<pre //case "csv":
style={{ whiteSpace: "pre-wrap" }} // return <CsvRenderer content={content} />;
><code lang={ext.slice(1)}>{content}</code></pre> default:
); return <>error: invalid type: {props.type} content: {content}</>;
//case "csv": }
// return <CsvRenderer content={content} />;
default:
return <>error: invalid type: {props.type} content: {content}</>;
}
} }
export function RenderView(props: { src: string }) { export function RenderView(props: {src: string}) {
const src = props.src; const src = props.src;
const type = extToType(extname(src)); const type = extToType(extname(src));
switch (type) { switch (type) {
case "text": case "text":
case "md": case "md":
case "code": case "code":
return <FetchAndRender src={src} type={type}></FetchAndRender>; return <FetchAndRender src={src} type={type}></FetchAndRender>
//case "csv": //case "csv":
// return <CsvRenderer content={content} />; // return <CsvRenderer content={content} />;
case "image": case "image":
return <img style={{ width: "100%" }} src={src} />; return <img style={{ width: "100%" }} src={src} />;
case "video": case "video":
return <video style={{ width: "100%" }} controls src={src} />; return <video style={{ width: "100%" }} controls src={src} />;
case "audio": case "audio":
return <audio style={{ width: "100%" }} controls src={src} />; return <audio style={{ width: "100%" }} controls src={src} />;
default: default:
return <>error: invalid type: {type} src: {src}</>; return <>error: invalid type: {type} src: {src}</>;
} }
} }
export default RenderView; export default RenderView;

View File

@ -1,108 +1,94 @@
import { asset, Head } from "$fresh/runtime.ts"; import { Head, asset } from "$fresh/runtime.ts";
import { useState } from "preact/hooks"; import { useState } from "preact/hooks";
import { extname, join } from "path/posix.ts"; import { extname, join } from "path/posix.ts";
import { ComponentChild } from "preact"; import { ComponentChild } from "preact";
import UpList from "./UpList.tsx"; import UpList from "./UpList.tsx";
import { extToIcon } from "../src/media.ts"; import {extToIcon} from "../src/media.ts";
import { encodePath } from "../util/util.ts"; import { encodePath } from "../util/util.ts";
function ListItem(props: { function ListItem(props:{
href: string; href: string,
icon: string; icon: string,
children: ComponentChild; children: ComponentChild
}) { }) {
return ( return (
<li class="p-1 hover:bg-gray-400 transition-colors"> <li class="p-1 hover:bg-gray-400 transition-colors">
<a class="flex gap-2" href={props.href}> <a class="flex gap-2" href={props.href}>
<img src={asset(props.icon)} /> <img src={asset(props.icon)}/><p class="">{props.children}</p></a>
<p class="">{props.children}</p> </li>
</a> );
</li>
);
} }
export interface EntryInfo { export interface EntryInfo{
name: string; name: string;
isFile: boolean; isFile: boolean;
isDirectory: boolean; isDirectory: boolean;
isSymlink: boolean; isSymlink: boolean;
size: number; size: number;
lastModified?: Date; lastModified?: Date;
} }
interface DirListProps { interface DirListProps {
path: string; path: string;
files: EntryInfo[]; files: EntryInfo[];
} }
export function DirList(props: DirListProps) { export function DirList(props: DirListProps) {
const data = props; const data = props;
const [files, setFiles] = useState(data.files); const [files, setFiles] = useState(data.files);
return ( return (<div>
<div> <UpList path={data.path}></UpList>
<UpList path={data.path}></UpList> <ul class="border-2 rounded-md">
<ul class="border-2 rounded-md"> <li class="p-1 flex gap-2">
<li class="p-1 flex gap-2"> <button class="flex" onClick={sortDir}>
<button class="flex" onClick={sortDir}> <img src={asset("/icon/sort-down.svg")}/> Sort Directory
<img src={asset("/icon/sort-down.svg")} /> Sort Directory </button>
</button> <button class="flex" onClick={sortAlpha}>
<button class="flex" onClick={sortAlpha}> <img src={asset("/icon/sort-alpha-down.svg")} /> Sort Alphabet
<img src={asset("/icon/sort-alpha-down.svg")} /> Sort Alphabet </button>
</button> </li>
</li> <ListItem key=".." href={`/dir/${encodePath(join(data.path,".."))}`}
<ListItem icon="/icon/back.svg"
key=".." >...</ListItem>
href={`/dir/${encodePath(join(data.path, ".."))}`} {files.map((file) => (
icon="/icon/back.svg" <ListItem key={file.name} href={`/dir/${encodePath(join(data.path,file.name))}`}
> icon={file.isDirectory ? "/icon/folder.svg": extToIcon(extname(file.name))}
... >{file.name}</ListItem>
</ListItem> ))}
{files.map((file) => ( </ul>
<ListItem </div>)
key={file.name} function sortDir() {
href={`/dir/${encodePath(join(data.path, file.name))}`} // sort by directory first then by index
icon={file.isDirectory const sorted_files = files.map((x,i)=>
? "/icon/folder.svg" ([x,i] as [EntryInfo, number]))
: extToIcon(extname(file.name))} .sort(
> ([a, ai],[b,bi]) => {
{file.name} if (a.isDirectory && !b.isDirectory) {
</ListItem> return -1;
))} } else if (!a.isDirectory && b.isDirectory) {
</ul> return 1;
</div> } else {
); return ai - bi;
function sortDir() { }
// sort by directory first then by index });
const sorted_files = files.map((x, i) => ([x, i] as [EntryInfo, number])) setFiles(sorted_files.map(([x,_])=>x));
.sort( }
([a, ai], [b, bi]) => { function sortAlpha() {
if (a.isDirectory && !b.isDirectory) { // sort by alphabet first then by index
return -1; const sorted_files = files.map((x,i)=>
} else if (!a.isDirectory && b.isDirectory) { ([x,i] as [EntryInfo, number]))
return 1; .sort(
} else { ([a, ai],[b,bi]) => {
return ai - bi; const ret = a.name.localeCompare(b.name);
} if (ret === 0) {
}, return ai - bi;
); } else {
setFiles(sorted_files.map(([x, _]) => x)); return ret;
} }
function sortAlpha() { });
// sort by alphabet first then by index setFiles(sorted_files.map(([x,_])=>x));
const sorted_files = files.map((x, i) => ([x, i] as [EntryInfo, number])) }
.sort(
([a, ai], [b, bi]) => {
const ret = a.name.localeCompare(b.name);
if (ret === 0) {
return ai - bi;
} else {
return ret;
}
},
);
setFiles(sorted_files.map(([x, _]) => x));
}
} }
export default DirList; export default DirList;

View File

@ -3,52 +3,43 @@ import { useEffect, useState } from "preact/hooks";
import { Index } from "../src/client_search.ts"; import { Index } from "../src/client_search.ts";
import { encodePath } from "../util/util.ts"; import { encodePath } from "../util/util.ts";
function SearchBar(props: { function SearchBar(props:{
search?: string; search?: string;
onSearch?: (search: string) => void; onSearch?: (search: string) => void;
}) { }){
const [search, setSearch] = useState(props.search ?? ""); const [search, setSearch] = useState(props.search ?? "");
return ( return (
<div class="flex items-center justify-center"> <div class="flex items-center justify-center">
<input <input type="text" class="w-1/2 px-4 py-2 border-2 rounded-lg" placeholder="Search..."
type="text" //onChange={(event)=>{}}
class="w-1/2 px-4 py-2 border-2 rounded-lg" onKeyUp={(event)=>{
placeholder="Search..." if (event.currentTarget.value === search) return;
//onChange={(event)=>{}} setSearch(event.currentTarget.value);
onKeyUp={(event) => { props.onSearch?.(event.currentTarget.value);
if (event.currentTarget.value === search) return; }}>{search}</input>
setSearch(event.currentTarget.value); </div>
props.onSearch?.(event.currentTarget.value); )
}}
>
{search}
</input>
</div>
);
} }
export default function DocSearch(props: { export default function DocSearch(props: {
docs: Doc[]; docs: Doc[]
}) { }){
const [docs, setDocs] = useState(props.docs); const [docs, setDocs] = useState(props.docs);
const index = Index.createIndex(props.docs); const index = Index.createIndex(props.docs);
return ( return (
<> <>
<SearchBar <SearchBar onSearch={(s)=>{
onSearch={(s) => { setDocs(index.search(s));
setDocs(index.search(s)); }}></SearchBar>
}} <h1 class="text-2xl font-bold">Doc</h1>
> <ul class="mt-4">
</SearchBar> {docs.map((doc) => (
<h1 class="text-2xl font-bold">Doc</h1> <li class="mt-2">
<ul class="mt-4"> <a href={`/dir/${encodePath(doc.path)}`}> {doc.path}</a>
{docs.map((doc) => ( </li>
<li class="mt-2"> ))}
<a href={`/dir/${encodePath(doc.path)}`}>{doc.path}</a> </ul>
</li> </>
))} )
</ul> }
</>
);
}

View File

@ -4,15 +4,15 @@ import { extname } from "path/mod.ts";
import { encodePath } from "../util/util.ts"; import { encodePath } from "../util/util.ts";
export default function FileViewer(props: { path: string }) { export default function FileViewer(props: { path: string }) {
const { path } = props; const { path } = props;
const srcPath = `/fs/${encodePath(path)}`; const srcPath = `/fs/${encodePath(path)}`;
return ( return (
<div class="p-4 mx-auto max-w-screen-md"> <div class="p-4 mx-auto max-w-screen-md">
<UpList path={path} /> <UpList path={path} />
<a href={srcPath}>Direct link</a> <a href={srcPath}>Direct link</a>
<div class="p-2 border-2 rounded-lg"> <div class="p-2 border-2 rounded-lg">
<RenderView src={srcPath} /> <RenderView src={srcPath}/>
</div> </div>
</div> </div>
); )
} }

View File

@ -1,18 +1,13 @@
import { marked } from "https://deno.land/x/marked@1.0.1/mod.ts"; import { marked } from "https://deno.land/x/marked@1.0.1/mod.ts";
export function MarkdownRenderer(props: { text: string | undefined }) { export function MarkdownRenderer(props: { text: string | undefined }) {
let text = props.text; let text = props.text;
if (text === undefined) { if (text === undefined) {
text = ""; text = "";
} }
const index = text.indexOf("\n---", 3); const index = text.indexOf('\n---', 3);
const c = text.slice(index + 4, text.length); const c = text.slice(index + 4, text.length);
return ( return <div class="markdown-body" dangerouslySetInnerHTML={{ __html: marked.parse(c) }} />;
<div
class="markdown-body"
dangerouslySetInnerHTML={{ __html: marked.parse(c) }}
/>
);
} }
export default MarkdownRenderer; export default MarkdownRenderer;

View File

@ -1,44 +1,40 @@
import { asset, Head } from "$fresh/runtime.ts"; import { Head, asset } from "$fresh/runtime.ts";
import { join } from "path/posix.ts"; import { join } from "path/posix.ts";
import { ComponentChild } from "preact"; import { ComponentChild } from "preact";
import { encodePath } from "../util/util.ts"; import { encodePath } from "../util/util.ts";
function stairs(path: string) {
if (path === ".") return []; function stairs(path: string){
const uplist = path.split("/"); if (path === ".") return [];
let current = "."; const uplist = path.split("/");
const stairs = []; let current = ".";
for (const up of uplist) { const stairs = [];
current = join(current, up); for (const up of uplist){
stairs.push([current, up]); current = join(current, up);
} stairs.push([current, up]);
return stairs; }
return stairs;
} }
export default function UpList(props: { path: string }) { export default function UpList(props:{path: string}) {
const data = props; const data = props;
const uplist = stairs(data.path); const uplist = stairs(data.path);
return ( return (<div>
<div> <h1 class={"text-2xl flex flex-wrap"}>
<h1 class={"text-2xl flex flex-wrap"}> <a href="/dir/" class="flex flex-wrap p-2 hover:bg-gray-400 rounded-sm">
<a href="/dir/" class="flex flex-wrap p-2 hover:bg-gray-400 rounded-sm"> <img src={asset("/icon/house.svg")}/>
<img src={asset("/icon/house.svg")} /> <span class="ml-1">Home</span></a>
<span class="ml-1">Home</span> {
</a> uplist.map(([cur, up], i) => (
{uplist.map(([cur, up], i) => ( <>
<> <span class="p-2">/</span>
<span class="p-2">/</span> <a class="flex flex-wrap p-2 hover:bg-gray-400 rounded-sm" href={`/dir/${encodePath(cur)}`}>
<a <img src={asset("/icon/folder.svg")} />
class="flex flex-wrap p-2 hover:bg-gray-400 rounded-sm" <span class="ml-1">{up}</span>
href={`/dir/${encodePath(cur)}`} </a>
> </>
<img src={asset("/icon/folder.svg")} /> ))
<span class="ml-1">{up}</span> }</h1>
</a> </div>)
</> }
))}
</h1>
</div>
);
}

View File

@ -4,27 +4,24 @@ import { prepareSecretKey } from "./util/secret.ts";
export const key_out_cmd = new Command(); export const key_out_cmd = new Command();
key_out_cmd.name("keyout") key_out_cmd.name("keyout")
.description("Output the secret key.") .description("Output the secret key.")
.option( .option("-f, --file <file:string>", "The file to output the key to. (default: stdout)")
"-f, --file <file:string>", .option("--dotenv", "Output the key in dotenv format.")
"The file to output the key to. (default: stdout)", .action(async ({file, dotenv}) => {
)
.option("--dotenv", "Output the key in dotenv format.")
.action(async ({ file, dotenv }) => {
const key = await prepareSecretKey(); const key = await prepareSecretKey();
const keyout = await crypto.subtle.exportKey("jwk", key); const keyout = await crypto.subtle.exportKey("jwk", key);
let out = JSON.stringify(keyout); let out = JSON.stringify(keyout);
if (dotenv) { if (dotenv){
out = [`SECRET_KEY='${out}'`].join("\n"); out = [`SECRET_KEY='${out}'`].join("\n");
} }
if (file) { if (file){
await Deno.writeTextFile(file, out); await Deno.writeTextFile(file, out);
} else { } else {
console.log(out); console.log(out);
} }
}); });
if (import.meta.main) { if ( import.meta.main ){
await key_out_cmd.parse(Deno.args); await key_out_cmd.parse(Deno.args);
} }

121
main.ts
View File

@ -4,19 +4,14 @@
/// <reference lib="dom.asynciterable" /> /// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" /> /// <reference lib="deno.ns" />
import { import { PluginRenderResult, Plugin, ServerContext, Manifest, StartOptions } from "$fresh/server.ts";
Manifest,
Plugin,
PluginRenderResult,
ServerContext,
StartOptions,
} from "$fresh/server.ts";
import manifest from "./fresh.gen.ts"; import manifest from "./fresh.gen.ts";
import twindPlugin from "$fresh/plugins/twind.ts"; import twindPlugin from "$fresh/plugins/twind.ts";
import twindConfig from "./twind.config.ts"; import twindConfig from "./twind.config.ts";
import "https://deno.land/std@0.170.0/dotenv/load.ts"; import "https://deno.land/std@0.170.0/dotenv/load.ts";
import { Command } from "https://deno.land/x/cliffy@v0.25.6/mod.ts"; import { Command } from "https://deno.land/x/cliffy@v0.25.6/mod.ts";
import { fromFileUrl, join } from "path/mod.ts"; import { fromFileUrl, join } from "path/mod.ts";
import { prepareSecretKey } from "./util/secret.ts"; import { prepareSecretKey } from "./util/secret.ts";
@ -24,84 +19,72 @@ import { serve } from "http/server.ts";
import { user_command } from "./user.ts"; import { user_command } from "./user.ts";
import { key_out_cmd } from "./keyout.ts"; import { key_out_cmd } from "./keyout.ts";
import { prepareDocs } from "./src/store/doc.ts";
const github_markdown = await Deno.readTextFile( const github_markdown= await Deno.readTextFile(join(fromFileUrl(import.meta.url), "..", "static", "github-markdown.css"))
join(fromFileUrl(import.meta.url), "..", "static", "github-markdown.css"),
);
const CSSPlugin: Plugin = { const CSSPlugin: Plugin = {
name: "css plugin", name:"css plugin",
// deno-lint-ignore require-await // deno-lint-ignore require-await
render(ctx): PluginRenderResult { render(ctx): PluginRenderResult{
ctx.render(); ctx.render();
return { return {
styles: [{ styles: [{
cssText: github_markdown, cssText: github_markdown,
}], }]
}; }
}, }
}; };
await prepareSecretKey(); await prepareSecretKey();
async function startServer(manifest: Manifest, options: StartOptions = {}) { async function startServer(manifest: Manifest, options: StartOptions = {}){
const ctx = await ServerContext.fromManifest(manifest, options); const ctx = await ServerContext.fromManifest(manifest, options);
options.port ??= 8000; options.port ??= 8000;
if (options.experimentalDenoServe === true) { if (options.experimentalDenoServe === true) {
// @ts-ignore as `Deno.serve` is still unstable. // @ts-ignore as `Deno.serve` is still unstable.
await Deno.serve(ctx.handler() as Deno.ServeHandler, options); await Deno.serve(ctx.handler() as Deno.ServeHandler, options);
} else { } else {
await serve(ctx.handler(), options); await serve(ctx.handler(), options);
} }
} }
async function start( async function start({port = 8000, hostname = "localhost"}: {port?: number, hostname?: string} = {}){
{ port = 8000, hostname = "localhost" }: { await startServer(manifest, { plugins: [twindPlugin(twindConfig), CSSPlugin],
port?: number; port: port,
hostname?: string; hostname: hostname,
} = {}, });
) {
await startServer(manifest, {
plugins: [twindPlugin(twindConfig), CSSPlugin],
port: port,
hostname: hostname,
});
} }
if (import.meta.main) { if (import.meta.main){
const cmd = new Command(); const cmd = new Command();
cmd.name("fs-server") cmd.name("fs-server")
.description( .description("A simple file server that supports search, upload, and download.")
"A simple file server that supports search, upload, and download.",
)
.version("0.0.1") .version("0.0.1")
.globalOption("-d, --debug", "Enable debug mode.") .globalOption("-d, --debug", "Enable debug mode.")
.command("start", "Start the server.") .command("start", "Start the server.")
.option("-p, --port <port:number>", "The port to listen on.", { .option("-p, --port <port:number>", "The port to listen on.",
default: 8000, { default: 8000 })
})
.option("--auth", "Enable authentication.") .option("--auth", "Enable authentication.")
.arguments("[hostname:string]") .arguments("[hostname:string]")
.action(async ({ debug, port, auth }, hostname) => { .action(async ({debug, port, auth }, hostname) => {
hostname ??= "localhost"; hostname ??= "localhost";
if (auth) { if (auth){
Deno.env.set("AUTH_REQUIRED", "true"); Deno.env.set("AUTH_REQUIRED", "true");
} }
if (debug) { if (debug){
console.log("Debug mode enabled."); console.log("Debug mode enabled.");
} }
await prepareDocs(); await start({
await start({ port: port,
port: port, hostname: hostname,
hostname: hostname, });
}); }
}) )
.command("user", user_command) .command("user", user_command)
.command("keyout", key_out_cmd); .command("keyout", key_out_cmd);
await cmd.parse(Deno.args); await cmd.parse(Deno.args);
} else {
await prepareDocs();
await start();
} }
else {
await start();
}

View File

@ -1,21 +1,20 @@
import { MiddlewareHandlerContext } from "$fresh/server.ts"; import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { getCookies } from "http/cookie.ts"; import { getCookies } from "http/cookie.ts";
import { verify } from "djwt"; import { decode, verify } from "djwt";
import { prepareSecretKey } from "../util/secret.ts"; import { prepareSecretKey } from "../util/secret.ts";
const secret_key = await prepareSecretKey(); const secret_key = await prepareSecretKey();
export const handler = async ( export const handler =
req: Request, async (req: Request , ctx: MiddlewareHandlerContext<Record<string, unknown>>) => {
ctx: MiddlewareHandlerContext<Record<string, unknown>>, const cookies = getCookies(req.headers);
) => { const jwt = cookies["auth"];
const cookies = getCookies(req.headers); try{
const jwt = cookies["auth"]; const payload = await verify(jwt, secret_key);
try { ctx.state["login"] = payload;
const payload = await verify(jwt, secret_key); }
ctx.state["login"] = payload; catch (e){
} catch (e) { ctx.state["login"] = null;
ctx.state["login"] = null; }
} return await ctx.next();
return await ctx.next(); }
};

View File

@ -6,44 +6,44 @@ import { getUser, verifyUser } from "../../src/user/user.ts";
import { create as createJWT } from "djwt"; import { create as createJWT } from "djwt";
import { prepareSecretKey } from "../../util/secret.ts"; import { prepareSecretKey } from "../../util/secret.ts";
const SECRET_KEY = await prepareSecretKey();
const SECRET_KEY = await prepareSecretKey();
async function POST(req: Request, ctx: HandlerContext): Promise<Response> { async function POST(req: Request, ctx: HandlerContext): Promise<Response> {
const url = new URL(req.url); const url = new URL(req.url);
const form = await req.formData(); const form = await req.formData();
const username = form.get("username"); const username = form.get("username");
const password = form.get("password"); const password = form.get("password");
if (username && password) { if (username && password){
const DB = connectDB(); const DB = connectDB();
const user = await getUser(DB, username.toString()); const user = await getUser(DB, username.toString());
if (user) { if (user){
if (await verifyUser(user, password.toString())) { if (await verifyUser(user, password.toString())){
const headers = new Headers(); const headers = new Headers();
const jwt = await createJWT({ alg: "HS512", typ: "JWT" }, { const jwt = await createJWT({alg:"HS512", typ: "JWT"},{
username: user.name, username: user.name
}, SECRET_KEY); }, SECRET_KEY);
setCookie(headers, { setCookie(headers, {
name: "auth", name: "auth",
value: jwt, value: jwt,
httpOnly: true, httpOnly: true,
sameSite: "Strict", sameSite: "Strict",
maxAge: 60 * 60 * 24 * 7, maxAge: 60 * 60 * 24 * 7,
domain: url.hostname, domain: url.hostname,
path: "/", path: "/",
secure: url.protocol === "https:", secure: url.protocol === "https:"
}); });
headers.set("Location", "/"); headers.set("Location", "/");
return new Response(null, { return new Response(null,{
status: Status.SeeOther, // See Other status: Status.SeeOther, // See Other
headers: headers, headers: headers
}); });
} }
}
} }
}
return new Response( return new Response(`<!DOCTYPE html><html>
`<!DOCTYPE html><html>
<head> <title> Login Failed </title> </head> <head> <title> Login Failed </title> </head>
<body> <body>
<h1> Login Failed </h1> <h1> Login Failed </h1>
@ -52,16 +52,14 @@ async function POST(req: Request, ctx: HandlerContext): Promise<Response> {
document.location.href = "/login"; document.location.href = "/login";
</script> </script>
</body> </body>
</html>`, </html>`, {
{ headers:{
headers: { "Content-Type": "text/html"
"Content-Type": "text/html", },
}, status: Status.Forbidden,
status: Status.Forbidden, });
},
);
} }
export const handler = { export const handler = {
POST, POST
}; };

View File

@ -14,4 +14,4 @@ export const handler: Handlers = {
headers, headers,
}); });
}, },
}; };

View File

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

View File

@ -1,37 +1,20 @@
import { Head } from "$fresh/runtime.ts"; import { Head } from "$fresh/runtime.ts";
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts"; import { PageProps, Handlers, HandlerContext } from "$fresh/server.ts";
import DocSearch from "../../islands/DocSearch.tsx"; import DocSearch from "../../islands/DocSearch.tsx";
import { Doc } from "../../src/collect.ts"; import { Doc } from "../../src/collect.ts";
import { docCollector } from "../../src/store/doc.ts"; import { docCollector } from "../../src/store/doc.ts";
async function GET(req: Request, ctx: HandlerContext): Promise<Response> { async function GET(req: Request, ctx: HandlerContext): Promise<Response> {
const authRequired = Deno.env.get("AUTH_REQUIRED") === "true"; const docs = docCollector.getDocs();
if (authRequired) { return await ctx.render({docs});
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",
},
});
}
}
const docs = docCollector.getDocs();
return await ctx.render({ docs });
} }
export const handler: Handlers = { export const handler: Handlers = {
GET, GET,
}; }
export default function Docs(props: PageProps<{ docs: Doc[] }>) { export default function Docs(props: PageProps<{docs:Doc[]}>) {
const { docs } = props.data; const {docs} = props.data;
return ( return (
<> <>
<Head> <Head>
@ -42,4 +25,4 @@ export default function Docs(props: PageProps<{ docs: Doc[] }>) {
</div> </div>
</> </>
); );
} }

View File

@ -1,82 +1,74 @@
import { HandlerContext, Handlers } from "$fresh/server.ts"; import { HandlerContext, Handlers } from "$fresh/server.ts";
import { serveFile } from "http/file_server.ts"; import { serveFile } from "http/file_server.ts";
import { removePrefixFromPathname } from "../../util/util.ts"; import {removePrefixFromPathname} from "../../util/util.ts";
export async function GET( export async function GET(req: Request, ctx: HandlerContext): Promise<Response> {
req: Request, const url = new URL(req.url);
ctx: HandlerContext, const path = removePrefixFromPathname(decodeURI(url.pathname), "/fs");
): Promise<Response> { // if auth is required, check if the user is logged in.
const url = new URL(req.url); // if not, return a 401.
const path = removePrefixFromPathname(decodeURI(url.pathname), "/fs"); const authRequired = Deno.env.get("AUTH_REQUIRED") === "true";
// if auth is required, check if the user is logged in. if (authRequired) {
// if not, return a 401. const login = ctx.state["login"];
const authRequired = Deno.env.get("AUTH_REQUIRED") === "true"; if (!login) {
if (authRequired) { return new Response(null, {
const login = ctx.state["login"]; status: 401,
if (!login) { headers: {
return new Response(null, { "content-type": "text/plain",
status: 302, "Access-Control-Allow-Origin": "*",
headers: { "Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"Location": "/login", "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
"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",
},
});
}
}
try {
const fileInfo = await Deno.stat(path);
if (fileInfo.isDirectory) {
// if index.html exists, serve it.
// otherwise, serve a directory listing.
const indexPath = path + "/index.html";
try {
await Deno.stat(indexPath);
const res = await serveFile(req, indexPath);
return res;
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
const list: Deno.DirEntry[] = [];
for await (const entry of Deno.readDir(path)) {
list.push(entry);
}
return new Response(
JSON.stringify(
list,
),
{
headers: {
"content-type": "application/json",
"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",
},
status: 200,
},
);
} }
}
} }
const res = await serveFile(req, path, {
fileInfo, try{
});
return res; const fileInfo = await Deno.stat(path);
} catch (e) { if (fileInfo.isDirectory) {
if (e instanceof Deno.errors.NotFound) { // if index.html exists, serve it.
return new Response("Not Found", { // otherwise, serve a directory listing.
status: 404, const indexPath = path + "/index.html";
}); try {
await Deno.stat(indexPath);
const res = await serveFile(req, indexPath)
return res;
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
const list: Deno.DirEntry[] = []
for await (const entry of Deno.readDir(path)){
list.push(entry);
}
return new Response(JSON.stringify(
list
), {
headers: { "content-type": "application/json",
"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"},
status: 200,
});
}
}
}
const res = await serveFile(req, path, {
fileInfo
});
return res;
}
catch (e) {
if (e instanceof Deno.errors.NotFound) {
return new Response("Not Found", {
status: 404,
});
}
throw e;
} }
throw e;
}
} }
export const handler: Handlers = { export const handler: Handlers = {
GET, GET
}; }

View File

@ -13,8 +13,7 @@ export default function Home() {
alt="the fresh logo: a sliced lemon dripping with juice" alt="the fresh logo: a sliced lemon dripping with juice"
/> />
<p class="my-6"> <p class="my-6">
This is a simple file server. It serves files from the{" "} This is a simple file server. It serves files from the <code>CWD</code>.
<code>CWD</code>.
</p> </p>
<a href="/dir/">Go To CWD</a> | <a href="/doc/">Doc</a> <a href="/dir/">Go To CWD</a> | <a href="/doc/">Doc</a>
<hr></hr> <hr></hr>

View File

@ -1,55 +1,38 @@
import { Head } from "$fresh/runtime.ts"; import { Head } from "$fresh/runtime.ts";
export default function Login() { export default function Login() {
return ( return (
<> <>
<Head> <Head>
<title>Simple file server - Login</title> <title>Simple file server - Login</title>
</Head> </Head>
<div class=""> <div class="">
<div class="p-4 absolute top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%] <div class="p-4 absolute top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]
flex flex-col items-center border-gray-500 border-2 rounded-md flex flex-col items-center border-gray-500 border-2 rounded-md
sm:max-w-screen-sm max-w-screen-md"> sm:max-w-screen-sm max-w-screen-md">
<img <img
src="/logo.svg" src="/logo.svg"
class="w-32 h-32" class="w-32 h-32"
alt="the fresh logo: a sliced lemon dripping with juice" alt="the fresh logo: a sliced lemon dripping with juice"
/> />
<form <form action="/api/login" method="POST" class="flex flex-col gap-2 items-stretch">
action="/api/login" <div class="flex gap-2 flex-wrap">
method="POST" <div class="basis-40 flex items-center flex-1">
class="flex flex-col gap-2 items-stretch" <label for="username" class="w-20">Username</label>
> <input type="text" name="username" id="username"
<div class="flex gap-2 flex-wrap"> class="border-b-2 focus:border-green-500 transition-colors flex-1" />
<div class="basis-40 flex items-center flex-1"> </div>
<label for="username" class="w-20">Username</label> <div class="flex items-center flex-1">
<input <label for="password" class="w-20">Password</label>
type="text" <input type="password" name="password" id="password"
name="username" class="border-b-2 focus:border-green-500 transition-colors flex-1" />
id="username" </div>
class="border-b-2 focus:border-green-500 transition-colors flex-1" </div>
/> <button type="submit" class="bg-gray-400 p-2 rounded
</div> m-auto">Login</button>
<div class="flex items-center flex-1"> </form>
<label for="password" class="w-20">Password</label> </div>
<input
type="password"
name="password"
id="password"
class="border-b-2 focus:border-green-500 transition-colors flex-1"
/>
</div>
</div> </div>
<button </>
type="submit" );
class="bg-gray-400 p-2 rounded
m-auto"
>
Login
</button>
</form>
</div>
</div>
</>
);
} }

152
search.ts
View File

@ -2,90 +2,84 @@ import { Command } from "https://deno.land/x/cliffy@v0.25.6/mod.ts";
import { Index } from "./src/client_search.ts"; import { Index } from "./src/client_search.ts";
import { Doc, DocCollector, loadDocuments } from "./src/collect.ts"; import { Doc, DocCollector, loadDocuments } from "./src/collect.ts";
export async function collectDocuments(path: string, out: string) { export async function collectDocuments(path: string, out: string){
const collector = new DocCollector({ summaryOnly: true, dropContent: true }); const collector = new DocCollector({ summaryOnly: true, dropContent: true });
await collector.walkDir(path); await collector.walkDir(path);
const docs = collector.getDocs(); const docs = collector.getDocs();
await Deno.writeTextFile(out, JSON.stringify(docs)); await Deno.writeTextFile(out, JSON.stringify(docs));
} }
export async function watchDocuments(doc: string, options?: { export async function watchDocuments(doc: string , options?:{
abort?: AbortSignal; abort?: AbortSignal,
}) { }){
const doc_dump = await loadDocuments(doc); const doc_dump = await loadDocuments(doc);
const collector = new DocCollector({ summaryOnly: true, dropContent: true }); const collector = new DocCollector({ summaryOnly: true, dropContent: true });
collector.setDocs(doc_dump); collector.setDocs(doc_dump);
const index = Index.createIndex(doc_dump); const index = Index.createIndex(doc_dump);
async function update() { async function update(){
index.setDocs(collector.getDocs()); index.setDocs(collector.getDocs());
await Deno.writeTextFile(doc, JSON.stringify(collector.getDocs())); await Deno.writeTextFile(doc, JSON.stringify(collector.getDocs()));
} }
collector.watchDir(".", { collector.watchDir(".", {
async onAdd(doc) { async onAdd(doc){
console.log("onAdd :", doc.path); console.log("onAdd :", doc.path);
await update(); await update();
}, },
async onRemove(path) { async onRemove(path){
console.log("onRemove :", path); console.log("onRemove :", path);
await update(); await update();
}, },
async onChange(doc) { async onChange(doc){
console.log("onModify :", doc.path); console.log("onModify :", doc.path);
await update(); await update();
}, },
abort: options?.abort, abort: options?.abort,
}); });
return index; return index;
} }
export const search = new Command(); export const search = new Command();
search.name("search") search.name("search")
.description("Search for a document.") .description("Search for a document.")
.command("collect", "Collect a document.") .command("collect", "Collect a document.")
.description("Collect documents and index documents.") .description("Collect documents and index documents.")
.arguments("<path:string>") .arguments("<path:string>")
.option("-o, --out <path:string>", "out file to write the index to.", { .option("-o, --out <path:string>", "out file to write the index to.", {default: "collected_docs.json"})
default: "collected_docs.json", .action(async ({out} ,path: string) => {
}) console.log("collecting", path);
.action(async ({ out }, path: string) => { await collectDocuments(path, out);
console.log("collecting", path); })
await collectDocuments(path, out); .command("search", "Search for a document.")
}) .description("Search for a document.")
.command("search", "Search for a document.") .arguments("<query:string>")
.description("Search for a document.") .option("-d, --docs <path:string>", "collected document file to search", {default: "collected_docs.json"})
.arguments("<query:string>") .action(async ({docs}, query: string) => {
.option("-d, --docs <path:string>", "collected document file to search", { console.log("searching", query);
default: "collected_docs.json", const doc_dump = await loadDocuments(docs);
}) const results = Index.createIndex(doc_dump).search(query);
.action(async ({ docs }, query: string) => { console.log(results);
console.log("searching", query); })
const doc_dump = await loadDocuments(docs); .command("interact", "watch the index and search for a document.")
const results = Index.createIndex(doc_dump).search(query); .description("watch the index and search for a document.")
console.log(results); .option("-d, --doc <path:string>", "doc file to read the docs from.", {default: "collected_docs.json"})
}) .action(async ({doc}) => {
.command("interact", "watch the index and search for a document.") console.log("interacting");
.description("watch the index and search for a document.") const index = await watchDocuments(doc);
.option("-d, --doc <path:string>", "doc file to read the docs from.", {
default: "collected_docs.json",
})
.action(async ({ doc }) => {
console.log("interacting");
const index = await watchDocuments(doc);
// interact // interact
while (true) { while (true){
const query = await prompt("query: "); const query = await prompt("query: ");
if (query === null) { if (query === null){
continue; continue;
} }
if (query === ":exit") { if (query === ":exit"){
break; break;
} }
const results = index.search(query); const results = index.search(query);
console.log(results); console.log(results);
} }
}); });
if (import.meta.main) { if ( import.meta.main ){
await search.parse(Deno.args); await search.parse(Deno.args);
} }

View File

@ -1,38 +1,31 @@
//// @deno-types="https://deno.land/x/fuse@v6.4.1/dist/fuse.d.ts" //// @deno-types="https://deno.land/x/fuse@v6.4.1/dist/fuse.d.ts"
import Fuse from "https://deno.land/x/fuse@v6.4.1/dist/fuse.esm.min.js"; import Fuse from 'https://deno.land/x/fuse@v6.4.1/dist/fuse.esm.min.js';
import { Doc } from "./collect.ts"; import { Doc } from "./collect.ts";
export class Index { export class Index{
private index: Fuse; private index: Fuse;
private constructor(index: Fuse) { private constructor(index: Fuse){
this.index = index; this.index = index;
} }
public setDocs(docs: Doc[]) { public setDocs(docs: Doc[]){
this.index.setCollection(docs); this.index.setCollection(docs);
} }
public search(query: string): Doc[] { public search(query: string): Doc[]{
return this.index.search(query, { limit: 10 }).map(( return this.index.search(query, {limit: 10}).map((
result, result) =>
) => result.item as Doc); result.item as Doc);
} }
public static createIndex(docs: Doc[]) { public static createIndex(docs: Doc[]){
const index = new Fuse(docs, { const index = new Fuse(docs,{
keys: [ keys: ["attributes.title", "attributes.japanese_title", "attributes.tags", "attributes.rjcode", "attributes.author", "path"],
"attributes.title", includeScore: true,
"attributes.japanese_title", includeMatches: true,
"attributes.tags", })
"attributes.rjcode",
"attributes.author",
"path",
],
includeScore: true,
includeMatches: true,
});
return new Index(index); return new Index(index);
} }
} }

View File

@ -1,208 +1,210 @@
import { basename, extname, join, relative } from "path/mod.ts"; import {join, extname, relative, basename} from "path/mod.ts";
import { readMarkdownDoc } from "./readDoc.ts"; import { readMarkdownDoc } from "./readDoc.ts";
import { Index } from "./client_search.ts"; import { Index } from "./client_search.ts";
export interface Doc { export interface Doc{
path: string; path: string;
content: string; content: string;
attributes: { attributes: {
title?: string; title?: string;
japanese_title?: string; japanese_title?: string;
tags?: string[]; tags?: string[];
rjcode?: string; rjcode?: string;
author?: string; author?: string;
}; };
} }
export async function loadDocuments(path: string): Promise<Doc[]> { export async function loadDocuments(path: string): Promise<Doc[]>{
const doc_json = await Deno.readTextFile(path); const doc_json = await Deno.readTextFile(path);
return JSON.parse(doc_json) as Doc[]; return JSON.parse(doc_json) as Doc[];
} }
export interface DocCollectorOptions { export interface DocCollectorOptions{
summaryOnly?: boolean; summaryOnly?: boolean;
dropContent?: boolean; dropContent?: boolean;
} }
export class DocCollector { export class DocCollector {
private doc_map: Map<string, Doc>; private doc_map: Map<string,Doc>;
private options: DocCollectorOptions; private options: DocCollectorOptions;
constructor(options: DocCollectorOptions = {}) { constructor(options: DocCollectorOptions = {}){
this.doc_map = new Map(); this.doc_map = new Map();
this.options = options; this.options = options;
}
public getDocs(): Doc[] {
return [...this.doc_map.values()];
}
public setDoc(doc: Doc) {
if (this.options.dropContent) {
doc.content = "";
}
this.doc_map.set(doc.path, doc);
}
public setDocs(docs: Doc[]) {
for (const doc of docs) {
this.setDoc(doc);
}
}
public removeDoc(path: string) {
this.doc_map.delete(path);
}
public async walkDir(path: string) {
const dir = Deno.readDir(path);
const fileList = [];
for await (const entry of dir) {
fileList.push(entry);
} }
if (fileList.some((entry) => entry.name === "SUMMARY.md")) { public getDocs(): Doc[]{
const { content, metadata } = await readMarkdownDoc( return [...this.doc_map.values()];
join(path, "SUMMARY.md"), }
);
this.setDoc({ public setDoc(doc: Doc){
path: join(path, "SUMMARY.md"), if (this.options.dropContent){
content: content, doc.content = "";
attributes: metadata,
});
} else {
for (const entry of fileList) {
if (entry.isDirectory) {
await this.walkDir(join(path, entry.name));
} else if (entry.isFile && !this.options.summaryOnly) {
const doc = await this.readDoc(join(path, entry.name));
this.setDoc(doc);
} }
} this.doc_map.set(doc.path,doc);
} }
} public setDocs(docs: Doc[]){
for (const doc of docs){
public async readDoc(path: string): Promise<Doc> {
const ext = extname(path);
if (ext === ".md") {
return await this.readMarkdown(path);
} else if (ext === ".html" || ext === ".htm" || ext === ".xhtml") {
return await this.readHTML(path);
} else if (ext === ".txt") {
return await this.readText(path);
} else {
return {
path: path,
content: "",
attributes: {},
};
}
}
public async readHTML(path: string): Promise<Doc> {
const content = await Deno.readTextFile(path);
return {
path: path,
content: content,
attributes: {},
};
}
public async readText(path: string): Promise<Doc> {
const content = await Deno.readTextFile(path);
return {
path: path,
content: content,
attributes: {},
};
}
public async readMarkdown(path: string): Promise<Doc> {
const { content, metadata } = await readMarkdownDoc(path);
return {
path: path,
content: content,
attributes: metadata,
};
}
async watchDir(path: string, {
onRemove = (_path: string) => {},
onAdd = (_doc: Doc) => {},
onChange = (_doc: Doc) => {},
abort = undefined,
}: {
onRemove?: (path: string) => void | Promise<void>;
onAdd?: (doc: Doc) => void | Promise<void>;
onChange?: (doc: Doc) => void | Promise<void>;
abort?: AbortSignal;
}) {
const watcher = Deno.watchFs(path);
if (abort) {
abort.addEventListener("abort", () => {
watcher.close();
});
}
for await (const event of watcher) {
if (
event.kind === "access" || event.kind === "other" ||
event.kind === "any"
) {
continue;
}
if (event.paths.length === 0) {
continue;
}
for (const path of event.paths) {
const relpath = relative(Deno.cwd(), path);
const filename = basename(relpath);
if (filename === "SUMMARY.md") {
if (event.kind === "remove") {
this.doc_map.delete(relpath);
await onRemove(relpath);
} else if (event.kind === "create" || event.kind === "modify") {
const { content, metadata } = await readMarkdownDoc(relpath);
const doc = {
path: relpath,
content: content,
attributes: metadata,
};
this.setDoc(doc); this.setDoc(doc);
if (event.kind === "create") {
await onAdd(doc);
} else if (event.kind === "modify") {
await onChange(doc);
}
}
} }
}
} }
} public removeDoc(path: string){
this.doc_map.delete(path);
}
makeIndex(options?: { public async walkDir(path: string){
onUpdate?: (() => void) | (() => Promise<void>); const dir = Deno.readDir(path);
abort?: AbortSignal; const fileList = [];
watch?: boolean; for await (const entry of dir){
}) { fileList.push(entry);
const opt = options ?? {}; }
const index = Index.createIndex(this.getDocs());
if (!opt.watch) { if (fileList.some((entry) => entry.name === "SUMMARY.md")){
return index; const {content, metadata} = await readMarkdownDoc(join(path, "SUMMARY.md"));
this.setDoc({
path: join(path, "SUMMARY.md"),
content: content,
attributes: metadata,
});
}
else {
for (const entry of fileList){
if (entry.isDirectory){
await this.walkDir(join(path, entry.name));
}
else if (entry.isFile && !this.options.summaryOnly){
const doc = await this.readDoc(join(path, entry.name));
this.setDoc(doc);
}
}
}
} }
const update = async () => {
index.setDocs(this.getDocs()); public async readDoc(path: string): Promise<Doc>{
if (opt.onUpdate) { const ext = extname(path);
await opt.onUpdate(); if (ext === ".md"){
} return await this.readMarkdown(path);
}; }
this.watchDir(".", { else if (ext === ".html" || ext === ".htm" || ext === ".xhtml"){
async onAdd(_doc) { return await this.readHTML(path);
await update(); }
}, else if (ext === ".txt"){
async onRemove(_path) { return await this.readText(path);
await update(); }
}, else {
async onChange(_doc) { return {
await update(); path: path,
}, content: "",
abort: opt.abort, attributes: {}
}); }
return index; }
} }
}
public async readHTML(path: string): Promise<Doc>{
const content = await Deno.readTextFile(path);
return {
path: path,
content: content,
attributes: {},
}
}
public async readText(path: string): Promise<Doc>{
const content = await Deno.readTextFile(path);
return {
path: path,
content: content,
attributes: {},
}
}
public async readMarkdown(path: string): Promise<Doc>{
const {content, metadata} = await readMarkdownDoc(path);
return {
path: path,
content: content,
attributes: metadata,
}
}
async watchDir(path: string, {
onRemove = (_path: string) => {},
onAdd = (_doc: Doc) => {},
onChange = (_doc: Doc) => {},
abort = undefined,
}:{
onRemove?: (path: string) => void | Promise<void>,
onAdd?: (doc: Doc) => void | Promise<void>,
onChange?: (doc: Doc) => void | Promise<void>,
abort?: AbortSignal,
}){
const watcher = Deno.watchFs(path);
if (abort){
abort.addEventListener("abort", () => {
watcher.close();
});
}
for await (const event of watcher){
if (event.kind === "access" || event.kind === "other" || event.kind === "any"){
continue;
}
if (event.paths.length === 0){
continue;
}
for (const path of event.paths){
const relpath = relative(Deno.cwd(), path);
const filename = basename(relpath);
if (filename === "SUMMARY.md"){
if( event.kind === "remove"){
this.doc_map.delete(relpath);
await onRemove(relpath);
}
else if (event.kind === "create" || event.kind === "modify"){
const {content, metadata} = await readMarkdownDoc(relpath);
const doc = {
path: relpath,
content: content,
attributes: metadata,
};
this.setDoc(doc);
if (event.kind === "create"){
await onAdd(doc);
}
else if (event.kind === "modify"){
await onChange(doc);
}
}
}
}
}
}
makeIndex(options? : {
onUpdate?: (() => void) | (() => Promise<void>),
abort?: AbortSignal,
watch?: boolean,
}){
const opt = options ?? {};
const index = Index.createIndex(this.getDocs());
if (!opt.watch){
return index;
}
const update = async () => {
index.setDocs(this.getDocs());
if (opt.onUpdate){
await opt.onUpdate();
}
}
this.watchDir(".", {
async onAdd(_doc){
await update();
},
async onRemove(_path){
await update();
},
async onChange(_doc){
await update();
},
abort: opt.abort,
});
return index;
}
}

View File

@ -1,59 +1,60 @@
const ICON_MAP: Record<string, string> = {
".pdf": "file-pdf",
".zip": "file-zip",
".rar": "file-zip",
".7z": "file-zip",
".tar": "file-zip",
".gz": "file-zip",
".bz2": "file-zip",
".xz": "file-zip",
".doc": "file-word",
".docx": "file-word",
".xls": "file-excel",
".xlsx": "file-excel",
".ppt": "file-ppt",
".pptx": "file-ppt",
".txt": "file-text",
".md": "filetype-md",
".html": "filetype-html",
".ts": "file-code",
".tsx": "filetype-tsx",
".js": "filetype-js",
".json": "filetype-json",
".jsx": "filetype-jsx",
".css": "filetype-css",
".scss": "filetype-scss",
".csv": "filetype-csv",
".xml": "filetype-xml",
".svg": "filetype-svg",
".mp3": "file-music",
".wav": "file-music",
".ogg": "file-music",
".flac": "file-music",
".mp4": "file-play",
".mkv": "file-play",
".avi": "file-play",
".mov": "file-play",
".wmv": "file-play",
".webm": "file-play",
".mpg": "file-play",
".mpeg": "file-play",
".flv": "file-play",
".m4v": "file-play",
".m4a": "file-play",
".aac": "file-play",
".jpg": "file-image",
".jpeg": "file-image",
".png": "file-image",
".gif": "file-image",
".bmp": "file-image",
".ico": "file-image",
".tiff": "file-image",
".tif": "file-image",
".webp": "file-image",
".psd": "file-image",
};
export function extToIcon(s: string): string { const ICON_MAP: Record<string, string> = {
return `/icon/${(ICON_MAP[s] ?? "file")}.svg`; ".pdf": "file-pdf",
".zip": "file-zip",
".rar": "file-zip",
".7z": "file-zip",
".tar": "file-zip",
".gz": "file-zip",
".bz2": "file-zip",
".xz": "file-zip",
".doc": "file-word",
".docx": "file-word",
".xls": "file-excel",
".xlsx": "file-excel",
".ppt": "file-ppt",
".pptx": "file-ppt",
".txt": "file-text",
".md": "filetype-md",
".html": "filetype-html",
".ts": "file-code",
".tsx": "filetype-tsx",
".js": "filetype-js",
".json": "filetype-json",
".jsx": "filetype-jsx",
".css": "filetype-css",
".scss": "filetype-scss",
".csv": "filetype-csv",
".xml": "filetype-xml",
".svg": "filetype-svg",
".mp3": "file-music",
".wav": "file-music",
".ogg": "file-music",
".flac": "file-music",
".mp4": "file-play",
".mkv": "file-play",
".avi": "file-play",
".mov": "file-play",
".wmv": "file-play",
".webm": "file-play",
".mpg": "file-play",
".mpeg": "file-play",
".flv": "file-play",
".m4v": "file-play",
".m4a": "file-play",
".aac": "file-play",
".jpg": "file-image",
".jpeg": "file-image",
".png": "file-image",
".gif": "file-image",
".bmp": "file-image",
".ico": "file-image",
".tiff": "file-image",
".tif": "file-image",
".webp": "file-image",
".psd": "file-image",
} }
export function extToIcon(s: string): string{
return `/icon/${(ICON_MAP[s] ?? "file")}.svg`;
}

View File

@ -1,41 +1,36 @@
import { import {parse as parseYaml, stringify} from "https://deno.land/std@0.170.0/encoding/yaml.ts";
parse as parseYaml,
stringify,
} from "https://deno.land/std@0.170.0/encoding/yaml.ts";
function trimSubstring(str: string, start: number, end: number) { function trimSubstring(str: string, start: number, end: number) {
while ( while (str[start] === ' ' || str[start] === '\t' || str[start] === '\r' || str[start] === '\n') {
str[start] === " " || str[start] === "\t" || str[start] === "\r" || start++;
str[start] === "\n" }
) { return str.substring(start, end);
start++;
}
return str.substring(start, end);
} }
interface Doc { interface Doc {
metadata: Record<string, string | string[]>; metadata: Record<string, string | string[]>;
content: string; content: string;
} }
export function parse(content: string): Doc { export function parse(content: string): Doc {
if (!content.startsWith("---")) { if(!content.startsWith('---')){
return {
metadata: {},
content: content,
}
}
const index = content.indexOf('\n---', 3);
const meta = content.substring(3, index);
const c = trimSubstring(content, index + 4, content.length);
const metadata = parseYaml(meta) as Record<string, string | string[]>;
return { return {
metadata: {}, metadata: metadata,
content: content, content: c,
}; }
}
const index = content.indexOf("\n---", 3);
const meta = content.substring(3, index);
const c = trimSubstring(content, index + 4, content.length);
const metadata = parseYaml(meta) as Record<string, string | string[]>;
return {
metadata: metadata,
content: c,
};
} }
export async function readMarkdownDoc(path: string): Promise<Doc> { export async function readMarkdownDoc(path: string): Promise<Doc> {
const doc = await Deno.readTextFile(path); const doc = await Deno.readTextFile(path);
return parse(doc); return parse(doc);
} }

View File

@ -1,43 +1,44 @@
import { Index } from "../client_search.ts"; import { Index } from "../client_search.ts";
import { Doc, DocCollector } from "../collect.ts"; import { Doc, DocCollector } from "../collect.ts";
export const docCollector = new DocCollector( export const docCollector = new DocCollector(
{ {
dropContent: true, dropContent: true,
summaryOnly: true, summaryOnly: true,
}, });
);
export let docIndex: Index | undefined = undefined; export let docIndex: Index | undefined = undefined;
export async function prepareDocs() { export async function prepareDocs() {
const docPath = Deno.env.get("COLLECT_DOC_PATH"); const docPath = Deno.env.get("COLLECT_DOC_PATH");
if (!docPath) { if (!docPath) {
await docCollector.walkDir("."); await docCollector.walkDir(".");
docIndex = docCollector.makeIndex({ docIndex = docCollector.makeIndex({
watch: true, watch: true
});
return docIndex;
}
try {
const doc_dump = await Deno.readTextFile(docPath);
const docs = JSON.parse(doc_dump) as Doc[];
docCollector.setDocs(docs);
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
await docCollector.walkDir(".");
await Deno.writeTextFile(docPath, JSON.stringify(docCollector.getDocs()));
}
else {
throw error;
}
}
docIndex = docCollector.makeIndex({
watch: true,
onUpdate: async () => {
await Deno.writeTextFile(docPath, JSON.stringify(docCollector.getDocs()));
}
}); });
return docIndex; return docIndex;
}
try {
const doc_dump = await Deno.readTextFile(docPath);
const docs = JSON.parse(doc_dump) as Doc[];
docCollector.setDocs(docs);
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
await docCollector.walkDir(".");
await Deno.writeTextFile(docPath, JSON.stringify(docCollector.getDocs()));
} else {
throw error;
}
}
docIndex = docCollector.makeIndex({
watch: true,
onUpdate: async () => {
await Deno.writeTextFile(docPath, JSON.stringify(docCollector.getDocs()));
},
});
return docIndex;
} }

View File

@ -1,13 +1,13 @@
import { DB } from "sqlite"; import {DB} from 'sqlite';
import { createSchema } from "./user.ts"; import {createSchema} from './user.ts';
export function connectDB(): DB { export function connectDB(): DB {
let DB_path = Deno.env.get("DB_PATH"); let DB_path = Deno.env.get("DB_PATH");
if (DB_path === undefined) { if (DB_path === undefined){
Deno.env.set("DB_PATH", "./db.sqlite"); Deno.env.set("DB_PATH", "./db.sqlite");
DB_path = "./db.sqlite"; DB_path = "./db.sqlite";
} }
let db = new DB(DB_path); let db = new DB(DB_path);
createSchema(db); createSchema(db);
return db; return db;
} }

View File

@ -1,74 +1,65 @@
import { compare, genSalt, hash } from "bcrypt"; import {genSalt, hash, compare} from "bcrypt";
import { DB } from "sqlite"; import { DB } from "sqlite";
interface User { interface User{
name: string; name: string;
salted_password: string; salted_password: string;
salt: string; salt: string;
} }
export async function createUser(name: string, password: string) { export async function createUser(name: string, password: string){
const salt = await genSalt(10); const salt = await genSalt(10);
const salted_password = await hash(password, salt); const salted_password = await hash(password, salt);
const user: User = { const user: User = {
name: name, name: name,
salted_password: salted_password, salted_password: salted_password,
salt: salt, salt: salt
}; }
return user; return user;
} }
export async function verifyUser(user: User, password: string) { export async function verifyUser(user: User, password: string){
return await compare(password, user.salted_password); return await compare(password, user.salted_password);
} }
export async function getAllUsers(db: DB): Promise<User[]> { export async function getAllUsers(db :DB): Promise<User[]>{
const users = await db.query<[string, string, string]>( const users = await db.query<[string, string, string]>
"SELECT name, salted_password, salt FROM users", ("SELECT name, salted_password, salt FROM users");
); return users.map(([name, salted_password, salt])=>({
return users.map(([name, salted_password, salt]) => ({ name,
name, salted_password,
salted_password, salt,
salt, }));
}));
} }
export async function getUser(db: DB, name: string): Promise<User | undefined> { export async function getUser(db: DB, name: string): Promise<User | undefined>{
const users = await db.query<[string, string, string]>( const users = await db.query<[string, string, string]>
"SELECT name, salted_password, salt FROM users WHERE name = ?", ("SELECT name, salted_password, salt FROM users WHERE name = ?", [name]);
[name], if (users === undefined || users.length === 0){
); return undefined;
if (users === undefined || users.length === 0) { }
return undefined; const user = users[0];
} return {
const user = users[0]; name: user[0],
return { salted_password: user[1],
name: user[0], salt: user[2],
salted_password: user[1], }
salt: user[2],
};
} }
export async function addUser(db: DB, user: User) { export async function addUser(db: DB, user: User){
await db.query( await db.query("INSERT INTO users (name, salted_password, salt) VALUES (?, ?, ?)",
"INSERT INTO users (name, salted_password, salt) VALUES (?, ?, ?)", [user.name, user.salted_password, user.salt]);
[user.name, user.salted_password, user.salt],
);
} }
export async function updateUser(db: DB, user: User) { export async function updateUser(db: DB, user: User){
await db.query( await db.query("UPDATE users SET salted_password = ?, salt = ? WHERE name = ?",
"UPDATE users SET salted_password = ?, salt = ? WHERE name = ?", [user.salted_password, user.salt, user.name]);
[user.salted_password, user.salt, user.name],
);
} }
export async function deleteUser(db: DB, name: string) { export async function deleteUser(db: DB, name: string){
await db.query("DELETE FROM users WHERE name = ?", [name]); await db.query("DELETE FROM users WHERE name = ?", [name]);
} }
export async function createSchema(db: DB) { export async function createSchema(db: DB){
await db.query( await db.query("CREATE TABLE IF NOT EXISTS users (name TEXT PRIMARY KEY, salted_password TEXT, salt TEXT)");
"CREATE TABLE IF NOT EXISTS users (name TEXT PRIMARY KEY, salted_password TEXT, salt TEXT)", }
);
}

View File

@ -1995,4 +1995,4 @@
"sina-weibo": 63690, "sina-weibo": 63690,
"tencent-qq": 63691, "tencent-qq": 63691,
"wikipedia": 63692 "wikipedia": 63692
} }

View File

@ -5,4 +5,4 @@ module.exports = {
extend: {}, extend: {},
}, },
plugins: [], plugins: [],
}; }

View File

@ -2,7 +2,6 @@
title: "hello" title: "hello"
tags: ["asdf","wer"] tags: ["asdf","wer"]
--- ---
# hello # hello
- [hello](hello.md) - [hello](hello.md)
@ -10,4 +9,4 @@ tags: ["asdf","wer"]
asdf asdf
File: test_data\d\hello.md File: test_data\d\hello.md

View File

@ -3,12 +3,8 @@ rjcode: RJ130512
title: Summary of the 13th Meeting of the Joint Committee on the Safety of Nuclear Installations title: Summary of the 13th Meeting of the Joint Committee on the Safety of Nuclear Installations
tags: ["summary", "meeting", "joint committee", "safety", "nuclear installations"] tags: ["summary", "meeting", "joint committee", "safety", "nuclear installations"]
--- ---
# Summary of the 13th Meeting of the Joint Committee on the Safety of Nuclear Installations # Summary of the 13th Meeting of the Joint Committee on the Safety of Nuclear Installations
## 1. Opening of the meeting ## 1. Opening of the meeting
The 13th meeting of the Joint Committee on the Safety of Nuclear Installations The 13th meeting of the Joint Committee on the Safety of Nuclear Installations (JCSNI) was held in Vienna on 12 May 2013. The meeting was chaired by Mr. J. M. Sánchez, Director of the Nuclear Safety Department of the Spanish Ministry of Industry, Energy and Tourism, and the Vice-Chairman of the JCSNI.
(JCSNI) was held in Vienna on 12 May 2013. The meeting was chaired by Mr. J. M.
Sánchez, Director of the Nuclear Safety Department of the Spanish Ministry of
Industry, Energy and Tourism, and the Vice-Chairman of the JCSNI.

View File

@ -3,4 +3,4 @@ title: "한글 테스트. 띄어쓰기없이도되나?"
tags: ["한글", "테스트"] tags: ["한글", "테스트"]
--- ---
# 한글 테스트. 띄어쓰기없이도되나? # 한글 테스트. 띄어쓰기없이도되나?

View File

@ -1,4 +0,0 @@
---
title: "SUMMARY"
tags: ["SUMMARY"]
---

119
user.ts
View File

@ -1,66 +1,63 @@
import { import { Command, Input, Secret } from "https://deno.land/x/cliffy@v0.25.6/mod.ts";
Command,
Input,
Secret,
} from "https://deno.land/x/cliffy@v0.25.6/mod.ts";
import { connectDB } from "./src/user/db.ts"; import { connectDB } from "./src/user/db.ts";
import * as users from "./src/user/user.ts"; import * as users from "./src/user/user.ts";
export const user_command = new Command() export const user_command = new Command()
.description("Manage users.") .description("Manage users.")
.command("add", "add a user") .command("add", "add a user")
.arguments("[username:string]") .arguments("[username:string]")
.option("-p, --password <password:string>", "The password for the user.") .option("-p, --password <password:string>", "The password for the user.")
.option("-q, --quiet", "quiet output.") .option("-q, --quiet", "quiet output.")
.action(async ({ quiet, password }, username) => { .action(async ({quiet, password}
if (username === undefined) { , username) => {
username = await Input.prompt("Username: "); if(username === undefined){
} username = await Input.prompt("Username: ");
if (password === undefined) { }
password = await Secret.prompt("Password: "); if(password === undefined){
const password2 = await Secret.prompt("Confirm password: "); password = await Secret.prompt("Password: ");
if (password !== password2) { const password2 = await Secret.prompt("Confirm password: ");
console.error("Passwords do not match."); if (password !== password2){
Deno.exit(1); console.error("Passwords do not match.");
} Deno.exit(1);
} }
const db = connectDB(); }
const new_user = await users.createUser(username, password); const db = connectDB();
await users.addUser(db, new_user); const new_user = await users.createUser( username, password);
if (!quiet) { await users.addUser(db, new_user);
console.log(`Added user ${username}`); if (!quiet){
} console.log(`Added user ${username}`);
}) }
.command("delete", "delete a user") })
.arguments("<username:string>") .command("delete", "delete a user")
.option("-q, --quiet", "Quiet output.") .arguments("<username:string>")
.action(async ({ quiet }, username) => { .option("-q, --quiet", "Quiet output.")
const db = connectDB(); .action(async ({quiet}, username) => {
await users.deleteUser(db, username); const db = connectDB();
if (!quiet) { await users.deleteUser(db, username);
console.log(`Deleting user ${username}`); if (!quiet){
} console.log(`Deleting user ${username}`);
}) }
.command("list", "list all users") })
.action(async () => { .command("list", "list all users")
const db = connectDB(); .action(async () => {
const all_users = await users.getAllUsers(db); const db = connectDB();
for (const user of all_users) { const all_users = await users.getAllUsers(db);
console.log(`${user.name}`); for (const user of all_users){
} console.log(`${user.name}`);
}) }
.command("reset", "reset a user's password") })
.arguments("<username:string> <password:string>") .command("reset", "reset a user's password")
.option("-q, --quiet", "quiet output.") .arguments("<username:string> <password:string>")
.action(async ({ quiet }, [username, password]) => { .option("-q, --quiet", "quiet output.")
const db = connectDB(); .action(async ({quiet}, [username, password]) => {
const new_user = await users.createUser(username, password); const db = connectDB();
await users.updateUser(db, new_user); const new_user = await users.createUser( username, password);
if (!quiet) { await users.updateUser(db, new_user);
console.log(`Resetting password for user ${username}`); if (!quiet){
} console.log(`Resetting password for user ${username}`);
}); }
});
if (import.meta.main) { if (import.meta.main){
await user_command.parse(Deno.args); await user_command.parse(Deno.args);
} }

View File

@ -1,31 +1,28 @@
export async function generateSecretKey() { export async function generateSecretKey() {
const key = await crypto.subtle.generateKey( const key = await crypto.subtle.generateKey(
{ name: "HMAC", hash: "SHA-512" },
true,
["sign", "verify"],
);
return key;
}
export async function prepareSecretKey() {
const key = Deno.env.get("SECRET_KEY");
if (key) {
const jwk = JSON.parse(key) as JsonWebKey;
{
const key = await crypto.subtle.importKey(
"jwk",
jwk,
{ name: "HMAC", hash: "SHA-512" }, { name: "HMAC", hash: "SHA-512" },
true, true,
["sign", "verify"], ["sign", "verify"],
); );
return key;
}
} else {
const key = await generateSecretKey();
const out = await crypto.subtle.exportKey("jwk", key);
Deno.env.set("SECRET_KEY", JSON.stringify(out));
return key; return key;
}
} }
export async function prepareSecretKey(){
const key = Deno.env.get("SECRET_KEY");
if (key){
const jwk = JSON.parse(key) as JsonWebKey;
{
const key = await crypto.subtle.importKey("jwk", jwk,
{ name: "HMAC", hash: "SHA-512" }, true, ["sign", "verify"]);
return key;
}
}
else {
const key = await generateSecretKey();
const out = await crypto.subtle.exportKey("jwk", key);
Deno.env.set("SECRET_KEY", JSON.stringify(out));
return key;
}
}

View File

@ -1,18 +1,15 @@
export function removePrefixFromPathname( export function removePrefixFromPathname(pathname: string, prefix: string): string {
pathname: string, let ret = pathname;
prefix: string, ret = ret.slice(prefix.length);
): string { if (ret.startsWith("/")) {
let ret = pathname; ret = ret.slice(1);
ret = ret.slice(prefix.length); }
if (ret.startsWith("/")) { if (ret === "") {
ret = ret.slice(1); ret = ".";
} }
if (ret === "") { return ret;
ret = ".";
}
return ret;
} }
export function encodePath(path: string): string { export function encodePath(path: string): string {
return path.split("/").map(encodeURIComponent).join("/"); return path.split("/").map(encodeURIComponent).join("/");
} }