From 4da7cb9b0a279ddb300beed06ca0ac0b952ff5ac Mon Sep 17 00:00:00 2001 From: Oliver-Akins Date: Fri, 23 Jul 2021 13:22:57 -0600 Subject: [PATCH] Update all the endpoints to work with the new DB structure --- src/endpoints/discord/webhook.ts | 1 + src/endpoints/management/check_for_tie.ts | 38 ----------- src/endpoints/management/create_bracket.ts | 73 ++++++++++++---------- src/endpoints/management/get_winners.ts | 21 ------- src/endpoints/management/is_tied.ts | 48 ++++++++++++++ src/endpoints/management/winners.ts | 34 ++++++++++ 6 files changed, 123 insertions(+), 92 deletions(-) delete mode 100644 src/endpoints/management/check_for_tie.ts delete mode 100644 src/endpoints/management/get_winners.ts create mode 100644 src/endpoints/management/is_tied.ts create mode 100644 src/endpoints/management/winners.ts diff --git a/src/endpoints/discord/webhook.ts b/src/endpoints/discord/webhook.ts index 725f877..d7a33ec 100644 --- a/src/endpoints/discord/webhook.ts +++ b/src/endpoints/discord/webhook.ts @@ -32,6 +32,7 @@ async function handleButton(data: any): Promise { export default { method: `POST`, path: `/discord/webhook`, + options: { auth: false }, async handler(request: Request, h: ResponseToolkit) { let sig = request.headers[`x-signature-ed25519`]; let timestamp = request.headers[`x-signature-timestamp`]; diff --git a/src/endpoints/management/check_for_tie.ts b/src/endpoints/management/check_for_tie.ts deleted file mode 100644 index 80b078f..0000000 --- a/src/endpoints/management/check_for_tie.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { Request, ResponseToolkit } from "@hapi/hapi"; -import { DISCORD_API_URI } from "@/constants"; -import { config, db } from "@/main"; -import axios from "axios"; - -export default { - method: `GET`, path: `/bracket/isTie`, - async handler(request: Request, h: ResponseToolkit) { - let r = await request.server.inject(`/bracket/winners`); - let winners = JSON.parse(r.payload).winners; - - if (winners.length >= 2) { - - let r = await axios.get( - `${DISCORD_API_URI}/webhooks/${db.webhook.id}/${db.webhook.token}` - ); - let { guild_id, channel_id } = r.data; - - let content = `The bracket currently has a tie between:\n> ${winners.join('\n~~------------------------------------~~\n> ')}`; - - if (winners.length > Math.floor(config.discord.quote_max / 2)) { - content += `\n\n**If this tie is not broken, all of the quotes will be eliminated**` - }; - - // Assert that the guild and channel are both properly defined - if (guild_id && channel_id) { - content += `\n\n[Click Here To Jump To The Bracket](https://discord.com/channels/${guild_id}/${channel_id}/${db.bracket.msg})` - } - - await axios.post( - `${DISCORD_API_URI}/webhooks/${db.webhook.id}/${db.webhook.token}`, - { content } - ); - }; - - return { status: 200 } - }, -} \ No newline at end of file diff --git a/src/endpoints/management/create_bracket.ts b/src/endpoints/management/create_bracket.ts index e4e4660..c3777f7 100644 --- a/src/endpoints/management/create_bracket.ts +++ b/src/endpoints/management/create_bracket.ts @@ -1,58 +1,64 @@ import { Request, ResponseToolkit } from "@hapi/hapi"; -import { DISCORD_API_URI } from "@/constants"; +import { loadHistory, saveHistory } from "@/utils/data"; import { getQuote } from "@/utils/quotes"; -import { config, db } from "@/main"; -import fs from "fs/promises"; +import { db, config } from "@/main"; +import { BRACKET_DATA, DISCORD_API_URI } from "@/constants"; import axios from "axios"; export default { - method: `GET`, path: `/bracket/finish`, + method: `POST`, path: `/{guild_id}/bracket`, async handler(request: Request, h: ResponseToolkit) { + let { guild_id: gID } = request.params; + let wh = db[gID].webhook; - if (!db.bracket.msg) { - var quotes = await getQuote(config.discord.quote_max); + // Create the very first quote bracket + let quotes: string[]; + if (!db[gID].bracket.msg) { + quotes = await getQuote(gID, config.guilds[gID].quote_max); } else { - // Delete the old message from Discord while processing the new one - let wh = db.webhook; - await axios.delete(`${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}/messages/${db.bracket.msg}`); - // Save the previous bracket to the history file - let pastBrackets = JSON.parse( - await fs.readFile(config.server.bracket_history, `utf-8`) - ); - pastBrackets.push({ - quotes: db.bracket.quotes, - votes: db.bracket.votes, + let response = await request.server.inject({ + method: `DELETE`, + url: `/${gID}/bracket/${config.guilds[gID].delete_mode}` }); - await fs.writeFile(config.server.bracket_history, JSON.stringify(pastBrackets)); + let pastBrackets = await loadHistory(gID); + pastBrackets.push({ + quotes: db[gID].bracket.quotes, + votes: db[gID].bracket.votes, + }); + saveHistory(gID, pastBrackets); // Calculate the winners from the previous bracket let r = await request.server.inject(`/bracket/winners`); - var quotes: string[] = JSON.parse(r.payload).winners; - var winner_count = quotes.length; + var data = JSON.parse(r.payload); + var winner_count = data.count; - // Ensure that the all elimination limit didn't get hit - if (quotes.length > Math.floor(config.discord.quote_max / 2)) { + // Check if we are getting rid of all winners + if (data.eliminate_all) { quotes = []; + winner_count = 0; + } else { + quotes = data.winners; }; - // Get any new quotes for the bracket - quotes.push(...(await getQuote(config.discord.quote_max - quotes.length))); - } + // Get enough quotes to meet the maximum for the guild + let new_quotes = await getQuote( + gID, + config.guilds[gID].quote_max - quotes.length + ); + quotes.push(...new_quotes); + }; // Setup the database for the new bracket - db.bracket.quotes = quotes; - db.bracket.votes = {}; - db.bracket.users = {}; - db.bracket.msg = ""; - + db[gID].bracket = JSON.parse(JSON.stringify(BRACKET_DATA)); + db[gID].bracket.quotes = quotes; let message = { content: `New Quote Bracket!`, embeds: [ { - description: `Note: If **more than ${Math.floor(config.discord.quote_max / 2)}** of the quotes tie, they will all be eliminated, otherwise, the ones that tie will move on to the next bracket.`, + description: `Note: If **more than ${Math.floor(config.guilds[gID].quote_max / 2)}** of the quotes tie, they will all be eliminated, otherwise, the ones that tie will move on to the next bracket.`, fields: quotes.map((quote, i) => { return { name: `${i < winner_count ? '👑 ' : ''}Quote: ${i + 1}`, value: quote, @@ -99,6 +105,7 @@ export default { ] }; + // Add the development-only buttons if needed if (config.discord.dev_buttons) { message.components.push({ type: 1, @@ -119,9 +126,9 @@ export default { }); }; - let url = `${DISCORD_API_URI}/webhooks/${db.webhook.id}/${db.webhook.token}`; + let url = `${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}`; let r = await axios.post(url, message, { params: { wait: true } }); - db.bracket.msg = r.data.id; - return { status: r.status } + db[gID].bracket.msg = r.data.id; + return h.response(r.data).code(r.status); }, } \ No newline at end of file diff --git a/src/endpoints/management/get_winners.ts b/src/endpoints/management/get_winners.ts deleted file mode 100644 index e94060e..0000000 --- a/src/endpoints/management/get_winners.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { db } from "@/main" - -export default { - method: `GET`, path: `/bracket/winners`, - async handler() { - let winners: string[] = []; - let highest = -1; - - // Find the winners of the quote - for (var i in db.bracket.quotes) { - if (db.bracket.votes[i] > highest) { - winners = [ db.bracket.quotes[i] ]; - highest = db.bracket.votes[i]; - } else if (db.bracket.votes[i] === highest) { - winners.push(db.bracket.quotes[i]); - }; - }; - - return { winners }; - }, -} \ No newline at end of file diff --git a/src/endpoints/management/is_tied.ts b/src/endpoints/management/is_tied.ts new file mode 100644 index 0000000..027a4f5 --- /dev/null +++ b/src/endpoints/management/is_tied.ts @@ -0,0 +1,48 @@ +import { Request, ResponseToolkit } from "@hapi/hapi"; +import { DISCORD_API_URI } from "@/constants"; +import { config, db } from "@/main"; +import axios from "axios"; + +export default { + method: `GET`, path: `/{guild_id}/bracket/isTied`, + async handler(request: Request, h: ResponseToolkit) { + let gID = request.params.guild_id; + + let r = await request.server.inject(`/${gID}/bracket/winners`); + let data = JSON.parse(r.payload); + + if (data.count >= 2) { + + // Get the webhook's current information + let wh = db[gID].webhook; + let r = await axios.get( + `${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}` + ); + let { channel_id } = r.data; + + // Construct the primary body of the message + let content = `The bracket currently has a tie between:\n> ${data.winners.join('\n~~------------------------------------~~\n> ')}`; + + // Alert users if all will be eliminated or not + if (data.eliminate_all) { + content += `\n\n**If the tie remains, all quotes will be eliminated**`; + } else { + content += `\n\n**All of these quotes will advance if the tie isn't broken.**`; + }; + + // Add link if we know what channel the message was posted in + if (channel_id) { + content += `\n\n[Jump To Bracket](https://discord.com/${gID}/${channel_id}/${db[gID].bracket.msg})` + }; + + r = await axios.post( + `${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}`, + { content }, + { params: { wait: true } } + ); + return h.response(r.data).code(r.status); + }; + + return h.response().code(200); + }, +} \ No newline at end of file diff --git a/src/endpoints/management/winners.ts b/src/endpoints/management/winners.ts new file mode 100644 index 0000000..ab12726 --- /dev/null +++ b/src/endpoints/management/winners.ts @@ -0,0 +1,34 @@ +import { Request, ResponseToolkit } from "@hapi/hapi"; +import { config, db } from "@/main"; + +export default { + method: `GET`, path: `/{guild_id}/bracket/winners`, + async handler(request: Request, h: ResponseToolkit) { + let gID = request.params.guild_id; + let data = db[gID].bracket; + + let winners: string[] = []; + let highest = -1; + + // Iterate through all quotes that were voted for + for (var quote in data.votes) { + + // New maximum, reset array of winners + if (data.votes[quote] > highest) { + winners = [ data.quotes[quote] ]; + } + + // Tied highest, add to list + else if (data.votes[quote] == highest) { + winners.push( data.quotes[quote] ); + }; + }; + + let count = winners.length; + return h.response({ + winners, + count, + eliminate_all: count > Math.floor(config.guilds[gID].quote_max / 2), + }).code(200); + }, +} \ No newline at end of file