Major changes
This commit is contained in:
28
README.md
28
README.md
@@ -14,11 +14,12 @@ On startup, this application will look for two files. If either cannot be read,
|
||||
|
||||
<details> <summary>Configuration Example</summary>
|
||||
|
||||
* `couchdb.host`: Hostname/IP address and port of a CouchDB server.
|
||||
* `couchdb.authorization`: Username & password used to access the CouchDB server, in HTTP Basic authentication format, e.g. `username:password`.
|
||||
* `blog.postsDirectory`: Directory that will be parsed when calling /blogposts. If running in Docker this directory will need to be mounted to the container.
|
||||
* `blog.postsDirUrl`: Location of the posts directory on the web server.
|
||||
* `nowplaying.*.target`: Set to the Last.fm/Jellyfin username to query for playback information.
|
||||
* `couchdbHhost`: URL of CouchDB server.
|
||||
* `mailjet.apiKey`: Mailjet API Key.
|
||||
* `mailjet.senderAddress`: Email address that emails will be received from, must be verified in Mailjet admin panel.
|
||||
* `frontpage.frontpageDir`: Directory of frontpage, will be served at root with modifications.
|
||||
* `nowplaying.*.apiKey`: API key of respective service.
|
||||
* `nowplaying.*.target`: User that should be queried to retrieve playback information.
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -27,28 +28,21 @@ On startup, this application will look for two files. If either cannot be read,
|
||||
"routesDir": "./routes"
|
||||
},
|
||||
|
||||
"couchdb": {
|
||||
"host": "hazeldale:5984",
|
||||
"authorization": ""
|
||||
},
|
||||
"couchdbHost": "",
|
||||
|
||||
"mailjet": {
|
||||
"apiKey": "",
|
||||
"senderAddress": "apinotifications@enstrayed.com",
|
||||
"senderName": "API Notifications",
|
||||
|
||||
"authKeysDoc": "mailjet"
|
||||
"senderAddress": ""
|
||||
},
|
||||
|
||||
"blog": {
|
||||
"postsDirectory": "C:/Users/natha/Downloads/proto/posts",
|
||||
"postsDirUrl": "/posts"
|
||||
"frontpage": {
|
||||
"frontpageDir": ""
|
||||
},
|
||||
|
||||
"nowplaying": {
|
||||
"lastfm": {
|
||||
"apiKey": "",
|
||||
"target": "enstrayed"
|
||||
"target": ""
|
||||
},
|
||||
"jellyfin": {
|
||||
"apiKey": "",
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
const { globalConfig } = require("../index.js")
|
||||
|
||||
/**
|
||||
* Checks if a token exists in the sessions file (authentication) and if it has the correct permissions (authorization)
|
||||
* @param {string} token Token as received by client
|
||||
* @param {string} scope Scope the token will need to have in order to succeed
|
||||
* @returns True for successful authentication and authorization, false if either fail
|
||||
*/
|
||||
async function checkToken(token,scope) {
|
||||
return await fetch(`${globalConfig.couchdbHost}/auth/sessions`).then(fetchRes => {
|
||||
|
||||
// CouchDB should only ever return 200/304 for success so this should work
|
||||
// https://docs.couchdb.org/en/stable/api/document/common.html#get--db-docid
|
||||
if (fetchRes.status !== 200 || fetchRes.status !== 304) {
|
||||
console.log(`ERROR: auth.js: Database request returned ${fetchRes.status}`)
|
||||
return false
|
||||
} else {
|
||||
|
||||
return fetchRes.json().then(dbRes => {
|
||||
|
||||
if (dbRes.sessions[token] == undefined) { // If the token is not on the sessions list then reject
|
||||
@@ -21,10 +20,9 @@ async function checkToken(token,scope) {
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
}).catch(error => {
|
||||
console.log("ERROR: auth.js: " + error)
|
||||
console.log(`ERROR: auth.js: Fetch failed: ${error}`)
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
const { globalConfig } = require("../index.js")
|
||||
|
||||
async function checkAuthorization(documentToUse,keyToCheck) {
|
||||
return await fetch(`${globalConfig.couchdbHost}/apiauthkeys/${documentToUse}`).then(fetchRes => {
|
||||
|
||||
if (fetchRes.status === 404) { // If document doesnt exist fail gracefully
|
||||
|
||||
console.log("ERROR: Failed to check authorization: Requested document returned 404")
|
||||
return false
|
||||
|
||||
} else if (fetchRes.status === 401) { // If couchdb is reporting unauthorized fail gracefully
|
||||
|
||||
console.log("ERROR: Failed to check authorization: Database authorization is incorrect")
|
||||
return false
|
||||
|
||||
} else {
|
||||
return fetchRes.json().then(dbRes => { // Get response json and check it
|
||||
|
||||
if (dbRes["content"][keyToCheck.split("_")[0]] === keyToCheck.split("_")[1]) {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
}).catch(error => {
|
||||
console.log("ERROR: Failed to check authorization: " + error)
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {checkAuthorization}
|
||||
@@ -1,12 +1,16 @@
|
||||
const { globalConfig } = require("../index.js")
|
||||
|
||||
/**
|
||||
* Queries LastFM for user set in config file and returns formatted result
|
||||
* @returns {object} Object containing response in JSON and HTML (as string), WILL RETURN EMPTY OBJECT ON FAILURE!
|
||||
*/
|
||||
async function queryLastfm() {
|
||||
return await fetch(`https://ws.audioscrobbler.com/2.0/?format=json&method=user.getrecenttracks&limit=1&api_key=${globalConfig.nowplaying.lastfm.apiKey}&user=${globalConfig.nowplaying.lastfm.target}`).then(response => response.json()).then(response => {
|
||||
if (response["recenttracks"] == undefined) {
|
||||
return 1
|
||||
return {}
|
||||
} else {
|
||||
if (response.recenttracks.track[0]["@attr"] == undefined) {
|
||||
return 1
|
||||
return {}
|
||||
} else {
|
||||
return {
|
||||
"json": {
|
||||
@@ -20,6 +24,9 @@ async function queryLastfm() {
|
||||
}
|
||||
}
|
||||
}
|
||||
}).catch(fetchError => {
|
||||
console.log("libnowplaying.js: Fetch failed! "+fetchError)
|
||||
return {}
|
||||
})
|
||||
}
|
||||
|
||||
17
liberals/logging.js
Normal file
17
liberals/logging.js
Normal file
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Logs various details about the request (IP, Token, Method, Path, etc) to the console for later review
|
||||
* @param {object} response Parent response object
|
||||
* @param {object} request Parent request object
|
||||
* @param {number} code Status code to log, should be same as sent to client
|
||||
* @param {string} extra Optional extra details to add to log, ideal for caught errors
|
||||
*/
|
||||
function logRequest(response,request,code,extra) {
|
||||
if (extra) {
|
||||
actualExtra = "; Extra: "+extra
|
||||
} else {
|
||||
actualExtra = ""
|
||||
}
|
||||
console.log(`${request.get("cf-connecting-ip") ?? request.ip} (${request.get("Authorization")}) ${request.method} ${request.path} returned ${code}${actualExtra}`)
|
||||
}
|
||||
|
||||
module.exports = { logRequest }
|
||||
@@ -1,55 +0,0 @@
|
||||
const { app, globalConfig, fs } = require("../index.js") // Get globals from index
|
||||
|
||||
var timeSinceLastQuery = Date.now()-10000
|
||||
var cachedResult = {}
|
||||
|
||||
app.get("/blogposts", (rreq, rres) => {
|
||||
|
||||
if (Date.now() < timeSinceLastQuery+10000) { // if it has been <10 seconds since last request
|
||||
|
||||
|
||||
if (rreq.query.format === "html") { // if ?format=html then send HTML
|
||||
rres.send(cachedResult.asHtml)
|
||||
} else { // otherwise send json
|
||||
rres.send(cachedResult.asJson)
|
||||
}
|
||||
|
||||
} else {
|
||||
timeSinceLastQuery = Date.now()
|
||||
cachedResult = parseFiles()
|
||||
|
||||
|
||||
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() {
|
||||
let files = fs.readdirSync(globalConfig.blog.postsDirectory)
|
||||
let result = {
|
||||
asJson: [],
|
||||
asHtml: ""
|
||||
}
|
||||
|
||||
for (x in files) {
|
||||
if (files[x].endsWith(".html") === false) { break } // If file/dir is not .html then ignore
|
||||
|
||||
let date = files[x].split("-")[0]
|
||||
if (date < 10000000 || date > 99999999) { break } // If date does not fit ISO8601 format then ignore
|
||||
|
||||
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
|
||||
|
||||
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 result
|
||||
}
|
||||
|
||||
module.exports = {app}
|
||||
@@ -1,8 +1,9 @@
|
||||
const { app, globalConfig } = require("../index.js") // Get globals from index
|
||||
const { checkToken } = require("../liberals/auth.js")
|
||||
const { logRequest } = require("../liberals/logging.js")
|
||||
|
||||
app.get("/etyd*", (rreq,rres) => {
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd","")}`).then(dbRes => {
|
||||
app.get("/api/etyd*", (rreq,rres) => {
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd","")}`).then(dbRes => {
|
||||
if (dbRes.status == 404) {
|
||||
rres.sendStatus(404)
|
||||
} else {
|
||||
@@ -10,18 +11,18 @@ app.get("/etyd*", (rreq,rres) => {
|
||||
try {
|
||||
rres.redirect(dbRes.content.url) // Node will crash if the Database entry is malformed
|
||||
} catch (responseError) {
|
||||
logRequest(rres,rreq,500,responseError)
|
||||
rres.sendStatus(500)
|
||||
console.log(`${rres.get("cf-connecting-ip")} GET ${rreq.path} returned 500: ${responseError}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
}).catch(fetchError => {
|
||||
logRequest(rres,rreq,500,fetchError)
|
||||
rres.sendStatus(500)
|
||||
console.log(`${rres.get("cf-connecting-ip")} GET ${rreq.path} returned 500: ${fetchError}`)
|
||||
})
|
||||
})
|
||||
|
||||
app.delete("/etyd*", (rreq,rres) => {
|
||||
app.delete("/api/etyd*", (rreq,rres) => {
|
||||
|
||||
if (rreq.get("Authorization") === undefined) {
|
||||
rres.sendStatus(400)
|
||||
@@ -31,25 +32,27 @@ app.delete("/etyd*", (rreq,rres) => {
|
||||
rres.sendStatus(401)
|
||||
} else if (authRes === true) { // Authorization successful
|
||||
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd", "")}`).then(dbRes => {
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd", "")}`).then(dbRes => {
|
||||
|
||||
if (dbRes.status == 404) {
|
||||
rres.sendStatus(404)
|
||||
rres.sendStatus(404) // Entry does not exist
|
||||
} else {
|
||||
dbRes.json().then(dbRes => {
|
||||
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd", "")}`, {
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd", "")}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"If-Match": dbRes["_rev"] // Using the If-Match header is easiest for deleting entries in couchdb
|
||||
}
|
||||
}).then(fetchRes => {
|
||||
if (fetchRes.status == 200) {
|
||||
console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 200 KEY: ${rreq.get("Authorization")}`)
|
||||
// console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 200 KEY: ${rreq.get("Authorization")}`)
|
||||
logRequest(rres,rreq,200)
|
||||
rres.sendStatus(200)
|
||||
}
|
||||
}).catch(fetchError => {
|
||||
console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`)
|
||||
// console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`)
|
||||
logRequest(rres,rreq,500,fetchError)
|
||||
rres.sendStatus(500)
|
||||
})
|
||||
|
||||
@@ -57,7 +60,7 @@ app.delete("/etyd*", (rreq,rres) => {
|
||||
}
|
||||
|
||||
}).catch(fetchError => {
|
||||
console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`)
|
||||
logRequest(rres,rreq,500,fetchError)
|
||||
rres.sendStatus(500)
|
||||
})
|
||||
|
||||
@@ -67,7 +70,7 @@ app.delete("/etyd*", (rreq,rres) => {
|
||||
|
||||
})
|
||||
|
||||
app.post("/etyd*", (rreq,rres) => {
|
||||
app.post("/api/etyd*", (rreq,rres) => {
|
||||
|
||||
if (rreq.get("Authorization") === undefined) {
|
||||
rres.sendStatus(400)
|
||||
@@ -80,7 +83,7 @@ app.post("/etyd*", (rreq,rres) => {
|
||||
if (rreq.body["url"] == undefined) {
|
||||
rres.sendStatus(400)
|
||||
} else {
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd", "")}`, {
|
||||
fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd", "")}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
"content": {
|
||||
@@ -95,16 +98,17 @@ app.post("/etyd*", (rreq,rres) => {
|
||||
break;
|
||||
|
||||
case 201:
|
||||
rres.status(200).send(rreq.path.replace("/etyd", ""))
|
||||
rres.status(200).send(rreq.path.replace("/api/etyd", ""))
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log(`ERROR: CouchDB PUT did not return expected code: ${dbRes.status}`)
|
||||
logRequest(rres,rreq,500,`CouchDB PUT did not return expected code: ${dbRes.status}`)
|
||||
rres.sendStatus(500)
|
||||
break;
|
||||
}
|
||||
|
||||
}).catch(fetchError => {
|
||||
console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`)
|
||||
logRequest(rres,rreq,500,fetchError)
|
||||
rres.sendStatus(500)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const { app } = require("../index.js")
|
||||
|
||||
app.get("/ip", (rreq,rres) => {
|
||||
app.get("/api/ip", (rreq,rres) => {
|
||||
let jsonResponse = {
|
||||
"IP": rreq.get("cf-connecting-ip") || rreq.ip,
|
||||
"Country": rreq.get("cf-ipcountry") || "not_cloudflare",
|
||||
@@ -10,7 +10,7 @@ app.get("/ip", (rreq,rres) => {
|
||||
rres.send(jsonResponse)
|
||||
})
|
||||
|
||||
app.get("/headers", (rreq,rres) => {
|
||||
app.get("/api/headers", (rreq,rres) => {
|
||||
rres.send(rreq.headers)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,38 +1,22 @@
|
||||
const { app, globalConfig } = require("../index.js") // Get globals from index
|
||||
const { checkToken } = require("../liberals/auth.js")
|
||||
const { logRequest } = require("../liberals/logging.js")
|
||||
|
||||
app.post("/sendemail", (rreq,rres) => {
|
||||
|
||||
app.post("/api/sendemail", (rreq,rres) => {
|
||||
checkToken(rreq.get("Authorization"),"mailjet").then(authRes => {
|
||||
if (authRes === false) { // If the supplied authorization is invalid or an error occured
|
||||
|
||||
console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 401`) // Log the request
|
||||
if (authRes === false) {
|
||||
rres.sendStatus(401)
|
||||
|
||||
} else if (authRes === true) { // If the authorization was valid, continue function
|
||||
|
||||
// 2024-05-11: Turbo bodge check to make sure request JSON is valid, probably wont work but whatever
|
||||
if (rreq.body == undefined || rreq.body.recipient == undefined) {
|
||||
console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 400 KEY:${rreq.get("Authorization").split("_")[0]}`)
|
||||
} else if (authRes === true) {
|
||||
if (rreq.body == undefined || rreq.body.recipient == undefined) { // 2024-05-11: Turbo bodge check to make sure request JSON is valid, probably wont work but whatever
|
||||
rres.sendStatus(400)
|
||||
} else {
|
||||
|
||||
let message = {
|
||||
"Messages": [
|
||||
{
|
||||
"From": {
|
||||
"Email": globalConfig.mailjet.senderAddress
|
||||
},
|
||||
"To": [
|
||||
{
|
||||
"Email": rreq.body.recipient,
|
||||
}
|
||||
],
|
||||
|
||||
"Messages": [{
|
||||
"From": { "Email": globalConfig.mailjet.senderAddress },
|
||||
"To": [{ "Email": rreq.body.recipient, }],
|
||||
"Subject": rreq.body.subject || "Request did not include a subject.",
|
||||
"TextPart": rreq.body.message || "Request did not include a message.",
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
|
||||
fetch("https://api.mailjet.com/v3.1/send", {
|
||||
@@ -44,17 +28,16 @@ app.post("/sendemail", (rreq,rres) => {
|
||||
body: JSON.stringify(message)
|
||||
}).then(fetchRes => {
|
||||
if (fetchRes.status == 200) {
|
||||
console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 200 KEY:${rreq.get("Authorization").split("_")[1]}`)
|
||||
logRequest(rres,rreq,200)
|
||||
rres.sendStatus(200)
|
||||
} else {
|
||||
console.log(`Mailjet Fetch returned result other than OK: ${fetchRes.status} ${fetchRes.statusText}`)
|
||||
logRequest(rres,rreq,500,`Mailjet fetch did not return OK: ${fetchRes.status} ${fetchRes.statusText}`)
|
||||
rres.sendStatus(500)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
module.exports = {app} // export routes to be imported by index for execution
|
||||
module.exports = {app}
|
||||
@@ -1,5 +1,5 @@
|
||||
const { app, globalConfig } = require("../index.js")
|
||||
const { queryLastfm } = require("../liberals/nowplaying.js")
|
||||
const { queryLastfm } = require("../liberals/libnowplaying.js")
|
||||
|
||||
var timeSinceLastLastfmQuery = Date.now()-5000
|
||||
var cachedLastfmResult = {}
|
||||
@@ -11,14 +11,14 @@ const notPlayingAnythingPlaceholder = {
|
||||
"html": `<span>I'm not currently listening to anything.</span>`
|
||||
}
|
||||
|
||||
app.get("/nowplaying", (rreq,rres) => {
|
||||
app.get("/api/nowplaying", (rreq,rres) => {
|
||||
|
||||
if (Date.now() < timeSinceLastLastfmQuery+5000) {
|
||||
rres.send(cachedLastfmResult[rreq.query.format] ?? cachedLastfmResult.json)
|
||||
} else {
|
||||
timeSinceLastLastfmQuery = Date.now()
|
||||
queryLastfm().then(response => {
|
||||
if (response == 1) {
|
||||
if (response == {}) {
|
||||
cachedLastfmResult = notPlayingAnythingPlaceholder
|
||||
} else {
|
||||
cachedLastfmResult = response
|
||||
|
||||
Reference in New Issue
Block a user