diff --git a/package-lock.json b/package-lock.json index 158f360..3f790d1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -149,6 +149,17 @@ "form-data": "^3.0.0" } }, + "@types/pg": { + "version": "7.14.10", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-7.14.10.tgz", + "integrity": "sha512-m6G0mrpj71YgVgHJF0cIHC3OZTKiQSUzTkMj869a+YWXF2tdbmO2PmIpNnDkiFPhHWcoGq2bk5P2e0CZX0F9Mg==", + "dev": true, + "requires": { + "@types/node": "*", + "pg-protocol": "^1.2.0", + "pg-types": "^2.2.0" + } + }, "@types/qs": { "version": "6.9.5", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.5.tgz", @@ -480,6 +491,11 @@ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" }, + "buffer-writer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/buffer-writer/-/buffer-writer-2.0.0.tgz", + "integrity": "sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw==" + }, "bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", @@ -2011,6 +2027,11 @@ "semver": "^5.1.0" } }, + "packet-reader": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/packet-reader/-/packet-reader-1.0.0.tgz", + "integrity": "sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ==" + }, "parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -2045,6 +2066,60 @@ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" }, + "pg": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.5.1.tgz", + "integrity": "sha512-9wm3yX9lCfjvA98ybCyw2pADUivyNWT/yIP4ZcDVpMN0og70BUWYEGXPCTAQdGTAqnytfRADb7NERrY1qxhIqw==", + "requires": { + "buffer-writer": "2.0.0", + "packet-reader": "1.0.0", + "pg-connection-string": "^2.4.0", + "pg-pool": "^3.2.2", + "pg-protocol": "^1.4.0", + "pg-types": "^2.1.0", + "pgpass": "1.x" + } + }, + "pg-connection-string": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.4.0.tgz", + "integrity": "sha512-3iBXuv7XKvxeMrIgym7njT+HlZkwZqqGX4Bu9cci8xHZNT+Um1gWKqCsAzcC0d95rcKMU5WBg6YRUcHyV0HZKQ==" + }, + "pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==" + }, + "pg-pool": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.2.2.tgz", + "integrity": "sha512-ORJoFxAlmmros8igi608iVEbQNNZlp89diFVx6yV5v+ehmpMY9sK6QgpmgoXbmkNaBAx8cOOZh9g80kJv1ooyA==" + }, + "pg-protocol": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.4.0.tgz", + "integrity": "sha512-El+aXWcwG/8wuFICMQjM5ZSAm6OWiJicFdNYo+VY3QP+8vI4SvLIWVe51PppTzMhikUJR+PsyIFKqfdXPz/yxA==" + }, + "pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "requires": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + } + }, + "pgpass": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.4.tgz", + "integrity": "sha512-YmuA56alyBq7M59vxVBfPJrGSozru8QAdoNlWuW3cz8l+UX3cWge0vTvjKhsSHSJpo3Bom8/Mm6hf0TR5GY0+w==", + "requires": { + "split2": "^3.1.1" + } + }, "picomatch": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", @@ -2057,6 +2132,29 @@ "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", "dev": true }, + "postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==" + }, + "postgres-bytea": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", + "integrity": "sha1-AntTPAqokOJtFy1Hz5zOzFIazTU=" + }, + "postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==" + }, + "postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "requires": { + "xtend": "^4.0.0" + } + }, "prepend-http": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", @@ -2132,6 +2230,16 @@ "strip-json-comments": "~2.0.1" } }, + "readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, "readdirp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.2.0.tgz", @@ -2340,6 +2448,14 @@ "source-map": "^0.6.0" } }, + "split2": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/split2/-/split2-3.2.2.tgz", + "integrity": "sha512-9NThjpgZnifTkJpzTZ7Eue85S49QwpNhZTq6GRJwObb6jnLFNGB7Qm73V5HewTROPyxD0C29xqmaI68bQtV+hg==", + "requires": { + "readable-stream": "^3.0.0" + } + }, "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -2425,6 +2541,14 @@ "es-abstract": "^1.17.5" } }, + "string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "requires": { + "safe-buffer": "~5.2.0" + } + }, "strip-eof": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", @@ -2854,6 +2978,11 @@ "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=", "dev": true }, + "xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" + }, "y18n": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", diff --git a/package.json b/package.json index b1deca9..1cd2362 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "http": "0.0.0", "iso8601-duration": "^1.2.0", "node-fetch": "^2.6.0", + "pg": "^8.5.1", "redis": "^3.0.2", "sync-mysql": "^3.0.1", "uuid": "^3.3.2", @@ -31,6 +32,7 @@ "@types/mocha": "^8.0.3", "@types/node": "^14.11.9", "@types/node-fetch": "^2.5.7", + "@types/pg": "^7.14.10", "@types/redis": "^2.8.28", "@types/request": "^2.48.5", "mocha": "^7.1.1", diff --git a/src/databases/IDatabase.ts b/src/databases/IDatabase.ts index f30a532..4bac1e3 100644 --- a/src/databases/IDatabase.ts +++ b/src/databases/IDatabase.ts @@ -1,13 +1,7 @@ export interface IDatabase { init(): void; - prepare(type: QueryType, query: string, params: any[]): any; - - get(query: string, params: any[]): TModel; - getAll(query: string, params: any[]): TModel[]; - run(query: string, params: any[]): void; - - exec(query: string): any; + prepare(type: QueryType, query: string, params: any[]): Promise; } export type QueryType = 'get' | 'all' | 'run'; diff --git a/src/databases/Mysql.ts b/src/databases/Mysql.ts index 5001a4c..4d9c675 100644 --- a/src/databases/Mysql.ts +++ b/src/databases/Mysql.ts @@ -9,14 +9,10 @@ export class Mysql implements IDatabase { constructor(private config: any) { } - init() { + init(): void { this.connection = new MysqlInterface(this.config); } - exec(query: string) { - this.prepare('run', query, []); - } - prepare(type: QueryType, query: string, params: any[]) { Logger.debug(`prepare (mysql): type: ${type}, query: ${query}, params: ${params}`); const queryResult = this.connection.query(query, params); @@ -34,16 +30,5 @@ export class Mysql implements IDatabase { } } - public get(query: string, params: any[]): TModel { - return this.prepare('get', query, params); - } - - public getAll(query: string, params: any[]): TModel[] { - return this.prepare('all', query, params); - } - - public run(query: string, params: any[]): void { - this.prepare('run', query, params); - } } diff --git a/src/databases/Postgres.ts b/src/databases/Postgres.ts new file mode 100644 index 0000000..2b6685a --- /dev/null +++ b/src/databases/Postgres.ts @@ -0,0 +1,31 @@ +import { Logger } from '../utils/logger'; +import { IDatabase, QueryType } from './IDatabase'; +import { Pool } from 'pg'; + +export class Mysql implements IDatabase { + private pool: Pool; + + constructor(private config: any) {} + + init(): void { + this.pool = new Pool(); + } + + async prepare(type: QueryType, query: string, params: any[]) { + Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`); + const queryResult = await this.pool.query(query, params); + + switch (type) { + case 'get': { + return queryResult.rows[0]; + } + case 'all': { + return queryResult.rows; + } + case 'run': { + break; + } + } + } +} + diff --git a/src/databases/Sqlite.ts b/src/databases/Sqlite.ts index 9a3b1fd..5cf0104 100644 --- a/src/databases/Sqlite.ts +++ b/src/databases/Sqlite.ts @@ -12,7 +12,7 @@ export class Sqlite implements IDatabase { { } - prepare(type: QueryType, query: string, params: any[]) { + async prepare(type: QueryType, query: string, params: any[]) { const preparedQuery = this.db.prepare(query); switch (type) { @@ -29,20 +29,6 @@ export class Sqlite implements IDatabase { } } - get(query: string, params: any[]): TModel { - return this.prepare('get', query, params); - } - getAll(query: string, params: any[]): TModel[] { - return this.prepare('all', query, params); - } - run(query: string, params: any[]): void { - this.prepare('run', query, params); - } - - exec(query: string) { - return this.db.exec(query); - } - init() { // Make dirs if required if (!fs.existsSync(path.join(this.config.dbPath, "../"))) { diff --git a/src/databases/databases.ts b/src/databases/databases.ts index 3b9e719..ef75d0a 100644 --- a/src/databases/databases.ts +++ b/src/databases/databases.ts @@ -9,8 +9,7 @@ let privateDB: IDatabase; if (config.mysql) { db = new Mysql(config.mysql); privateDB = new Mysql(config.privateMysql); -} -else { +} else { db = new Sqlite({ dbPath: config.db, dbSchemaFileName: config.dbSchema, diff --git a/src/middleware/requestRateLimit.ts b/src/middleware/requestRateLimit.ts index 807d291..c99cc5a 100644 --- a/src/middleware/requestRateLimit.ts +++ b/src/middleware/requestRateLimit.ts @@ -16,8 +16,8 @@ export function rateLimitMiddleware(limitConfig: RateLimitConfig, getUserID?: (r keyGenerator: (req) => { return getHash(getIP(req), 1); }, - handler: (req, res, next) => { - if (getUserID === undefined || !isUserVIP(getHash(getUserID(req)))) { + handler: async (req, res, next) => { + if (getUserID === undefined || !await isUserVIP(getHash(getUserID(req)))) { return res.status(limitConfig.statusCode).send(limitConfig.message); } else { return next(); diff --git a/src/routes/addUserAsVIP.ts b/src/routes/addUserAsVIP.ts index a30493f..346ab98 100644 --- a/src/routes/addUserAsVIP.ts +++ b/src/routes/addUserAsVIP.ts @@ -27,14 +27,14 @@ export async function addUserAsVIP(req: Request, res: Response) { } //check to see if this user is already a vip - const row = db.prepare('get', "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [userID]); + const row = await db.prepare('get', "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [userID]); if (enabled && row.userCount == 0) { //add them to the vip list - db.prepare('run', "INSERT INTO vipUsers VALUES(?)", [userID]); + await db.prepare('run', "INSERT INTO vipUsers VALUES(?)", [userID]); } else if (!enabled && row.userCount > 0) { //remove them from the shadow ban list - db.prepare('run', "DELETE FROM vipUsers WHERE userID = ?", [userID]); + await db.prepare('run', "DELETE FROM vipUsers WHERE userID = ?", [userID]); } res.sendStatus(200); diff --git a/src/routes/deleteNoSegments.ts b/src/routes/deleteNoSegments.ts index 5fa694e..6451e85 100644 --- a/src/routes/deleteNoSegments.ts +++ b/src/routes/deleteNoSegments.ts @@ -3,7 +3,7 @@ import {isUserVIP} from '../utils/isUserVIP'; import {getHash} from '../utils/getHash'; import {db} from '../databases/databases'; -export function deleteNoSegments(req: Request, res: Response) { +export async function deleteNoSegments(req: Request, res: Response) { // Collect user input data const videoID = req.body.videoID; let userID = req.body.userID; @@ -24,7 +24,7 @@ export function deleteNoSegments(req: Request, res: Response) { // Check if user is VIP userID = getHash(userID); - const userIsVIP = isUserVIP(userID); + const userIsVIP = await isUserVIP(userID); if (!userIsVIP) { res.status(403).json({ @@ -33,11 +33,13 @@ export function deleteNoSegments(req: Request, res: Response) { return; } - db.prepare("all", 'SELECT * FROM noSegments WHERE videoID = ?', [videoID]).filter((entry: any) => { + const entries = (await db.prepare("all", 'SELECT * FROM noSegments WHERE videoID = ?', [videoID])).filter((entry: any) => { return (categories.indexOf(entry.category) !== -1); - }).forEach((entry: any) => { - db.prepare('run', 'DELETE FROM noSegments WHERE videoID = ? AND category = ?', [videoID, entry.category]); }); + for (const entry of entries) { + await db.prepare('run', 'DELETE FROM noSegments WHERE videoID = ? AND category = ?', [videoID, entry.category]); + } + res.status(200).json({message: 'Removed no segments entrys for video ' + videoID}); } diff --git a/src/routes/getDaysSavedFormatted.ts b/src/routes/getDaysSavedFormatted.ts index 0179425..699e48d 100644 --- a/src/routes/getDaysSavedFormatted.ts +++ b/src/routes/getDaysSavedFormatted.ts @@ -1,8 +1,8 @@ import {db} from '../databases/databases'; import {Request, Response} from 'express'; -export function getDaysSavedFormatted(req: Request, res: Response) { - let row = db.prepare('get', "SELECT SUM((endTime - startTime) / 60 / 60 / 24 * views) as daysSaved from sponsorTimes where shadowHidden != 1", []); +export async function getDaysSavedFormatted(req: Request, res: Response) { + let row = await db.prepare('get', "SELECT SUM((endTime - startTime) / 60 / 60 / 24 * views) as daysSaved from sponsorTimes where shadowHidden != 1", []); if (row !== undefined) { //send this result diff --git a/src/routes/getIsUserVIP.ts b/src/routes/getIsUserVIP.ts index 597de25..927ca1f 100644 --- a/src/routes/getIsUserVIP.ts +++ b/src/routes/getIsUserVIP.ts @@ -4,7 +4,7 @@ import {isUserVIP} from '../utils/isUserVIP'; import {Request, Response} from 'express'; import { HashedUserID, UserID } from '../types/user.model'; -export function getIsUserVIP(req: Request, res: Response): void { +export async function getIsUserVIP(req: Request, res: Response): Promise { const userID = req.query.userID as UserID; if (userID == undefined) { @@ -17,7 +17,7 @@ export function getIsUserVIP(req: Request, res: Response): void { const hashedUserID: HashedUserID = getHash(userID); try { - let vipState = isUserVIP(hashedUserID); + let vipState = await isUserVIP(hashedUserID); res.status(200).json({ hashedUserID: hashedUserID, vip: vipState, diff --git a/src/routes/getSavedTimeForUser.ts b/src/routes/getSavedTimeForUser.ts index fbf28dc..0d54f59 100644 --- a/src/routes/getSavedTimeForUser.ts +++ b/src/routes/getSavedTimeForUser.ts @@ -2,7 +2,7 @@ import {db} from '../databases/databases'; import {Request, Response} from 'express'; import {getHash} from '../utils/getHash'; -export function getSavedTimeForUser(req: Request, res: Response) { +export async function getSavedTimeForUser(req: Request, res: Response) { let userID = req.query.userID as string; if (userID == undefined) { @@ -15,7 +15,7 @@ export function getSavedTimeForUser(req: Request, res: Response) { userID = getHash(userID); try { - let row = db.prepare("get", "SELECT SUM((endTime - startTime) / 60 * views) as minutesSaved FROM sponsorTimes WHERE userID = ? AND votes > -1 AND shadowHidden != 1 ", [userID]); + let row = await db.prepare("get", "SELECT SUM((endTime - startTime) / 60 * views) as minutesSaved FROM sponsorTimes WHERE userID = ? AND votes > -1 AND shadowHidden != 1 ", [userID]); if (row.minutesSaved != null) { res.send({ diff --git a/src/routes/getSkipSegments.ts b/src/routes/getSkipSegments.ts index 6b69e58..98d7178 100644 --- a/src/routes/getSkipSegments.ts +++ b/src/routes/getSkipSegments.ts @@ -11,8 +11,8 @@ import { Logger } from '../utils/logger'; import redis from '../utils/redis'; -function prepareCategorySegments(req: Request, videoID: VideoID, category: Category, segments: DBSegment[], cache: SegmentCache = {shadowHiddenSegmentIPs: {}}): Segment[] { - const filteredSegments = segments.filter((segment) => { +async function prepareCategorySegments(req: Request, videoID: VideoID, category: Category, segments: DBSegment[], cache: SegmentCache = {shadowHiddenSegmentIPs: {}}): Promise { + const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => { if (segment.votes < -1) { return false; //too untrustworthy, just ignore it } @@ -24,7 +24,7 @@ function prepareCategorySegments(req: Request, videoID: VideoID, category: Categ } if (cache.shadowHiddenSegmentIPs[videoID] === undefined) { - cache.shadowHiddenSegmentIPs[videoID] = privateDB.prepare('all', 'SELECT hashedIP FROM sponsorTimes WHERE videoID = ?', [videoID]) as { hashedIP: HashedIP }[]; + cache.shadowHiddenSegmentIPs[videoID] = await privateDB.prepare('all', 'SELECT hashedIP FROM sponsorTimes WHERE videoID = ?', [videoID]) as { hashedIP: HashedIP }[]; } //if this isn't their ip, don't send it to them @@ -36,7 +36,9 @@ function prepareCategorySegments(req: Request, videoID: VideoID, category: Categ return shadowHiddenSegment.hashedIP === cache.userHashedIP; }); - }); + })); + + const filteredSegments = segments.filter((_, index) => shouldFilter[index]); return chooseSegments(filteredSegments).map((chosenSegment) => ({ category, @@ -45,17 +47,17 @@ function prepareCategorySegments(req: Request, videoID: VideoID, category: Categ })); } -function getSegmentsByVideoID(req: Request, videoID: string, categories: Category[]): Segment[] { +async function getSegmentsByVideoID(req: Request, videoID: string, categories: Category[]): Promise { const cache: SegmentCache = {shadowHiddenSegmentIPs: {}}; const segments: Segment[] = []; try { - const segmentsByCategory: SBRecord = db + const segmentsByCategory: SBRecord = (await db .prepare( 'all', `SELECT startTime, endTime, votes, locked, UUID, category, shadowHidden FROM sponsorTimes WHERE videoID = ? AND category IN (${Array(categories.length).fill('?').join()}) ORDER BY startTime`, [videoID, categories] - ).reduce((acc: SBRecord, segment: DBSegment) => { + )).reduce((acc: SBRecord, segment: DBSegment) => { acc[segment.category] = acc[segment.category] || []; acc[segment.category].push(segment); @@ -63,7 +65,7 @@ function getSegmentsByVideoID(req: Request, videoID: string, categories: Categor }, {}); for (const [category, categorySegments] of Object.entries(segmentsByCategory)) { - segments.push(...prepareCategorySegments(req, videoID as VideoID, category as Category, categorySegments, cache)); + segments.push(...(await prepareCategorySegments(req, videoID as VideoID, category as Category, categorySegments, cache))); } return segments; @@ -75,19 +77,19 @@ function getSegmentsByVideoID(req: Request, videoID: string, categories: Categor } } -function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[]): SBRecord { +async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[]): Promise> { const cache: SegmentCache = {shadowHiddenSegmentIPs: {}}; const segments: SBRecord = {}; try { type SegmentWithHashPerVideoID = SBRecord}>; - const segmentPerVideoID: SegmentWithHashPerVideoID = db + const segmentPerVideoID: SegmentWithHashPerVideoID = (await db .prepare( 'all', `SELECT videoID, startTime, endTime, votes, locked, UUID, category, shadowHidden, hashedVideoID FROM sponsorTimes WHERE hashedVideoID LIKE ? AND category IN (${Array(categories.length).fill('?').join()}) ORDER BY startTime`, [hashedVideoIDPrefix + '%', categories] - ).reduce((acc: SegmentWithHashPerVideoID, segment: DBSegment) => { + )).reduce((acc: SegmentWithHashPerVideoID, segment: DBSegment) => { acc[segment.videoID] = acc[segment.videoID] || { hash: segment.hashedVideoID, segmentPerCategory: {}, @@ -107,7 +109,7 @@ function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categ }; for (const [category, segmentPerCategory] of Object.entries(videoData.segmentPerCategory)) { - segments[videoID].segments.push(...prepareCategorySegments(req, videoID as VideoID, category as Category, segmentPerCategory, cache)); + segments[videoID].segments.push(...(await prepareCategorySegments(req, videoID as VideoID, category as Category, segmentPerCategory, cache))); } } @@ -241,7 +243,7 @@ async function handleGetSegments(req: Request, res: Response): Promise { - const userNames = []; - const viewCounts = []; - const totalSubmissions = []; - const minutesSaved = []; - const categoryStats: any[] = categoryStatsEnabled ? [] : undefined; +async function generateTopUsersStats(sortBy: string, categoryStatsEnabled: boolean = false) { + const userNames = []; + const viewCounts = []; + const totalSubmissions = []; + const minutesSaved = []; + const categoryStats: any[] = categoryStatsEnabled ? [] : undefined; - let additionalFields = ''; + let additionalFields = ''; + if (categoryStatsEnabled) { + additionalFields += "SUM(CASE WHEN category = 'sponsor' THEN 1 ELSE 0 END) as categorySponsor, " + + "SUM(CASE WHEN category = 'intro' THEN 1 ELSE 0 END) as categorySumIntro, " + + "SUM(CASE WHEN category = 'outro' THEN 1 ELSE 0 END) as categorySumOutro, " + + "SUM(CASE WHEN category = 'interaction' THEN 1 ELSE 0 END) as categorySumInteraction, " + + "SUM(CASE WHEN category = 'selfpromo' THEN 1 ELSE 0 END) as categorySelfpromo, " + + "SUM(CASE WHEN category = 'music_offtopic' THEN 1 ELSE 0 END) as categoryMusicOfftopic, "; + } + + const rows = await db.prepare('all', "SELECT COUNT(*) as totalSubmissions, SUM(views) as viewCount," + + "SUM((sponsorTimes.endTime - sponsorTimes.startTime) / 60 * sponsorTimes.views) as minutesSaved, " + + "SUM(votes) as userVotes, " + + additionalFields + + "IFNULL(userNames.userName, sponsorTimes.userID) as userName FROM sponsorTimes LEFT JOIN userNames ON sponsorTimes.userID=userNames.userID " + + "LEFT JOIN privateDB.shadowBannedUsers ON sponsorTimes.userID=privateDB.shadowBannedUsers.userID " + + "WHERE sponsorTimes.votes > -1 AND sponsorTimes.shadowHidden != 1 AND privateDB.shadowBannedUsers.userID IS NULL " + + "GROUP BY IFNULL(userName, sponsorTimes.userID) HAVING userVotes > 20 " + + "ORDER BY " + sortBy + " DESC LIMIT 100", []); + + for (let i = 0; i < rows.length; i++) { + userNames[i] = rows[i].userName; + + viewCounts[i] = rows[i].viewCount; + totalSubmissions[i] = rows[i].totalSubmissions; + minutesSaved[i] = rows[i].minutesSaved; if (categoryStatsEnabled) { - additionalFields += "SUM(CASE WHEN category = 'sponsor' THEN 1 ELSE 0 END) as categorySponsor, " + - "SUM(CASE WHEN category = 'intro' THEN 1 ELSE 0 END) as categorySumIntro, " + - "SUM(CASE WHEN category = 'outro' THEN 1 ELSE 0 END) as categorySumOutro, " + - "SUM(CASE WHEN category = 'interaction' THEN 1 ELSE 0 END) as categorySumInteraction, " + - "SUM(CASE WHEN category = 'selfpromo' THEN 1 ELSE 0 END) as categorySelfpromo, " + - "SUM(CASE WHEN category = 'music_offtopic' THEN 1 ELSE 0 END) as categoryMusicOfftopic, "; + categoryStats[i] = [ + rows[i].categorySponsor, + rows[i].categorySumIntro, + rows[i].categorySumOutro, + rows[i].categorySumInteraction, + rows[i].categorySelfpromo, + rows[i].categoryMusicOfftopic, + ]; } + } - const rows = db.prepare('all', "SELECT COUNT(*) as totalSubmissions, SUM(views) as viewCount," + - "SUM((sponsorTimes.endTime - sponsorTimes.startTime) / 60 * sponsorTimes.views) as minutesSaved, " + - "SUM(votes) as userVotes, " + - additionalFields + - "IFNULL(userNames.userName, sponsorTimes.userID) as userName FROM sponsorTimes LEFT JOIN userNames ON sponsorTimes.userID=userNames.userID " + - "LEFT JOIN privateDB.shadowBannedUsers ON sponsorTimes.userID=privateDB.shadowBannedUsers.userID " + - "WHERE sponsorTimes.votes > -1 AND sponsorTimes.shadowHidden != 1 AND privateDB.shadowBannedUsers.userID IS NULL " + - "GROUP BY IFNULL(userName, sponsorTimes.userID) HAVING userVotes > 20 " + - "ORDER BY " + sortBy + " DESC LIMIT 100", []); - - for (let i = 0; i < rows.length; i++) { - userNames[i] = rows[i].userName; - - viewCounts[i] = rows[i].viewCount; - totalSubmissions[i] = rows[i].totalSubmissions; - minutesSaved[i] = rows[i].minutesSaved; - if (categoryStatsEnabled) { - categoryStats[i] = [ - rows[i].categorySponsor, - rows[i].categorySumIntro, - rows[i].categorySumOutro, - rows[i].categorySumInteraction, - rows[i].categorySelfpromo, - rows[i].categoryMusicOfftopic, - ]; - } - } - - resolve({ - userNames, - viewCounts, - totalSubmissions, - minutesSaved, - categoryStats, - }); - }); + return { + userNames, + viewCounts, + totalSubmissions, + minutesSaved, + categoryStats, + }; } export async function getTopUsers(req: Request, res: Response) { diff --git a/src/routes/getTotalStats.ts b/src/routes/getTotalStats.ts index b5e6bf8..dcc94e6 100644 --- a/src/routes/getTotalStats.ts +++ b/src/routes/getTotalStats.ts @@ -13,8 +13,8 @@ let apiUsersCache = 0; let lastUserCountCheck = 0; -export function getTotalStats(req: Request, res: Response) { - let row = db.prepare('get', "SELECT COUNT(DISTINCT userID) as userCount, COUNT(*) as totalSubmissions, " + +export async function getTotalStats(req: Request, res: Response) { + let row = await db.prepare('get', "SELECT COUNT(DISTINCT userID) as userCount, COUNT(*) as totalSubmissions, " + "SUM(views) as viewCount, SUM((endTime - startTime) / 60 * views) as minutesSaved FROM sponsorTimes WHERE shadowHidden != 1 AND votes >= 0", []); if (row !== undefined) { diff --git a/src/routes/getUserInfo.ts b/src/routes/getUserInfo.ts index 99c7694..a8d92c7 100644 --- a/src/routes/getUserInfo.ts +++ b/src/routes/getUserInfo.ts @@ -3,9 +3,9 @@ import {getHash} from '../utils/getHash'; import {Request, Response} from 'express'; import {Logger} from '../utils/logger' -function dbGetSubmittedSegmentSummary(userID: string): any { +async function dbGetSubmittedSegmentSummary(userID: string): Promise<{ minutesSaved: number, segmentCount: number }> { try { - let row = db.prepare("get", "SELECT SUM(((endTime - startTime) / 60) * views) as minutesSaved, count(*) as segmentCount FROM sponsorTimes WHERE userID = ? AND votes > -2 AND shadowHidden != 1", [userID]); + let row = await db.prepare("get", "SELECT SUM(((endTime - startTime) / 60) * views) as minutesSaved, count(*) as segmentCount FROM sponsorTimes WHERE userID = ? AND votes > -2 AND shadowHidden != 1", [userID]); if (row.minutesSaved != null) { return { minutesSaved: row.minutesSaved, @@ -18,13 +18,13 @@ function dbGetSubmittedSegmentSummary(userID: string): any { }; } } catch (err) { - return false; + return null; } } -function dbGetUsername(userID: string) { +async function dbGetUsername(userID: string) { try { - let row = db.prepare('get', "SELECT userName FROM userNames WHERE userID = ?", [userID]); + let row = await db.prepare('get', "SELECT userName FROM userNames WHERE userID = ?", [userID]); if (row !== undefined) { return row.userName; } else { @@ -36,9 +36,9 @@ function dbGetUsername(userID: string) { } } -function dbGetViewsForUser(userID: string) { +async function dbGetViewsForUser(userID: string) { try { - let row = db.prepare('get', "SELECT SUM(views) as viewCount FROM sponsorTimes WHERE userID = ? AND votes > -2 AND shadowHidden != 1", [userID]); + let row = await db.prepare('get', "SELECT SUM(views) as viewCount FROM sponsorTimes WHERE userID = ? AND votes > -2 AND shadowHidden != 1", [userID]); //increase the view count by one if (row.viewCount != null) { return row.viewCount; @@ -50,9 +50,9 @@ function dbGetViewsForUser(userID: string) { } } -function dbGetWarningsForUser(userID: string): number { +async function dbGetWarningsForUser(userID: string): Promise { try { - let rows = db.prepare('all', "SELECT * FROM warnings WHERE userID = ?", [userID]); + let rows = await db.prepare('all', "SELECT * FROM warnings WHERE userID = ?", [userID]); return rows.length; } catch (err) { Logger.error('Couldn\'t get warnings for user ' + userID + '. returning 0'); @@ -60,7 +60,7 @@ function dbGetWarningsForUser(userID: string): number { } } -export function getUserInfo(req: Request, res: Response) { +export async function getUserInfo(req: Request, res: Response) { let userID = req.query.userID as string; if (userID == undefined) { @@ -72,13 +72,17 @@ export function getUserInfo(req: Request, res: Response) { //hash the userID userID = getHash(userID); - const segmentsSummary = dbGetSubmittedSegmentSummary(userID); - res.send({ - userID, - userName: dbGetUsername(userID), - minutesSaved: segmentsSummary.minutesSaved, - segmentCount: segmentsSummary.segmentCount, - viewCount: dbGetViewsForUser(userID), - warnings: dbGetWarningsForUser(userID), - }); + const segmentsSummary = await dbGetSubmittedSegmentSummary(userID); + if (segmentsSummary) { + res.send({ + userID, + userName: await dbGetUsername(userID), + minutesSaved: segmentsSummary.minutesSaved, + segmentCount: segmentsSummary.segmentCount, + viewCount: await dbGetViewsForUser(userID), + warnings: await dbGetWarningsForUser(userID), + }); + } else { + res.status(400).send(); + } } diff --git a/src/routes/getUsername.ts b/src/routes/getUsername.ts index 3d78de9..ef8966a 100644 --- a/src/routes/getUsername.ts +++ b/src/routes/getUsername.ts @@ -3,7 +3,7 @@ import {getHash} from '../utils/getHash'; import {Logger} from '../utils/logger'; import {Request, Response} from 'express'; -export function getUsername(req: Request, res: Response) { +export async function getUsername(req: Request, res: Response) { let userID = req.query.userID as string; if (userID == undefined) { @@ -16,7 +16,7 @@ export function getUsername(req: Request, res: Response) { userID = getHash(userID); try { - let row = db.prepare('get', "SELECT userName FROM userNames WHERE userID = ?", [userID]); + let row = await db.prepare('get', "SELECT userName FROM userNames WHERE userID = ?", [userID]); if (row !== undefined) { res.send({ diff --git a/src/routes/getViewsForUser.ts b/src/routes/getViewsForUser.ts index 1237100..2daba71 100644 --- a/src/routes/getViewsForUser.ts +++ b/src/routes/getViewsForUser.ts @@ -3,7 +3,7 @@ import {Request, Response} from 'express'; import {getHash} from '../utils/getHash'; import {Logger} from '../utils/logger'; -export function getViewsForUser(req: Request, res: Response) { +export async function getViewsForUser(req: Request, res: Response) { let userID = req.query.userID as string; if (userID == undefined) { @@ -16,7 +16,7 @@ export function getViewsForUser(req: Request, res: Response) { userID = getHash(userID); try { - let row = db.prepare('get', "SELECT SUM(views) as viewCount FROM sponsorTimes WHERE userID = ?", [userID]); + let row = await db.prepare('get', "SELECT SUM(views) as viewCount FROM sponsorTimes WHERE userID = ?", [userID]); //increase the view count by one if (row.viewCount != null) { diff --git a/src/routes/postNoSegments.ts b/src/routes/postNoSegments.ts index 04f6989..c92a19b 100644 --- a/src/routes/postNoSegments.ts +++ b/src/routes/postNoSegments.ts @@ -4,7 +4,7 @@ import {isUserVIP} from '../utils/isUserVIP'; import {db} from '../databases/databases'; import {Request, Response} from 'express'; -export function postNoSegments(req: Request, res: Response) { +export async function postNoSegments(req: Request, res: Response) { // Collect user input data let videoID = req.body.videoID; let userID = req.body.userID; @@ -25,7 +25,7 @@ export function postNoSegments(req: Request, res: Response) { // Check if user is VIP userID = getHash(userID); - let userIsVIP = isUserVIP(userID); + let userIsVIP = await isUserVIP(userID); if (!userIsVIP) { res.status(403).json({ @@ -35,7 +35,7 @@ export function postNoSegments(req: Request, res: Response) { } // Get existing no segment markers - let noSegmentList = db.prepare('all', 'SELECT category from noSegments where videoID = ?', [videoID]); + let noSegmentList = await db.prepare('all', 'SELECT category from noSegments where videoID = ?', [videoID]); if (!noSegmentList || noSegmentList.length === 0) { noSegmentList = []; } else { @@ -57,9 +57,9 @@ export function postNoSegments(req: Request, res: Response) { }); // create database entry - categoriesToMark.forEach((category) => { + for (const category of categoriesToMark) { try { - db.prepare('run', "INSERT INTO noSegments (videoID, userID, category) VALUES(?, ?, ?)", [videoID, userID, category]); + await db.prepare('run', "INSERT INTO noSegments (videoID, userID, category) VALUES(?, ?, ?)", [videoID, userID, category]); } catch (err) { Logger.error("Error submitting 'noSegment' marker for category '" + category + "' for video '" + videoID + "'"); Logger.error(err); @@ -67,7 +67,7 @@ export function postNoSegments(req: Request, res: Response) { message: "Internal Server Error: Could not write marker to the database.", }); } - }); + }; res.status(200).json({ submitted: categoriesToMark, diff --git a/src/routes/postSegmentShift.ts b/src/routes/postSegmentShift.ts index a885b06..47e0f85 100644 --- a/src/routes/postSegmentShift.ts +++ b/src/routes/postSegmentShift.ts @@ -45,7 +45,7 @@ function shiftSegment(segment: any, shift: { startTime: any; endTime: any }) { return {action: ACTION_NONE, segment}; } -export function postSegmentShift(req: Request, res: Response): Response { +export async function postSegmentShift(req: Request, res: Response): Promise { // Collect user input data const videoID = req.body.videoID; const startTime = req.body.startTime; @@ -66,7 +66,7 @@ export function postSegmentShift(req: Request, res: Response): Response { // Check if user is VIP userID = getHash(userID); - const userIsVIP = isUserVIP(userID); + const userIsVIP = await isUserVIP(userID); if (!userIsVIP) { res.status(403).json({ @@ -76,22 +76,23 @@ export function postSegmentShift(req: Request, res: Response): Response { } try { - const segments = db.prepare('all', 'SELECT startTime, endTime, UUID FROM sponsorTimes WHERE videoID = ?', [videoID]); + const segments = await db.prepare('all', 'SELECT startTime, endTime, UUID FROM sponsorTimes WHERE videoID = ?', [videoID]); const shift = { startTime, endTime, }; - segments.forEach((segment: any) => { + + for (const segment of segments) { const result = shiftSegment(segment, shift); switch (result.action) { case ACTION_UPDATE: - db.prepare('run', 'UPDATE sponsorTimes SET startTime = ?, endTime = ? WHERE UUID = ?', [result.segment.startTime, result.segment.endTime, result.segment.UUID]); + await db.prepare('run', 'UPDATE sponsorTimes SET startTime = ?, endTime = ? WHERE UUID = ?', [result.segment.startTime, result.segment.endTime, result.segment.UUID]); break; case ACTION_REMOVE: - db.prepare('run', 'UPDATE sponsorTimes SET startTime = ?, endTime = ?, votes = -2 WHERE UUID = ?', [result.segment.startTime, result.segment.endTime, result.segment.UUID]); + await db.prepare('run', 'UPDATE sponsorTimes SET startTime = ?, endTime = ?, votes = -2 WHERE UUID = ?', [result.segment.startTime, result.segment.endTime, result.segment.UUID]); break; } - }); + }; } catch (err) { Logger.error(err); res.sendStatus(500); diff --git a/src/routes/postSkipSegments.ts b/src/routes/postSkipSegments.ts index 1029f3f..d17f4f0 100644 --- a/src/routes/postSkipSegments.ts +++ b/src/routes/postSkipSegments.ts @@ -15,8 +15,8 @@ import { skipSegmentsKey } from '../middleware/redisKeys'; import redis from '../utils/redis'; -function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: any, {submissionStart, submissionEnd}: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) { - const row = db.prepare('get', "SELECT userName FROM userNames WHERE userID = ?", [userID]); +async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: any, {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; const video = youtubeData.items[0]; @@ -45,9 +45,9 @@ function sendWebhookNotification(userID: string, videoID: string, UUID: string, }); } -function sendWebhooks(userID: string, videoID: string, UUID: string, segmentInfo: any) { +async function sendWebhooks(userID: string, videoID: string, UUID: string, segmentInfo: any) { if (config.youtubeAPIKey !== null) { - const userSubmissionCountRow = db.prepare('get', "SELECT count(*) as submissionCount FROM sponsorTimes WHERE userID = ?", [userID]); + const userSubmissionCountRow = await db.prepare('get', "SELECT count(*) as submissionCount FROM sponsorTimes WHERE userID = ?", [userID]); YouTubeAPI.listVideos(videoID, (err: any, data: any) => { if (err || data.items.length === 0) { @@ -105,8 +105,8 @@ function sendWebhooks(userID: string, videoID: string, UUID: string, segmentInfo } } -function sendWebhooksNB(userID: string, videoID: string, UUID: string, startTime: number, endTime: number, category: string, probability: number, ytData: any) { - const submissionInfoRow = db.prepare('get', "SELECT " + +async function sendWebhooksNB(userID: string, videoID: string, UUID: string, startTime: number, endTime: number, category: string, probability: number, ytData: any) { + const submissionInfoRow = await db.prepare('get', "SELECT " + "(select count(1) from sponsorTimes where userID = ?) count, " + "(select count(1) from sponsorTimes where userID = ? and votes <= -2) disregarded, " + "coalesce((select userName FROM userNames WHERE userID = ?), ?) userName", @@ -304,20 +304,20 @@ export async function postSkipSegments(req: Request, res: Response) { const MILLISECONDS_IN_HOUR = 3600000; const now = Date.now(); - const warningsCount = db.prepare('get', "SELECT count(1) as count FROM warnings WHERE userID = ? AND issueTime > ? AND enabled = 1", + const warningsCount = (await db.prepare('get', "SELECT count(1) as count FROM warnings WHERE userID = ? AND issueTime > ? AND enabled = 1", [userID, Math.floor(now - (config.hoursAfterWarningExpires * MILLISECONDS_IN_HOUR))], - ).count; + )).count; if (warningsCount >= config.maxNumberOfActiveWarnings) { return res.status(403).send('Submission rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes that are not malicious, and we just want to clarify the rules. Could you please send a message in Discord or Matrix so we can further help you?'); } - const noSegmentList = db.prepare('all', 'SELECT category from noSegments where videoID = ?', [videoID]).map((list: any) => { + const noSegmentList = (await db.prepare('all', 'SELECT category from noSegments where videoID = ?', [videoID])).map((list: any) => { return list.category; }); //check if this user is on the vip list - const isVIP = db.prepare("get", "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [userID]).userCount > 0; + const isVIP = (await db.prepare("get", "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [userID])).userCount > 0; const decreaseVotes = 0; @@ -366,7 +366,7 @@ export async function postSkipSegments(req: Request, res: Response) { } //check if this info has already been submitted before - const duplicateCheck2Row = db.prepare('get', "SELECT COUNT(*) as count FROM sponsorTimes WHERE startTime = ? " + + const duplicateCheck2Row = await db.prepare('get', "SELECT COUNT(*) as count FROM sponsorTimes WHERE startTime = ? " + "and endTime = ? and category = ? and videoID = ?", [startTime, endTime, segments[i].category, videoID]); if (duplicateCheck2Row.count > 0) { res.sendStatus(409); @@ -401,7 +401,7 @@ export async function postSkipSegments(req: Request, res: Response) { // Disable IP ratelimiting for now if (false) { //check to see if this ip has submitted too many sponsors today - const rateLimitCheckRow = privateDB.prepare('get', "SELECT COUNT(*) as count FROM sponsorTimes WHERE hashedIP = ? AND videoID = ? AND timeSubmitted > ?", [hashedIP, videoID, yesterday]); + const rateLimitCheckRow = await privateDB.prepare('get', "SELECT COUNT(*) as count FROM sponsorTimes WHERE hashedIP = ? AND videoID = ? AND timeSubmitted > ?", [hashedIP, videoID, yesterday]); if (rateLimitCheckRow.count >= 10) { //too many sponsors for the same video from the same ip address @@ -414,7 +414,7 @@ export async function postSkipSegments(req: Request, res: Response) { // Disable max submissions for now if (false) { //check to see if the user has already submitted sponsors for this video - const duplicateCheckRow = db.prepare('get', "SELECT COUNT(*) as count FROM sponsorTimes WHERE userID = ? and videoID = ?", [userID, videoID]); + const duplicateCheckRow = await db.prepare('get', "SELECT COUNT(*) as count FROM sponsorTimes WHERE userID = ? and videoID = ?", [userID, videoID]); if (duplicateCheckRow.count >= 16) { //too many sponsors for the same video from the same user @@ -425,7 +425,7 @@ export async function postSkipSegments(req: Request, res: Response) { } //check to see if this user is shadowbanned - const shadowBanRow = privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedUsers WHERE userID = ?", [userID]); + const shadowBanRow = await privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedUsers WHERE userID = ?", [userID]); let shadowBanned = shadowBanRow.userCount; @@ -445,7 +445,7 @@ export async function postSkipSegments(req: Request, res: Response) { Logger.error("Error while submitting when connecting to YouTube API: " + err); } else { //get all segments for this video and user - const allSubmittedByUser = db.prepare('all', "SELECT startTime, endTime FROM sponsorTimes WHERE userID = ? and videoID = ? and votes > -1", [userID, videoID]); + const allSubmittedByUser = await db.prepare('all', "SELECT startTime, endTime FROM sponsorTimes WHERE userID = ? and videoID = ? and votes > -1", [userID, videoID]); const allSegmentTimes = []; if (allSubmittedByUser !== undefined) { //add segments the user has previously submitted @@ -489,7 +489,7 @@ export async function postSkipSegments(req: Request, res: Response) { const startingLocked = isVIP ? 1 : 0; try { - db.prepare('run', "INSERT INTO sponsorTimes " + + await db.prepare('run', "INSERT INTO sponsorTimes " + "(videoID, startTime, endTime, votes, locked, UUID, userID, timeSubmitted, views, category, shadowHidden, hashedVideoID)" + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [ videoID, segmentInfo.segment[0], segmentInfo.segment[1], startingVotes, startingLocked, UUID, userID, timeSubmitted, 0, segmentInfo.category, shadowBanned, getHash(videoID, 1), @@ -497,7 +497,7 @@ export async function postSkipSegments(req: Request, res: Response) { ); //add to private db as well - privateDB.prepare('run', "INSERT INTO sponsorTimes VALUES(?, ?, ?)", [videoID, hashedIP, timeSubmitted]); + await privateDB.prepare('run', "INSERT INTO sponsorTimes VALUES(?, ?, ?)", [videoID, hashedIP, timeSubmitted]); // Clear redis cache for this video redis.delAsync(skipSegmentsKey(videoID)); diff --git a/src/routes/postWarning.ts b/src/routes/postWarning.ts index 6feedef..1d3a362 100644 --- a/src/routes/postWarning.ts +++ b/src/routes/postWarning.ts @@ -5,7 +5,7 @@ import {isUserVIP} from '../utils/isUserVIP'; import {getHash} from '../utils/getHash'; import { HashedUserID, UserID } from '../types/user.model'; -export function postWarning(req: Request, res: Response) { +export async function postWarning(req: Request, res: Response) { // Collect user input data let issuerUserID: HashedUserID = getHash( req.body.issuerUserID); let userID: UserID = req.body.userID; @@ -13,7 +13,7 @@ export function postWarning(req: Request, res: Response) { let enabled: boolean = req.body.enabled ?? true; // Ensure user is a VIP - if (!isUserVIP(issuerUserID)) { + if (!await isUserVIP(issuerUserID)) { Logger.warn("Permission violation: User " + issuerUserID + " attempted to warn user " + userID + "."); res.status(403).json({"message": "Not a VIP"}); return; @@ -22,17 +22,17 @@ export function postWarning(req: Request, res: Response) { let resultStatus = ""; if (enabled) { - let previousWarning = db.prepare('get', 'SELECT * FROM warnings WHERE userID = ? AND issuerUserID = ?', [userID, issuerUserID]); + let previousWarning = await db.prepare('get', 'SELECT * FROM warnings WHERE userID = ? AND issuerUserID = ?', [userID, issuerUserID]); if (!previousWarning) { - db.prepare('run', 'INSERT INTO warnings (userID, issueTime, issuerUserID, enabled) VALUES (?, ?, ?, 1)', [userID, issueTime, issuerUserID]); + await db.prepare('run', 'INSERT INTO warnings (userID, issueTime, issuerUserID, enabled) VALUES (?, ?, ?, 1)', [userID, issueTime, issuerUserID]); resultStatus = "issued to"; } else { res.status(409).send(); return; } } else { - db.prepare('run', 'UPDATE warnings SET enabled = 0 WHERE userID = ? AND issuerUserID = ?', [userID, issuerUserID]); + await db.prepare('run', 'UPDATE warnings SET enabled = 0 WHERE userID = ? AND issuerUserID = ?', [userID, issuerUserID]); resultStatus = "removed from"; } diff --git a/src/routes/setUsername.ts b/src/routes/setUsername.ts index 228a1b1..02ae415 100644 --- a/src/routes/setUsername.ts +++ b/src/routes/setUsername.ts @@ -4,7 +4,7 @@ import {db} from '../databases/databases'; import {getHash} from '../utils/getHash'; import {Request, Response} from 'express'; -export function setUsername(req: Request, res: Response) { +export async function setUsername(req: Request, res: Response) { let userID = req.query.userID as string; let userName = req.query.username as string; @@ -38,14 +38,14 @@ export function setUsername(req: Request, res: Response) { try { //check if username is already set - let row = db.prepare('get', "SELECT count(*) as count FROM userNames WHERE userID = ?", [userID]); + let row = await db.prepare('get', "SELECT count(*) as count FROM userNames WHERE userID = ?", [userID]); if (row.count > 0) { //already exists, update this row - db.prepare('run', "UPDATE userNames SET userName = ? WHERE userID = ?", [userName, userID]); + await db.prepare('run', "UPDATE userNames SET userName = ? WHERE userID = ?", [userName, userID]); } else { //add to the db - db.prepare('run', "INSERT INTO userNames VALUES(?, ?)", [userID, userName]); + await db.prepare('run', "INSERT INTO userNames VALUES(?, ?)", [userID, userName]); } res.sendStatus(200); diff --git a/src/routes/shadowBanUser.ts b/src/routes/shadowBanUser.ts index d782990..a115c7c 100644 --- a/src/routes/shadowBanUser.ts +++ b/src/routes/shadowBanUser.ts @@ -23,7 +23,7 @@ export async function shadowBanUser(req: Request, res: Response) { //hash the userID adminUserIDInput = getHash(adminUserIDInput); - const isVIP = db.prepare("get", "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [adminUserIDInput]).userCount > 0; + const isVIP = (await db.prepare("get", "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [adminUserIDInput])).userCount > 0; if (!isVIP) { //not authorized res.sendStatus(403); @@ -32,30 +32,30 @@ export async function shadowBanUser(req: Request, res: Response) { if (userID) { //check to see if this user is already shadowbanned - const row = privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedUsers WHERE userID = ?", [userID]); + const row = await privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedUsers WHERE userID = ?", [userID]); if (enabled && row.userCount == 0) { //add them to the shadow ban list //add it to the table - privateDB.prepare('run', "INSERT INTO shadowBannedUsers VALUES(?)", [userID]); + await privateDB.prepare('run', "INSERT INTO shadowBannedUsers VALUES(?)", [userID]); //find all previous submissions and hide them if (unHideOldSubmissions) { - db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 1 WHERE userID = ?" + await db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 1 WHERE userID = ?" + " AND NOT EXISTS ( SELECT videoID, category FROM noSegments WHERE" + " sponsorTimes.videoID = noSegments.videoID AND sponsorTimes.category = noSegments.category)", [userID]); } } else if (!enabled && row.userCount > 0) { //remove them from the shadow ban list - privateDB.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]); + await privateDB.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]); //find all previous submissions and unhide them if (unHideOldSubmissions) { - let segmentsToIgnore = db.prepare('all', "SELECT UUID FROM sponsorTimes st " + let segmentsToIgnore = (await db.prepare('all', "SELECT UUID FROM sponsorTimes st " + "JOIN noSegments ns on st.videoID = ns.videoID AND st.category = ns.category WHERE st.userID = ?" - , [userID]).map((item: {UUID: string}) => item.UUID); - let allSegments = db.prepare('all', "SELECT UUID FROM sponsorTimes st WHERE st.userID = ?", [userID]) + , [userID])).map((item: {UUID: string}) => item.UUID); + let allSegments = (await db.prepare('all', "SELECT UUID FROM sponsorTimes st WHERE st.userID = ?", [userID])) .map((item: {UUID: string}) => item.UUID); allSegments.filter((item: {uuid: string}) => { @@ -68,29 +68,29 @@ export async function shadowBanUser(req: Request, res: Response) { } else if (hashedIP) { //check to see if this user is already shadowbanned - // let row = privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedIPs WHERE hashedIP = ?", [hashedIP]); + // let row = await privateDB.prepare('get', "SELECT count(*) as userCount FROM shadowBannedIPs WHERE hashedIP = ?", [hashedIP]); // if (enabled && row.userCount == 0) { if (enabled) { //add them to the shadow ban list //add it to the table - // privateDB.prepare('run', "INSERT INTO shadowBannedIPs VALUES(?)", [hashedIP]); + // await privateDB.prepare('run', "INSERT INTO shadowBannedIPs VALUES(?)", [hashedIP]); //find all previous submissions and hide them if (unHideOldSubmissions) { - db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 1 WHERE timeSubmitted IN " + + await db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 1 WHERE timeSubmitted IN " + "(SELECT privateDB.timeSubmitted FROM sponsorTimes LEFT JOIN privateDB.sponsorTimes as privateDB ON sponsorTimes.timeSubmitted=privateDB.timeSubmitted " + "WHERE privateDB.hashedIP = ?)", [hashedIP]); } } /*else if (!enabled && row.userCount > 0) { // //remove them from the shadow ban list - // privateDB.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]); + // await privateDB.prepare('run', "DELETE FROM shadowBannedUsers WHERE userID = ?", [userID]); // //find all previous submissions and unhide them // if (unHideOldSubmissions) { - // db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE userID = ?", [userID]); + // await db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE userID = ?", [userID]); // } }*/ } diff --git a/src/routes/viewedVideoSponsorTime.ts b/src/routes/viewedVideoSponsorTime.ts index 5d9dda6..41c6484 100644 --- a/src/routes/viewedVideoSponsorTime.ts +++ b/src/routes/viewedVideoSponsorTime.ts @@ -1,7 +1,7 @@ import {db} from '../databases/databases'; import {Request, Response} from 'express'; -export function viewedVideoSponsorTime(req: Request, res: Response): Response { +export async function viewedVideoSponsorTime(req: Request, res: Response): Promise { let UUID = req.query.UUID; if (UUID == undefined) { @@ -10,7 +10,7 @@ export function viewedVideoSponsorTime(req: Request, res: Response): Response { } //up the view count by one - db.prepare('run', "UPDATE sponsorTimes SET views = views + 1 WHERE UUID = ?", [UUID]); + await db.prepare('run', "UPDATE sponsorTimes SET views = views + 1 WHERE UUID = ?", [UUID]); return res.sendStatus(200); } diff --git a/src/routes/voteOnSponsorTime.ts b/src/routes/voteOnSponsorTime.ts index 5fedb8e..41ca838 100644 --- a/src/routes/voteOnSponsorTime.ts +++ b/src/routes/voteOnSponsorTime.ts @@ -35,14 +35,14 @@ interface VoteData { oldIncrementAmount: number; } -function sendWebhooks(voteData: VoteData) { - const submissionInfoRow = db.prepare('get', "SELECT s.videoID, s.userID, s.startTime, s.endTime, s.category, u.userName, " + +async function sendWebhooks(voteData: VoteData) { + 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=?", [voteData.UUID]); - const userSubmissionCountRow = db.prepare('get', "SELECT count(*) as submissionCount FROM sponsorTimes WHERE userID = ?", [voteData.nonAnonUserID]); + const userSubmissionCountRow = await db.prepare('get', "SELECT count(*) as submissionCount FROM sponsorTimes WHERE userID = ?", [voteData.nonAnonUserID]); if (submissionInfoRow !== undefined && userSubmissionCountRow != undefined) { let webhookURL: string = null; @@ -141,9 +141,9 @@ function sendWebhooks(voteData: VoteData) { } } -function categoryVote(UUID: string, userID: string, isVIP: boolean, isOwnSubmission: boolean, category: string, hashedIP: string, res: Response) { +async function categoryVote(UUID: string, userID: string, isVIP: boolean, isOwnSubmission: boolean, category: string, hashedIP: string, res: Response) { // Check if they've already made a vote - const usersLastVoteInfo = privateDB.prepare('get', "select count(*) as votes, category from categoryVotes where UUID = ? and userID = ?", [UUID, userID]); + const usersLastVoteInfo = await privateDB.prepare('get', "select count(*) as votes, category from categoryVotes where UUID = ? and userID = ?", [UUID, userID]); if (usersLastVoteInfo?.category === category) { // Double vote, ignore @@ -151,7 +151,7 @@ function categoryVote(UUID: string, userID: string, isVIP: boolean, isOwnSubmiss return; } - const currentCategory = db.prepare('get', "select category from sponsorTimes where UUID = ?", [UUID]); + const currentCategory = await db.prepare('get', "select category from sponsorTimes where UUID = ?", [UUID]); if (!currentCategory) { // Submission doesn't exist res.status(400).send("Submission doesn't exist."); @@ -163,36 +163,36 @@ function categoryVote(UUID: string, userID: string, isVIP: boolean, isOwnSubmiss return; } - const nextCategoryInfo = db.prepare("get", "select votes from categoryVotes where UUID = ? and category = ?", [UUID, category]); + const nextCategoryInfo = await db.prepare("get", "select votes from categoryVotes where UUID = ? and category = ?", [UUID, category]); const timeSubmitted = Date.now(); const voteAmount = isVIP ? 500 : 1; // Add the vote - if (db.prepare('get', "select count(*) as count from categoryVotes where UUID = ? and category = ?", [UUID, category]).count > 0) { + if ((await db.prepare('get', "select count(*) as count from categoryVotes where UUID = ? and category = ?", [UUID, category])).count > 0) { // Update the already existing db entry - db.prepare('run', "update categoryVotes set votes = votes + ? where UUID = ? and category = ?", [voteAmount, UUID, category]); + await db.prepare('run', "update categoryVotes set votes = votes + ? where UUID = ? and category = ?", [voteAmount, UUID, category]); } else { // Add a db entry - db.prepare('run', "insert into categoryVotes (UUID, category, votes) values (?, ?, ?)", [UUID, category, voteAmount]); + await db.prepare('run', "insert into categoryVotes (UUID, category, votes) values (?, ?, ?)", [UUID, category, voteAmount]); } // Add the info into the private db if (usersLastVoteInfo?.votes > 0) { // Reverse the previous vote - db.prepare('run', "update categoryVotes set votes = votes - ? where UUID = ? and category = ?", [voteAmount, UUID, usersLastVoteInfo.category]); + await db.prepare('run', "update categoryVotes set votes = votes - ? where UUID = ? and category = ?", [voteAmount, UUID, usersLastVoteInfo.category]); - privateDB.prepare('run', "update categoryVotes set category = ?, timeSubmitted = ?, hashedIP = ? where userID = ? and UUID = ?", [category, timeSubmitted, hashedIP, userID, UUID]); + await privateDB.prepare('run', "update categoryVotes set category = ?, timeSubmitted = ?, hashedIP = ? where userID = ? and UUID = ?", [category, timeSubmitted, hashedIP, userID, UUID]); } else { - privateDB.prepare('run', "insert into categoryVotes (UUID, userID, hashedIP, category, timeSubmitted) values (?, ?, ?, ?, ?)", [UUID, userID, hashedIP, category, timeSubmitted]); + await privateDB.prepare('run', "insert into categoryVotes (UUID, userID, hashedIP, category, timeSubmitted) values (?, ?, ?, ?, ?)", [UUID, userID, hashedIP, category, timeSubmitted]); } // See if the submissions category is ready to change - const currentCategoryInfo = db.prepare("get", "select votes from categoryVotes where UUID = ? and category = ?", [UUID, currentCategory.category]); + const currentCategoryInfo = await db.prepare("get", "select votes from categoryVotes where UUID = ? and category = ?", [UUID, currentCategory.category]); - const submissionInfo = db.prepare("get", "SELECT userID, timeSubmitted, votes FROM sponsorTimes WHERE UUID = ?", [UUID]); - const isSubmissionVIP = submissionInfo && isUserVIP(submissionInfo.userID); + const submissionInfo = await db.prepare("get", "SELECT userID, timeSubmitted, votes FROM sponsorTimes WHERE UUID = ?", [UUID]); + const isSubmissionVIP = submissionInfo && await isUserVIP(submissionInfo.userID); const startingVotes = isSubmissionVIP ? 10000 : 1; // Change this value from 1 in the future to make it harder to change categories @@ -201,9 +201,9 @@ function categoryVote(UUID: string, userID: string, isVIP: boolean, isOwnSubmiss // Add submission as vote if (!currentCategoryInfo && submissionInfo) { - db.prepare("run", "insert into categoryVotes (UUID, category, votes) values (?, ?, ?)", [UUID, currentCategory.category, currentCategoryCount]); + await db.prepare("run", "insert into categoryVotes (UUID, category, votes) values (?, ?, ?)", [UUID, currentCategory.category, currentCategoryCount]); - privateDB.prepare("run", "insert into categoryVotes (UUID, userID, hashedIP, category, timeSubmitted) values (?, ?, ?, ?, ?)", [UUID, submissionInfo.userID, "unknown", currentCategory.category, submissionInfo.timeSubmitted]); + await privateDB.prepare("run", "insert into categoryVotes (UUID, userID, hashedIP, category, timeSubmitted) values (?, ?, ?, ?, ?)", [UUID, submissionInfo.userID, "unknown", currentCategory.category, submissionInfo.timeSubmitted]); } const nextCategoryCount = (nextCategoryInfo?.votes || 0) + voteAmount; @@ -212,7 +212,7 @@ function categoryVote(UUID: string, userID: string, isVIP: boolean, isOwnSubmiss // VIPs change it every time if (nextCategoryCount - currentCategoryCount >= Math.max(Math.ceil(submissionInfo?.votes / 2), 2) || isVIP || isOwnSubmission) { // Replace the category - db.prepare('run', "update sponsorTimes set category = ? where UUID = ?", [category, UUID]); + await db.prepare('run', "update sponsorTimes set category = ? where UUID = ?", [category, UUID]); } res.sendStatus(200); @@ -245,20 +245,20 @@ export async function voteOnSponsorTime(req: Request, res: Response) { const hashedIP = getHash(ip + config.globalSalt); //check if this user is on the vip list - const isVIP = db.prepare('get', "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [nonAnonUserID]).userCount > 0; + const isVIP = (await db.prepare('get', "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [nonAnonUserID])).userCount > 0; //check if user voting on own submission - const isOwnSubmission = db.prepare("get", "SELECT UUID as submissionCount FROM sponsorTimes where userID = ? AND UUID = ?", [nonAnonUserID, UUID]) !== undefined; + const isOwnSubmission = (await db.prepare("get", "SELECT UUID as submissionCount FROM sponsorTimes where userID = ? AND UUID = ?", [nonAnonUserID, UUID])) !== undefined; // If not upvote if (!isVIP && type !== 1) { - const isSegmentLocked = () => !!db.prepare('get', "SELECT locked FROM sponsorTimes WHERE UUID = ?", [UUID])?.locked; - const isVideoLocked = () => !!db.prepare('get', 'SELECT noSegments.category from noSegments left join sponsorTimes' + + const isSegmentLocked = async () => !!(await db.prepare('get', "SELECT locked FROM sponsorTimes WHERE UUID = ?", [UUID]))?.locked; + const isVideoLocked = async () => !!(await db.prepare('get', 'SELECT noSegments.category from noSegments left join sponsorTimes' + ' on (noSegments.videoID = sponsorTimes.videoID and noSegments.category = sponsorTimes.category)' + - ' where UUID = ?', [UUID]); + ' where UUID = ?', [UUID])); - if (isSegmentLocked() || isVideoLocked()) { + if (await isSegmentLocked() || await isVideoLocked()) { res.status(403).send("Vote rejected: A moderator has decided that this segment is correct"); return; } @@ -270,7 +270,7 @@ export async function voteOnSponsorTime(req: Request, res: Response) { if (type == 1 && !isVIP && !isOwnSubmission) { // Check if upvoting hidden segment - const voteInfo = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", [UUID]); + const voteInfo = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", [UUID]); if (voteInfo && voteInfo.votes <= -2) { res.status(403).send("Not allowed to upvote segment with too many downvotes unless you are VIP."); @@ -280,9 +280,9 @@ export async function voteOnSponsorTime(req: Request, res: Response) { const MILLISECONDS_IN_HOUR = 3600000; const now = Date.now(); - const warningsCount = db.prepare('get', "SELECT count(1) as count FROM warnings WHERE userID = ? AND issueTime > ? AND enabled = 1", + const warningsCount = (await db.prepare('get', "SELECT count(1) as count FROM warnings WHERE userID = ? AND issueTime > ? AND enabled = 1", [nonAnonUserID, Math.floor(now - (config.hoursAfterWarningExpires * MILLISECONDS_IN_HOUR))], - ).count; + )).count; if (warningsCount >= config.maxNumberOfActiveWarnings) { return res.status(403).send('Vote rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes that are not malicious, and we just want to clarify the rules. Could you please send a message in Discord or Matrix so we can further help you?'); @@ -292,7 +292,7 @@ export async function voteOnSponsorTime(req: Request, res: Response) { try { //check if vote has already happened - const votesRow = privateDB.prepare('get', "SELECT type FROM votes WHERE userID = ? AND UUID = ?", [userID, UUID]); + const votesRow = await privateDB.prepare('get', "SELECT type FROM votes WHERE userID = ? AND UUID = ?", [userID, UUID]); //-1 for downvote, 1 for upvote. Maybe more depending on reputation in the future let incrementAmount = 0; @@ -338,7 +338,7 @@ export async function voteOnSponsorTime(req: Request, res: Response) { } //check if the increment amount should be multiplied (downvotes have more power if there have been many views) - const row = db.prepare('get', "SELECT videoID, votes, views FROM sponsorTimes WHERE UUID = ?", [UUID]) as + const row = await db.prepare('get', "SELECT videoID, votes, views FROM sponsorTimes WHERE UUID = ?", [UUID]) as {videoID: VideoID, votes: number, views: number}; if (voteTypeEnum === voteTypes.normal) { @@ -357,16 +357,16 @@ export async function voteOnSponsorTime(req: Request, res: Response) { // Only change the database if they have made a submission before and haven't voted recently const ableToVote = isVIP - || (db.prepare("get", "SELECT userID FROM sponsorTimes WHERE userID = ?", [nonAnonUserID]) !== undefined - && privateDB.prepare("get", "SELECT userID FROM shadowBannedUsers WHERE userID = ?", [nonAnonUserID]) === undefined - && privateDB.prepare("get", "SELECT UUID FROM votes WHERE UUID = ? AND hashedIP = ? AND userID != ?", [UUID, hashedIP, userID]) === undefined); + || ((await db.prepare("get", "SELECT userID FROM sponsorTimes WHERE userID = ?", [nonAnonUserID])) !== undefined + && (await privateDB.prepare("get", "SELECT userID FROM shadowBannedUsers WHERE userID = ?", [nonAnonUserID])) === undefined + && (await privateDB.prepare("get", "SELECT UUID FROM votes WHERE UUID = ? AND hashedIP = ? AND userID != ?", [UUID, hashedIP, userID])) === undefined); if (ableToVote) { //update the votes table if (votesRow != undefined) { - privateDB.prepare('run', "UPDATE votes SET type = ? WHERE userID = ? AND UUID = ?", [type, userID, UUID]); + await privateDB.prepare('run', "UPDATE votes SET type = ? WHERE userID = ? AND UUID = ?", [type, userID, UUID]); } else { - privateDB.prepare('run', "INSERT INTO votes VALUES(?, ?, ?, ?)", [UUID, userID, hashedIP, type]); + await privateDB.prepare('run', "INSERT INTO votes VALUES(?, ?, ?, ?)", [UUID, userID, hashedIP, type]); } let columnName = ""; @@ -378,13 +378,13 @@ export async function voteOnSponsorTime(req: Request, res: Response) { //update the vote count on this sponsorTime //oldIncrementAmount will be zero is row is null - db.prepare('run', "UPDATE sponsorTimes SET " + columnName + " = " + columnName + " + ? WHERE UUID = ?", [incrementAmount - oldIncrementAmount, UUID]); + await db.prepare('run', "UPDATE sponsorTimes SET " + columnName + " = " + columnName + " + ? WHERE UUID = ?", [incrementAmount - oldIncrementAmount, UUID]); if (isVIP && incrementAmount > 0 && voteTypeEnum === voteTypes.normal) { // Lock this submission - db.prepare('run', "UPDATE sponsorTimes SET locked = 1 WHERE UUID = ?", [UUID]); + await db.prepare('run', "UPDATE sponsorTimes SET locked = 1 WHERE UUID = ?", [UUID]); } else if (isVIP && incrementAmount < 0 && voteTypeEnum === voteTypes.normal) { // Unlock if a VIP downvotes it - db.prepare('run', "UPDATE sponsorTimes SET locked = 0 WHERE UUID = ?", [UUID]); + await db.prepare('run', "UPDATE sponsorTimes SET locked = 0 WHERE UUID = ?", [UUID]); } // Clear redis cache for this video @@ -393,7 +393,7 @@ export async function voteOnSponsorTime(req: Request, res: Response) { //for each positive vote, see if a hidden submission can be shown again if (incrementAmount > 0 && voteTypeEnum === voteTypes.normal) { //find the UUID that submitted the submission that was voted on - const submissionUserIDInfo = db.prepare('get', "SELECT userID FROM sponsorTimes WHERE UUID = ?", [UUID]); + const submissionUserIDInfo = await db.prepare('get', "SELECT userID FROM sponsorTimes WHERE UUID = ?", [UUID]); if (!submissionUserIDInfo) { // They are voting on a non-existent submission res.status(400).send("Voting on a non-existent submission"); @@ -403,14 +403,14 @@ export async function voteOnSponsorTime(req: Request, res: Response) { const submissionUserID = submissionUserIDInfo.userID; //check if any submissions are hidden - const hiddenSubmissionsRow = db.prepare('get', "SELECT count(*) as hiddenSubmissions FROM sponsorTimes WHERE userID = ? AND shadowHidden > 0", [submissionUserID]); + const hiddenSubmissionsRow = await db.prepare('get', "SELECT count(*) as hiddenSubmissions FROM sponsorTimes WHERE userID = ? AND shadowHidden > 0", [submissionUserID]); if (hiddenSubmissionsRow.hiddenSubmissions > 0) { //see if some of this users submissions should be visible again if (await isUserTrustworthy(submissionUserID)) { //they are trustworthy again, show 2 of their submissions again, if there are two to show - db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE ROWID IN (SELECT ROWID FROM sponsorTimes WHERE userID = ? AND shadowHidden = 1 LIMIT 2)", [submissionUserID]); + await db.prepare('run', "UPDATE sponsorTimes SET shadowHidden = 0 WHERE ROWID IN (SELECT ROWID FROM sponsorTimes WHERE userID = ? AND shadowHidden = 1 LIMIT 2)", [submissionUserID]); } } } diff --git a/src/utils/isUserTrustworthy.ts b/src/utils/isUserTrustworthy.ts index 884ea2e..93bb6f0 100644 --- a/src/utils/isUserTrustworthy.ts +++ b/src/utils/isUserTrustworthy.ts @@ -6,11 +6,11 @@ import {db} from '../databases/databases'; */ export async function isUserTrustworthy(userID: string): Promise { //check to see if this user how many submissions this user has submitted - const totalSubmissionsRow = db.prepare('get', "SELECT count(*) as totalSubmissions, sum(votes) as voteSum FROM sponsorTimes WHERE userID = ?", [userID]); + const totalSubmissionsRow = await db.prepare('get', "SELECT count(*) as totalSubmissions, sum(votes) as voteSum FROM sponsorTimes WHERE userID = ?", [userID]); if (totalSubmissionsRow.totalSubmissions > 5) { //check if they have a high downvote ratio - const downvotedSubmissionsRow = db.prepare('get', "SELECT count(*) as downvotedSubmissions FROM sponsorTimes WHERE userID = ? AND (votes < 0 OR shadowHidden > 0)", [userID]); + const downvotedSubmissionsRow = await db.prepare('get', "SELECT count(*) as downvotedSubmissions FROM sponsorTimes WHERE userID = ? AND (votes < 0 OR shadowHidden > 0)", [userID]); return (downvotedSubmissionsRow.downvotedSubmissions / totalSubmissionsRow.totalSubmissions) < 0.6 || (totalSubmissionsRow.voteSum > downvotedSubmissionsRow.downvotedSubmissions); diff --git a/src/utils/isUserVIP.ts b/src/utils/isUserVIP.ts index 3704791..596ac62 100644 --- a/src/utils/isUserVIP.ts +++ b/src/utils/isUserVIP.ts @@ -1,8 +1,8 @@ import {db} from '../databases/databases'; import { HashedUserID } from '../types/user.model'; -export function isUserVIP(userID: HashedUserID): boolean { - return db.prepare('get', "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [userID]).userCount > 0; +export async function isUserVIP(userID: HashedUserID): Promise { + return (await db.prepare('get', "SELECT count(*) as userCount FROM vipUsers WHERE userID = ?", [userID])).userCount > 0; } diff --git a/test/cases/dbUpgrade.ts b/test/cases/dbUpgrade.ts index 03fd6c5..8762b5d 100644 --- a/test/cases/dbUpgrade.ts +++ b/test/cases/dbUpgrade.ts @@ -2,9 +2,9 @@ import {db, privateDB} from '../../src/databases/databases'; import {Done} from '../utils'; describe('dbUpgrade', () => { - it('Should update the database version when starting the application', (done: Done) => { - let dbVersion = db.prepare('get', 'SELECT key, value FROM config where key = ?', ['version']).value; - let privateVersion = privateDB.prepare('get', 'SELECT key, value FROM config where key = ?', ['version']).value; + it('Should update the database version when starting the application', async (done: Done) => { + let dbVersion = (await db.prepare('get', 'SELECT key, value FROM config where key = ?', ['version'])).value; + let privateVersion = (await privateDB.prepare('get', 'SELECT key, value FROM config where key = ?', ['version'])).value; if (dbVersion >= 1 && privateVersion >= 1) done(); else done('Versions are not at least 1. db is ' + dbVersion + ', private is ' + privateVersion); }); diff --git a/test/cases/noSegmentRecords.ts b/test/cases/noSegmentRecords.ts index 9437295..172227f 100644 --- a/test/cases/noSegmentRecords.ts +++ b/test/cases/noSegmentRecords.ts @@ -22,7 +22,7 @@ describe('noSegmentRecords', () => { }); it('Should update the database version when starting the application', (done: Done) => { - let version = db.prepare('get', 'SELECT key, value FROM config where key = ?', ['version']).value; + let version = await db.prepare('get', 'SELECT key, value FROM config where key = ?', ['version']).value; if (version > 1) done(); else done('Version isn\'t greater than 1. Version is ' + version); }); @@ -95,7 +95,7 @@ describe('noSegmentRecords', () => { }) .then(async res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['no-segments-video-id-1']); + let result = await db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['no-segments-video-id-1']); if (result.length !== 4) { console.log(result); done("Expected 4 entrys in db, got " + result.length); @@ -129,7 +129,7 @@ describe('noSegmentRecords', () => { }) .then(async res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['underscore']); + let result = await db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['underscore']); if (result.length !== 1) { console.log(result); done("Expected 1 entrys in db, got " + result.length); @@ -163,7 +163,7 @@ describe('noSegmentRecords', () => { }) .then(async res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['bothCases']); + let result = await db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['bothCases']); if (result.length !== 1) { console.log(result); done("Expected 1 entrys in db, got " + result.length); @@ -197,7 +197,7 @@ describe('noSegmentRecords', () => { }) .then(async res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['specialChar']); + let result = await db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['specialChar']); if (result.length !== 0) { console.log(result); done("Expected 0 entrys in db, got " + result.length); @@ -395,7 +395,7 @@ describe('noSegmentRecords', () => { }) .then(res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['delete-record']); + let result = await db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['delete-record']); if (result.length === 0) { done(); } else { @@ -426,7 +426,7 @@ describe('noSegmentRecords', () => { }) .then(res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['delete-record-1']); + let result = await db.prepare('all', 'SELECT * FROM noSegments WHERE videoID = ?', ['delete-record-1']); if (result.length === 1) { done(); } else { diff --git a/test/cases/oldSubmitSponsorTimes.ts b/test/cases/oldSubmitSponsorTimes.ts index 68a3242..616dec7 100644 --- a/test/cases/oldSubmitSponsorTimes.ts +++ b/test/cases/oldSubmitSponsorTimes.ts @@ -9,7 +9,7 @@ describe('postVideoSponsorTime (Old submission method)', () => { + "/api/postVideoSponsorTimes?videoID=dQw4w9WgXcQ&startTime=1&endTime=10&userID=test") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcQ"]); + let row = await db.prepare('get', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcQ"]); if (row.startTime === 1 && row.endTime === 10 && row.category === "sponsor") { done(); } else { @@ -32,7 +32,7 @@ describe('postVideoSponsorTime (Old submission method)', () => { }) .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcE"]); + let row = await db.prepare('get', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcE"]); if (row.startTime === 1 && row.endTime === 11 && row.category === "sponsor") { done(); } else { diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index 29f6ee8..9f1058a 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -53,7 +53,7 @@ describe('postSkipSegments', () => { }) .then(res => { if (res.status === 200) { - const row = db.prepare('get', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcR"]); + const row = await db.prepare('get', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcR"]); if (row.startTime === 2 && row.endTime === 10 && row.category === "sponsor") { done(); } else { @@ -84,7 +84,7 @@ describe('postSkipSegments', () => { }) .then(res => { if (res.status === 200) { - const row = db.prepare('get', "SELECT startTime, endTime, locked, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcF"]); + const row = await db.prepare('get', "SELECT startTime, endTime, locked, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcF"]); if (row.startTime === 0 && row.endTime === 10 && row.locked === 0 && row.category === "sponsor") { done(); } else { @@ -115,7 +115,7 @@ describe('postSkipSegments', () => { }) .then(res => { if (res.status === 200) { - const row = db.prepare('get', "SELECT startTime, endTime, locked, category FROM sponsorTimes WHERE videoID = ?", ["vipuserIDSubmission"]); + const row = await db.prepare('get', "SELECT startTime, endTime, locked, category FROM sponsorTimes WHERE videoID = ?", ["vipuserIDSubmission"]); if (row.startTime === 0 && row.endTime === 10 && row.locked === 1 && row.category === "sponsor") { done(); } else { @@ -149,7 +149,7 @@ describe('postSkipSegments', () => { }) .then(res => { if (res.status === 200) { - const rows = db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcR"]); + const rows = await db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ?", ["dQw4w9WgXcR"]); let success = true; if (rows.length === 2) { for (const row of rows) { @@ -196,7 +196,7 @@ describe('postSkipSegments', () => { }) .then(res => { if (res.status === 200) { - const rows = db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ? and votes > -1", ["L_jWHffIx5E"]); + const rows = await db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ? and votes > -1", ["L_jWHffIx5E"]); let success = true; if (rows.length === 4) { for (const row of rows) { @@ -245,7 +245,7 @@ describe('postSkipSegments', () => { }) .then(res => { if (res.status === 400) { - const rows = db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ? and votes > -1", ["n9rIGdXnSJc"]); + const rows = await db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ? and votes > -1", ["n9rIGdXnSJc"]); let success = true; if (rows.length === 4) { for (const row of rows) { @@ -293,7 +293,7 @@ describe('postSkipSegments', () => { }) .then(res => { if (res.status === 400) { - const rows = db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ? and votes > -1", ["80percent_video"]); + const rows = await db.prepare('all', "SELECT startTime, endTime, category FROM sponsorTimes WHERE videoID = ? and votes > -1", ["80percent_video"]); let success = rows.length == 2; for (const row of rows) { if ((row.startTime === 2000 || row.endTime === 4000 || row.category === "sponsor") || diff --git a/test/cases/postWarning.ts b/test/cases/postWarning.ts index fa766ff..eda2761 100644 --- a/test/cases/postWarning.ts +++ b/test/cases/postWarning.ts @@ -23,7 +23,7 @@ describe('postWarning', () => { }) .then(async res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT userID, issueTime, issuerUserID, enabled FROM warnings WHERE userID = ?", [json.userID]); + let row = await db.prepare('get', "SELECT userID, issueTime, issuerUserID, enabled FROM warnings WHERE userID = ?", [json.userID]); if (row?.enabled == 1 && row?.issuerUserID == getHash(json.issuerUserID)) { done(); } else { @@ -54,7 +54,7 @@ describe('postWarning', () => { }) .then(async res => { if (res.status === 409) { - let row = db.prepare('get', "SELECT userID, issueTime, issuerUserID, enabled FROM warnings WHERE userID = ?", [json.userID]); + let row = await db.prepare('get', "SELECT userID, issueTime, issuerUserID, enabled FROM warnings WHERE userID = ?", [json.userID]); if (row?.enabled == 1 && row?.issuerUserID == getHash(json.issuerUserID)) { done(); } else { @@ -86,7 +86,7 @@ describe('postWarning', () => { }) .then(async res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT userID, issueTime, issuerUserID, enabled FROM warnings WHERE userID = ?", [json.userID]); + let row = await db.prepare('get', "SELECT userID, issueTime, issuerUserID, enabled FROM warnings WHERE userID = ?", [json.userID]); if (row?.enabled == 0) { done(); } else { diff --git a/test/cases/segmentShift.ts b/test/cases/segmentShift.ts index af87638..3b9caeb 100644 --- a/test/cases/segmentShift.ts +++ b/test/cases/segmentShift.ts @@ -21,13 +21,13 @@ function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, en } function dbSponsorTimesSetByUUID(db: IDatabase, UUID: string, startTime: number, endTime: number) { - db.prepare('run', `UPDATE sponsorTimes SET startTime = ?, endTime = ? WHERE UUID = ?`, [startTime, endTime, UUID]); + await db.prepare('run', `UPDATE sponsorTimes SET startTime = ?, endTime = ? WHERE UUID = ?`, [startTime, endTime, UUID]); } function dbSponsorTimesCompareExpect(db: IDatabase, expect: any) { for (let i = 0, len = expect.length; i < len; i++) { const expectSeg = expect[i]; - let seg = db.prepare('get', "SELECT startTime, endTime FROM sponsorTimes WHERE UUID = ?", [expectSeg.UUID]); + let seg = await db.prepare('get', "SELECT startTime, endTime FROM sponsorTimes WHERE UUID = ?", [expectSeg.UUID]); if ('removed' in expect) { if (expect.removed === true && seg.votes === -2) { return; diff --git a/test/cases/unBan.ts b/test/cases/unBan.ts index a9bc1da..5324c49 100644 --- a/test/cases/unBan.ts +++ b/test/cases/unBan.ts @@ -31,7 +31,7 @@ describe('unBan', () => { }) .then(async res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM sponsorTimes WHERE videoID = ? AND userID = ? AND shadowHidden = ?', ['unBan-videoID-0', 'testMan-unBan', 1]); + let result = await db.prepare('all', 'SELECT * FROM sponsorTimes WHERE videoID = ? AND userID = ? AND shadowHidden = ?', ['unBan-videoID-0', 'testMan-unBan', 1]); if (result.length !== 0) { console.log(result); done("Expected 0 banned entrys in db, got " + result.length); @@ -56,7 +56,7 @@ describe('unBan', () => { }) .then(async res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM sponsorTimes WHERE videoID = ? AND userID = ? AND shadowHidden = ?', ['unBan-videoID-1', 'testWoman-unBan', 1]); + let result = await db.prepare('all', 'SELECT * FROM sponsorTimes WHERE videoID = ? AND userID = ? AND shadowHidden = ?', ['unBan-videoID-1', 'testWoman-unBan', 1]); if (result.length !== 1) { console.log(result); done("Expected 1 banned entry1 in db, got " + result.length); @@ -81,7 +81,7 @@ describe('unBan', () => { }) .then(async res => { if (res.status === 200) { - let result = db.prepare('all', 'SELECT * FROM sponsorTimes WHERE userID = ? AND shadowHidden = ?', ['testEntity-unBan', 1]); + let result = await db.prepare('all', 'SELECT * FROM sponsorTimes WHERE userID = ? AND shadowHidden = ?', ['testEntity-unBan', 1]); if (result.length !== 1) { console.log(result); done("Expected 1 banned entry1 in db, got " + result.length); diff --git a/test/cases/voteOnSponsorTime.ts b/test/cases/voteOnSponsorTime.ts index 8345448..c0d1a65 100644 --- a/test/cases/voteOnSponsorTime.ts +++ b/test/cases/voteOnSponsorTime.ts @@ -68,7 +68,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID&UUID=vote-uuid-0&type=1") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-0"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-0"]); if (row.votes === 3) { done(); } else { @@ -86,7 +86,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-2"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-2"]); if (row.votes < 10) { done(); } else { @@ -104,7 +104,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID3&UUID=vote-uuid-2&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-2"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-2"]); if (row.votes === 9) { done(); } else { @@ -122,7 +122,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID4&UUID=vote-uuid-1.6&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-1.6"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-1.6"]); if (row.votes === 10) { done(); } else { @@ -140,7 +140,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1&type=1") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-1"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-1"]); if (row.votes === 2) { done(); } else { @@ -158,7 +158,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1.5&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-1.5"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-1.5"]); if (row.votes === 10) { done(); } else { @@ -176,7 +176,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-3&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-3"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-3"]); if (row.votes <= -2) { done(); } else { @@ -194,7 +194,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=own-submission-id&UUID=own-submission-uuid&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["own-submission-uuid"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["own-submission-uuid"]); if (row.votes <= -2) { done(); } else { @@ -212,7 +212,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID2&UUID=not-own-submission-uuid&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["not-own-submission-uuid"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["not-own-submission-uuid"]); if (row.votes === 499) { done(); } else { @@ -230,8 +230,8 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=intro") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-4"]); - let categoryRows = db.prepare('all', "SELECT votes, category FROM categoryVotes WHERE UUID = ?", ["vote-uuid-4"]); + let row = await db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-4"]); + let categoryRows = await db.prepare('all', "SELECT votes, category FROM categoryVotes WHERE UUID = ?", ["vote-uuid-4"]); if (row.category === "sponsor" && categoryRows.length === 2 && categoryRows[0]?.votes === 1 && categoryRows[0]?.category === "intro" && categoryRows[1]?.votes === 1 && categoryRows[1]?.category === "sponsor") { @@ -251,7 +251,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=fakecategory") .then(res => { if (res.status === 400) { - let row = db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["incorrect-category"]); + let row = await db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["incorrect-category"]); if (row.category === "sponsor") { done(); } else { @@ -269,8 +269,8 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=outro") .then(res => { if (res.status === 200) { - let submissionRow = db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-4"]); - let categoryRows = db.prepare('all', "SELECT votes, category FROM categoryVotes WHERE UUID = ?", ["vote-uuid-4"]); + let submissionRow = await db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-4"]); + let categoryRows = await db.prepare('all', "SELECT votes, category FROM categoryVotes WHERE UUID = ?", ["vote-uuid-4"]); let introVotes = 0; let outroVotes = 0; let sponsorVotes = 0; @@ -299,7 +299,7 @@ describe('voteOnSponsorTime', () => { fetch(getbaseURL() + "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category-change&category=" + inputCat) .then(res => { - let row = db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["incorrect-category-change"]); + let row = await db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["incorrect-category-change"]); if (row.category === assertCat) { callback(); } else { @@ -319,8 +319,8 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&category=outro") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-5"]); - let row2 = db.prepare('get', "SELECT votes FROM categoryVotes WHERE UUID = ? and category = ?", ["vote-uuid-5", "outro"]); + let row = await db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-5"]); + let row2 = await db.prepare('get', "SELECT votes FROM categoryVotes WHERE UUID = ? and category = ?", ["vote-uuid-5", "outro"]); if (row.category === "outro" && row2.votes === 500) { done(); } else { @@ -338,7 +338,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=testman&UUID=vote-uuid-5_1&category=outro") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-5"]); + let row = await db.prepare('get', "SELECT category FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-5"]); if (row.category === "outro") { done(); } else { @@ -382,7 +382,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&type=1") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-5"]); + let row = await db.prepare('get', "SELECT votes FROM sponsorTimes WHERE UUID = ?", ["vote-uuid-5"]); if (row.votes > -3) { done(); } else { @@ -452,7 +452,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=1") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT locked FROM sponsorTimes WHERE UUID = ?", ["segment-locking-uuid-1"]); + let row = await db.prepare('get', "SELECT locked FROM sponsorTimes WHERE UUID = ?", ["segment-locking-uuid-1"]); if (row?.locked) { done(); } else { @@ -470,7 +470,7 @@ describe('voteOnSponsorTime', () => { + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=0") .then(res => { if (res.status === 200) { - let row = db.prepare('get', "SELECT locked FROM sponsorTimes WHERE UUID = ?", ["segment-locking-uuid-1"]); + let row = await db.prepare('get', "SELECT locked FROM sponsorTimes WHERE UUID = ?", ["segment-locking-uuid-1"]); if (!row?.locked) { done(); } else {