Violets-Purgatory/pageUpdater.js

271 lines
8.9 KiB
JavaScript
Raw Normal View History

2024-02-08 12:30:38 -06:00
const path = require('path'),
2024-02-12 08:46:49 -06:00
fs = require('fs'),
WebSocket = require('ws'),
2024-02-18 08:01:58 -06:00
minify = require('minify-html'),
2024-03-03 23:57:30 -06:00
activityToHTML = require("./overcomplicatedStatuses.js"),
weatherGenerator = require("./weatherGenerator")
2024-02-08 12:30:38 -06:00
var config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json')))
2024-02-08 17:52:26 -06:00
2024-02-08 12:30:38 -06:00
var highlightedWords = config.highlightedWords
2024-02-08 17:52:26 -06:00
var quotes = config.quotes
2024-02-08 18:28:33 -06:00
var titles = config.titles
2024-02-08 12:30:38 -06:00
2024-03-03 21:51:28 -06:00
var commitCount = "400+"
2024-02-08 17:28:17 -06:00
2024-02-12 08:46:49 -06:00
var lanyardData = undefined
2024-02-08 16:03:40 -06:00
2024-02-12 08:46:49 -06:00
var uptime = Date.now()
2024-02-08 16:03:40 -06:00
2024-03-03 23:57:30 -06:00
function converter(html, query) {
2024-02-18 08:01:58 -06:00
while (html.includes("{PATH_")) {
var pagePath = html.substring(html.indexOf("{PATH_"))
pagePath = pagePath.substring(6, pagePath.indexOf('}'))
var stringIndex = `{PATH_${pagePath}}`
pagePath = pagePath.toLowerCase()
var pageHTML = fs.readFileSync(path.join(__dirname, 'static', pagePath, 'index.html')).toString()
pageHTML = pageHTML.substring(pageHTML.indexOf('<main>') + 6, pageHTML.indexOf('</main>'))
html = html.replace(stringIndex, pageHTML)
}
var statusText = ""
2024-02-12 08:46:49 -06:00
if (lanyardData) {
var statusData = config.discStatuses[lanyardData.discord_status]
2024-02-18 08:01:58 -06:00
var username = lanyardData.discord_user.username
if (lanyardData.activities[0] && lanyardData.activities[0].type == 4) {
var statusText = `<hr><p>${lanyardData.activities[0].state}</p>`
}
2024-02-12 08:46:49 -06:00
} else {
var statusData = config.discStatuses.offline
2024-02-18 08:01:58 -06:00
var username = "bingus_violet"
2024-02-12 08:46:49 -06:00
}
2024-02-18 08:01:58 -06:00
2024-03-03 23:57:30 -06:00
var time = new Date(Date.now())
2024-02-12 08:46:49 -06:00
var replacers = {
"COMMIT_COUNT": commitCount,
"RANDOM_QUOTE": quotes[Math.floor(Math.random() * quotes.length)],
"QUOTE_COUNT": quotes.length,
"RANDOM_TITLE": titles[Math.floor(Math.random() * titles.length)],
"DISCORD_STATUS":
`<span style="color: ${statusData.color};">${statusData.text}</span>` +
2024-02-12 15:52:17 -06:00
`<style>.pfp { border-color: ${statusData.color} }</style>`,
"UPTIME": uptime,
2024-02-18 08:01:58 -06:00
"TOPBAR": `<div id="topbar"><h3><a href="/socials">Socials</a></h3></div>`,
"DISCORD_USER": username,
2024-02-28 19:02:30 -06:00
"CUSTOM_STATUS": statusText
2024-02-12 08:46:49 -06:00
}
2024-02-08 17:52:26 -06:00
2024-02-12 08:46:49 -06:00
var rpTable = Object.keys(replacers)
2024-02-08 17:52:26 -06:00
2024-02-12 08:46:49 -06:00
for (let index = 0; index < rpTable.length; index++) {
const text = rpTable[index];
html = html.replaceAll(`{${text}}`, replacers[text])
}
2024-02-08 18:28:33 -06:00
var bodyHTML = html.substring(html.indexOf("<body>") + 6, html.lastIndexOf("</body>"))
var highTable = Object.keys(highlightedWords)
for (let index = 0; index < highTable.length; index++) {
var term = highTable[index];
var replacement = `<span style="color: ${highlightedWords[term]}">${term}</span>`
bodyHTML = bodyHTML.replaceAll(`{${term}}`, "TEMPORARY_REPLACE")
bodyHTML = bodyHTML.replaceAll(term, replacement)
2024-02-13 08:57:08 -06:00
bodyHTML = bodyHTML.replaceAll("TEMPORARY_REPLACE", `${term}`)
}
2024-02-28 19:02:30 -06:00
bodyHTML = bodyHTML.replaceAll("{ACTIVITIES}", activityToHTML.activitiesToHTML(lanyardData, cachedImages))
html = html.substring(0, html.indexOf("<body>")) + bodyHTML + html.substring(html.indexOf("</body>") + 7)
2024-03-23 01:24:58 -05:00
var weathers = ["rain", "none"]
2024-03-03 23:57:30 -06:00
var weather = weathers[time.getDate() % weathers.length]
2024-03-03 23:59:29 -06:00
if (weather == "rain" || "rain" in query || "hardRain" in query) {
2024-03-03 23:57:30 -06:00
html = html.replaceAll("{WEATHER_MODIFIER}", weatherGenerator.makeRain("hardRain" in query))
html = html.replaceAll("{WEATHER_TEXT}", `The rain is so pretty... <a href="?hardRain">I wish I saw it more...</a>`)
} else {
html = html.replaceAll("{WEATHER_MODIFIER}", "")
html = html.replaceAll("{WEATHER_TEXT}", "")
}
2024-02-08 12:30:38 -06:00
return html
}
2024-02-08 17:30:52 -06:00
module.exports = {
2024-03-08 10:49:47 -06:00
getActivities: function () {
return activityToHTML.activitiesToHTML(lanyardData, cachedImages)
},
2024-02-08 17:30:52 -06:00
middleWare: function (req, res, next) {
2024-02-12 11:12:15 -06:00
var filePath = (req.baseUrl + req.path).trim()
2024-02-18 08:01:58 -06:00
if (filePath.includes("cached") || filePath.includes("imgs")) {
filePath = path.join(__dirname, 'static', filePath)
res.send(fs.readFileSync(filePath))
return
}
if (filePath.includes(".")) {
2024-02-12 11:12:15 -06:00
} else {
if (filePath.charAt(filePath.length - 1) != '/') {
res.redirect(filePath + '/')
return
}
filePath = path.join(filePath, '/index.html')
2024-02-08 17:30:52 -06:00
}
2024-02-12 11:12:15 -06:00
2024-02-08 17:30:52 -06:00
filePath = path.join(__dirname, 'static', filePath || 'index.html')
if (fs.existsSync(filePath)) {
var data = fs.readFileSync(filePath).toString()
2024-03-30 01:26:45 -05:00
res.contentType(path.basename(filePath))
// if (req.path.includes(".css")) {
// res.setHeader("Content-Type", "text/css")
// } else if (!req.path.includes(".woff2")) {
// data = converter(data, req.query)
// }
if (filePath.includes(".html")) {
2024-03-03 23:57:30 -06:00
data = converter(data, req.query)
2024-02-08 17:30:52 -06:00
}
2024-03-30 01:26:45 -05:00
res.send(data)
2024-02-08 17:30:52 -06:00
} else {
res.status(404).send(`
2024-02-12 15:51:12 -06:00
<link rel="stylesheet" href="/style.css">
<h1>404</h1>
<p>Uh oh... I think your lost? There's nothing here :P</p>
2024-02-08 17:30:52 -06:00
`)
}
2024-02-08 12:30:38 -06:00
}
}
2024-02-08 17:28:17 -06:00
async function updateCommits() {
var codebergResponse = await (await fetch(`https://codeberg.org/Bingus_Violet/Violets-Purgatory/src/branch/${process.env.BRANCH || "origin"}`)).text()
var commits = codebergResponse.substring(0, codebergResponse.indexOf("Commits"))
commits = commits.substring(commits.lastIndexOf("<b>") + 3, commits.lastIndexOf("</b>"))
commitCount = commits
}
2024-02-12 08:46:49 -06:00
updateCommits()
// Lanyard Stuffs
var lastLanyardUpdate = Date.now()
var lastPong = 0
2024-02-12 08:46:49 -06:00
var activityImages = config.activityImages
var cachedImages = {}
function get_img_url(activity, size = "large_image") {
if ("assets" in activity) {
var image = activity.assets[size]
if (image) {
if (image.includes("https/")) {
return decodeURIComponent('https://' + image.substr(image.indexOf('https/') + 6, image.length))
} else if (image.includes("spotify")) {
return decodeURIComponent('https://i.scdn.co/image/' + image.substr(image.indexOf('spotify:') + 8, image.length))
2024-03-24 16:54:09 -05:00
} else {
return decodeURIComponent('https://cdn.discordapp.com/app-assets/' + activity.application_id + "/" + image + ".png")
2024-02-12 08:46:49 -06:00
}
2024-03-24 16:55:00 -05:00
}
2024-02-12 08:46:49 -06:00
}
if (!image && size == "large_image") {
2024-02-12 08:46:49 -06:00
if (activity.name in activityImages) {
return decodeURIComponent(activityImages[activity.name])
}
}
return null
2024-02-12 08:46:49 -06:00
}
function socketeer() {
var lanyard = new WebSocket('https://api.violets-purgatory.dev')
lanyard.on("error", (error) =>{
console.log(error)
})
lanyard.on("close", () => {
console.log("Connection Closed. Attempting Reconnect in 30 seconds.")
setTimeout(() => {
socketeer()
}, 3000);
})
2024-02-12 08:46:49 -06:00
function ping(dur) {
lanyard.send(JSON.stringify({
op: 3
}))
setTimeout(() => {
ping(dur)
if (Date.now() - lastPong > 120000) {
lanyard.close()
console.log("Max duration since last pong exceeded- Closing socket.")
2024-02-12 08:46:49 -06:00
}
}, dur);
}
lanyard.addEventListener("message", async (res) => {
var data = JSON.parse(res.data)
2024-03-18 21:22:32 -05:00
// console.log(data.op)
2024-02-12 08:46:49 -06:00
if (data.op == 1) {
console.log("Connected to Discord Websocket!")
2024-02-12 08:46:49 -06:00
ping(30000)
lastPong = Date.now()
2024-03-18 21:22:32 -05:00
} else if (data.op == 3) {
lastPong = Date.now()
2024-02-12 08:46:49 -06:00
} else if (data.op == 0) {
lanyardData = data.d
lastLanyardUpdate = Date.now()
for (let index = 0; index < lanyardData.activities.length; index++) {
const activity = lanyardData.activities[index];
if (get_img_url(activity)) {
var url = get_img_url(activity)
var fn = Math.ceil(Math.random() * 100_000_000_000).toString()
var fp = path.join(__dirname, 'static/cached', fn)
if (!cachedImages[url]) {
const response = await (await fetch(url)).arrayBuffer()
fs.writeFileSync(fp, Buffer.from(response))
cachedImages[url] = fn
}
}
if (get_img_url(activity, "small_image")) {
var url = get_img_url(activity, "small_image")
var fn = Math.ceil(Math.random() * 100_000_000_000).toString()
var fp = path.join(__dirname, 'static/cached', fn)
if (!cachedImages[url]) {
const response = await (await fetch(url)).arrayBuffer()
fs.writeFileSync(fp, Buffer.from(response))
cachedImages[url] = fn
}
}
}
}
})
}
socketeer()