FileSharer/index.js
2024-09-16 17:15:37 -05:00

140 lines
3.5 KiB
JavaScript

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}", "<h3>404: not found!</h3><a href='/'>Go to root</a>")
res.send(html)
return
}
addedHTML += `<h3>${dirContents.length} Files</h3>`.trim()
if (file != '') {
addedHTML += '<a href="../">Parent Directory</a><br>'
}
var dirs = []
var ogFolder = file
addedHTML += "<ul>"
for (let index = 0; index < dirContents.length; index++) {
const file = dirContents[index];
var userPath = path.join(ogFolder, file)
var fileStats = fs.statSync(path.join(absPath, file))
if (!fileStats.isDirectory()) {
addedHTML += `<li><a href="./${file}">${file}</a> | ${humanFileSize(fileStats.size)} | <a href="/download/${userPath}">download</a></li>`
} else {
dirs.push(file)
}
}
for (let index = 0; index < dirs.length; index++) {
const file = dirs[index];
var fileStats = fs.statSync(path.join(absPath, file))
addedHTML += `<li><a href="./${file}">./${file}/</a></li>`
}
// res.write(`<a href="./${file}">./${file}/</a><br>`)
addedHTML += "</ul>"
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}`,
);
});