youtube-po-token-generator/index.js
Fijxu c1417a6913
All checks were successful
Docker build image / build (push) Successful in 33s
add support to disable the key
2024-12-21 17:07:50 -03:00

97 lines
2.7 KiB
JavaScript

const { env } = require('process');
const { createTask } = require('./lib/task')
const { fetchVisitorData } = require('./lib/workflow')
const http = require('http');
const port = env.PORT || "3000"
const address = env.ADDRESS || "0.0.0.0"
const key = env.KEY
const nokey = env.USE_KEY || "false"
let tokens = {};
const generate = async () => {
console.debug("[DEBUG] generate called")
try {
const visitorData = await fetchVisitorData()
const task = await createTask(visitorData)
const { poToken } = await task.start()
return { visitorData, poToken }
} catch (e) {
console.error(`generate: Error ${e}`)
}
}
const refreshTokens = async () => {
console.log("[DEBUG] generateTokens called")
try {
const { visitorData, poToken } = await generate();
tokens.visitorData = visitorData;
tokens.poToken = poToken;
console.log("[DEBUG] generateTokens finished")
} catch (e) {
console.error(`refreshTokens: Error ${e}`)
}
}
const server = http.Server(async (req, res) => {
switch (req.url) {
case "/generate":
if (tokens.visitorData == undefined || tokens.poToken == undefined) {
res.writeHead(500)
res.write("Tokens are not yet generated");
return res.end()
}
const host = req.headers.host;
const json = {
potoken: tokens.poToken,
visitorData: tokens.visitorData,
};
if (nokey) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(json));
return res.end();
}
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(json));
return res.end();
} else {
if (key != "" && key != undefined) {
const auth = req.headers.authorization;
if (auth == `Bearer ${key}`) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write(JSON.stringify(json));
return res.end();
} else {
res.writeHead(401, { 'Content-Type': 'text/plain' });
return res.end();
}
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write(JSON.stringify(json));
return res.end();
}
}
case "/update":
await refreshTokens();
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.write("Tokens updated")
return res.end()
default:
return res.end()
}
})
refreshTokens();
setInterval(refreshTokens, (env.RENEW_INTERVAL || 60) * 1000)
server.listen(port, address, () => {
console.log("Listening at port", port);
})
module.exports = { generate }