Violets-Purgatory/api.js

126 lines
3.3 KiB
JavaScript
Raw Normal View History

2024-06-25 01:02:28 -05:00
const path = require("path"),
fs = require("fs"),
WebSocket = require('ws'),
EventEmitter = require("events").EventEmitter
const events = new EventEmitter();
const constants = JSON.parse(fs.readFileSync(path.join(__dirname, "constants.json")))
var lastPong = 0
module.exports = {
"lanyard": undefined,
"socials": undefined,
2024-06-25 01:02:28 -05:00
"connected": false,
"lastLanyardUpdate": Date.now(),
2024-07-07 23:33:16 -05:00
"blogConnected": false,
"blogPosts": undefined,
2024-06-25 01:02:28 -05:00
"events": events,
"spins": 0,
}
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.")
module.exports.lanyard = constants.fallbackLanyard
2024-06-25 01:05:18 -05:00
module.exports.connected = false
2024-06-25 01:02:28 -05:00
setTimeout(() => {
socketeer()
}, 30000);
})
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.")
}
}, dur);
}
lanyard.addEventListener("message", async (res) => {
var data = JSON.parse(res.data)
// console.log(data.op)
if (data.op == 1) {
console.log("Connected to Discord Websocket!")
2024-06-25 01:05:18 -05:00
module.exports.connected = true
2024-06-25 01:02:28 -05:00
ping(30000)
lastPong = Date.now()
events.emit("lanyardConnect")
2024-06-25 01:02:28 -05:00
} else if (data.op == 3) {
lastPong = Date.now()
} else if (data.op == 0) {
module.exports.lanyard = data.d
module.exports.lastLanyardUpdate = Date.now()
events.emit("lanyardUpdate")
} else if (data.op == 4) {
module.exports.spins = data.spins
}
})
}
2024-07-07 23:33:16 -05:00
socketeer()
function blogSocket() {
var blog = new WebSocket('https://blog.violets-purgatory.dev')
blog.on("error", (error) => {
console.log(error)
})
blog.on("close", () => {
console.log("Connection Closed. Attempting Reconnect in 30 seconds.")
module.exports.blogConnected = false
setTimeout(() => {
blogSocket()
}, 30000);
})
function ping(dur) {
blog.send(JSON.stringify({
type: "ping"
}))
setTimeout(() => {
ping(dur)
if (Date.now() - lastPong > 120000) {
blog.close()
console.log("Max duration since last pong exceeded- Closing socket.")
}
}, dur);
}
blog.addEventListener("message", async (res) => {
var data = JSON.parse(res.data)
if (data.type == "init") {
console.log("Connected to Blog Websocket!")
module.exports.blogConnected = true
ping(30000)
lastPong = Date.now()
events.emit("blogConnect")
} else if (data.type == "ping") {
lastPong = Date.now()
} else if (data.type == "allPosts") {
console.log("Recieved posts!")
module.exports.blogPosts = data.data
events.emit("blogUpdate")
} else {
console.log(data)
}
})
}
blogSocket()