improve blogpost and disable cider
This commit is contained in:
@@ -7,19 +7,33 @@ app.get("/blogposts", (rreq, rres) => {
|
|||||||
|
|
||||||
if (Date.now() < timeSinceLastQuery+10000) { // if it has been <10 seconds since last request
|
if (Date.now() < timeSinceLastQuery+10000) { // if it has been <10 seconds since last request
|
||||||
rres.set("Access-Control-Allow-Origin","*")
|
rres.set("Access-Control-Allow-Origin","*")
|
||||||
rres.send(cachedResult) // send cached json
|
|
||||||
|
if (rreq.query.format === "html") { // if ?format=html then send HTML
|
||||||
|
rres.send(cachedResult.asHtml)
|
||||||
|
} else { // otherwise send json
|
||||||
|
rres.send(cachedResult.asJson)
|
||||||
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
timeSinceLastQuery = Date.now()
|
timeSinceLastQuery = Date.now()
|
||||||
cachedResult = parseFiles()
|
cachedResult = parseFiles()
|
||||||
rres.set("Access-Control-Allow-Origin","*")
|
rres.set("Access-Control-Allow-Origin","*")
|
||||||
rres.send(cachedResult);
|
|
||||||
|
if (rreq.query.format === "html") { // if ?format=html then send HTML
|
||||||
|
rres.send(cachedResult.asHtml)
|
||||||
|
} else { // otherwise send json
|
||||||
|
rres.send(cachedResult.asJson)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
function parseFiles() {
|
function parseFiles() {
|
||||||
let files = fs.readdirSync(globalConfig.blog.postsDirectory)
|
let files = fs.readdirSync(globalConfig.blog.postsDirectory)
|
||||||
let parsedFiles = []
|
let result = {
|
||||||
|
asJson: [],
|
||||||
|
asHtml: ""
|
||||||
|
}
|
||||||
|
|
||||||
for (x in files) {
|
for (x in files) {
|
||||||
if (files[x].endsWith(".html") === false) { break } // If file/dir is not .html then ignore
|
if (files[x].endsWith(".html") === false) { break } // If file/dir is not .html then ignore
|
||||||
@@ -29,12 +43,13 @@ function parseFiles() {
|
|||||||
|
|
||||||
date = date.replace(/.{2}/g,"$&-").replace("-","").slice(0,-1) // Insert a dash every 2 characters, remove the first dash, remove the last character
|
date = date.replace(/.{2}/g,"$&-").replace("-","").slice(0,-1) // Insert a dash every 2 characters, remove the first dash, remove the last character
|
||||||
|
|
||||||
let name = files[x].slice(9).replace(/÷/g," ").replace(".html","") // Strip Date, replace seperator with space & remove file extension
|
let name = files[x].slice(9).replace(/-/g," ").replace(".html","") // Strip Date, replace seperator with space & remove file extension
|
||||||
|
|
||||||
parsedFiles.push({ "date": date, "name": name, "path": `${globalConfig.blog.postsDirUrl}/${files[x]}`}) // Add metadata as JSON to array
|
result.asJson.unshift({ "date": date, "name": name, "path": `${globalConfig.blog.postsDirUrl}/${files[x]}`}) // Add to asJson array in the result
|
||||||
|
result.asHtml = `<span>${date} <a href="${globalConfig.blog.postsDirUrl}/${files[x]}">${name}</a></span>`+result.asHtml
|
||||||
}
|
}
|
||||||
|
|
||||||
return parsedFiles.reverse()
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {app}
|
module.exports = {app}
|
||||||
154
routes/cider.js
154
routes/cider.js
@@ -2,87 +2,99 @@ const { app, db, globalConfig } = require("../index.js") // Get globals from ind
|
|||||||
|
|
||||||
var timeSinceLastCiderQuery = Date.now()-2000;
|
var timeSinceLastCiderQuery = Date.now()-2000;
|
||||||
var currentListening = {}
|
var currentListening = {}
|
||||||
|
var currentListeningHtml = ""
|
||||||
|
|
||||||
app.get("/cider", (rreq,rres) => { // GET current listening from target
|
app.get("/cider", (rreq,rres) => {
|
||||||
|
rres.send("<span>Cider endpoint is temporarily unavailable.")
|
||||||
if (Date.now() < timeSinceLastCiderQuery+2000) {
|
|
||||||
rres.send(currentListening); // If it has been <2 seconds since the last request, return the cached result.
|
|
||||||
} else {
|
|
||||||
getCurrentListening(globalConfig.cider.targetHosts[0]).then(funcRes => {
|
|
||||||
if (funcRes == 1) {
|
|
||||||
rres.sendStatus(503) // If there was a problem getting the upstream JSON, return 503 Service Unavailable.
|
|
||||||
} else {
|
|
||||||
rres.set("Access-Control-Allow-Origin","*") // Required (I think?) because of CORS.
|
|
||||||
currentListening = funcRes
|
|
||||||
rres.send(funcRes)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// app.get("/cider", (rreq,rres) => { // GET current listening from target
|
||||||
|
|
||||||
app.post("/cider", (rreq,rres) => { // POST stop listening on cider target
|
// if (Date.now() < timeSinceLastCiderQuery+2000) {
|
||||||
|
// rres.send(currentListening); // If it has been <2 seconds since the last request, return the cached result.
|
||||||
|
// } else {
|
||||||
|
// getCurrentListening(globalConfig.cider.targetHosts[0],"json").then(funcRes => {
|
||||||
|
// if (funcRes == 1) {
|
||||||
|
// rres.sendStatus(503) // If there was a problem getting the upstream JSON, return 503 Service Unavailable.
|
||||||
|
// } else {
|
||||||
|
// rres.set("Access-Control-Allow-Origin","*") // Required (I think?) because of CORS.
|
||||||
|
// currentListening = funcRes
|
||||||
|
// rres.send(funcRes)
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
|
||||||
fetch(`http://${globalConfig.couchdb.host}/apiauthkeys/${globalConfig.cider.authKeysDoc}`, {
|
// })
|
||||||
headers: {
|
|
||||||
"Authorization": `Basic ${btoa(globalConfig.couchdb.authorization)}`
|
|
||||||
}
|
|
||||||
}).then(dbRes => dbRes.json()).then(dbRes => {
|
|
||||||
|
|
||||||
if (dbRes.status == 404) { // If document containing cider auth keys does not exist
|
// app.post("/cider", (rreq,rres) => { // POST stop listening on cider target
|
||||||
console.log(`ERROR: Could not find apiauthkeys/${globalConfig.mailjet.authKeysDoc}`)
|
|
||||||
rres.sendStatus(500) // Refuse request
|
|
||||||
} else {
|
|
||||||
if (dbRes["content"][rreq.get("Authorization").split("_")[0]] === rreq.get("Authorization").split("_")[1]) {
|
|
||||||
|
|
||||||
fetch(`http://${globalConfig.cider.targetHosts[0]}/stop`).then(fres => { // send GET /stop to cider target
|
// fetch(`http://${globalConfig.couchdb.host}/apiauthkeys/${globalConfig.cider.authKeysDoc}`, {
|
||||||
if (fres.status == 204) {
|
// headers: {
|
||||||
console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 200 KEY:${rreq.get("Authorization")}`)
|
// "Authorization": `Basic ${btoa(globalConfig.couchdb.authorization)}`
|
||||||
rres.sendStatus(200) // if that works then 200
|
// }
|
||||||
} else {
|
// }).then(dbRes => dbRes.json()).then(dbRes => {
|
||||||
rres.sendStatus(500) // otherwise lol
|
|
||||||
}
|
|
||||||
}).catch(ferror => {
|
|
||||||
rres.sendStatus(503) // and if a problem happens its probably cause cider target is unavailable
|
|
||||||
})
|
|
||||||
|
|
||||||
} else {
|
// if (dbRes.status == 404) { // If document containing cider auth keys does not exist
|
||||||
console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 401`) // log ip of unauthorized requests
|
// console.log(`ERROR: Could not find apiauthkeys/${globalConfig.mailjet.authKeysDoc}`)
|
||||||
rres.sendStatus(401) // received auth key was not in database
|
// rres.sendStatus(500) // Refuse request
|
||||||
}
|
// } else {
|
||||||
}
|
// if (dbRes["content"][rreq.get("Authorization").split("_")[0]] === rreq.get("Authorization").split("_")[1]) {
|
||||||
})
|
|
||||||
|
|
||||||
})
|
// fetch(`http://${globalConfig.cider.targetHosts[0]}/stop`).then(fres => { // send GET /stop to cider target
|
||||||
|
// if (fres.status == 204) {
|
||||||
|
// console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 200 KEY:${rreq.get("Authorization")}`)
|
||||||
|
// rres.sendStatus(200) // if that works then 200
|
||||||
|
// } else {
|
||||||
|
// rres.sendStatus(500) // otherwise lol
|
||||||
|
// }
|
||||||
|
// }).catch(ferror => {
|
||||||
|
// rres.sendStatus(503) // and if a problem happens its probably cause cider target is unavailable
|
||||||
|
// })
|
||||||
|
|
||||||
|
// } else {
|
||||||
|
// console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 401`) // log ip of unauthorized requests
|
||||||
|
// rres.sendStatus(401) // received auth key was not in database
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
|
||||||
|
// })
|
||||||
|
|
||||||
// 2024-04-10: Retrieves currentPlayingSong JSON from specified Cider host and
|
// 2024-04-10: Retrieves currentPlayingSong JSON from specified Cider host and
|
||||||
// returns JSON containing the useful bits if successful, returning 1 if not.
|
// returns JSON/HTML containing the useful bits if successful, returning 1 if not.
|
||||||
async function getCurrentListening(host) { // Host should be hostname/ip & port only.
|
|
||||||
timeSinceLastCiderQuery = Date.now(); // Save last time function was run, used to indicate when the cache needs refreshed.
|
// async function getCurrentListening(host,contentType) { // Host should be hostname/ip & port only.
|
||||||
return await fetch(`http://${host}/currentPlayingSong`).then(fetchRes => {
|
// timeSinceLastCiderQuery = Date.now(); // Save last time function was run, used to indicate when the cache needs refreshed.
|
||||||
if (fetchRes.status == 502) {
|
// return await fetch(`http://${host}/currentPlayingSong`).then(fetchRes => {
|
||||||
return 1 // If the upstream server returns 502 (Bad Gateway) then internally return 1, indicating error.
|
// if (fetchRes.status == 502) {
|
||||||
} else {
|
// return 1 // If the upstream server returns 502 (Bad Gateway) then internally return 1, indicating error.
|
||||||
return fetchRes.json().then(jsonRes => {
|
// } else {
|
||||||
if (jsonRes.info.name == undefined) {
|
// return fetchRes.json().then(jsonRes => {
|
||||||
return 1 // If Cider is running but not playing a song this check prevents an undefined variable error.
|
// if (jsonRes.info.name == undefined) {
|
||||||
} else {
|
// return 1 // If Cider is running but not playing a song this check prevents an undefined variable error.
|
||||||
return {
|
// } else {
|
||||||
"songName": jsonRes.info.name,
|
// if (contentType === "json") {
|
||||||
"artistName": jsonRes.info.artistName,
|
// return {
|
||||||
"albumName": jsonRes.info.albumName,
|
// "songName": jsonRes.info.name,
|
||||||
"songLinkUrl": jsonRes.info.url.songLink,
|
// "artistName": jsonRes.info.artistName,
|
||||||
"endtimeEpochInMs": jsonRes.info.endTime,
|
// "albumName": jsonRes.info.albumName,
|
||||||
"artworkUrl": jsonRes.info.artwork.url.replace("{w}", jsonRes.info.artwork.width).replace("{h}", jsonRes.info.artwork.height)
|
// "songLinkUrl": jsonRes.info.url.songLink,
|
||||||
}
|
// "endtimeEpochInMs": jsonRes.info.endTime,
|
||||||
}
|
// "artworkUrl": jsonRes.info.artwork.url.replace("{w}", jsonRes.info.artwork.width).replace("{h}", jsonRes.info.artwork.height)
|
||||||
})
|
// }
|
||||||
}
|
// } else if (contentType === "html") {
|
||||||
}).catch(fetchError => {
|
// return `<img src="${jsonRes.info.artwork.url.replace("{w}", jsonRes.info.artwork.width).replace("{h}", jsonRes.info.artwork.height)}" alt="Album Art" id="nowplaying-albumart" style="width: 10em;"> <div class="textlist"><p>I'm listening to</p><h3>${`${jsonRes.info.name} by ${jsonRes.info.artistName}`}</h3><p>from ${jsonRes.info.albumName}</p><a href="${jsonRes.info.url.songLink}" class="noindent">song.link</a></div>`
|
||||||
console.error("Error fetch()ing upstream Cider host: "+fetchError)
|
// } else {
|
||||||
return 1 // If something else happens then log it and return 1, indicating error.
|
// return 1
|
||||||
})
|
// }
|
||||||
}
|
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
// }).catch(fetchError => {
|
||||||
|
// console.error("Error fetch()ing upstream Cider host: "+fetchError)
|
||||||
|
// return 1 // If something else happens then log it and return 1, indicating error.
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
|
||||||
module.exports = {app} // export routes to be imported by index for execution
|
module.exports = {app} // export routes to be imported by index for execution
|
||||||
Reference in New Issue
Block a user