From 078d44980ba85863582bb8d16db753f41b0e6935 Mon Sep 17 00:00:00 2001 From: Michael C Date: Thu, 27 Oct 2022 01:37:13 -0400 Subject: [PATCH 1/8] partial rewrite --- src/routes/postSkipSegments.ts | 34 +++++++------ src/routes/voteOnSponsorTime.ts | 84 +++++++++++++-------------------- src/types/webhook.model.ts | 42 +++++++++++++++++ src/utils/webhookUtils.ts | 42 +++++++++++++++-- test/cases/webhoook.ts | 0 5 files changed, 133 insertions(+), 69 deletions(-) create mode 100644 src/types/webhook.model.ts create mode 100644 test/cases/webhoook.ts diff --git a/src/routes/postSkipSegments.ts b/src/routes/postSkipSegments.ts index b6d6947f..78b38847 100644 --- a/src/routes/postSkipSegments.ts +++ b/src/routes/postSkipSegments.ts @@ -46,22 +46,25 @@ async function sendWebhookNotification(userID: string, videoID: string, UUID: st } dispatchEvent(scopeName, { - "video": { - "id": videoID, - "title": youtubeData?.title, - "thumbnail": getMaxResThumbnail(videoID), - "url": `https://www.youtube.com/watch?v=${videoID}`, + user: { + status: "new" }, - "submission": { - "UUID": UUID, - "category": segmentInfo.category, - "startTime": submissionStart, - "endTime": submissionEnd, - "user": { - "UUID": userID, - "username": userName, - }, + video: { + id: (videoID as VideoID), + title: youtubeData?.title, + url: `https://www.youtube.com/watch?v=${videoID}`, + thumbnail: getMaxResThumbnail(videoID), }, + submission: { + UUID: UUID as SegmentUUID, + category: segmentInfo.category, + startTime: submissionStart, + endTime: submissionEnd, + user: { + UUID: userID as HashedUserID, + username: userName, + }, + } }); } @@ -71,6 +74,7 @@ async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, video const startTime = parseFloat(segmentInfo.segment[0]); const endTime = parseFloat(segmentInfo.segment[1]); + const webhookData = sendWebhookNotification(userID, videoID, UUID, userSubmissionCountRow.submissionCount, apiVideoDetails, { submissionStart: startTime, submissionEnd: endTime, @@ -78,7 +82,7 @@ async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, video // If it is a first time submission // Then send a notification to discord - if (config.discordFirstTimeSubmissionsWebhookURL === null || userSubmissionCountRow.submissionCount > 1) return; + if (!config.discordFirstTimeSubmissionsWebhookURL || userSubmissionCountRow.submissionCount > 1) return; axios.post(config.discordFirstTimeSubmissionsWebhookURL, { embeds: [{ diff --git a/src/routes/voteOnSponsorTime.ts b/src/routes/voteOnSponsorTime.ts index 186c8f9f..dafc3c35 100644 --- a/src/routes/voteOnSponsorTime.ts +++ b/src/routes/voteOnSponsorTime.ts @@ -4,8 +4,8 @@ import { isUserVIP } from "../utils/isUserVIP"; import { isUserTempVIP } from "../utils/isUserTempVIP"; import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi"; import { db, privateDB } from "../databases/databases"; -import { dispatchEvent, getVoteAuthor, getVoteAuthorRaw } from "../utils/webhookUtils"; -import { getFormattedTime } from "../utils/getFormattedTime"; +import { dispatchEvent, getVoteAuthorRaw, createDiscordVoteEmbed } from "../utils/webhookUtils"; +import { WebhookData } from "../types/webhook.model"; import { getIP } from "../utils/getIP"; import { getHashCache } from "../utils/getHashCache"; import { config } from "../config"; @@ -35,7 +35,7 @@ interface FinalResponse { } interface VoteData { - UUID: string; + UUID: SegmentUUID; nonAnonUserID: string; originalType: VoteType; voteTypeEnum: number; @@ -47,7 +47,7 @@ interface VoteData { views: number; locked: boolean; }; - category: string; + category: Category; incrementAmount: number; oldIncrementAmount: number; finalResponse: FinalResponse; @@ -101,7 +101,7 @@ async function checkVideoDuration(UUID: SegmentUUID) { } async function sendWebhooks(voteData: VoteData) { - const submissionInfoRow = await db.prepare("get", `SELECT "s"."videoID", "s"."userID", s."startTime", s."endTime", s."category", u."userName", + const submissionInfoRow = await 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"=?`, @@ -133,62 +133,44 @@ async function sendWebhooks(voteData: VoteData) { const isUpvote = voteData.incrementAmount > 0; // Send custom webhooks - dispatchEvent(isUpvote ? "vote.up" : "vote.down", { - "user": { - "status": getVoteAuthorRaw(userSubmissionCountRow.submissionCount, voteData.isTempVIP, voteData.isVIP, voteData.isOwnSubmission), + const webhookData: WebhookData = { + user: { + status: getVoteAuthorRaw(userSubmissionCountRow.submissionCount, voteData.isTempVIP, voteData.isVIP, voteData.isOwnSubmission), }, - "video": { - "id": submissionInfoRow.videoID, - "title": data?.title, - "url": `https://www.youtube.com/watch?v=${videoID}`, - "thumbnail": getMaxResThumbnail(videoID), + video: { + id: submissionInfoRow.videoID, + title: data?.title, + url: `https://www.youtube.com/watch?v=${videoID}`, + thumbnail: getMaxResThumbnail(videoID), }, - "submission": { - "UUID": voteData.UUID, - "views": voteData.row.views, - "category": voteData.category, - "startTime": submissionInfoRow.startTime, - "endTime": submissionInfoRow.endTime, - "user": { - "UUID": submissionInfoRow.userID, - "username": submissionInfoRow.userName, - "submissions": { - "total": submissionInfoRow.count, - "ignored": submissionInfoRow.disregarded, + submission: { + UUID: voteData.UUID as SegmentUUID, + views: voteData.row.views, + locked: voteData.row.locked, + category: voteData.category as Category, + startTime: submissionInfoRow.startTime, + endTime: submissionInfoRow.endTime, + user: { + UUID: submissionInfoRow.userID, + username: submissionInfoRow.userName, + submissions: { + total: submissionInfoRow.count, + ignored: submissionInfoRow.disregarded, }, }, }, - "votes": { - "before": voteData.row.votes, - "after": (voteData.row.votes + voteData.incrementAmount - voteData.oldIncrementAmount), + votes: { + before: voteData.row.votes, + after: (voteData.row.votes + voteData.incrementAmount - voteData.oldIncrementAmount), }, - }); + authorName: voteData.finalResponse?.webhookMessage ?? voteData.finalResponse?.finalMessage + }; + dispatchEvent(isUpvote ? "vote.up" : "vote.down", webhookData); // Send discord message if (webhookURL !== null && !isUpvote) { axios.post(webhookURL, { - "embeds": [{ - "title": data?.title, - "url": `https://www.youtube.com/watch?v=${submissionInfoRow.videoID}&t=${(submissionInfoRow.startTime.toFixed(0) - 2)}s#requiredSegment=${voteData.UUID}`, - "description": `**${voteData.row.votes} Votes Prior | \ - ${(voteData.row.votes + voteData.incrementAmount - voteData.oldIncrementAmount)} Votes Now | ${voteData.row.views} \ - Views**\n\n**Locked**: ${voteData.row.locked}\n\n**Submission ID:** ${voteData.UUID}\ - \n**Category:** ${submissionInfoRow.category}\ - \n\n**Submitted by:** ${submissionInfoRow.userName}\n${submissionInfoRow.userID}\ - \n\n**Total User Submissions:** ${submissionInfoRow.count}\ - \n**Ignored User Submissions:** ${submissionInfoRow.disregarded}\ - \n\n**Timestamp:** \ - ${getFormattedTime(submissionInfoRow.startTime)} to ${getFormattedTime(submissionInfoRow.endTime)}`, - "color": 10813440, - "author": { - "name": voteData.finalResponse?.webhookMessage ?? - voteData.finalResponse?.finalMessage ?? - `${getVoteAuthor(userSubmissionCountRow.submissionCount, voteData.isTempVIP, voteData.isVIP, voteData.isOwnSubmission)}${voteData.row.locked ? " (Locked)" : ""}`, - }, - "thumbnail": { - "url": getMaxResThumbnail(videoID), - }, - }], + "embeds": [createDiscordVoteEmbed(webhookData)], }) .then(res => { if (res.status >= 400) { diff --git a/src/types/webhook.model.ts b/src/types/webhook.model.ts new file mode 100644 index 00000000..5538ddda --- /dev/null +++ b/src/types/webhook.model.ts @@ -0,0 +1,42 @@ +import * as segments from "./segments.model"; +import { HashedUserID } from "./user.model"; + +export enum voteType { + "up" = "vote.up", + "down" = "vote.down", +} + +export type authorType = "self" | "temp vip" | "vip" | "new" | "other"; + +export interface WebhookData { + user: { + status: authorType + } + video: { + id: segments.VideoID + title: string | undefined, + url: URL | string, + thumbnail: URL | string, + }, + submission: { + UUID: segments.SegmentUUID, + views?: number, + locked?: boolean, + category: segments.Category, + startTime: number, + endTime: number, + user: { + UUID: HashedUserID, + username: string | HashedUserID, + submissions?: { + total: number, + ignored: number, + }, + }, + }, + votes?: { + before: number, + after: number + } + authorName?: string +} \ No newline at end of file diff --git a/src/utils/webhookUtils.ts b/src/utils/webhookUtils.ts index 7180a98f..c30311df 100644 --- a/src/utils/webhookUtils.ts +++ b/src/utils/webhookUtils.ts @@ -1,8 +1,10 @@ import { config } from "../config"; import { Logger } from "../utils/logger"; +import { authorType, WebhookData } from "../types/webhook.model"; +import { getFormattedTime } from "../utils/getFormattedTime"; import axios from "axios"; -function getVoteAuthorRaw(submissionCount: number, isTempVIP: boolean, isVIP: boolean, isOwnSubmission: boolean): string { +function getVoteAuthorRaw(submissionCount: number, isTempVIP: boolean, isVIP: boolean, isOwnSubmission: boolean): authorType { if (isOwnSubmission) { return "self"; } else if (isTempVIP) { @@ -30,7 +32,40 @@ function getVoteAuthor(submissionCount: number, isTempVIP: boolean, isVIP: boole return ""; } -function dispatchEvent(scope: string, data: Record): void { +const voteAuthorMap: Record = { + "self": "Report by Submitter", + "temp vip": "Report by Temp VIP", + "vip": "Report by VIP User", + "new": "Report by New User", + "other": "" +}; + +const createDiscordVoteEmbed = (data: WebhookData) => { + const startTime = Math.max(0, data.submission.startTime - 2); + const startTimeParam = startTime > 0 ? `&t=${startTime}s` : ""; + return { + title: data.video.title, + url: `https://www.youtube.com/watch?v=${data.video.id}${startTimeParam}#requiredSegment=${data.submission.UUID}`, + description: `**${data.votes.before} Votes Prior | \ + ${(data.votes.after)} Votes Now | ${data.submission.views} \ + Views**\n\n**Locked**: ${data.submission.locked}\n\n**Submission ID:** ${data.submission.UUID}\ + \n**Category:** ${data.submission.category}\ + \n\n**Submitted by:** ${data.submission.user.username}\n${data.submission.user.UUID}\ + \n\n**Total User Submissions:** ${data.submission.user.submissions.total}\ + \n**Ignored User Submissions:** ${data.submission.user.submissions.ignored}\ + \n\n**Timestamp:** \ + ${getFormattedTime(data.submission.startTime)} to ${getFormattedTime(data.submission.endTime)}`, + color: 10813440, + author: { + name: data.authorName ?? `${voteAuthorMap[data.user.status]}${data.submission.locked ? " (Locked)" : ""}`, + }, + thumbnail: { + url: data.video.thumbnail, + }, + }; +}; + +function dispatchEvent(scope: string, data: WebhookData): void { const webhooks = config.webhooks; if (webhooks === undefined || webhooks.length === 0) return; Logger.debug("Dispatching webhooks"); @@ -61,4 +96,5 @@ export { getVoteAuthorRaw, getVoteAuthor, dispatchEvent, -}; + createDiscordVoteEmbed +}; \ No newline at end of file diff --git a/test/cases/webhoook.ts b/test/cases/webhoook.ts new file mode 100644 index 00000000..e69de29b From 3a0de295e0f025789110406054f80a09a0395c98 Mon Sep 17 00:00:00 2001 From: Ajay Date: Sun, 22 Jan 2023 18:59:51 -0500 Subject: [PATCH 2/8] remove temp server outage error --- src/routes/postSkipSegments.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/postSkipSegments.ts b/src/routes/postSkipSegments.ts index 78b38847..58d57c96 100644 --- a/src/routes/postSkipSegments.ts +++ b/src/routes/postSkipSegments.ts @@ -348,7 +348,7 @@ async function checkByAutoModerator(videoID: any, userID: any, segments: Array Date: Sun, 1 Jan 2023 02:50:49 -0500 Subject: [PATCH 3/8] add ETag to skipSegments byHash --- src/app.ts | 3 ++ src/middleware/cors.ts | 2 +- src/middleware/etag.ts | 48 +++++++++++++++++++++++++++++ src/routes/getSkipSegmentsByHash.ts | 4 +++ src/utils/queryCacher.ts | 14 ++++++++- src/utils/redis.ts | 2 ++ 6 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 src/middleware/etag.ts diff --git a/src/app.ts b/src/app.ts index 61b23475..d680073a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -50,6 +50,7 @@ import { getVideoLabelsByHash } from "./routes/getVideoLabelByHash"; import { addFeature } from "./routes/addFeature"; import { generateTokenRequest } from "./routes/generateToken"; import { verifyTokenRequest } from "./routes/verifyToken"; +import { cacheMiddlware } from "./middleware/etag"; export function createServer(callback: () => void): Server { // Create a service (the app object is just a callback). @@ -57,11 +58,13 @@ export function createServer(callback: () => void): Server { const router = ExpressPromiseRouter(); app.use(router); + app.set("etag", false); // disable built in etag //setup CORS correctly router.use(corsMiddleware); router.use(loggerMiddleware); router.use("/api/", apiCspMiddleware); + router.use(cacheMiddlware); router.use(express.json()); if (config.userCounterURL) router.use(userCounter); diff --git a/src/middleware/cors.ts b/src/middleware/cors.ts index e3b71ab5..6e5f2c2c 100644 --- a/src/middleware/cors.ts +++ b/src/middleware/cors.ts @@ -3,6 +3,6 @@ import { NextFunction, Request, Response } from "express"; export function corsMiddleware(req: Request, res: Response, next: NextFunction): void { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE"); - res.header("Access-Control-Allow-Headers", "Content-Type"); + res.header("Access-Control-Allow-Headers", "Content-Type, If-None-Match"); next(); } diff --git a/src/middleware/etag.ts b/src/middleware/etag.ts new file mode 100644 index 00000000..4a7cb58b --- /dev/null +++ b/src/middleware/etag.ts @@ -0,0 +1,48 @@ +import { NextFunction, Request, Response } from "express"; +import { VideoID, VideoIDHash, Service } from "../types/segments.model"; +import { QueryCacher } from "../utils/queryCacher"; +import { skipSegmentsHashKey, skipSegmentsKey, videoLabelsHashKey, videoLabelsKey } from "../utils/redisKeys"; + +type hashType = "skipSegments" | "skipSegmentsHash" | "videoLabel" | "videoLabelHash"; +type ETag = `${hashType};${VideoIDHash};${Service};${number}`; + +export function cacheMiddlware(req: Request, res: Response, next: NextFunction): void { + const reqEtag = req.get("If-None-Match") as string; + // if weak etag, do not handle + if (!reqEtag || reqEtag.startsWith("W/")) return next(); + // split into components + const [hashType, hashKey, service, lastModified] = reqEtag.split(";"); + // fetch last-modified + getLastModified(hashType as hashType, hashKey as VideoIDHash, service as Service) + .then(redisLastModified => { + if (redisLastModified <= new Date(Number(lastModified) + 1000)) { + // match cache, generate etag + const etag = `${hashType};${hashKey};${service};${redisLastModified.getTime()}` as ETag; + res.status(304).set("etag", etag).send(); + } + else next(); + }) + .catch(next); +} + +function getLastModified(hashType: hashType, hashKey: (VideoID | VideoIDHash), service: Service): Promise { + let redisKey: string | null; + if (hashType === "skipSegments") redisKey = skipSegmentsKey(hashKey as VideoID, service); + else if (hashType === "skipSegmentsHash") redisKey = skipSegmentsHashKey(hashKey as VideoIDHash, service); + else if (hashType === "videoLabel") redisKey = videoLabelsKey(hashKey as VideoID, service); + else if (hashType === "videoLabelHash") redisKey = videoLabelsHashKey(hashKey as VideoIDHash, service); + else return Promise.reject(); + return QueryCacher.getKeyLastModified(redisKey); +} + +export async function getEtag(hashType: hashType, hashKey: VideoIDHash, service: Service): Promise { + const lastModified = await getLastModified(hashType, hashKey, service); + return `${hashType};${hashKey};${service};${lastModified.getTime()}` as ETag; +} + +/* example usage +import { getEtag } from "../middleware/etag"; +await getEtag(hashType, hashPrefix, service) + .then(etag => res.set("ETag", etag)) + .catch(() => null); +*/ \ No newline at end of file diff --git a/src/routes/getSkipSegmentsByHash.ts b/src/routes/getSkipSegmentsByHash.ts index 7847879a..270ade28 100644 --- a/src/routes/getSkipSegmentsByHash.ts +++ b/src/routes/getSkipSegmentsByHash.ts @@ -4,6 +4,7 @@ import { Request, Response } from "express"; import { ActionType, Category, SegmentUUID, VideoIDHash, Service } from "../types/segments.model"; import { getService } from "../utils/getService"; import { Logger } from "../utils/logger"; +import { getEtag } from "../middleware/etag"; export async function getSkipSegmentsByHash(req: Request, res: Response): Promise { let hashPrefix = req.params.prefix as VideoIDHash; @@ -69,6 +70,9 @@ export async function getSkipSegmentsByHash(req: Request, res: Response): Promis const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, requiredSegments, service); try { + await getEtag("skipSegmentsHash", hashPrefix, service) + .then(etag => res.set("ETag", etag)) + .catch(() => null); const output = Object.entries(segments).map(([videoID, data]) => ({ videoID, segments: data.segments, diff --git a/src/utils/queryCacher.ts b/src/utils/queryCacher.ts index 1b3f6a18..6b022682 100644 --- a/src/utils/queryCacher.ts +++ b/src/utils/queryCacher.ts @@ -87,6 +87,17 @@ function clearSegmentCache(videoInfo: { videoID: VideoID; hashedVideoID: VideoID } } +async function getKeyLastModified(key: string): Promise { + if (!config.redis?.enabled) return Promise.reject("ETag - Redis not enabled"); + return await redis.ttl(key) + .then(ttl => { + const sinceLive = config.redis?.expiryTime - ttl; + const now = Math.floor(Date.now() / 1000); + return new Date((now-sinceLive) * 1000); + }) + .catch(() => Promise.reject("ETag - Redis error")); +} + function clearRatingCache(videoInfo: { hashedVideoID: VideoIDHash; service: Service;}): void { if (videoInfo) { redis.del(ratingHashKey(videoInfo.hashedVideoID, videoInfo.service)).catch((err) => Logger.error(err)); @@ -101,6 +112,7 @@ export const QueryCacher = { get, getAndSplit, clearSegmentCache, + getKeyLastModified, clearRatingCache, - clearFeatureCache + clearFeatureCache, }; \ No newline at end of file diff --git a/src/utils/redis.ts b/src/utils/redis.ts index 01761aee..ef55906f 100644 --- a/src/utils/redis.ts +++ b/src/utils/redis.ts @@ -19,6 +19,7 @@ interface RedisSB { del(...keys: [RedisCommandArgument]): Promise; increment?(key: RedisCommandArgument): Promise; sendCommand(args: RedisCommandArguments, options?: RedisClientOptions): Promise; + ttl(key: RedisCommandArgument): Promise; quit(): Promise; } @@ -30,6 +31,7 @@ let exportClient: RedisSB = { increment: () => new Promise((resolve) => resolve(null)), sendCommand: () => new Promise((resolve) => resolve(null)), quit: () => new Promise((resolve) => resolve(null)), + ttl: () => new Promise((resolve) => resolve(null)), }; let lastClientFail = 0; From 112b1c855502cc5713a3fe5b3dbfe5cf431d267b Mon Sep 17 00:00:00 2001 From: Michael C Date: Sun, 1 Jan 2023 02:51:44 -0500 Subject: [PATCH 4/8] lock redis, postgres versions, no persistence in redis --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index c8718956..c47f3490 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,8 @@ "cover:report": "nyc report", "dev": "nodemon", "dev:bash": "nodemon -x 'npm test ; npm start'", - "postgres:docker": "docker run --rm -p 5432:5432 -e POSTGRES_USER=ci_db_user -e POSTGRES_PASSWORD=ci_db_pass postgres:alpine", - "redis:docker": "docker run --rm -p 6379:6379 redis:alpine", + "postgres:docker": "docker run --rm -p 5432:5432 -e POSTGRES_USER=ci_db_user -e POSTGRES_PASSWORD=ci_db_pass postgres:14-alpine", + "redis:docker": "docker run --rm -p 6379:6379 redis:7-alpine --save '' --appendonly no", "start": "ts-node src/index.ts", "tsc": "tsc -p tsconfig.json", "lint": "eslint src test", From 4bd2204c3bb2f21f4f2a233e1d30e07fa738d591 Mon Sep 17 00:00:00 2001 From: Michael C Date: Sun, 1 Jan 2023 04:59:57 -0500 Subject: [PATCH 5/8] optimize skipSegments, add eTag - moved skipSegments parameter parsing to new file - added oldGetVideoSponsorTimes to getSkipSegments.ts --- src/app.ts | 5 +- src/middleware/etag.ts | 5 +- src/routes/getSkipSegments.ts | 121 +++++++++----------------- src/routes/getSkipSegmentsByHash.ts | 59 ++----------- src/routes/oldGetVideoSponsorTimes.ts | 24 ----- src/routes/viewedVideoSponsorTime.ts | 4 +- src/utils/parseSkipSegments.ts | 75 ++++++++++++++++ 7 files changed, 130 insertions(+), 163 deletions(-) delete mode 100644 src/routes/oldGetVideoSponsorTimes.ts create mode 100644 src/utils/parseSkipSegments.ts diff --git a/src/app.ts b/src/app.ts index d680073a..b2f44927 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,7 +1,6 @@ import express, { Request, RequestHandler, Response, Router } from "express"; import { config } from "./config"; import { oldSubmitSponsorTimes } from "./routes/oldSubmitSponsorTimes"; -import { oldGetVideoSponsorTimes } from "./routes/oldGetVideoSponsorTimes"; import { postSegmentShift } from "./routes/postSegmentShift"; import { postWarning } from "./routes/postWarning"; import { getIsUserVIP } from "./routes/getIsUserVIP"; @@ -21,13 +20,13 @@ import { viewedVideoSponsorTime } from "./routes/viewedVideoSponsorTime"; import { voteOnSponsorTime, getUserID as voteGetUserID } from "./routes/voteOnSponsorTime"; import { getSkipSegmentsByHash } from "./routes/getSkipSegmentsByHash"; import { postSkipSegments } from "./routes/postSkipSegments"; -import { endpoint as getSkipSegments } from "./routes/getSkipSegments"; +import { getSkipSegments, oldGetVideoSponsorTimes } from "./routes/getSkipSegments"; import { userCounter } from "./middleware/userCounter"; import { loggerMiddleware } from "./middleware/logger"; import { corsMiddleware } from "./middleware/cors"; import { apiCspMiddleware } from "./middleware/apiCsp"; import { rateLimitMiddleware } from "./middleware/requestRateLimit"; -import dumpDatabase, { appExportPath, downloadFile } from "./routes/dumpDatabase"; +import dumpDatabase from "./routes/dumpDatabase"; import { endpoint as getSegmentInfo } from "./routes/getSegmentInfo"; import { postClearCache } from "./routes/postClearCache"; import { addUnlistedVideo } from "./routes/addUnlistedVideo"; diff --git a/src/middleware/etag.ts b/src/middleware/etag.ts index 4a7cb58b..826c3052 100644 --- a/src/middleware/etag.ts +++ b/src/middleware/etag.ts @@ -5,6 +5,7 @@ import { skipSegmentsHashKey, skipSegmentsKey, videoLabelsHashKey, videoLabelsKe type hashType = "skipSegments" | "skipSegmentsHash" | "videoLabel" | "videoLabelHash"; type ETag = `${hashType};${VideoIDHash};${Service};${number}`; +type hashKey = string | VideoID | VideoIDHash; export function cacheMiddlware(req: Request, res: Response, next: NextFunction): void { const reqEtag = req.get("If-None-Match") as string; @@ -25,7 +26,7 @@ export function cacheMiddlware(req: Request, res: Response, next: NextFunction): .catch(next); } -function getLastModified(hashType: hashType, hashKey: (VideoID | VideoIDHash), service: Service): Promise { +function getLastModified(hashType: hashType, hashKey: hashKey, service: Service): Promise { let redisKey: string | null; if (hashType === "skipSegments") redisKey = skipSegmentsKey(hashKey as VideoID, service); else if (hashType === "skipSegmentsHash") redisKey = skipSegmentsHashKey(hashKey as VideoIDHash, service); @@ -35,7 +36,7 @@ function getLastModified(hashType: hashType, hashKey: (VideoID | VideoIDHash), s return QueryCacher.getKeyLastModified(redisKey); } -export async function getEtag(hashType: hashType, hashKey: VideoIDHash, service: Service): Promise { +export async function getEtag(hashType: hashType, hashKey: hashKey, service: Service): Promise { const lastModified = await getLastModified(hashType, hashKey, service); return `${hashType};${hashKey};${service};${lastModified.getTime()}` as ETag; } diff --git a/src/routes/getSkipSegments.ts b/src/routes/getSkipSegments.ts index 2e1c4bce..2a72dca0 100644 --- a/src/routes/getSkipSegments.ts +++ b/src/routes/getSkipSegments.ts @@ -12,7 +12,8 @@ import { QueryCacher } from "../utils/queryCacher"; import { getReputation } from "../utils/reputation"; import { getService } from "../utils/getService"; import { promiseOrTimeout } from "../utils/promise"; - +import { parseSkipSegments } from "../utils/parseSkipSegments"; +import { getEtag } from "../middleware/etag"; async function prepareCategorySegments(req: Request, videoID: VideoID, service: Service, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }, useCache: boolean): Promise { const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => { @@ -86,9 +87,6 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories: } try { - categories = categories.filter((category) => !/[^a-z|_|-]/.test(category)); - if (categories.length === 0) return null; - const segments: DBSegment[] = (await getSegmentsFromDBByVideoID(videoID, service)) .map((segment: DBSegment) => { if (filterRequiredSegments(segment.UUID, requiredSegments)) segment.required = true; @@ -139,9 +137,6 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, try { type SegmentPerVideoID = SBRecord; - categories = categories.filter((category) => !(/[^a-z|_|-]/.test(category))); - if (categories.length === 0) return null; - const segmentPerVideoID: SegmentPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service)) .reduce((acc: SegmentPerVideoID, segment: DBSegment) => { acc[segment.videoID] = acc[segment.videoID] || { @@ -396,75 +391,59 @@ function splitPercentOverlap(groups: OverlappingSegmentGroup[]): OverlappingSegm }); } -/** - * - * Returns what would be sent to the client. - * Will respond with errors if required. Returns false if it errors. - * - * @param req - * @param res - * - * @returns - */ -async function handleGetSegments(req: Request, res: Response): Promise { +async function getSkipSegments(req: Request, res: Response): Promise { const videoID = req.query.videoID as VideoID; if (!videoID) { - res.status(400).send("videoID not specified"); - return false; - } - // Default to sponsor - // If using params instead of JSON, only one category can be pulled - const categories: Category[] = req.query.categories - ? JSON.parse(req.query.categories as string) - : req.query.category - ? Array.isArray(req.query.category) - ? req.query.category - : [req.query.category] - : ["sponsor"]; - if (!Array.isArray(categories)) { - res.status(400).send("Categories parameter does not match format requirements."); - return false; + return res.status(400).send("videoID not specified"); } - const actionTypes: ActionType[] = req.query.actionTypes - ? JSON.parse(req.query.actionTypes as string) - : req.query.actionType - ? Array.isArray(req.query.actionType) - ? req.query.actionType - : [req.query.actionType] - : [ActionType.Skip]; - if (!Array.isArray(actionTypes)) { - res.status(400).send("actionTypes parameter does not match format requirements."); - return false; + const parseResult = parseSkipSegments(req); + if (parseResult.errors.length > 0) { + return res.status(400).send(parseResult.errors); } - const requiredSegments: SegmentUUID[] = req.query.requiredSegments - ? JSON.parse(req.query.requiredSegments as string) - : req.query.requiredSegment - ? Array.isArray(req.query.requiredSegment) - ? req.query.requiredSegment - : [req.query.requiredSegment] - : []; - if (!Array.isArray(requiredSegments)) { - res.status(400).send("requiredSegments parameter does not match format requirements."); - return false; + const { categories, actionTypes, requiredSegments, service } = parseResult; + const segments = await getSegmentsByVideoID(req, videoID, categories, actionTypes, requiredSegments, service); + + if (segments === null || segments === undefined) { + return res.sendStatus(500); + } else if (segments.length === 0) { + return res.sendStatus(404); } - const service = getService(req.query.service, req.body.service); + await getEtag("skipSegments", (videoID as string), service) + .then(etag => res.set("ETag", etag)) + .catch(() => null); + return res.send(segments); +} - const segments = await getSegmentsByVideoID(req, videoID, categories, actionTypes, requiredSegments, service); +async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise { + const videoID = req.query.videoID as VideoID; + if (!videoID) { + return res.status(400).send("videoID not specified"); + } + + const segments = await getSegmentsByVideoID(req, videoID, ["sponsor"] as Category[], [ActionType.Skip], [], Service.YouTube); if (segments === null || segments === undefined) { - res.sendStatus(500); - return false; + return res.sendStatus(500); + } else if (segments.length === 0) { + return res.sendStatus(404); } - if (segments.length === 0) { - res.sendStatus(404); - return false; + // Convert to old outputs + const sponsorTimes = []; + const UUIDs = []; + + for (const segment of segments) { + sponsorTimes.push(segment.segment); + UUIDs.push(segment.UUID); } - return segments; + return res.send({ + sponsorTimes, + UUIDs, + }); } const filterRequiredSegments = (UUID: SegmentUUID, requiredSegments: SegmentUUID[]): boolean => { @@ -474,25 +453,9 @@ const filterRequiredSegments = (UUID: SegmentUUID, requiredSegments: SegmentUUID return false; }; -async function endpoint(req: Request, res: Response): Promise { - try { - const segments = await handleGetSegments(req, res); - - // If false, res.send has already been called - if (segments) { - //send result - return res.send(segments); - } - } catch (err) /* istanbul ignore next */ { - if (err instanceof SyntaxError) { - return res.status(400).send("Categories parameter does not match format requirements."); - } else return res.sendStatus(500); - } -} - export { getSegmentsByVideoID, getSegmentsByHash, - endpoint, - handleGetSegments + getSkipSegments, + oldGetVideoSponsorTimes }; diff --git a/src/routes/getSkipSegmentsByHash.ts b/src/routes/getSkipSegmentsByHash.ts index 270ade28..eaf7f97a 100644 --- a/src/routes/getSkipSegmentsByHash.ts +++ b/src/routes/getSkipSegmentsByHash.ts @@ -1,9 +1,9 @@ import { hashPrefixTester } from "../utils/hashPrefixTester"; import { getSegmentsByHash } from "./getSkipSegments"; import { Request, Response } from "express"; -import { ActionType, Category, SegmentUUID, VideoIDHash, Service } from "../types/segments.model"; -import { getService } from "../utils/getService"; +import { VideoIDHash } from "../types/segments.model"; import { Logger } from "../utils/logger"; +import { parseSkipSegments } from "../utils/parseSkipSegments"; import { getEtag } from "../middleware/etag"; export async function getSkipSegmentsByHash(req: Request, res: Response): Promise { @@ -13,58 +13,11 @@ export async function getSkipSegmentsByHash(req: Request, res: Response): Promis } hashPrefix = hashPrefix.toLowerCase() as VideoIDHash; - let categories: Category[] = []; - try { - categories = req.query.categories - ? JSON.parse(req.query.categories as string) - : req.query.category - ? Array.isArray(req.query.category) - ? req.query.category - : [req.query.category] - : ["sponsor"]; - if (!Array.isArray(categories)) { - return res.status(400).send("Categories parameter does not match format requirements."); - } - } catch(error) { - return res.status(400).send("Bad parameter: categories (invalid JSON)"); + const parseResult = parseSkipSegments(req); + if (parseResult.errors.length > 0) { + return res.status(400).send(parseResult.errors); } - - let actionTypes: ActionType[] = []; - try { - actionTypes = req.query.actionTypes - ? JSON.parse(req.query.actionTypes as string) - : req.query.actionType - ? Array.isArray(req.query.actionType) - ? req.query.actionType - : [req.query.actionType] - : [ActionType.Skip]; - if (!Array.isArray(actionTypes)) { - return res.status(400).send("actionTypes parameter does not match format requirements."); - } - } catch(error) { - return res.status(400).send("Bad parameter: actionTypes (invalid JSON)"); - } - - let requiredSegments: SegmentUUID[] = []; - try { - requiredSegments = req.query.requiredSegments - ? JSON.parse(req.query.requiredSegments as string) - : req.query.requiredSegment - ? Array.isArray(req.query.requiredSegment) - ? req.query.requiredSegment - : [req.query.requiredSegment] - : []; - if (!Array.isArray(requiredSegments)) { - return res.status(400).send("requiredSegments parameter does not match format requirements."); - } - } catch(error) { - return res.status(400).send("Bad parameter: requiredSegments (invalid JSON)"); - } - - const service: Service = getService(req.query.service, req.body.service); - - // filter out none string elements, only flat array with strings is valid - categories = categories.filter((item: any) => typeof item === "string"); + const { categories, actionTypes, requiredSegments, service } = parseResult; // Get all video id's that match hash prefix const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, requiredSegments, service); diff --git a/src/routes/oldGetVideoSponsorTimes.ts b/src/routes/oldGetVideoSponsorTimes.ts deleted file mode 100644 index 90a58ae6..00000000 --- a/src/routes/oldGetVideoSponsorTimes.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { handleGetSegments } from "./getSkipSegments"; -import { Request, Response } from "express"; - -export async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise { - const segments = await handleGetSegments(req, res); - - if (segments) { - // Convert to old outputs - const sponsorTimes = []; - const UUIDs = []; - - for (const segment of segments) { - sponsorTimes.push(segment.segment); - UUIDs.push(segment.UUID); - } - - return res.send({ - sponsorTimes, - UUIDs, - }); - } - - // Error has already been handled in the other method -} diff --git a/src/routes/viewedVideoSponsorTime.ts b/src/routes/viewedVideoSponsorTime.ts index f111cab1..168a92dc 100644 --- a/src/routes/viewedVideoSponsorTime.ts +++ b/src/routes/viewedVideoSponsorTime.ts @@ -2,9 +2,9 @@ import { db } from "../databases/databases"; import { Request, Response } from "express"; export async function viewedVideoSponsorTime(req: Request, res: Response): Promise { - const UUID = req.query.UUID; + const UUID = req.query?.UUID; - if (UUID == undefined) { + if (!UUID) { //invalid request return res.sendStatus(400); } diff --git a/src/utils/parseSkipSegments.ts b/src/utils/parseSkipSegments.ts new file mode 100644 index 00000000..f9e5b96f --- /dev/null +++ b/src/utils/parseSkipSegments.ts @@ -0,0 +1,75 @@ +import { Request } from "express"; +import { ActionType, SegmentUUID, Category, Service } from "../types/segments.model"; +import { getService } from "./getService"; + +type fn = (req: Request) => any[]; + +const syntaxErrorWrapper = (fn: fn, req: Request) => { + try { return fn(req); } + catch (e) { return undefined; } +}; + +// Default to sponsor +const getCategories = (req: Request): Category[] => + req.query.categories + ? JSON.parse(req.query.categories as string) + : req.query.category + ? Array.isArray(req.query.category) + ? req.query.category + : [req.query.category] + : ["sponsor"]; + +// Default to skip +const getActionTypes = (req: Request): ActionType[] => + req.query.actionTypes + ? JSON.parse(req.query.actionTypes as string) + : req.query.actionType + ? Array.isArray(req.query.actionType) + ? req.query.actionType + : [req.query.actionType] + : [ActionType.Skip]; + +// Default to empty array +const getRequiredSegments = (req: Request): SegmentUUID[] => + req.query.requiredSegments + ? JSON.parse(req.query.requiredSegments as string) + : req.query.requiredSegment + ? Array.isArray(req.query.requiredSegment) + ? req.query.requiredSegment + : [req.query.requiredSegment] + : []; + +const errorMessage = (parameter: string) => `${parameter} parameter does not match format requirements.`; + +export function parseSkipSegments(req: Request): { + categories: Category[]; + actionTypes: ActionType[]; + requiredSegments: SegmentUUID[]; + service: Service; + errors: string[]; +} { + let categories: Category[] = syntaxErrorWrapper(getCategories, req); + const actionTypes: ActionType[] = syntaxErrorWrapper(getActionTypes, req); + const requiredSegments: SegmentUUID[] = syntaxErrorWrapper(getRequiredSegments, req); + const service: Service = getService(req.query.service, req.body.services); + const errors: string[] = []; + if (!Array.isArray(categories)) errors.push(errorMessage("categories")); + else { + // check category names for invalid characters + // and none string elements + categories = categories + .filter((item: any) => typeof item === "string") + .filter((category) => !(/[^a-z|_|-]/.test(category))); + if (categories.length === 0) errors.push("No valid categories provided."); + } + if (!Array.isArray(actionTypes)) errors.push(errorMessage("actionTypes")); + if (!Array.isArray(requiredSegments)) errors.push(errorMessage("requiredSegments")); + // finished parsing + return { + categories, + actionTypes, + requiredSegments, + service, + errors + }; +} \ No newline at end of file From ee224dde3be90b6d6188e61944b44cb30d17aa3e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 28 Jan 2023 01:22:05 -0500 Subject: [PATCH 6/8] Bump luxon from 1.28.0 to 1.28.1 (#535) Bumps [luxon](https://github.com/moment/luxon) from 1.28.0 to 1.28.1. - [Release notes](https://github.com/moment/luxon/releases) - [Changelog](https://github.com/moment/luxon/blob/master/CHANGELOG.md) - [Commits](https://github.com/moment/luxon/compare/1.28.0...1.28.1) --- updated-dependencies: - dependency-name: luxon dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8c1cd6de..8ab460a0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3518,9 +3518,9 @@ } }, "node_modules/luxon": { - "version": "1.28.0", - "resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.0.tgz", - "integrity": "sha512-TfTiyvZhwBYM/7QdAVDh+7dBTBA29v4ik0Ce9zda3Mnf8on1S5KJI8P2jKFZ8+5C0jhmr0KwJEO/Wdpm0VeWJQ==", + "version": "1.28.1", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.1.tgz", + "integrity": "sha512-gYHAa180mKrNIUJCbwpmD0aTu9kV0dREDrwNnuyFAsO1Wt0EVYSZelPnJlbj9HplzXX/YWXHFTL45kvZ53M0pw==", "engines": { "node": "*" } @@ -8398,9 +8398,9 @@ } }, "luxon": { - "version": "1.28.0", - "resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.0.tgz", - "integrity": "sha512-TfTiyvZhwBYM/7QdAVDh+7dBTBA29v4ik0Ce9zda3Mnf8on1S5KJI8P2jKFZ8+5C0jhmr0KwJEO/Wdpm0VeWJQ==" + "version": "1.28.1", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.1.tgz", + "integrity": "sha512-gYHAa180mKrNIUJCbwpmD0aTu9kV0dREDrwNnuyFAsO1Wt0EVYSZelPnJlbj9HplzXX/YWXHFTL45kvZ53M0pw==" }, "make-dir": { "version": "3.1.0", From da4fef60136a75d23069a3658389782bcc8d1375 Mon Sep 17 00:00:00 2001 From: Michael C Date: Sat, 18 Feb 2023 01:29:40 -0500 Subject: [PATCH 7/8] simplify webhook enum, update innertube --- src/types/webhook.model.ts | 12 ++++++++--- src/utils/innerTubeAPI.ts | 2 +- src/utils/webhookUtils.ts | 43 ++++++++++---------------------------- 3 files changed, 21 insertions(+), 36 deletions(-) diff --git a/src/types/webhook.model.ts b/src/types/webhook.model.ts index 5538ddda..0d1ae39f 100644 --- a/src/types/webhook.model.ts +++ b/src/types/webhook.model.ts @@ -2,11 +2,17 @@ import * as segments from "./segments.model"; import { HashedUserID } from "./user.model"; export enum voteType { - "up" = "vote.up", - "down" = "vote.down", + up = "vote.up", + down = "vote.down", } -export type authorType = "self" | "temp vip" | "vip" | "new" | "other"; +export enum authorType { + Self = "self", + TempVIP = "temp vip", + VIP = "vip", + New = "new", + Other = "other", +} export interface WebhookData { user: { diff --git a/src/utils/innerTubeAPI.ts b/src/utils/innerTubeAPI.ts index dbdd728f..ac34fafd 100644 --- a/src/utils/innerTubeAPI.ts +++ b/src/utils/innerTubeAPI.ts @@ -34,7 +34,7 @@ async function getFromITube (videoID: string): Promise { context: { client: { clientName: "WEB", - clientVersion: "2.20221215.04.01" + clientVersion: "2.20230217.01.00" } }, videoId: videoID diff --git a/src/utils/webhookUtils.ts b/src/utils/webhookUtils.ts index c30311df..65c80e2e 100644 --- a/src/utils/webhookUtils.ts +++ b/src/utils/webhookUtils.ts @@ -5,39 +5,19 @@ import { getFormattedTime } from "../utils/getFormattedTime"; import axios from "axios"; function getVoteAuthorRaw(submissionCount: number, isTempVIP: boolean, isVIP: boolean, isOwnSubmission: boolean): authorType { - if (isOwnSubmission) { - return "self"; - } else if (isTempVIP) { - return "temp vip"; - } else if (isVIP) { - return "vip"; - } else if (submissionCount === 0) { - return "new"; - } else { - return "other"; - } -} - -function getVoteAuthor(submissionCount: number, isTempVIP: boolean, isVIP: boolean, isOwnSubmission: boolean): string { - if (isOwnSubmission) { - return "Report by Submitter"; - } else if (isTempVIP) { - return "Report by Temp VIP"; - } else if (isVIP) { - return "Report by VIP User"; - } else if (submissionCount === 0) { - return "Report by New User"; - } - - return ""; + if (isOwnSubmission) return authorType.Self; + else if (isTempVIP) return authorType.TempVIP; + else if (isVIP) return authorType.VIP; + else if (submissionCount === 0) authorType.New; + else return authorType.Other; } const voteAuthorMap: Record = { - "self": "Report by Submitter", - "temp vip": "Report by Temp VIP", - "vip": "Report by VIP User", - "new": "Report by New User", - "other": "" + [authorType.Self]: "Report by Submitter", + [authorType.TempVIP]: "Report by Temp VIP", + [authorType.VIP]: "Report by VIP User", + [authorType.New]: "Report by New User", + [authorType.Other]: "" }; const createDiscordVoteEmbed = (data: WebhookData) => { @@ -67,7 +47,7 @@ const createDiscordVoteEmbed = (data: WebhookData) => { function dispatchEvent(scope: string, data: WebhookData): void { const webhooks = config.webhooks; - if (webhooks === undefined || webhooks.length === 0) return; + if (!webhooks?.length) return; Logger.debug("Dispatching webhooks"); for (const webhook of webhooks) { @@ -94,7 +74,6 @@ function dispatchEvent(scope: string, data: WebhookData): void { export { getVoteAuthorRaw, - getVoteAuthor, dispatchEvent, createDiscordVoteEmbed }; \ No newline at end of file From b5739e64b581c6ccb6b6f9d27d7b1d79780d653a Mon Sep 17 00:00:00 2001 From: Michael C Date: Sat, 18 Feb 2023 01:57:06 -0500 Subject: [PATCH 8/8] change postSkipSegments to new webhook format --- src/routes/postSkipSegments.ts | 85 +++++++++++---------------------- src/routes/voteOnSponsorTime.ts | 2 +- src/types/webhook.model.ts | 2 +- src/utils/webhookUtils.ts | 65 ++++++++++++++++--------- 4 files changed, 73 insertions(+), 81 deletions(-) diff --git a/src/routes/postSkipSegments.ts b/src/routes/postSkipSegments.ts index 707d6523..917cae60 100644 --- a/src/routes/postSkipSegments.ts +++ b/src/routes/postSkipSegments.ts @@ -6,8 +6,7 @@ import { getSubmissionUUID } from "../utils/getSubmissionUUID"; import { getHash } from "../utils/getHash"; import { getHashCache } from "../utils/getHashCache"; import { getIP } from "../utils/getIP"; -import { getFormattedTime } from "../utils/getFormattedTime"; -import { dispatchEvent } from "../utils/webhookUtils"; +import { createDiscordSegmentEmbed, dispatchEvent } from "../utils/webhookUtils"; import { Request, Response } from "express"; import { ActionType, Category, IncomingSegment, IPAddress, SegmentUUID, Service, VideoDuration, VideoID } from "../types/segments.model"; import { deleteLockCategories } from "./deleteLockCategories"; @@ -24,6 +23,7 @@ import { canSubmit } from "../utils/permissions"; import { getVideoDetails, videoDetails } from "../utils/getVideoDetails"; import * as youtubeID from "../utils/youtubeID"; import { banUser } from "./shadowBanUser"; +import { authorType } from "../types/webhook.model"; type CheckResult = { pass: boolean, @@ -37,71 +37,44 @@ const CHECK_PASS: CheckResult = { errorCode: 0 }; -async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: videoDetails, { submissionStart, submissionEnd }: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) { - const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]); - const userName = row !== undefined ? row.userName : null; - - let scopeName = "submissions.other"; - if (submissionCount <= 1) { - scopeName = "submissions.new"; - } - - dispatchEvent(scopeName, { - user: { - status: "new" - }, - video: { - id: (videoID as VideoID), - title: youtubeData?.title, - url: `https://www.youtube.com/watch?v=${videoID}`, - thumbnail: getMaxResThumbnail(videoID), - }, - submission: { - UUID: UUID as SegmentUUID, - category: segmentInfo.category, - startTime: submissionStart, - endTime: submissionEnd, - user: { - UUID: userID as HashedUserID, - username: userName, - }, - } - }); -} - async function sendWebhooks(apiVideoDetails: videoDetails, userID: string, videoID: string, UUID: string, segmentInfo: any, service: Service) { if (apiVideoDetails && service == Service.YouTube) { const userSubmissionCountRow = await db.prepare("get", `SELECT count(*) as "submissionCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]); + const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]); + const username = row?.userName ?? null; const startTime = parseFloat(segmentInfo.segment[0]); const endTime = parseFloat(segmentInfo.segment[1]); - const webhookData = - sendWebhookNotification(userID, videoID, UUID, userSubmissionCountRow.submissionCount, apiVideoDetails, { - submissionStart: startTime, - submissionEnd: endTime, - }, segmentInfo).catch((e) => Logger.error(`sending webhooks: ${e}`)); + const newUser = userSubmissionCountRow.submissionCount <= 1; + const webhookData = { + user: { + status: newUser ? authorType.New : authorType.Other + }, + video: { + id: (videoID as VideoID), + title: apiVideoDetails?.title, + url: `https://www.youtube.com/watch?v=${videoID}`, + thumbnail: getMaxResThumbnail(videoID), + }, + submission: { + UUID: UUID as SegmentUUID, + category: segmentInfo.category, + startTime: startTime, + endTime: endTime, + user: { + userID: userID as HashedUserID, + username, + }, + } + }; + const discordEmbed = createDiscordSegmentEmbed(webhookData); + dispatchEvent(newUser ? "submissions.new": "submissions.other", webhookData); // If it is a first time submission // Then send a notification to discord if (!config.discordFirstTimeSubmissionsWebhookURL || userSubmissionCountRow.submissionCount > 1) return; - axios.post(config.discordFirstTimeSubmissionsWebhookURL, { - embeds: [{ - title: apiVideoDetails.title, - url: `https://www.youtube.com/watch?v=${videoID}&t=${(parseInt(startTime.toFixed(0)) - 2)}s#requiredSegment=${UUID}`, - description: `Submission ID: ${UUID}\ - \n\nTimestamp: \ - ${getFormattedTime(startTime)} to ${getFormattedTime(endTime)}\ - \n\nCategory: ${segmentInfo.category}`, - color: 10813440, - author: { - name: userID, - }, - thumbnail: { - url: getMaxResThumbnail(videoID), - }, - }], - }) + axios.post(config.discordFirstTimeSubmissionsWebhookURL, { embeds: [discordEmbed] }) .then(res => { if (res.status >= 400) { Logger.error("Error sending first time submission Discord hook"); diff --git a/src/routes/voteOnSponsorTime.ts b/src/routes/voteOnSponsorTime.ts index b110254a..ad87afb3 100644 --- a/src/routes/voteOnSponsorTime.ts +++ b/src/routes/voteOnSponsorTime.ts @@ -151,7 +151,7 @@ async function sendWebhooks(voteData: VoteData) { startTime: submissionInfoRow.startTime, endTime: submissionInfoRow.endTime, user: { - UUID: submissionInfoRow.userID, + userID: submissionInfoRow.userID, username: submissionInfoRow.userName, submissions: { total: submissionInfoRow.count, diff --git a/src/types/webhook.model.ts b/src/types/webhook.model.ts index 0d1ae39f..4b430d83 100644 --- a/src/types/webhook.model.ts +++ b/src/types/webhook.model.ts @@ -32,7 +32,7 @@ export interface WebhookData { startTime: number, endTime: number, user: { - UUID: HashedUserID, + userID: HashedUserID, username: string | HashedUserID, submissions?: { total: number, diff --git a/src/utils/webhookUtils.ts b/src/utils/webhookUtils.ts index 65c80e2e..8a3d3fe4 100644 --- a/src/utils/webhookUtils.ts +++ b/src/utils/webhookUtils.ts @@ -20,31 +20,50 @@ const voteAuthorMap: Record = { [authorType.Other]: "" }; -const createDiscordVoteEmbed = (data: WebhookData) => { - const startTime = Math.max(0, data.submission.startTime - 2); - const startTimeParam = startTime > 0 ? `&t=${startTime}s` : ""; - return { - title: data.video.title, - url: `https://www.youtube.com/watch?v=${data.video.id}${startTimeParam}#requiredSegment=${data.submission.UUID}`, - description: `**${data.votes.before} Votes Prior | \ - ${(data.votes.after)} Votes Now | ${data.submission.views} \ - Views**\n\n**Locked**: ${data.submission.locked}\n\n**Submission ID:** ${data.submission.UUID}\ - \n**Category:** ${data.submission.category}\ - \n\n**Submitted by:** ${data.submission.user.username}\n${data.submission.user.UUID}\ - \n\n**Total User Submissions:** ${data.submission.user.submissions.total}\ - \n**Ignored User Submissions:** ${data.submission.user.submissions.ignored}\ - \n\n**Timestamp:** \ - ${getFormattedTime(data.submission.startTime)} to ${getFormattedTime(data.submission.endTime)}`, - color: 10813440, - author: { - name: data.authorName ?? `${voteAuthorMap[data.user.status]}${data.submission.locked ? " (Locked)" : ""}`, - }, - thumbnail: { - url: data.video.thumbnail, - }, - }; +const youtubeUrlCreator = (videoId: string, startTime: number, uuid: string): string => { + const startTimeNumber = Math.max(0, startTime - 2); + const startTimeParam = startTime > 0 ? `&t=${startTimeNumber}s` : ""; + return `https://www.youtube.com/watch?v=${videoId}${startTimeParam}#requiredSegment=${uuid}`; }; +const createDiscordVoteEmbed = (data: WebhookData) => ({ + title: data.video.title, + url: youtubeUrlCreator(data.video.id, data.submission.startTime, data.submission.UUID), + description: `**${data.votes.before} Votes Prior | \ + ${(data.votes.after)} Votes Now | ${data.submission.views} \ + Views**\n\n**Locked**: ${data.submission.locked}\n\n**Submission ID:** ${data.submission.UUID}\ + \n**Category:** ${data.submission.category}\ + \n\n**Submitted by:** ${data.submission.user.username}\n${data.submission.user.userID}\ + \n\n**Total User Submissions:** ${data.submission.user.submissions.total}\ + \n**Ignored User Submissions:** ${data.submission.user.submissions.ignored}\ + \n\n**Timestamp:** \ + ${getFormattedTime(data.submission.startTime)} to ${getFormattedTime(data.submission.endTime)}`, + color: 10813440, + author: { + name: data.authorName ?? `${voteAuthorMap[data.user.status]}${data.submission.locked ? " (Locked)" : ""}`, + }, + thumbnail: { + url: data.video.thumbnail, + }, +}); + +export const createDiscordSegmentEmbed = (data: WebhookData) => ({ + title: data.video.title, + url: youtubeUrlCreator(data.video.id, data.submission.startTime, data.submission.UUID), + description: `Submission ID: ${data.submission.UUID}\ + \n\nTimestamp: \ + ${getFormattedTime(data.submission.startTime)} to ${getFormattedTime(data.submission.endTime)}\ + \n\nCategory: ${data.submission.category}`, + color: 10813440, + author: { + name: data.submission.user.userID, + }, + thumbnail: { + url: data.video.thumbnail + }, +}); + + function dispatchEvent(scope: string, data: WebhookData): void { const webhooks = config.webhooks; if (!webhooks?.length) return;