const express = require("express"), fs = require("fs"), path = require("path") var app = express() var PORT = process.env.PORT || 8080 var directory = process.env.FILES_DIR var pubDir = path.join(directory, 'public') var privDir = path.join(directory, 'private') function humanFileSize(bytes, si = false, dp = 1) { const thresh = si ? 1000 : 1024; if (Math.abs(bytes) < thresh) { return bytes + ' B'; } const units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; let u = -1; const r = 10 ** dp; do { bytes /= thresh; ++u; } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1); return bytes.toFixed(dp) + ' ' + units[u]; } if (!directory) { console.error("No directory specified! Please specify one using the environment variable FILES_DIR.") return } const videoFormats = ["mp4", "mkv", "webm"] app.use(express.static(privDir)) app.use(express.static(pubDir)) app.use(express.static(path.join(__dirname, 'resources'))) app.listen(PORT, () => { console.log("Now listening on PORT: " + PORT) }) app.get("/download/*", (req, res) => { var download = req.params[0] var downloadPath = path.join(directory, download) var downloadName = downloadPath.substring(downloadPath.lastIndexOf("/")) if (!fs.existsSync(downloadPath)) { downloadPath = path.join(pubDir, download) } res.setHeader('Content-disposition', `attachment; filename=${downloadName}`); var stream = fs.createReadStream(downloadPath) stream.pipe(res) }) app.get("/watch/*", (req, res) => { res.redirect("/" + req.params[0]) }) app.get("/*", (req, res) => { var file = req.params[0] var absPath = path.join(pubDir, file) var html = fs.readFileSync(path.join(__dirname, 'resources/base.html')).toString() res.setHeader('Content-Type', 'text/html') var addedHTML = "" html = html.replace("{TITLE}", '/' + file) try { var dirContents = fs.readdirSync(absPath) var dirStats = fs.statSync(absPath) } catch (error) { html = html.replace("{CONTENT}", "

404: not found!

Go to root") res.send(html) return } addedHTML += `

${dirContents.length} Files

`.trim() if (file != '') { addedHTML += 'Parent Directory
' } var dirs = [] var ogFolder = file addedHTML += "" html = html.replace("{CONTENT}", addedHTML) res.write(html, () => { res.end() }) }) process.on('uncaughtException', (err, origin) => { fs.writeSync( process.stderr.fd, `Caught exception: ${err}\n` + `Exception origin: ${origin}`, ); });