Skip to content

Commit

Permalink
Merge pull request #216 from kgpmask/discord-hooks
Browse files Browse the repository at this point in the history
Separate discord hooks
  • Loading branch information
Goose-Of-War authored Jul 15, 2023
2 parents e9759c9 + e055ac5 commit d72989a
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 46 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# Server secrets
*credentials.*
*hook_links.json

# Testing template, test changes here
/templates/test*.njk
Expand Down
5 changes: 2 additions & 3 deletions routes/git-hook.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const crypto = require('crypto');
const router = require('express').Router();

const Tools = require('../src/tools');
const hooks = require('../src/hooks');

router.post('/', async (req, res) => {
// Console log git hook requests
Expand Down Expand Up @@ -42,7 +41,7 @@ router.post('/', async (req, res) => {
return process.exit(0);
} catch (err) {
console.log(`updateCode failed\n\tReason: ${err}`);
await Tools.alertToDiscord(pushBranch === 'dev' ? 'dev' : 'prod', req.body.head_commit, err);
await hooks.deployErrorHook(pushBranch === 'dev' ? 'dev' : 'prod', req.body.head_commit, err);
}
});

Expand Down
18 changes: 9 additions & 9 deletions routes/submission.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const router = require('express').Router();

const hooks = require('../src/hooks');
const dbh = require('../database/handler');

router.get('/', (req, res) => {
Expand All @@ -12,7 +12,8 @@ router.get('/', (req, res) => {

router.post('/', async (req, res) => {
if (PARAMS.mongoless) return res.status(403).send('Not allowed in mongoless');
const data = req.body.data;
// req.body = { email, name, member, link, proof, social }
const data = req.body;
if (!data.email) return res.send({ success: false, message: 'No email has been provided. Please check again.' });
if (!data.name) return res.send(
{ success: false, message: 'No name has been provided. Use "Anonymous" if you do not want to share your name.' }
Expand All @@ -22,14 +23,13 @@ router.post('/', async (req, res) => {
if (!data.link) return res.send({ success: false, message: 'No link has been provided.' });
if (!data.proof) delete data.proof;
if (!data.social) delete data.social;
try {
response = await dbh.addSubmission(data);
return res.send({ success: true, message: 'Successfully Added', response: response });
} catch (e) {
console.log(e);
return res.send({ success: false, message: 'Error while adding' });
// adding submission to db
const submission = await dbh.addSubmission(data);
// discord hook for submission form data
if (!PARAMS.discordless) {
await hooks.submissionHook(submission);
}
// Add a Discord hook to send a message in case of new submission
return res.status(200).send({ success: true, message: 'Your submission has been accepted', response: submission });
});

module.exports = {
Expand Down
14 changes: 12 additions & 2 deletions src/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ const aliases = {
q: 'quiz',
u: 'userless',
t: 'test',
j: 'jsonuser'
j: 'jsonuser',
d: 'discordless'
};
const validParams = ['dev', 'local', 'prod', 'mongoless', 'userless', 'quiz', 'test', 'maintenance', 'jsonuser'];
const validParams = ['dev', 'local', 'prod', 'mongoless', 'userless', 'quiz', 'test', 'maintenance', 'jsonuser', 'discordless'];
if (!global.PARAMS) {
if (process.env['NODE_ENV'] === 'production') process.env.prod = true;
const shorts = new Set();
Expand Down Expand Up @@ -60,4 +61,13 @@ exports.init = () => {
if (!PARAMS.prod) process.env.MONGO_URL = process.env.MONGO_TEST_URL;
if (PARAMS.local) process.env.MONGO_URL = 'mongodb://127.0.0.1/mask';
if (PARAMS.maintenance) PARAMS.mongoless = PARAMS.userless = true;
if (!PARAMS.discordless) {
try {
const hookData = require('./hook_links.json');
process.env.DISCORD_HOOKS = JSON.stringify(hookData);
} catch (err) {
PARAMS.discordless = true;
console.log('Operating in discordless mode.');
}
}
};
55 changes: 55 additions & 0 deletions src/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const axios = require('axios');
const hooks = !PARAMS.discordless ? JSON.parse(process.env.DISCORD_HOOKS) : {};

async function deployErrorHook (env, commit, err) {
// env: prod | dev
const webhookLink = hooks.deploy;
const webhookObject = {
embeds: [
{
title: `Deploy failed in ${env}`,
fields: [
{ name: 'Error', value: `${err}` },
{ name: 'Commit', value: `\`${commit.id.slice(0, 7)}\` ${commit.message}` }
]
}
]
};
await axios.post(webhookLink, webhookObject);
return 'Success';
}

async function submissionHook (data) {
const webhookLink = hooks.submission;
const dataTypes = {
'dig-art': 'Digital Art',
'trd-art': 'Traditional Art',
'amv-vid': 'AMV Video',
'ani-vid': 'Animation Video',
'ins-mus': 'Instrumental Music',
'voc-mus': 'Vocal Music'
};
const webhookObject = {
embeds: [
{
title: `Submission: ${ dataTypes[data.type] }`,
fields: [
{ name: 'Email', value: `${ data.email }` },
{ name: 'Name', value: `${ data.name }` },
{ name: 'Link', value: `[Submission Link](${ data.link })` },
{ name: 'Member of KGP', value: `${ data.member ? 'Yes' : 'No' }`, inline: true },
{ name: 'Proof', value: `${ data.proof ?? 'Not provided' }`, inline: true }
]
}
]
};
await axios.post(webhookLink, webhookObject);
return 'Success';
}


module.exports = {
deployErrorHook,
submissionHook
};

25 changes: 0 additions & 25 deletions src/tools.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const axios = require('axios');
const childProcess = require('child_process');
const util = require('util');

Expand Down Expand Up @@ -115,30 +114,6 @@ exports.updateCode = async function () {
return { gitFetch, gitMerge, npmInstall };
};

exports.alertToDiscord = async function (env, commit, err) {
// env: prod | dev
const webhookLink = process.env.DISCORD_WEBHOOK_LINK;
const webhookObject = {
embeds: [
{
title: `Deploy failed in ${env}`,
fields: [
{
name: 'Error',
value: `${err}`
},
{
name: 'Commit',
value: `\`${commit.id.slice(0, 7)}\` ${commit.message}`
}
]
}
]
};
await axios.post(webhookLink, webhookObject);
return 'Success';
};

/*************
* Prototypes *
*************/
Expand Down
5 changes: 3 additions & 2 deletions templates/submissions.njk
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@
async function submitForm () {
const data = getData();
var response = (await axios.post('/submissions', { data: data })).data;
console.log(data);
const response = (await axios.post('/submissions', data)).data;
message(response, '/');
}
</script>
{% endblock %}
{% endblock %}
9 changes: 7 additions & 2 deletions test/site-mongoless.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const PORT = 42070;
process.env.PORT = PORT;
global.PARAMS = { mongoless: true, test: true, userless: true };
global.PARAMS = { mongoless: true, test: true, userless: true, discordless: true };

const assert = require('assert');
const axios = require('axios');
Expand All @@ -14,7 +14,12 @@ describe('Server (Mongoless mode)', () => {
await server.ready();
});

it('should have the right PARAMS object', () => assert.deepEqual(PARAMS, { mongoless: true, test: true, userless: true }));
it('should have the right PARAMS object', () => assert.deepEqual(PARAMS, {
mongoless: true,
test: true,
userless: true,
discordless: true
}));

pages.forEach(page => {
it(`should serve page (${page || '/'})`, () => axios.get(`http://localhost:${PORT}/${page}`))
Expand Down
8 changes: 6 additions & 2 deletions test/site-userless.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const PORT = 42071;
process.env.PORT = PORT;
global.PARAMS = { test: true, userless: true };
global.PARAMS = { test: true, userless: true, discordless: true };

const assert = require('assert');
const axios = require('axios');
Expand All @@ -15,7 +15,11 @@ describe('Server (Userless mode)', () => {
await server.ready();
});

it('should have the right PARAMS object', () => assert.deepEqual(PARAMS, { test: true, userless: true }));
it('should have the right PARAMS object', () => assert.deepEqual(PARAMS, {
test: true,
userless: true,
discordless: true
}));

pages.forEach(page => {
it(`should serve page (${page || '/'})`, () => axios.get(`http://localhost:${PORT}/${page}`))
Expand Down
3 changes: 2 additions & 1 deletion test/site.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const PORT = 42069;
process.env.PORT = PORT;
global.PARAMS = { test: true, discordless: true };

const assert = require('assert');
const axios = require('axios');
Expand Down Expand Up @@ -27,7 +28,7 @@ describe('Server', () => {
}).timeout(10_000);
});

it('should have the right PARAMS object', () => assert.deepEqual(PARAMS, { test: true }));
it('should have the right PARAMS object', () => assert.deepEqual(PARAMS, { test: true, discordless: true }));

pages.forEach(page => {
it(`should serve page (${page || '/'})`, () => axios.get(`http://localhost:${PORT}/${page}`))
Expand Down

0 comments on commit d72989a

Please sign in to comment.