Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom webhooks #118

Merged
merged 28 commits into from
Aug 29, 2020
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
f7d162b
Add custom webhooks for votes
Aug 23, 2020
81cb93d
Merge remote-tracking branch 'origin/master' into master
Aug 23, 2020
2ffed72
Fix merge conflicts
Aug 23, 2020
77d08d2
Use logger instead of console.log
Aug 23, 2020
a268f9a
Update example & test config
Aug 23, 2020
e5aa631
Refactor custom webhooks
Aug 23, 2020
7ae97e4
Change submission id to UUID
Aug 23, 2020
2597a57
Update user status to include self remove
Aug 23, 2020
14a990f
Remove duplicate isOwnSubmission
Aug 23, 2020
20d813d
Fix missing semicolon
Aug 23, 2020
9eddc33
Move getVoteAuthor to webhookUtils and move user status (api) to webh…
Aug 23, 2020
a897c31
Remove broken and unnecessary check
Aug 23, 2020
16777c3
Change .size to .length
Aug 23, 2020
aca4318
Move dispatchEvent to webhookUtils
Aug 24, 2020
2c70f87
Add webhooks to postSkipSegments
Aug 24, 2020
5c9aa8c
Cleaned up function names
Aug 24, 2020
3085b0e
Remove random s
Aug 24, 2020
75a62a5
make tests hit webhook code
Joe-Dowd Aug 24, 2020
72b3173
Merge pull request #1 from Joe-Dowd/testing-custom-webhooks
Aug 24, 2020
3066a07
added failed webhook call to tests
Joe-Dowd Aug 24, 2020
2dc5dea
Merge pull request #2 from Joe-Dowd/testing-custom-webhooks
TAG-Epic Aug 24, 2020
eb9282c
add unresolvable host test - introduces tets faiulure
Joe-Dowd Aug 24, 2020
ec1a294
Merge pull request #3 from Joe-Dowd/testing-custom-webhooks
TAG-Epic Aug 24, 2020
3563924
Fixed undesolved test error
Joe-Dowd Aug 24, 2020
dc7dadd
tidy undesolved fix
Joe-Dowd Aug 24, 2020
83ec232
added wrong port test
Joe-Dowd Aug 24, 2020
f7ea706
Merge pull request #4 from Joe-Dowd/testing-custom-webhooks
TAG-Epic Aug 24, 2020
800a3df
Send webhooks after response
ajayyy Aug 29, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@
"dbSchema": "./databases/_sponsorTimes.db.sql",
"privateDBSchema": "./databases/_private.db.sql",
"mode": "development",
"readOnly": false
"readOnly": false,
"webhooks": []
ajayyy marked this conversation as resolved.
Show resolved Hide resolved
}
110 changes: 67 additions & 43 deletions src/routes/voteOnSponsorTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ var config = require('../config.js');
var getHash = require('../utils/getHash.js');
var getIP = require('../utils/getIP.js');
var getFormattedTime = require('../utils/getFormattedTime.js');
var isUserTrustworthy = require('../utils/isUserTrustworthy.js')
var isUserTrustworthy = require('../utils/isUserTrustworthy.js');
const dispatchWebhooks = require('../utils/dispatchWebhooks.js');
const {getVoteAuthor, getVoteAuthorRaw} = require('../utils/webhookUtils.js');


var databases = require('../databases/databases.js');
var db = databases.db;
Expand All @@ -13,17 +16,6 @@ var YouTubeAPI = require('../utils/youtubeAPI.js');
var request = require('request');
const logger = require('../utils/logger.js');

function getVoteAuthor(submissionCount, isVIP, isOwnSubmission) {
if (submissionCount === 0) {
return "Report by New User";
} else if (isVIP) {
return "Report by VIP User";
} else if (isOwnSubmission) {
return "Report by Submitter";
}

return "";
}

function categoryVote(UUID, userID, isVIP, category, hashedIP, res) {
// Check if they've already made a vote
Expand Down Expand Up @@ -194,41 +186,72 @@ async function voteOnSponsorTime(req, res) {
}
}

// Send discord message
if (incrementAmount < 0) {
// Get video ID
let submissionInfoRow = db.prepare('get', "SELECT s.videoID, s.userID, s.startTime, s.endTime, s.category, u.userName, " +
"(select count(1) from sponsorTimes where userID = s.userID) count, " +
"(select count(1) from sponsorTimes where userID = s.userID and votes <= -2) disregarded " +
"FROM sponsorTimes s left join userNames u on s.userID = u.userID where s.UUID=?",
[UUID]);

let userSubmissionCountRow = db.prepare('get', "SELECT count(*) as submissionCount FROM sponsorTimes WHERE userID = ?", [nonAnonUserID]);

if (submissionInfoRow !== undefined && userSubmissionCountRow != undefined) {
let webhookURL = null;
if (voteTypeEnum === voteTypes.normal) {
webhookURL = config.discordReportChannelWebhookURL;
} else if (voteTypeEnum === voteTypes.incorrect) {
webhookURL = config.discordCompletelyIncorrectReportWebhookURL;
}

if (config.youtubeAPIKey !== null && webhookURL !== null) {
YouTubeAPI.videos.list({
part: "snippet",
id: submissionInfoRow.videoID
}, function (err, data) {
if (err || data.items.length === 0) {
err && logger.error(err);
return;
// Get video ID
let submissionInfoRow = db.prepare('get', "SELECT s.videoID, s.userID, s.startTime, s.endTime, s.category, u.userName, " +
"(select count(1) from sponsorTimes where userID = s.userID) count, " +
"(select count(1) from sponsorTimes where userID = s.userID and votes <= -2) disregarded " +
"FROM sponsorTimes s left join userNames u on s.userID = u.userID where s.UUID=?",
[UUID]);

let userSubmissionCountRow = db.prepare('get', "SELECT count(*) as submissionCount FROM sponsorTimes WHERE userID = ?", [nonAnonUserID]);

if (submissionInfoRow !== undefined && userSubmissionCountRow != undefined) {
let webhookURL = null;
if (voteTypeEnum === voteTypes.normal) {
webhookURL = config.discordReportChannelWebhookURL;
} else if (voteTypeEnum === voteTypes.incorrect) {
webhookURL = config.discordCompletelyIncorrectReportWebhookURL;
}

if (config.youtubeAPIKey !== null) {
YouTubeAPI.videos.list({
part: "snippet",
id: submissionInfoRow.videoID
}, function (err, data) {
if (err || data.items.length === 0) {
err && logger.error(err);
return;
}
let isUpvote = incrementAmount > 0;
// Send custom webhooks
dispatchWebhooks(isUpvote ? "vote.up" : "vote.down", {
"user": {
"status": getVoteAuthorRaw(userSubmissionCountRow.submissionCount, isVIP, isOwnSubmission)
},
"video": {
"id": submissionInfoRow.videoID,
"title": data.items[0].snippet.title,
"url": "https://www.youtube.com/watch?v=" + submissionInfoRow.videoID,
"thumbnail": data.items[0].snippet.thumbnails.maxres ? data.items[0].snippet.thumbnails.maxres.url : ""
},
"submission": {
"UUID": UUID,
"views": row.views,
"category": category,
"startTime": submissionInfoRow.startTime,
"endTime": submissionInfoRow.endTime,
"user": {
"UUID": submissionInfoRow.userID,
"username": submissionInfoRow.userName,
"submissions": {
"total": submissionInfoRow.count,
"ignored": submissionInfoRow.disregarded
}
}
},
"votes": {
"before": row.votes,
"after": (row.votes + incrementAmount - oldIncrementAmount)
}

});
// Send discord message
if (webhookURL !== null && !isUpvote) {
request.post(webhookURL, {
json: {
"embeds": [{
"title": data.items[0].snippet.title,
"url": "https://www.youtube.com/watch?v=" + submissionInfoRow.videoID
+ "&t=" + (submissionInfoRow.startTime.toFixed(0) - 2),
+ "&t=" + (submissionInfoRow.startTime.toFixed(0) - 2),
"description": "**" + row.votes + " Votes Prior | " + (row.votes + incrementAmount - oldIncrementAmount) + " Votes Now | " + row.views
+ " Views**\n\n**Submission ID:** " + UUID
+ "\n**Category:** " + submissionInfoRow.category
Expand Down Expand Up @@ -257,8 +280,9 @@ async function voteOnSponsorTime(req, res) {
logger.error("\n");
}
});
});
}
}

});
}
}

Expand Down
22 changes: 22 additions & 0 deletions src/utils/dispatchWebhooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const config = require("../config.js");
const logger = require('../utils/logger.js');
const request = require('request');


function dispatchEvent(scope, data) {
let webhooks = config.webhooks;
if (webhooks === undefined || webhooks.length === 0) return;
logger.debug("Dispatching webhooks");
webhooks.forEach(webhook => {
let webhookURL = webhook.url;
let authKey = webhook.key;
let scopes = webhook.scopes || [];
if (!scopes.includes(scope.toLowerCase())) return;
request.post(webhookURL, {json: data, headers: {
"Authorization": authKey,
"Event-Type": scope // Maybe change this in the future?
}});
});
}
TAG-Epic marked this conversation as resolved.
Show resolved Hide resolved

module.exports = dispatchEvent;
26 changes: 26 additions & 0 deletions src/utils/webhookUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
function getVoteAuthorRaw(submissionCount, isVIP, isOwnSubmission) {
if (isOwnSubmission) {
return "self";
} else if (isVIP) {
return "vip";
} else if (submissionCount === 0) {
return "new";
} else {
return "other";
};
};

function getVoteAuthor(submissionCount, isVIP, isOwnSubmission) {
if (submissionCount === 0) {
return "Report by New User";
} else if (isVIP) {
return "Report by VIP User";
} else if (isOwnSubmission) {
return "Report by Submitter";
}

return "";
}

module.exports.getVoteAuthorRaw = getVoteAuthorRaw;
module.exports.getVoteAuthor = getVoteAuthor;
TAG-Epic marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 2 additions & 1 deletion test.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
"dbSchema": "./databases/_sponsorTimes.db.sql",
"privateDBSchema": "./databases/_private.db.sql",
"mode": "test",
"readOnly": false
"readOnly": false,
"webhooks": []
}