qonq/qonq.js

80 lines
2.8 KiB
JavaScript

require("dotenv").config();
var colors = require("colors");
var express = require("express");
var serveIndex = require("serve-index");
var serveFavicon = require("serve-favicon");
var path = require("path");
var fs = require("fs");
try { var customGen = require("./customGen"); } catch(e) {}
var FILES_DIR = process.env.FILES_DIR || "files";
var app = express();
app.set("env", "production");
app.set('trust proxy', process.env.TRUST_PROXY || "loopback");
app.listen(process.env.PORT || 8568, process.env.ADDRESS);
app.use((req,res,next) => { res.header("Access-Control-Allow-Origin", '*'); next(); });
app.use((req, res, next)=>{
var d = new Date;
res.on("finish", () => {
var sc = res.statusCode.toString(), sc = sc.startsWith('2') ? sc.green : sc.startsWith('3') ? sc.cyan : sc.startsWith('4') ? sc.red : sc.startsWith('5') ? sc.yellow.bgRed : sc;
console.log(`${`[${d.toISOString()}]`.magenta} ${req.ip.cyan} ${req.method.bold.yellow} ${req.hostname}${req.url} ${sc} ${`"${req.headers["user-agent"]}"`.gray} ${Date.now()-d}ms`);
});
next();
});
app.use(serveFavicon("favicon.ico"));
app.post("*", (req, res, next) => {
if (req.headers.authentication != process.env.AUTH_TOKEN) return void res.status(403).send("Unauthorized");
(function trymkdir() {
if (customGen) {
var g = customGen(req);
var filecode = g.next().value;
}
filecode ||= Math.random().toString(36).slice(2).substring(0,4);
var webroot = path.join(FILES_DIR, filecode);
fs.mkdir(webroot, function (error) {
if (error) if (error.code == "EEXIST") {
console.log("oof");
trymkdir();
} else next(error);
else {
var filename = req.headers.filename || "file";
var filepath = path.join(webroot, filename);
req.pipe(fs.createWriteStream(filepath));
req.on("close", () => {
var url = g?.next().value || `${req.protocol}://${filecode}.${process.env.BASE_HOSTNAME || req.hostname}`;
res.type('text').send(url);
require("./discord-preloader.js")(url);
});
}
});
})();
});
app.use(require("./antiscrape"));
app.get(['/', '/:code/', '/:code/*'], function(req, res, next){
var subdomain = req.subdomains.at(-1);
req.filecode = subdomain || req.params.code;
if (!req.filecode) req.filecode = "www";
var webroot = path.join(FILES_DIR, req.filecode);
fs.readdir(webroot, function(error, webrootdirlist) {
if (error) return void next(error.code == "ENOENT" ? "route" : error);
if (webrootdirlist.length > 1) {
if (subdomain) req.url = path.join(req.filecode, req.url);
next();
} else if (webrootdirlist.length == 1) {
res.sendFile(webrootdirlist[0], {
root: path.join(process.cwd(), webroot),
headers: {"Content-Disposition": `filename=${webrootdirlist[0]}`}
});
} else {
res.sendStatus(204);
}
});
}, express.static(FILES_DIR), serveIndex(FILES_DIR, {icons: true}));