QuickURL/shortener.js
2024-07-13 06:14:13 -05:00

88 lines
No EOL
2.5 KiB
JavaScript

const expressHandler = require("./expressHandler"),
fileHandler = require("./fileHandler.js")
paths = fileHandler.paths,
fs = require("fs")
const app = expressHandler.app
app.get("/makeURL", (req, res) => {
function writep(inp) {
return res.write("<p>" + inp + "</p>")
}
function finishHtml() {
res.write(html.substring(html.indexOf("{CONTENT}") + 9), () => {
res.end()
})
}
res.setHeader("X-Accel-Buffering", "no")
var html = fs.readFileSync(paths.postUrl).toString()
res.write(html.substring(0, html.indexOf("{CONTENT}")))
var config = fileHandler.config
writep("HTML Loaded.")
var url = req.query.url
if (!url.includes("http://") && !url.includes("https://")) {
writep("Error: URL is missing protocol! Please include http:// or https:// in the URL for it to be valid.")
finishHtml()
return
}
var domain = url.substring(url.indexOf("://") + 3)
if (domain.charAt(-1) != "/") {
domain += "/"
}
domain = domain.substring(0, domain.indexOf("/"))
domain = domain.substring(domain.lastIndexOf(".", domain.lastIndexOf(".") - 1) + 1).toLowerCase()
writep("Input URL: " + url)
writep("Domain: " + domain)
var trust = config.trust.includes(domain)
var blacklisted = config.blacklist.includes(domain)
writep("Domain on blacklist: " + blacklisted)
writep("Domain on trust list: " + trust)
if (blacklisted) {
writep("Error: Domain found on the blacklist! This URL is not allowed.")
finishHtml()
return
}
var shortURL = fileHandler.writeUrls({
"trusted": trust,
"expire": Date.now() + (7 * 24 * 60 * 60 * 1000),
"url": url
})
writep(`Done! Find your URL at: <a href="https://${fileHandler.config.domain}/url/${shortURL.shortCode}">${fileHandler.config.domain + "/url/" + shortURL.shortCode}</a><br>It will expire in 7 days!`)
finishHtml()
})
app.get("/url/:shortCode*", (req, res) => {
var shortCode = req.params.shortCode
var urls = fileHandler.urls
for (var i in urls) {
var data = urls[i]
if (data.shortCode == shortCode) {
if (data.trusted) {
res.redirect(data.url)
} else {
var html = fs.readFileSync(paths.redirWarn).toString()
html = html.replaceAll("{REDIRECT_URL}", data.url)
res.send(html)
}
continue
}
}
})