From 831016883aa49246f749ffee830bcb1c1d6d3c89 Mon Sep 17 00:00:00 2001 From: Andrei Jiroh Eugenio Halili Date: Mon, 25 Apr 2022 12:09:37 +0000 Subject: [PATCH] style(global): :art: format literally everything + update our secret loader for localdev Signed-off-by: Andrei Jiroh Eugenio Halili --- .eslintrc.js | 16 +++ .prettierrc.js | 6 + functions/debug/globalCommands.js | 6 +- functions/debug/secrets.js | 22 ++-- functions/events/autocode/self/deployed.js | 34 ++--- functions/events/discord/bot_mention.js | 48 +++---- .../events/discord/command/link-fandom.js | 18 ++- functions/events/discord/command/status.js | 100 +++++++------- .../events/discord/command/update-commands.js | 8 +- functions/events/discord/command/verify.js | 123 +++++++++--------- functions/events/github/issues.js | 43 +++--- functions/lookup.js | 4 +- functions/oauth/mediawiki/__main__.js | 19 +-- functions/oauth/mediawiki/callback.js | 17 ++- functions/response.js | 9 +- functions/updateCommands.js | 43 +++--- lib/embeds/verify.js | 8 +- lib/models/lookupIndex.js | 46 ++++++- lib/oauth/mw.js | 42 +++--- lib/secrets.js | 37 ++---- lib/slashCommands.js | 106 +++++++-------- 21 files changed, 402 insertions(+), 353 deletions(-) create mode 100644 .eslintrc.js create mode 100644 .prettierrc.js diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..24d6278 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,16 @@ +module.exports = { + env: { + es6: true, + browser: true, + es2021: true, + }, + extends: ["airbnb-base", "prettier", "plugin:prettier/recommended"], + parserOptions: { + ecmaVersion: 12, + sourceType: "module", + }, + rules: { + "prettier/prettier": "error", + }, + plugins: ["prettier"], +}; diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 0000000..e617454 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,6 @@ +module.exports = { + trailingComma: "es5", + tabWidth: 2, + semi: true, + singleQuote: false, +}; diff --git a/functions/debug/globalCommands.js b/functions/debug/globalCommands.js index f783e47..d116cb5 100755 --- a/functions/debug/globalCommands.js +++ b/functions/debug/globalCommands.js @@ -1,3 +1,5 @@ -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); -return lib.discord.commands['@0.1.0'].list(); +module.exports = async () => { + return lib.discord.commands["@0.1.0"].list(); +}; diff --git a/functions/debug/secrets.js b/functions/debug/secrets.js index 2045e34..f666774 100644 --- a/functions/debug/secrets.js +++ b/functions/debug/secrets.js @@ -1,12 +1,12 @@ -const {loadEnvFromFile} = require("../../lib/secrets") -loadEnvFromFile() -const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }) +const { loadEnvFromFile } = require("../../lib/secrets"); +loadEnvFromFile(); +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); -module.exports = async(secret) => { - return { - headers: { - "Content-Type": "application/json; charset=utf-8" - }, - body: Buffer.from(JSON.stringify(process.env)) - } -} \ No newline at end of file +module.exports = async (secret) => { + return { + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + body: Buffer.from(JSON.stringify(process.env)), + }; +}; diff --git a/functions/events/autocode/self/deployed.js b/functions/events/autocode/self/deployed.js index b5bc026..dd32760 100755 --- a/functions/events/autocode/self/deployed.js +++ b/functions/events/autocode/self/deployed.js @@ -4,24 +4,28 @@ * into their server. If you want to add new commandshere, use https://autocode.com/tools/discord/command-builder/ * to easily generate the code needed. */ -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); -const slashCommandsConfig = require("../../../../lib/slashCommands") +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); +const slashCommandsConfig = require("../../../../lib/slashCommands"); /** Internal commands go here **/ -status = await lib.discord.commands['@0.0.0'].create(slashCommandsConfig.status); +status = await lib.discord.commands["@0.0.0"].create( + slashCommandsConfig.status +); /** After all of these, public commands go here **/ -gitConnect = await lib.discord.commands['@0.0.0'].create(slashCommandsConfig.connectGit); -verify = await lib.discord.commands['@0.0.0'].create(slashCommandsConfig.verify); -userLookup = await lib.discord.commands['@0.0.0'].create(slashCommandsConfig.userinfo); -updateCommands = await lib.discord.commands['@0.0.0'].create(slashCommandsConfig.updateCommands); +gitConnect = await lib.discord.commands["@0.0.0"].create( + slashCommandsConfig.connectGit +); +verify = await lib.discord.commands["@0.0.0"].create( + slashCommandsConfig.verify +); +userLookup = await lib.discord.commands["@0.0.0"].create( + slashCommandsConfig.userinfo +); +updateCommands = await lib.discord.commands["@0.0.0"].create( + slashCommandsConfig.updateCommands +); return { - results: [ - status, - gitConnect, - verify, - userLookup, - updateCommands - ] -} \ No newline at end of file + results: [status, gitConnect, verify, userLookup, updateCommands], +}; diff --git a/functions/events/discord/bot_mention.js b/functions/events/discord/bot_mention.js index f2b33bc..625d183 100755 --- a/functions/events/discord/bot_mention.js +++ b/functions/events/discord/bot_mention.js @@ -1,32 +1,36 @@ // authenticates you with the API standard library -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); -let messageResponse = await lib.discord.channels['@0.0.6'].messages.create({ +let messageResponse = await lib.discord.channels["@0.0.6"].messages.create({ channel_id: `${context.params.event.channel_id}`, content: [ `Hey <@!${context.params.event.author.id}>! I'm a bot powered by Autocode, with love by the Recap Time Squad.`, - `Currently, most of the commands are only available via slash commands to simplify our workflow.` - ].join('\n'), + `Currently, most of the commands are only available via slash commands to simplify our workflow.`, + ].join("\n"), embed: { - title: 'About the bot', - type: 'rich', - color: 0x00AA00, // Green color - description: 'We built this bot for Discord, among other bots elsewhere, to compliment our verification process for both creators and communities on our platforms in an open-source way.', - fields: [{ - name: 'Where is the source code?', - value: [ - 'We\'re working on to make it open-source outside Autocode pretty soon. You could ask us to give you access to the project', - 'and also help us bring even more features to the bot.' - ].join(' ') - }, { - name: 'Link your Discord to GitHub/GitLab SaaS username', - value: [ - 'Check out the documentation on how you can', - 'https://autocode.com/app/discord/basic-discord-example/' - ].join('\n') - }] + title: "About the bot", + type: "rich", + color: 0x00aa00, // Green color + description: + "We built this bot for Discord, among other bots elsewhere, to compliment our verification process for both creators and communities on our platforms in an open-source way.", + fields: [ + { + name: "Where is the source code?", + value: [ + "We're working on to make it open-source outside Autocode pretty soon. You could ask us to give you access to the project", + "and also help us bring even more features to the bot.", + ].join(" "), + }, + { + name: "Link your Discord to GitHub/GitLab SaaS username", + value: [ + "Check out the documentation on how you can", + "https://autocode.com/app/discord/basic-discord-example/", + ].join("\n"), + }, + ], }, - tts: false + tts: false, }); return messageResponse; diff --git a/functions/events/discord/command/link-fandom.js b/functions/events/discord/command/link-fandom.js index ee9bd8e..45579ac 100755 --- a/functions/events/discord/command/link-fandom.js +++ b/functions/events/discord/command/link-fandom.js @@ -1,17 +1,15 @@ -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); -let userData = context.params.event.user +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); +let userData = context.params.event.user; let urlEncodedData = { user: encodeURIComponent(userData.username), - tag: userData.discriminator -} -let discordUserMinced = `${userData.username}#${userData.discriminator}` -let updateDiscordAccountLink = `https://community.fandom.com/wiki/Special:VerifyUser?user=${urlEncodedData.user}&tag=${urlEncodedData.tag}&ch=verify-${userData.id}` + tag: userData.discriminator, +}; +let discordUserMinced = `${userData.username}#${userData.discriminator}`; +let updateDiscordAccountLink = `https://community.fandom.com/wiki/Special:VerifyUser?user=${urlEncodedData.user}&tag=${urlEncodedData.tag}&ch=verify-${userData.id}`; function requestUserId(user) { - const result = todo + const result = todo; if (true) { - } else { - } -} \ No newline at end of file +} diff --git a/functions/events/discord/command/status.js b/functions/events/discord/command/status.js index a166944..4896ac0 100755 --- a/functions/events/discord/command/status.js +++ b/functions/events/discord/command/status.js @@ -1,70 +1,70 @@ // authenticates you with the API standard library // type `await lib.` to display API autocomplete -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); // our admin role ID and the guild ID for perm checks. let role = `${process.env.DISCORD_ROLE_ID}`; -let serverInfo = await lib.discord.guilds['@0.2.3'].retrieve({ +let serverInfo = await lib.discord.guilds["@0.2.3"].retrieve({ guild_id: `${process.env.DISCORD_GUILD_ID}`, - with_counts: false + with_counts: false, }); -let serverOwner = serverInfo.owner_id +let serverOwner = serverInfo.owner_id; // if they have admin perms and sent from an guild we specified earlier // or if they're the server owner themselves. -if (context.params.event.member.roles.includes(role) || context.params.event.member.user.id === serverOwner) { +if ( + context.params.event.member.roles.includes(role) || + context.params.event.member.user.id === serverOwner +) { /* fetch options from the payload */ let status = context.params.event.data.options[0].value; let type = context.params.event.data.options[1].value; let name = context.params.event.data.options[2].value; let url = context.params.event.data.options[3]; - + // Converting variable from URL option if (!url) { - url = ''; + url = ""; } else { url = url.value; } - - - await lib.discord.users['@0.1.5'].me.status.update({ - activity_name: name, - activity_type: type, - status: status, - url: url, - }); - - // TODO: Make this message invokation visible to sender only. - return await lib.discord.channels['@0.2.0'].messages.create({ - channel_id: `${context.params.event.channel_id}`, - content: ``, - "tts": false, - "embeds": [ - { - "type": "rich", - "title": `✅ Status message successfully updated`, - "description": `Your client should shown the changes immediately. Otherwise, please restart your Discord client.`, - "color": 0x00ff4c - } - ], - response_type: 'CHANNEL_MESSAGE_WITH_SOURCE' - }); - } - else { - // send a error message about missing perms and also pinging people with that role - let deny = await lib.discord.channels['@0.2.0'].messages.create({ - channel_id: `${context.params.event.channel_id}`, - content: ``, - tts: false, - embeds: [ - { - "type": "rich", - "title": `❌ You don't have enough permissions to do this!`, - "description": `<@${context.params.event.member.user.id}>, please ask a <@&${process.env.DISCORD_ROLE_ID}> to update te bot's status.`, - "color": 0xff0000 - } - ], - response_type: 'CHANNEL_MESSAGE_WITH_SOURCE' - }); - } - \ No newline at end of file + + await lib.discord.users["@0.1.5"].me.status.update({ + activity_name: name, + activity_type: type, + status: status, + url: url, + }); + + // TODO: Make this message invokation visible to sender only. + return await lib.discord.channels["@0.2.0"].messages.create({ + channel_id: `${context.params.event.channel_id}`, + content: ``, + tts: false, + embeds: [ + { + type: "rich", + title: `✅ Status message successfully updated`, + description: `Your client should shown the changes immediately. Otherwise, please restart your Discord client.`, + color: 0x00ff4c, + }, + ], + response_type: "CHANNEL_MESSAGE_WITH_SOURCE", + }); +} else { + // send a error message about missing perms and also pinging people with that role + let deny = await lib.discord.channels["@0.2.0"].messages.create({ + channel_id: `${context.params.event.channel_id}`, + content: ``, + tts: false, + embeds: [ + { + type: "rich", + title: `❌ You don't have enough permissions to do this!`, + description: `<@${context.params.event.member.user.id}>, please ask a <@&${process.env.DISCORD_ROLE_ID}> to update te bot's status.`, + color: 0xff0000, + }, + ], + response_type: "CHANNEL_MESSAGE_WITH_SOURCE", + }); +} diff --git a/functions/events/discord/command/update-commands.js b/functions/events/discord/command/update-commands.js index b2580bc..6ec1a29 100755 --- a/functions/events/discord/command/update-commands.js +++ b/functions/events/discord/command/update-commands.js @@ -1,10 +1,10 @@ // authenticates you with the API standard library // type `await lib.` to display API autocomplete -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); if (context.params.event.member.permission_names.includes("MANAGE_GUILD")) { - return lib.discord.interactions['@1.0.1'].followups.ephemeral.create({ + return lib.discord.interactions["@1.0.1"].followups.ephemeral.create({ token: `${context.params.event.token}`, - content: `<@${context.params.event.member.user.id}>, we're updated the slash commands for this server. If you still seeing old data, wait for up to an hour before retrying.\n\nIn case that didn't work, join the support server at https://discord.gg/5dURUcM under \`recaptime-support\` channel and let us know.` + content: `<@${context.params.event.member.user.id}>, we're updated the slash commands for this server. If you still seeing old data, wait for up to an hour before retrying.\n\nIn case that didn't work, join the support server at https://discord.gg/5dURUcM under \`recaptime-support\` channel and let us know.`, }); -} \ No newline at end of file +} diff --git a/functions/events/discord/command/verify.js b/functions/events/discord/command/verify.js index 5d94945..d2a54c7 100755 --- a/functions/events/discord/command/verify.js +++ b/functions/events/discord/command/verify.js @@ -1,95 +1,96 @@ // authenticates you with the API standard library // type `await lib.` to display API autocomplete -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); -let ghFormTemplateLink = `https://github.com/${process.env.GH_NAMESPACE}/${process.env.GH_REPO_SLUG}/issues/new?assignees=ajhalili2006%2CRecapTimeSquad&labels=request-forms%3Anew-entries%2Cenhancement&template=verify-an-entry.yml&title=Request+to+verify+Entry+Name+Here` -const { getEmbedTemplate } = require('../../../../lib/embeds/verify') +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); +let ghFormTemplateLink = `https://github.com/${process.env.GH_NAMESPACE}/${process.env.GH_REPO_SLUG}/issues/new?assignees=ajhalili2006%2CRecapTimeSquad&labels=request-forms%3Anew-entries%2Cenhancement&template=verify-an-entry.yml&title=Request+to+verify+Entry+Name+Here`; +const { getEmbedTemplate } = require("../../../../lib/embeds/verify"); msgTemplate = { - "content": `The embed below contains the instructions you needed to follow an the button links you need. When prompted for your Discord ID for verification, your ID can be copied from the account settings OR your profile when you enable \n\n⚠️**IMPORTANT: Never share your personal data, including your goernment IDs in the issue tracker.** An maintainer may ask you to provide these for the second stage of the verification process after getting the semi-verified status in a private setting.`, - "tts": false, - "components": [ + content: `The embed below contains the instructions you needed to follow an the button links you need. When prompted for your Discord ID for verification, your ID can be copied from the account settings OR your profile when you enable \n\n⚠️**IMPORTANT: Never share your personal data, including your goernment IDs in the issue tracker.** An maintainer may ask you to provide these for the second stage of the verification process after getting the semi-verified status in a private setting.`, + tts: false, + components: [ { - "type": 1, - "components": [ + type: 1, + components: [ { - "style": 5, - "label": `Submit new request`, - "url": `https://github.com/${process.env.GH_NAMESPACE}/${process.env.GH_REPO_SLUG}/issues/new?assignees=ajhalili2006%2CRecapTimeSquad&labels=request-forms%3Anew-entries%2Cenhancement&template=verify-an-entry.yml&title=Request+to+verify+Entry+Name+Here`, - "disabled": false, - "type": 2 + style: 5, + label: `Submit new request`, + url: `https://github.com/${process.env.GH_NAMESPACE}/${process.env.GH_REPO_SLUG}/issues/new?assignees=ajhalili2006%2CRecapTimeSquad&labels=request-forms%3Anew-entries%2Cenhancement&template=verify-an-entry.yml&title=Request+to+verify+Entry+Name+Here`, + disabled: false, + type: 2, }, { - "style": 5, - "label": `Recommended: Find existing issues first`, - "url": `https://gitlab.com/RecapTime/verify/issues`, - "disabled": false, - "type": 2 + style: 5, + label: `Recommended: Find existing issues first`, + url: `https://gitlab.com/RecapTime/verify/issues`, + disabled: false, + type: 2, }, { - "style": 5, - "label": `Learn more in project's README`, - "url": `https://gitlab.com/RecapTime/veriy`, - "disabled": false, - "type": 2 - } - ] - } + style: 5, + label: `Learn more in project's README`, + url: `https://gitlab.com/RecapTime/veriy`, + disabled: false, + type: 2, + }, + ], + }, ], - "embeds": [ + embeds: [ { - "type": "rich", - "title": `Instructions on how do you get Verified role in Recap Time Squad's server + services`, - "description": "", - "color": 0x00ff73, - "fields": [ + type: "rich", + title: `Instructions on how do you get Verified role in Recap Time Squad's server + services`, + description: "", + color: 0x00ff73, + fields: [ { - "name": `1. Press the button below to get the GitHub issue form.`, - "value": `In case GitHub is down or our GitHub app is having some hicupps on copying issues, you can directly [submit on GitLab here](https://gitlab.com/RecapTime/verify/issues/new) and select \`Add new entry\` issue template.` + name: `1. Press the button below to get the GitHub issue form.`, + value: `In case GitHub is down or our GitHub app is having some hicupps on copying issues, you can directly [submit on GitLab here](https://gitlab.com/RecapTime/verify/issues/new) and select \`Add new entry\` issue template.`, }, { - "name": `2. Read instructions as prompted. Any incomplete issue will be then closed without notice by any of the maintainers.`, - "value": `In GitLab, instructions are written as HTML comments, so please read them carefully. We're working on an webapp to simplify this workflow pretty soon.` + name: `2. Read instructions as prompted. Any incomplete issue will be then closed without notice by any of the maintainers.`, + value: `In GitLab, instructions are written as HTML comments, so please read them carefully. We're working on an webapp to simplify this workflow pretty soon.`, }, { - "name": `3. Once you're satisified, you can hit the \"Create issue\" button`, - "value": `**REMEMBER TO CHECK IF THERE ARE ANY EXISTING OPEN ISSUES!** If there are any, even close one, make sure to stay in the loop. You can also submit an merge request then. (We require each MRs to have its own issue for tracking purposes.)` - } - ] - } - ] -} + name: `3. Once you're satisified, you can hit the \"Create issue\" button`, + value: `**REMEMBER TO CHECK IF THERE ARE ANY EXISTING OPEN ISSUES!** If there are any, even close one, make sure to stay in the loop. You can also submit an merge request then. (We require each MRs to have its own issue for tracking purposes.)`, + }, + ], + }, + ], +}; if (!context.params.event.user) { - await lib.discord.interactions['@1.0.0'].responses.ephemeral.create({ // we send an ephemeral message to the user confirming that the responses have been logged + await lib.discord.interactions["@1.0.0"].responses.ephemeral.create({ + // we send an ephemeral message to the user confirming that the responses have been logged token: `${context.params.event.token}`, content: `<@!${context.params.event.member.user.id}>`, - "tts": false, + tts: false, embeds: [ { - "type": "rich", - "title": `Check your DMs for instructions!`, - "description": `If you don't allow server members to DMs you, including bots, please adjust your privacy settings for this server.`, - "color": 0x9900ff, - "image": { - "url": `https://i.imgur.com/vbPYlw1.png`, - "height": 0, - "width": 0 - } - } + type: "rich", + title: `Check your DMs for instructions!`, + description: `If you don't allow server members to DMs you, including bots, please adjust your privacy settings for this server.`, + color: 0x9900ff, + image: { + url: `https://i.imgur.com/vbPYlw1.png`, + height: 0, + width: 0, + }, + }, ], - response_type: 'CHANNEL_MESSAGE_WITH_SOURCE', + response_type: "CHANNEL_MESSAGE_WITH_SOURCE", }); - await lib.discord.users['@0.2.0'].dms.create({ + await lib.discord.users["@0.2.0"].dms.create({ recipient_id: `${context.params.event.member.user.id}`, content: msgTemplate.content, embeds: msgTemplate.embeds, - components: msgTemplate.components + components: msgTemplate.components, }); } else { - await lib.discord.channels['@0.3.1'].messages.create({ + await lib.discord.channels["@0.3.1"].messages.create({ channel_id: `${context.params.event.channel_id}`, content: msgTemplate.content, embeds: msgTemplate.embeds, - components: msgTemplate.components + components: msgTemplate.components, }); -} \ No newline at end of file +} diff --git a/functions/events/github/issues.js b/functions/events/github/issues.js index f130930..02ac478 100755 --- a/functions/events/github/issues.js +++ b/functions/events/github/issues.js @@ -4,42 +4,43 @@ * @returns {any} result */ module.exports = async (event, context) => { - // authenticates you with the API standard library // type `await lib.` to display API autocomplete - const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); + const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); - if (context.params.event.repository.owner.login == process.env.GH_NAMESPACE && context.params.event.repo == process.env.GH_REPO_SLUG) { - const issueMetadata = lib.github.issues['@0.3.5'].retrieve({ - owner: `${event.repository.owner.login}`, - repo: `${event.repository.name}`, - issue_number: Number(`${event.issue.id}`) - }); - const issueBody = issueMetadata.body - let glApiResponse = lib.http.request['@1.1.6'].post({ + if ( + context.params.event.repository.owner.login == process.env.GH_NAMESPACE && + context.params.event.repo == process.env.GH_REPO_SLUG + ) { + const issueMetadata = lib.github.issues["@0.3.5"].retrieve({ + owner: `${event.repository.owner.login}`, + repo: `${event.repository.name}`, + issue_number: Number(`${event.issue.id}`), + }); + const issueBody = issueMetadata.body; + let glApiResponse = lib.http.request["@1.1.6"].post({ url: `https://${process.env.GITLAB_HOST}/api/v3/projects/${process.env.GITLAB_PROJECT_ID}/issues`, authorization: `${process.env.GITLAB_TOKEN}`, params: { - 'title': `todo`, - 'body': `todo` - } + title: `todo`, + body: `todo`, + }, }); - let closeThis = lib.github.issues['@0.3.5'].update({ + let closeThis = lib.github.issues["@0.3.5"].update({ owner: `${event.repository.owner.login}`, repo: `${event.repository.name}`, issue_number: Number(`${event.issue.number}`), - state: 'closed' + state: "closed", }); - + return { github: closeThis, - gitlab: glApiResponse - } + gitlab: glApiResponse, + }; } else { return { ok: false, - error: "Repo name and owner login mismatch found!" - } + error: "Repo name and owner login mismatch found!", + }; } - }; diff --git a/functions/lookup.js b/functions/lookup.js index 8efef0a..8847590 100755 --- a/functions/lookup.js +++ b/functions/lookup.js @@ -5,5 +5,5 @@ * @param {string} type What index we should */ module.exports = async (username, type = "content_creator") => { - return "todo" -}; \ No newline at end of file + return "todo"; +}; diff --git a/functions/oauth/mediawiki/__main__.js b/functions/oauth/mediawiki/__main__.js index 363c8d2..1764a0c 100755 --- a/functions/oauth/mediawiki/__main__.js +++ b/functions/oauth/mediawiki/__main__.js @@ -1,17 +1,20 @@ -const { getRedirectUrl } = require('../../../lib/oauth/mw.js') +const { getRedirectUrl } = require("../../../lib/oauth/mw.js"); module.exports = async (state = "abc123") => { if (context.params.state) { return { - headers: {"Location": getRedirectUrl(context.params.state)}, + headers: { Location: getRedirectUrl(context.params.state) }, statusCode: 302, - body: Buffer.from('') - } + body: Buffer.from(""), + }; } else { return { - headers: {"Location": "https://recaptime.miraheze.org/wiki/Portal:NoStateCodeDetected"}, + headers: { + Location: + "https://recaptime.miraheze.org/wiki/Portal:NoStateCodeDetected", + }, statusCode: 302, - body: Buffer.from('') - } + body: Buffer.from(""), + }; } -} \ No newline at end of file +}; diff --git a/functions/oauth/mediawiki/callback.js b/functions/oauth/mediawiki/callback.js index 3d07cc9..dd565d9 100755 --- a/functions/oauth/mediawiki/callback.js +++ b/functions/oauth/mediawiki/callback.js @@ -1,16 +1,19 @@ -const { getToken, getMe } = require('../../../lib/oauth/mw.js') -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); +const { getToken, getMe } = require("../../../lib/oauth/mw.js"); +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); module.exports = async (state, code) => { if (state) { if (state == "abc123") { - return getToken(code, state) + return getToken(code, state); } } else { return { - headers: {"Location": "https://recaptime.miraheze.org/wiki/Portal:NoStateCodeDetected"}, + headers: { + Location: + "https://recaptime.miraheze.org/wiki/Portal:NoStateCodeDetected", + }, statusCode: 302, - body: Buffer.from('') - } + body: Buffer.from(""), + }; } -} \ No newline at end of file +}; diff --git a/functions/response.js b/functions/response.js index 9a01dd1..36d24b0 100755 --- a/functions/response.js +++ b/functions/response.js @@ -1,9 +1,8 @@ - return { statusCode: 404, - headers: {'Content-Type': 'application/json'}, + headers: { "Content-Type": "application/json" }, body: { ok: false, - error: "Endpoint not found" - } -}; \ No newline at end of file + error: "Endpoint not found", + }, +}; diff --git a/functions/updateCommands.js b/functions/updateCommands.js index 6c2c74f..051d8fb 100755 --- a/functions/updateCommands.js +++ b/functions/updateCommands.js @@ -1,39 +1,34 @@ -const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); -const slashCommandsConfig = require("../lib/slashCommands") +const lib = require("lib")({ token: process.env.STDLIB_SECRET_TOKEN }); +const slashCommandsConfig = require("../lib/slashCommands"); try { /** After all of these, public commands go here **/ - gitConnect = await lib.discord.commands['@0.0.0'].create({ + gitConnect = await lib.discord.commands["@0.0.0"].create({ name: slashCommandsConfig.connectGit.name, description: slashCommandsConfig.connectGit.description, - options: slashCommandsConfig.connectGit.options + options: slashCommandsConfig.connectGit.options, }); - verify = await lib.discord.commands['@0.0.0'].create({ + verify = await lib.discord.commands["@0.0.0"].create({ name: slashCommandsConfig.verify.name, - description: slashCommandsConfig.verify.description} - ); - userLookup = await lib.discord.commands['@0.0.0'].create({ + description: slashCommandsConfig.verify.description, + }); + userLookup = await lib.discord.commands["@0.0.0"].create({ name: slashCommandsConfig.userinfo.name, description: slashCommandsConfig.userinfo.description, - options: slashCommandsConfig.userinfo.options + options: slashCommandsConfig.userinfo.options, }); - updateCommands = await lib.discord.commands['@0.0.0'].create({ + updateCommands = await lib.discord.commands["@0.0.0"].create({ name: slashCommandsConfig.updateCommands.name, - description: slashCommandsConfig.updateCommands.description + description: slashCommandsConfig.updateCommands.description, }); - + return { statusCode: 200, body: { ok: true, - results: [ - gitConnect, - verify, - userLookup, - updateCommands - ] - } - } + results: [gitConnect, verify, userLookup, updateCommands], + }, + }; } catch (err) { console.warn(err); return { @@ -41,7 +36,7 @@ try { body: { ok: false, error: "Something went wrong.", - traceback: err - } - } -} \ No newline at end of file + traceback: err, + }, + }; +} diff --git a/lib/embeds/verify.js b/lib/embeds/verify.js index 12a0163..7d2c04c 100755 --- a/lib/embeds/verify.js +++ b/lib/embeds/verify.js @@ -1,11 +1,9 @@ function getEmbedTemplate(userId, serverId, submissionType) { if (submissionType == "content_creator") { - return { - - } + return {}; } } module.exports = { - getEmbedTemplate -} \ No newline at end of file + getEmbedTemplate, +}; diff --git a/lib/models/lookupIndex.js b/lib/models/lookupIndex.js index 7d5a81d..0200cf5 100755 --- a/lib/models/lookupIndex.js +++ b/lib/models/lookupIndex.js @@ -1,12 +1,44 @@ -const mongoose = require('mongoose'); +const mongoose = require("mongoose"); const Schema = mongoose.Schema; -const contentCreator = new Schema({ +const index = new Schema({ name: String, - type: "content_creator", - annonations: Object -}) + realName: { + type: String, + default: null + }, + socials: { + discord: [ + { + id: Number, + createdOn: Date, + discriminator: String + } + ], + twitter: [ + { + username: String, + id: Number, + createdOn: Date + } + ], + miraheze: [{ + username: String, + id: Number, + createdOn: Date + }], + telegram: [{ + username: { + type: String, + default: null + }, + id: Number + }] + }, + type: "content_creator" || "community" || "entity", + annonations: Object, +}); module.exports = { - contentCreator -} \ No newline at end of file + index, +}; diff --git a/lib/oauth/mw.js b/lib/oauth/mw.js index 59584ca..cd623a2 100755 --- a/lib/oauth/mw.js +++ b/lib/oauth/mw.js @@ -1,25 +1,25 @@ -const { loadEnvFromFile } = require("../secrets") -loadEnvFromFile() +const { loadEnvFromFile } = require("../secrets"); +loadEnvFromFile(); const authroot = process.env.MW_OAUTH_ROOT; -const authorize = `${authroot}/oauth2/authorize` -const token = `${authroot}/oauth2/access_token` -const profileurl = `${authroot}/oauth2/resource/profile` -const axios = require('axios'); +const authorize = `${authroot}/oauth2/authorize`; +const token = `${authroot}/oauth2/access_token`; +const profileurl = `${authroot}/oauth2/resource/profile`; +const axios = require("axios"); -function getRedirectUrl (oauthState) { - let callback = encodeURIComponent(process.env.MW_OAUTH_CALLBACK) - let str = `client_id=${process.env.MW_OAUTH_CLIENT_ID}&response_type=code&request_url=${callback}&state=${oauthState}` - return `${authorize}?${str}` +function getRedirectUrl(oauthState) { + let callback = encodeURIComponent(process.env.MW_OAUTH_CALLBACK); + let str = `client_id=${process.env.MW_OAUTH_CLIENT_ID}&response_type=code&request_url=${callback}&state=${oauthState}`; + return `${authorize}?${str}`; } /** * Gets an OAuth2 access token from specific server - * @param {"string"} respCode - * @param {"string"} oauthState - * @returns + * @param {"string"} respCode + * @param {"string"} oauthState + * @returns */ -function getToken (respCode, oauthState) { +function getToken(respCode, oauthState) { const oauthResult = axios(token, { method: "post", params: { @@ -28,19 +28,19 @@ function getToken (respCode, oauthState) { client_secret: process.env.MW_OAUTH_CLIENT_SECRET, redirect_url: process.env.MW_OAUTH_CALLBACK, code: respCode, - state: oauthState - } - }) + state: oauthState, + }, + }); console.log(oauthResult); - return oauthResult + return oauthResult; } -function getMe (token) { +function getMe(token) { // } module.exports = { getRedirectUrl, getToken, - getMe -} \ No newline at end of file + getMe, +}; diff --git a/lib/secrets.js b/lib/secrets.js index f9d4afd..99a7942 100644 --- a/lib/secrets.js +++ b/lib/secrets.js @@ -4,32 +4,17 @@ * when doing API development using Gitpod/containers. */ function loadEnvFromFile() { - const fs = require('fs'); - - fs.access("/opt/node_modules/autocode-common/configs", (err) => { - if (err) { - fs.access('env.json', (err) => { - /** - * If env.json exists locally, attempt to load them automagically within the Node.js process. - */ - const env = require("../env.json") - if (!err) { - process.env.MONGO_DATABASE = env.dev.MONGO_DATABASE - process.env.DISCORD_GUILD_ID = env.dev.DISCORD_GUILD_ID, - process.env.DISCORD_ROLE_ID = env.dev.DISCORD_GUILD_ID, - process.env.MW_OAUTH_CLIENT_ID = env.dev.MW_OAUTH_CLIENT_ID, - process.env.MW_OAUTH_CLIENT_SECRET = env.dev.MW_OAUTH_CLIENT_SECRET, - process.env.MW_MW_OAUTH_CALLBACK = env.dev.MW_OAUTH_CALLBACK, - process.env.MW_OAUTH_ROOT = env.dev.MW_OAUTH_ROOT - } else { - /** Otherwise, preload secrets using dotenv */ - require("dotenv").config() - } - }) - } - }); + const fs = require("fs"); + const env = require("../env.json") + if (process.env.LD == "/opt/node_modules/autocode-common/configs") { + // noop + } else { + Object.keys(env.dev).forEach(function (key) { + process.env[key] = env.dev[key] + }) + } } module.exports = { - loadEnvFromFile -} \ No newline at end of file + loadEnvFromFile, +}; diff --git a/lib/slashCommands.js b/lib/slashCommands.js index eecc8e3..4cdd9ac 100755 --- a/lib/slashCommands.js +++ b/lib/slashCommands.js @@ -1,28 +1,28 @@ module.exports = { verify: { - name: 'verify', + name: "verify", description: "Get you, your community or your company verified across Recap Time Squad's apps and through the API.", options: [], }, connectGit: { - name: 'connect-git', + name: "connect-git", description: - 'Connect your Discord account to your GitHub/GitLab SaaS username. Rerun this when you change them.', + "Connect your Discord account to your GitHub/GitLab SaaS username. Rerun this when you change them.", options: [ { type: 3, - name: 'host', + name: "host", description: "Git host we'll use to associate your CLA signature to your Discord account, among other things.", choices: [ { - name: 'GitHub', - value: 'github.com', + name: "GitHub", + value: "github.com", }, { - name: 'GitLab SaaS', - value: 'gitlab.com', + name: "GitLab SaaS", + value: "gitlab.com", }, ], required: true, @@ -30,14 +30,14 @@ module.exports = { ], }, userinfo: { - name: 'userinfo', - description: 'Query Discord user against the API for any associations.', + name: "userinfo", + description: "Query Discord user against the API for any associations.", options: [ { type: 6, - name: 'target_user', + name: "target_user", description: - 'Looks up either the mentioned Discord user or you against the API for any connected entries.', + "Looks up either the mentioned Discord user or you against the API for any connected entries.", }, ], }, @@ -48,72 +48,74 @@ module.exports = { options: [ { type: 3, - "name": "status", - "description": "Set the bot's status on Discord", - "choices": [ + name: "status", + description: "Set the bot's status on Discord", + choices: [ { - "name": "Online", - "value": "ONLINE" + name: "Online", + value: "ONLINE", }, { - "name": "Idle", - "value": "IDLE" + name: "Idle", + value: "IDLE", }, { - "name": "Do Not Disturb", - "value": "DND" + name: "Do Not Disturb", + value: "DND", }, { - "name": "Offline", - "value": "INVISIBLE" - } + name: "Offline", + value: "INVISIBLE", + }, ], - "required": true + required: true, }, { - "type": 3, - "name": "type", - "description": "Set the bot's activity type.", - "choices": [ + type: 3, + name: "type", + description: "Set the bot's activity type.", + choices: [ { - "name": "Playing", - "value": "GAME" + name: "Playing", + value: "GAME", }, { - "name": "Watching", - "value": "WATCHING" + name: "Watching", + value: "WATCHING", }, { - "name": "Listening to", - "value": "LISTENING" + name: "Listening to", + value: "LISTENING", }, { - "name": "Competing in", - "value": "COMPETING" + name: "Competing in", + value: "COMPETING", }, { - "name": "Streaming", - "value": "STREAMING" - } + name: "Streaming", + value: "STREAMING", + }, ], - "required": true + required: true, }, { - "type": 3, - "name": "name", - "description": "Set the name of your activity", - "required": true + type: 3, + name: "name", + description: "Set the name of your activity", + required: true, }, { - "type": 3, - "name": "url", - "description": "The URL your streaming status will link to. (Works on Streaming status only)" - } - ] + type: 3, + name: "url", + description: + "The URL your streaming status will link to. (Works on Streaming status only)", + }, + ], }, updateCommands: { name: "update-commands", - description: "Refreshes slash commands for this guild. Requires Manage Server perm to do this.", + description: + "Refreshes slash commands for this guild. Requires Manage Server perm to do this.", options: [], - } + }, };