Raccoon-Influencer-Search/app.js
2024-07-11 20:43:47 +02:00

98 lines
2.9 KiB
JavaScript

"use strict";
const fastify = require("fastify");
const path = require("node:path");
const models = require("./models");
const Game = models.Game;
const Channel = models.Channel;
const { cleanChannelsList, templateData } = require("./libs/utils");
const { getGame, getChannels, createGame, createChannel, updateChannel } = require("./libs/db");
const { fetchGame, getMedianViewCount, searchGameInChannel } = require("./libs/youtube");
function build(opts = {}) {
const app = fastify(opts);
app.register(require("@fastify/static"), {
root: path.join(__dirname, "public"),
});
app.get("/search", async function (request, reply) {
console.log("\n\n=================================================================")
const gameName = request.query.game;
const channelsNumber = request.query.channelsNumber
const minimumViews = request.query.minimumViews
// const daysInactive = request.query.daysInactive
const videoCount = request.query.videoCount
const forceGameFetch = !!request.query.forceGameFetch
const forceVideoFetch = !!request.query.forceVideoFetch
let gameDb = await getGame(gameName);
let cleanedChannels = undefined
if (!gameDb || forceGameFetch) {
const json = await fetchGame(gameName, channelsNumber)
cleanedChannels = await cleanChannelsList(json)
gameDb = await createGame(gameName, cleanedChannels)
} else {
cleanedChannels = JSON.parse(gameDb.channels)
}
let channelsDb = await getChannels(gameDb.id);
console.log(0, { channelsDb })
if (!channelsDb || forceVideoFetch) {
channelsDb = []
for (let channelId of cleanedChannels) {
const medianViews = await getMedianViewCount(channelId, videoCount)
// const medianViews = 501
if (medianViews >= minimumViews) {
const videos = await searchGameInChannel(gameName, channelId)
const channelInDb = await Channel.findOne({
where: { channelId: channelId }
})
if (channelInDb) {
const chan = await updateChannel(channelInDb, videos, medianViews)
channelsDb.push(chan)
} else {
const chan = await createChannel(gameDb.id, channelId, videos, medianViews)
channelsDb.push(chan)
}
}
}
}
console.log(1, channelsDb)
// Once both game and channels are recorded into DB, pull it from DB and return HTML
return await templateData(gameName, gameDb, channelsDb);
});
app.get("/allGames", async function (request, reply) {
let html = `< table > `;
for (let game of games) {
html += `
< tr >
<td>${game.name}</td>
<td>${game.updatedAt}</td>
<td>${game.channels}</td>
</tr >
`;
}
html += `</table > `;
return html;
});
app.get("/", async function (request, reply) {
return reply.sendFile("index.html");
});
return app;
}
module.exports = build;