astronomical-theater/handlers/static.js

52 lines
1.7 KiB
JavaScript

import * as path from "path"
import * as fs from "fs";
import DefaultHandler from "./default.js";
export default class StaticHandler extends DefaultHandler {
constructor(basePath, directoryList = false) {
super();
this.basePath = basePath;
this.directoryList = directoryList;
//This will throw if the file doesn't exist
this.isSingleFile = !fs.statSync(basePath).isDirectory();
this.matchesSubpaths = !this.isSingleFile;
}
// This is the handler
// url is the URL object, with url.pathname being the path. p is the 'client-side' basepath
handle (url, p) {
const relativePath = path.relative(p, url.pathname);
//Concat and normalize the passed URL as being relative to the base path
const toServe = path.join(this.basePath, relativePath);
//If the resulting path is a parent, relative to basePath, disallow that
if (path.relative(this.basePath, toServe).startsWith("..")) {
return "50"
}
console.log(`Attempting to serve ${toServe}.`);
try {
if (fs.statSync(toServe).isDirectory()) {
console.log(`File is a directory and directoryList is ${this.directoryList}.`);
if (this.directoryList) {
} else {
return "51 Not Found\r\n";
}
}
}catch (e) {
//If the file doesn't exist
console.log(`File doesn't exist or can't be opened.`)
return "51 Not Found\r\n";
}
//TODO: import mmmagic
//TODO: convert line endings
const data = fs.readFileSync(toServe);
return "20 text/gemini\r\n" + data;
}
}