This commit is contained in:
Ajay Ramachandran
2021-09-27 20:17:24 -04:00
95 changed files with 2727 additions and 2957 deletions

View File

@@ -25,5 +25,7 @@ module.exports = {
"quotes": ["warn", "double", { "avoidEscape": true, "allowTemplateLiterals": true }], "quotes": ["warn", "double", { "avoidEscape": true, "allowTemplateLiterals": true }],
"no-multiple-empty-lines": ["error", { max: 2, maxEOF: 0 }], "no-multiple-empty-lines": ["error", { max: 2, maxEOF: 0 }],
"indent": ["warn", 4, { "SwitchCase": 1 }], "indent": ["warn", 4, { "SwitchCase": 1 }],
"object-curly-spacing": ["warn", "always"],
"require-await": "warn",
}, },
}; };

41
package-lock.json generated
View File

@@ -10,6 +10,7 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@ajayyy/lru-diskcache": "^1.1.9", "@ajayyy/lru-diskcache": "^1.1.9",
"axios": "^0.21.4",
"better-sqlite3": "^7.4.3", "better-sqlite3": "^7.4.3",
"cron": "^1.8.2", "cron": "^1.8.2",
"express": "^4.17.1", "express": "^4.17.1",
@@ -1117,6 +1118,14 @@
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=",
"dev": true "dev": true
}, },
"node_modules/axios": {
"version": "0.21.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"dependencies": {
"follow-redirects": "^1.14.0"
}
},
"node_modules/babel-runtime": { "node_modules/babel-runtime": {
"version": "6.26.0", "version": "6.26.0",
"resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz",
@@ -2578,6 +2587,25 @@
"integrity": "sha512-XprP7lDrVT+kE2c2YlfiV+IfS9zxukiIOvNamPNsImNhXadSsQEbosItdL9bUQlCZXR13SvPk20BjWSWLA7m4A==", "integrity": "sha512-XprP7lDrVT+kE2c2YlfiV+IfS9zxukiIOvNamPNsImNhXadSsQEbosItdL9bUQlCZXR13SvPk20BjWSWLA7m4A==",
"dev": true "dev": true
}, },
"node_modules/follow-redirects": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.4.tgz",
"integrity": "sha512-zwGkiSXC1MUJG/qmeIFH2HBJx9u0V46QGUe3YR1fXG8bXQxq7fLj0RjLZQ5nubr9qNJUZrH+xUcwXEoXNpfS+g==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": { "node_modules/form-data": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz",
@@ -6674,6 +6702,14 @@
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=",
"dev": true "dev": true
}, },
"axios": {
"version": "0.21.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"requires": {
"follow-redirects": "^1.14.0"
}
},
"babel-runtime": { "babel-runtime": {
"version": "6.26.0", "version": "6.26.0",
"resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz",
@@ -7801,6 +7837,11 @@
"integrity": "sha512-XprP7lDrVT+kE2c2YlfiV+IfS9zxukiIOvNamPNsImNhXadSsQEbosItdL9bUQlCZXR13SvPk20BjWSWLA7m4A==", "integrity": "sha512-XprP7lDrVT+kE2c2YlfiV+IfS9zxukiIOvNamPNsImNhXadSsQEbosItdL9bUQlCZXR13SvPk20BjWSWLA7m4A==",
"dev": true "dev": true
}, },
"follow-redirects": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.4.tgz",
"integrity": "sha512-zwGkiSXC1MUJG/qmeIFH2HBJx9u0V46QGUe3YR1fXG8bXQxq7fLj0RjLZQ5nubr9qNJUZrH+xUcwXEoXNpfS+g=="
},
"form-data": { "form-data": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz",

View File

@@ -17,6 +17,7 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@ajayyy/lru-diskcache": "^1.1.9", "@ajayyy/lru-diskcache": "^1.1.9",
"axios": "^0.21.4",
"better-sqlite3": "^7.4.3", "better-sqlite3": "^7.4.3",
"cron": "^1.8.2", "cron": "^1.8.2",
"express": "^4.17.1", "express": "^4.17.1",

View File

@@ -10,6 +10,7 @@ export class Mysql implements IDatabase {
constructor(private config: unknown) { constructor(private config: unknown) {
} }
// eslint-disable-next-line require-await
async init(): Promise<void> { async init(): Promise<void> {
this.connection = new MysqlInterface(this.config); this.connection = new MysqlInterface(this.config);
} }

View File

@@ -12,6 +12,7 @@ export class Sqlite implements IDatabase {
{ {
} }
// eslint-disable-next-line require-await
async prepare(type: QueryType, query: string, params: any[] = []): Promise<any[]> { async prepare(type: QueryType, query: string, params: any[] = []): Promise<any[]> {
// Logger.debug(`prepare (sqlite): type: ${type}, query: ${query}, params: ${params}`); // Logger.debug(`prepare (sqlite): type: ${type}, query: ${query}, params: ${params}`);
const preparedQuery = this.db.prepare(query); const preparedQuery = this.db.prepare(query);
@@ -30,6 +31,7 @@ export class Sqlite implements IDatabase {
} }
} }
// eslint-disable-next-line require-await
async init(): Promise<void> { async init(): Promise<void> {
// Make dirs if required // Make dirs if required
if (!fs.existsSync(path.join(this.config.dbPath, "../"))) { if (!fs.existsSync(path.join(this.config.dbPath, "../"))) {

View File

@@ -1,4 +1,4 @@
import fetch from "node-fetch"; import axios from "axios";
import { Logger } from "../utils/logger"; import { Logger } from "../utils/logger";
import { config } from "../config"; import { config } from "../config";
import { getIP } from "../utils/getIP"; import { getIP } from "../utils/getIP";
@@ -6,7 +6,7 @@ import {getHash} from "../utils/getHash";
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
export function userCounter(req: Request, res: Response, next: NextFunction): void { export function userCounter(req: Request, res: Response, next: NextFunction): void {
fetch(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`, {method: "POST"}) axios.post(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`)
.catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`)); .catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
next(); next();

View File

@@ -10,7 +10,7 @@ type searchSegmentResponse = {
segments: DBSegment[] segments: DBSegment[]
}; };
async function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): Promise<DBSegment[]> { function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): Promise<DBSegment[]> {
return db.prepare( return db.prepare(
"all", "all",
`SELECT "UUID", "timeSubmitted", "startTime", "endTime", "category", "actionType", "votes", "views", "locked", "hidden", "shadowHidden" FROM "sponsorTimes" `SELECT "UUID", "timeSubmitted", "startTime", "endTime", "category", "actionType", "votes", "views", "locked", "hidden", "shadowHidden" FROM "sponsorTimes"

View File

@@ -1,7 +1,7 @@
import { hashPrefixTester } from "../utils/hashPrefixTester"; import { hashPrefixTester } from "../utils/hashPrefixTester";
import { getSegmentsByHash } from "./getSkipSegments"; import { getSegmentsByHash } from "./getSkipSegments";
import { Request, Response } from "express"; import { Request, Response } from "express";
import { ActionType, Category, SegmentUUID, Service, VideoIDHash } from "../types/segments.model"; import { ActionType, Category, SegmentUUID, VideoIDHash, Service } from "../types/segments.model";
import { getService } from "../utils/getService"; import { getService } from "../utils/getService";
export async function getSkipSegmentsByHash(req: Request, res: Response): Promise<Response> { export async function getSkipSegmentsByHash(req: Request, res: Response): Promise<Response> {

View File

@@ -2,6 +2,7 @@ import {db} from "../databases/databases";
import { config } from "../config"; import { config } from "../config";
import { Request, Response } from "express"; import { Request, Response } from "express";
import fetch from "node-fetch"; import fetch from "node-fetch";
import axios from "axios";
import { Logger } from "../utils/logger"; import { Logger } from "../utils/logger";
// A cache of the number of chrome web store users // A cache of the number of chrome web store users
@@ -44,10 +45,9 @@ export async function getTotalStats(req: Request, res: Response): Promise<void>
function updateExtensionUsers() { function updateExtensionUsers() {
if (config.userCounterURL) { if (config.userCounterURL) {
fetch(`${config.userCounterURL}/api/v1/userCount`) axios.get(`${config.userCounterURL}/api/v1/userCount`)
.then(res => res.json() as Record<string, any>) .then(res => {
.then(data => { apiUsersCache = Math.max(apiUsersCache, res.data.userCount);
apiUsersCache = Math.max(apiUsersCache, data.userCount);
}) })
.catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`)); .catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
} }

View File

@@ -116,7 +116,7 @@ const objSwitch = (cases: cases) => (defaultCase: string) => (key: string) =>
const functionSwitch = (cases: cases) => (defaultCase: string) => (key: string) => const functionSwitch = (cases: cases) => (defaultCase: string) => (key: string) =>
executeIfFunction(objSwitch(cases)(defaultCase)(key)); executeIfFunction(objSwitch(cases)(defaultCase)(key));
const dbGetValue = async (userID: HashedUserID, property: string): Promise<string|SegmentUUID|number> => { const dbGetValue = (userID: HashedUserID, property: string): Promise<string|SegmentUUID|number> => {
return functionSwitch({ return functionSwitch({
userID, userID,
userName: dbGetUsername(userID), userName: dbGetUsername(userID),

View File

@@ -1,7 +1,7 @@
import { postSkipSegments } from "./postSkipSegments"; import { postSkipSegments } from "./postSkipSegments";
import { Request, Response } from "express"; import { Request, Response } from "express";
export async function oldSubmitSponsorTimes(req: Request, res: Response): Promise<Response> { export function oldSubmitSponsorTimes(req: Request, res: Response): Promise<Response> {
req.query.category = "sponsor"; req.query.category = "sponsor";
return postSkipSegments(req, res); return postSkipSegments(req, res);
} }

View File

@@ -274,7 +274,7 @@ async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
} }
} }
async function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise<APIVideoInfo> { function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise<APIVideoInfo> {
if (config.newLeafURLs !== null) { if (config.newLeafURLs !== null) {
return YouTubeAPI.listVideos(videoID, ignoreCache); return YouTubeAPI.listVideos(videoID, ignoreCache);
} else { } else {

View File

@@ -4,7 +4,7 @@ import {db, privateDB} from "../databases/databases";
import { getHash } from "../utils/getHash"; import { getHash } from "../utils/getHash";
import { Request, Response } from "express"; import { Request, Response } from "express";
async function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise<Response> { function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise<Response> {
return privateDB.prepare("run", return privateDB.prepare("run",
`INSERT INTO "userNameLogs"("userID", "newUserName", "oldUserName", "updatedByAdmin", "updatedAt") VALUES(?, ?, ?, ?, ?)`, `INSERT INTO "userNameLogs"("userID", "newUserName", "oldUserName", "updatedByAdmin", "updatedAt") VALUES(?, ?, ?, ?, ?)`,
[userID, newUserName, oldUserName, + updatedByAdmin, new Date().getTime()] [userID, newUserName, oldUserName, + updatedByAdmin, new Date().getTime()]

View File

@@ -1,40 +1,43 @@
import assert from "assert"; import { strictEqual, ok } from "assert";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash";
import { archiveDownvoteSegment } from "../../src/cronjob/downvoteSegmentArchiveJob"; import { archiveDownvoteSegment } from "../../src/cronjob/downvoteSegmentArchiveJob";
import { DBSegment } from "../../src/types/segments.model"; import { DBSegment } from "../../src/types/segments.model";
const oct2021 = new Date("October 1, 2021").getTime();
const nov2021 = new Date("November 1, 2021").getTime();
const dec2021 = new Date("December 17, 2021").getTime();
const dec2022 = new Date("December 17, 2022").getTime();
const records = [ const records = [
["testtesttest", 1, 11, 2, 0, "1-uuid-0", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 100, 0, 0, getHash("testtesttest", 1)], ["dsajVideo0", 0, 0, 2, 0, "dsaj00", "dsajUser", dec2021, 0, 0, 0],
["testtesttest2", 1, 11, 2, 0, "1-uuid-0-1", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 120, 0, 0, getHash("testtesttest2", 1)], ["dsajVideo0", 0, 0, 2, 0, "dsaj01", "dsajUser", dec2021, 0, 0, 0],
["testtesttest", 12, 14, 2, 0, "1-uuid-0-2", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "mute", "ytb", 100, 0, 0, getHash("testtesttest", 1)], ["dsajVideo0", 0, 0, 2, 0, "dsaj02", "dsajUser", dec2021, 0, 0, 0],
["testtesttest", 20, 33, 2, 0, "1-uuid-2", "testman", new Date("December 17, 2021").getTime(), 50, "intro", "skip", "ytb", 101, 0, 0, getHash("testtesttest", 1)], ["dsajVideo0", 0, 0, 2, 0, "dsaj03", "dsajUser", dec2021, 0, 0, 0],
["testtesttest,test", 1, 11, 2, 0, "1-uuid-1", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 140, 0, 0, getHash("testtesttest,test", 1)], ["dsajVideo0", 0, 0, 2, 0, "dsaj04", "dsajUser", dec2021, 0, 0, 0,],
["test3", 1, 11, 2, 0, "1-uuid-4", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 200, 0, 0, getHash("test3", 1)], ["dsajVideo1", 0, 0, 2, 0, "dsaj10", "dsajUser", dec2021, 0, 0, 0],
["test3", 7, 22, -3, 0, "1-uuid-5", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 300, 0, 0, getHash("test3", 1)], ["dsajVideo1", 0, 0, -3, 0, "dsaj11", "dsajUser", dec2021, 0, 0, 0],
["multiple", 1, 11, 2, 0, "1-uuid-6", "testman", new Date("December 17, 2021").getTime(), 50, "intro", "skip", "ytb", 400, 0, 0, getHash("multiple", 1)], ["dsajVideo2", 0, 0, 2, 0, "dsaj20", "dsajUser", dec2021, 0, 0, 0],
["multiple", 20, 33, -4, 0, "1-uuid-7", "testman", new Date("October 1, 2021").getTime(), 50, "intro", "skip", "ytb", 500, 0, 0, getHash("multiple", 1)], ["dsajVideo2", 0, 0, -4, 0, "dsaj21", "dsajUser", oct2021, 0, 0, 0],
["locked", 20, 33, 2, 1, "1-uuid-locked-8", "testman", new Date("December 17, 2021").getTime(), 50, "intro", "skip", "ytb", 230, 0, 0, getHash("locked", 1)], ["dsajVideo3", 0, 0, 2, 1, "dsaj30", "dsajUser", dec2021, 0, 0, 0],
["locked", 20, 34, 100000, 0, "1-uuid-9", "testman", new Date("December 17, 2021").getTime(), 50, "intro", "skip", "ytb", 190, 0, 0, getHash("locked", 1)], ["dsajVideo3", 0, 0, 100000, 0, "dsaj31", "dsajUser", dec2021, 0, 0, 0],
["onlyHiddenSegments", 20, 34, 100000, 0, "onlyHiddenSegments", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 190, 1, 0, getHash("onlyHiddenSegments", 1)], ["dsajVideo4", 0, 0, 100000, 0, "dsaj40", "dsajUser", dec2021, 0, 1, 0],
["requiredSegmentVid-raw", 60, 70, 2, 0, "requiredSegmentVid-raw-1", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)], ["dsajVideo5", 0, 0, 2, 0, "dsaj50", "dsajUser", dec2021, 0, 0, 0],
["requiredSegmentVid-raw", 60, 70, -1, 0, "requiredSegmentVid-raw-2", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)], ["dsajVideo5", 0, 0, -1, 0, "dsaj51", "dsajUser", dec2021, 0, 0, 0],
["requiredSegmentVid-raw", 80, 90, -2, 0, "requiredSegmentVid-raw-3", "testman", new Date("November 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)], ["dsajVideo5", 0, 0, -2, 0, "dsaj52", "dsajUser", nov2021, 0, 0, 0],
["requiredSegmentVid-raw", 80, 90, 2, 0, "requiredSegmentVid-raw-4", "testman", new Date("December 17, 2021").getTime(), 50, "sponsor", "skip", "ytb", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)] ["dsajVideo5", 0, 0, 2, 0, "dsaj53", "dsajUser", dec2021, 0, 0, 0]
]; ];
describe("downvoteSegmentArchiveJob", () => { describe("downvoteSegmentArchiveJob", () => {
beforeEach(async () => { beforeEach(async () => {
const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", views, category, "actionType", "service", "videoDuration", "hidden", "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "hidden", "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
for (let i = 0; i < records.length; i += 1) { for (const record of records) {
await db.prepare("run", query, records[i]); await db.prepare("run", query, record);
} }
return; return;
@@ -42,7 +45,7 @@ describe("downvoteSegmentArchiveJob", () => {
it("Should update the database version when starting the application", async () => { it("Should update the database version when starting the application", async () => {
const version = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value; const version = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value;
assert.ok(version >= 21, "version should be greater or equal to 21"); ok(version >= 21, "version should be greater or equal to 21");
}); });
afterEach(async () => { afterEach(async () => {
@@ -50,12 +53,10 @@ describe("downvoteSegmentArchiveJob", () => {
await db.prepare("run", 'DELETE FROM "archivedSponsorTimes"'); await db.prepare("run", 'DELETE FROM "archivedSponsorTimes"');
}); });
const getArchivedSegment = (): Promise<DBSegment[]> => { const getArchivedSegment = (): Promise<DBSegment[]> => db.prepare("all", 'SELECT * FROM "archivedSponsorTimes"');
return db.prepare("all", 'SELECT * FROM "archivedSponsorTimes"');
};
const getSegmentsInMainTable = (dayLimit: number, voteLimit: number, now: number): Promise<DBSegment[]> => { const getSegmentsInMainTable = (dayLimit: number, voteLimit: number, now: number): Promise<DBSegment[]> =>
return db.prepare( db.prepare(
"all", "all",
'SELECT * FROM "sponsorTimes" WHERE "votes" < ? AND (? - "timeSubmitted") > ?', 'SELECT * FROM "sponsorTimes" WHERE "votes" < ? AND (? - "timeSubmitted") > ?',
[ [
@@ -64,109 +65,107 @@ describe("downvoteSegmentArchiveJob", () => {
dayLimit * 86400000, dayLimit * 86400000,
] ]
); );
};
const countSegmentInMainTable = (): Promise<number> => { const countSegmentInMainTable = (): Promise<number> =>
return db.prepare( db.prepare(
"get", "get",
'SELECT COUNT(*) as count FROM "sponsorTimes"' 'SELECT COUNT(*) as count FROM "sponsorTimes"'
).then(res => res.count); ).then(res => res.count);
};
it("Should archive all records match", async () => { it("Should archive all records match", async () => {
const dayLimit = 20; const dayLimit = 20;
const voteLimit = 0; const voteLimit = 0;
const time = new Date("December 17, 2022").getTime(); const time = dec2022;
const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); const res = await archiveDownvoteSegment(dayLimit, voteLimit, time);
assert.strictEqual(res, 0, "Expection in archiveDownvoteSegment"); strictEqual(res, 0, "Expection in archiveDownvoteSegment");
// check segments in archived table // check segments in archived table
const archivedSegment = await getArchivedSegment(); const archivedSegment = await getArchivedSegment();
assert.strictEqual(archivedSegment.length, 4, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 4`); strictEqual(archivedSegment.length, 4, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 4`);
// check segments not in main table // check segments not in main table
const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time); const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time);
assert.strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`); strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`);
// check number segments remain in main table // check number segments remain in main table
assert.strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table"); strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table");
}); });
it("Should archive records with vote < -1 match", async () => { it("Should archive records with vote < -1 match", async () => {
const dayLimit = 20; const dayLimit = 20;
const voteLimit = -1; const voteLimit = -1;
const time = new Date("December 17, 2022").getTime(); const time = dec2022;
const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); const res = await archiveDownvoteSegment(dayLimit, voteLimit, time);
assert.strictEqual(res, 0, ""); strictEqual(res, 0, "");
// check segments in archived table // check segments in archived table
const archivedSegment = await getArchivedSegment(); const archivedSegment = await getArchivedSegment();
assert.strictEqual(archivedSegment.length, 3, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 3`); strictEqual(archivedSegment.length, 3, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 3`);
// check segments not in main table // check segments not in main table
const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time); const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time);
assert.strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`); strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`);
// check number segments remain in main table // check number segments remain in main table
assert.strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table"); strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table");
}); });
it("Should archive records with vote < -2 and day < 30 match", async () => { it("Should archive records with vote < -2 and day < 30 match", async () => {
const dayLimit = 30; const dayLimit = 30;
const voteLimit = -2; const voteLimit = -2;
const time = new Date("December 17, 2021").getTime(); const time = dec2021;
const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); const res = await archiveDownvoteSegment(dayLimit, voteLimit, time);
assert.strictEqual(res, 0, ""); strictEqual(res, 0, "");
// check segments in archived table // check segments in archived table
const archivedSegment = await getArchivedSegment(); const archivedSegment = await getArchivedSegment();
assert.strictEqual(archivedSegment.length, 1, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 1`); strictEqual(archivedSegment.length, 1, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 1`);
assert.strictEqual(archivedSegment[0].votes, -4, `Incorrect segment vote in archiveTable: ${archivedSegment[0].votes} instead of -4`); strictEqual(archivedSegment[0].votes, -4, `Incorrect segment vote in archiveTable: ${archivedSegment[0].votes} instead of -4`);
// check segments not in main table // check segments not in main table
const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time); const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time);
assert.strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`); strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`);
// check number segments remain in main table // check number segments remain in main table
assert.strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table"); strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table");
}); });
it("Should archive records with vote < -2 and day < 300 match", async () => { it("Should archive records with vote < -2 and day < 300 match", async () => {
const dayLimit = 300; const dayLimit = 300;
const voteLimit = -2; const voteLimit = -2;
const time = new Date("December 17, 2022").getTime(); const time = dec2022;
const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); const res = await archiveDownvoteSegment(dayLimit, voteLimit, time);
assert.strictEqual(res, 0, ""); strictEqual(res, 0, "");
// check segments in archived table // check segments in archived table
const archivedSegment = await getArchivedSegment(); const archivedSegment = await getArchivedSegment();
assert.strictEqual(archivedSegment.length, 2, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 2`); strictEqual(archivedSegment.length, 2, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 2`);
// check segments not in main table // check segments not in main table
const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time); const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time);
assert.strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`); strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`);
// check number segments remain in main table // check number segments remain in main table
assert.strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table"); strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table");
}); });
it("Should not archive any", async () => { it("Should not archive any", async () => {
const dayLimit = 300; const dayLimit = 300;
const voteLimit = -2; const voteLimit = -2;
const time = new Date("December 17, 2021").getTime(); const time = dec2021;
const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); const res = await archiveDownvoteSegment(dayLimit, voteLimit, time);
assert.strictEqual(res, 0, ""); strictEqual(res, 0, "");
// check segments in archived table // check segments in archived table
const archivedSegment = await getArchivedSegment(); const archivedSegment = await getArchivedSegment();
assert.strictEqual(archivedSegment.length, 0, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 0`); strictEqual(archivedSegment.length, 0, `Incorrect segment in archiveTable: ${archivedSegment.length} instead of 0`);
// check segments not in main table // check segments not in main table
const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time); const segments = await getSegmentsInMainTable(dayLimit, voteLimit, time);
assert.strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`); strictEqual(segments.length, 0, `Incorrect segment in main table: ${segments.length} instead of 0`);
// check number segments remain in main table // check number segments remain in main table
assert.strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table"); strictEqual(await countSegmentInMainTable(), records.length - archivedSegment.length ,"Incorrect segment remain in main table");
}); });
}); });

View File

@@ -1,33 +1,33 @@
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import { notStrictEqual, strictEqual } from "assert";
describe("getHash", () => { describe("getHash", () => {
it("Should not output the input string", () => { it("Should not output the input string", () => {
assert(getHash("test") !== "test"); notStrictEqual(getHash("test"), "test");
assert(getHash("test", -1) !== "test"); notStrictEqual(getHash("test", -1), "test");
assert(getHash("test", 0) !== "test"); notStrictEqual(getHash("test", 0), "test");
assert(getHash("test", null) !== "test"); notStrictEqual(getHash("test", null), "test");
}); });
it("Should return a hashed value", () => { it("Should return a hashed value", () => {
assert.strictEqual(getHash("test"), "2f327ef967ade1ebf4319163f7debbda9cc17bb0c8c834b00b30ca1cf1c256ee"); strictEqual(getHash("test"), "2f327ef967ade1ebf4319163f7debbda9cc17bb0c8c834b00b30ca1cf1c256ee");
}); });
it("Should be able to output the same has the DB upgrade script will output", () => { it("Should be able to output the same has the DB upgrade script will output", () => {
assert.strictEqual(getHash("vid", 1), "1ff838dc6ca9680d88455341118157d59a055fe6d0e3870f9c002847bebe4663"); strictEqual(getHash("vid", 1), "1ff838dc6ca9680d88455341118157d59a055fe6d0e3870f9c002847bebe4663");
}); });
it("Should take a variable number of passes", () => { it("Should take a variable number of passes", () => {
assert.strictEqual(getHash("test", 1), "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"); strictEqual(getHash("test", 1), "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08");
assert.strictEqual(getHash("test", 2), "7b3d979ca8330a94fa7e9e1b466d8b99e0bcdea1ec90596c0dcc8d7ef6b4300c"); strictEqual(getHash("test", 2), "7b3d979ca8330a94fa7e9e1b466d8b99e0bcdea1ec90596c0dcc8d7ef6b4300c");
assert.strictEqual(getHash("test", 3), "5b24f7aa99f1e1da5698a4f91ae0f4b45651a1b625c61ed669dd25ff5b937972"); strictEqual(getHash("test", 3), "5b24f7aa99f1e1da5698a4f91ae0f4b45651a1b625c61ed669dd25ff5b937972");
}); });
it("Should default to 5000 passes", () => { it("Should default to 5000 passes", () => {
assert.strictEqual(getHash("test"), getHash("test", 5000)); strictEqual(getHash("test"), getHash("test", 5000));
}); });
it("Should not take a negative number of passes", () => { it("Should not take a negative number of passes", () => {
assert.strictEqual(getHash("test", -1), ""); strictEqual(getHash("test", -1), "");
}); });
}); });

View File

@@ -1,16 +1,20 @@
import fetch from "node-fetch";
import {getbaseURL, Done} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { client } from "../utils/httpClient";
import assert from "assert"; import assert from "assert";
const VIPUser = "isUserVIPVIP";
const normalUser = "isUserVIPNormal";
const endpoint = "/api/isUserVIP";
const vipUserRequest = (userID: string) => client.get(endpoint, { params: { userID } });
describe("getIsUserVIP", () => { describe("getIsUserVIP", () => {
before((done: Done) => { before(() => {
db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash("supertestman")]).then(done); db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash(VIPUser)]);
}); });
it("Should be able to get a 200", (done: Done) => { it("Should be able to get a 200", (done) => {
fetch(`${getbaseURL()}/api/isUserVIP?userID=supertestman`) vipUserRequest(VIPUser)
.then(res => { .then(res => {
assert.strictEqual(res.status, 200, "response should be 200"); assert.strictEqual(res.status, 200, "response should be 200");
done(); done();
@@ -19,8 +23,8 @@ describe("getIsUserVIP", () => {
}); });
it("Should get a 400 if no userID", (done: Done) => { it("Should get a 400 if no userID", (done) => {
fetch(`${getbaseURL()}/api/isUserVIP`) client.get(endpoint)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400, "response should be 400"); assert.strictEqual(res.status, 400, "response should be 400");
done(); done();
@@ -28,23 +32,21 @@ describe("getIsUserVIP", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should say a VIP is a VIP", (done: Done) => { it("Should say a VIP is a VIP", (done) => {
fetch(`${getbaseURL()}/api/isUserVIP?userID=supertestman`) vipUserRequest(VIPUser)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); assert.strictEqual(res.data.vip, true);
assert.strictEqual(data.vip, true);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should say a normal user is not a VIP", (done: Done) => { it("Should say a normal user is not a VIP", (done) => {
fetch(`${getbaseURL()}/api/isUserVIP?userID=regulartestman`) vipUserRequest(normalUser)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); assert.strictEqual(res.data.vip, false);
assert.strictEqual(data.vip, false);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));

View File

@@ -1,35 +1,33 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const endpoint = "/api/lockCategories";
const getLockCategories = (videoID: string) => client.get(endpoint, { params: { videoID } });
describe("getLockCategories", () => { describe("getLockCategories", () => {
before(async () => { before(async () => {
const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)';
await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-getLockCategories")]); await db.prepare("run", insertVipUserQuery, [getHash("getLockCategoriesVIP")]);
const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") VALUES (?, ?, ?, ?)'; const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") VALUES (?, ?, ?, ?)';
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLock-1", "sponsor", "1-short"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesVIP"), "getLock1", "sponsor", "1-short"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLock-1", "interaction", "1-longer-reason"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesVIP"), "getLock1", "interaction", "1-longer-reason"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLock-2", "preview", "2-reason"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesVIP"), "getLock2", "preview", "2-reason"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLock-3", "nonmusic", "3-reason"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesVIP"), "getLock3", "nonmusic", "3-reason"]);
}); });
it("Should update the database version when starting the application", async () => { it("Should update the database version when starting the application", async () => {
const version = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value; const version = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value;
if (version > 20) return; assert.ok(version > 20, `Version isn't greater than 20. Version is ${version}`);
else return `Version isn't greater than 20. Version is ${version}`;
}); });
it("Should be able to get multiple locks", (done: Done) => { it("Should be able to get multiple locks", (done) => {
fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock-1`) getLockCategories("getLock1")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
categories: [ categories: [
"sponsor", "sponsor",
@@ -37,31 +35,30 @@ describe("getLockCategories", () => {
], ],
reason: "1-longer-reason" reason: "1-longer-reason"
}; };
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get single locks", (done: Done) => { it("Should be able to get single locks", (done) => {
fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock-2`) getLockCategories("getLock2")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
categories: [ categories: [
"preview" "preview"
], ],
reason: "2-reason" reason: "2-reason"
}; };
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 404 if no lock exists", (done: Done) => { it("should return 404 if no lock exists", (done) => {
fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock-0`) getLockCategories("getLockNull")
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -69,8 +66,8 @@ describe("getLockCategories", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 400 if no videoID specified", (done: Done) => { it("should return 400 if no videoID specified", (done) => {
fetch(`${getbaseURL()}/api/lockCategories`) client.get(endpoint)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();

View File

@@ -1,25 +1,28 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const fakeHash = "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35";
const endpoint = "/api/lockCategories";
const getLockCategories = (hash: string) => client.get(`${endpoint}/${hash}`);
describe("getLockCategoriesByHash", () => { describe("getLockCategoriesByHash", () => {
before(async () => { before(async () => {
const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)';
await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-getLockCategories")]); await db.prepare("run", insertVipUserQuery, [getHash("getLockCategoriesHashVIP")]);
const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason", "hashedVideoID") VALUES (?, ?, ?, ?, ?)'; const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason", "hashedVideoID") VALUES (?, ?, ?, ?, ?)';
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLockHash-1", "sponsor", "1-reason-short", "67a654898fda3a5541774aea345796c7709982bb6018cb08d22a18eeddccc1d0"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "getLockHash1", "sponsor", "1-reason-short", getHash("getLockHash1", 1)]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLockHash-1", "interaction", "1-reason-longer", "67a654898fda3a5541774aea345796c7709982bb6018cb08d22a18eeddccc1d0"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "getLockHash1", "interaction", "1-reason-longer", getHash("getLockHash1", 1)]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLockHash-2", "preview", "2-reason", "dff09120437b4bd594dffae5f3cde3cfc5f6099fb01d0ef4051919b2908d9a50"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "getLockHash2", "preview", "2-reason", getHash("getLockHash2", 1)]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLockHash-3", "nonmusic", "3-reason", "bf1b122fd5630e0df8626d00c4a95c58954ad715e5595b0f75a19ac131e28928"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "getLockHash3", "nonmusic", "3-reason", getHash("getLockHash3", 1)]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "fakehash-1", "outro", "fake1-reason", "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "fakehash-1", "outro", "fake1-reason", fakeHash]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "fakehash-2", "intro", "fake2-longer-reason", "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "fakehash-2", "intro", "fake2-longer-reason", fakeHash]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "fakehash-2", "preview", "fake2-short", "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450"]); await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "fakehash-2", "preview", "fake2-short", fakeHash]);
}); });
it("Database should be greater or equal to version 20", async () => { it("Database should be greater or equal to version 20", async () => {
@@ -29,93 +32,95 @@ describe("getLockCategoriesByHash", () => {
`Version isn't greater than 20. Version is ${version}`); `Version isn't greater than 20. Version is ${version}`);
}); });
it("Should be able to get multiple locks in one object", (done: Done) => { it("Should be able to get multiple locks in one object", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/67a65`) const videoID = "getLockHash1";
.then(async res => { const hash = getHash(videoID, 1);
getLockCategories(hash.substring(0,4))
.then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "getLockHash-1", videoID,
hash: getHash("getLockHash-1", 1), hash,
categories: [ categories: [
"sponsor", "sponsor",
"interaction" "interaction"
], ],
reason: "1-reason-longer" reason: "1-reason-longer"
}]; }];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get single lock", (done: Done) => { it("Should be able to get single lock", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/dff09`) const videoID = "getLockHash2";
.then(async res => { const hash = getHash(videoID, 1);
getLockCategories(hash.substring(0,6))
.then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "getLockHash-2", videoID,
hash: getHash("getLockHash-2", 1), hash,
categories: [ categories: [
"preview" "preview"
], ],
reason: "2-reason" reason: "2-reason"
}]; }];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get by half full hash", (done: Done) => { it("Should be able to get by half full hash", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/bf1b122fd5630e0df8626d00c4a95c58`) const videoID = "getLockHash3";
.then(async res => { const hash = getHash(videoID, 1);
getLockCategories(hash.substring(0,32))
.then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "getLockHash-3", videoID,
hash: getHash("getLockHash-3", 1), hash,
categories: [ categories: [
"nonmusic" "nonmusic"
], ],
reason: "3-reason" reason: "3-reason"
}]; }];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get multiple by similar hash with multiple categories", (done: Done) => { it("Should be able to get multiple by similar hash with multiple categories", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/b05a`) getLockCategories(fakeHash.substring(0,5))
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "fakehash-1", videoID: "fakehash-1",
hash: "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35", hash: fakeHash,
categories: [ categories: [
"outro" "outro"
], ],
reason: "fake1-reason" reason: "fake1-reason"
}, { }, {
videoID: "fakehash-2", videoID: "fakehash-2",
hash: "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450", hash: fakeHash,
categories: [ categories: [
"intro", "intro",
"preview" "preview"
], ],
reason: "fake2-longer-reason" reason: "fake2-longer-reason"
}]; }];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 404 once hash prefix varies", (done: Done) => { it("should return 404 once hash prefix varies", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/b05aa`) getLockCategories("b05aa")
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -123,8 +128,8 @@ describe("getLockCategoriesByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 404 if no lock exists", (done: Done) => { it("should return 404 if no lock exists", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/aaaaaa`) getLockCategories("aaaaaa")
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -132,8 +137,8 @@ describe("getLockCategoriesByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 400 if no videoID specified", (done: Done) => { it("should return 400 if full hash sent", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/`) getLockCategories(fakeHash)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -141,8 +146,8 @@ describe("getLockCategoriesByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 400 if full hash sent", (done: Done) => { it("should return 400 if hash too short", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35`) getLockCategories("00")
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -150,17 +155,8 @@ describe("getLockCategoriesByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 400 if hash too short", (done: Done) => { it("should return 400 if no hash specified", (done) => {
fetch(`${getbaseURL()}/api/lockCategories/00`) getLockCategories("")
.then(res => {
assert.strictEqual(res.status, 400);
done();
})
.catch(err => done(err));
});
it("should return 400 if no hash specified", (done: Done) => {
fetch(`${getbaseURL()}/api/lockCategories/`)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();

View File

@@ -1,10 +1,9 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const endpoint = `${getbaseURL()}/api/lockReason`; const endpoint = "/api/lockReason";
describe("getLockReason", () => { describe("getLockReason", () => {
before(async () => { before(async () => {
@@ -27,71 +26,65 @@ describe("getLockReason", () => {
else return `Version isn't greater than 20. Version is ${version}`; else return `Version isn't greater than 20. Version is ${version}`;
}); });
it("Should be able to get single reason", (done: Done) => { it("Should be able to get single reason", (done) => {
fetch(`${endpoint}?videoID=getLockReason&category=sponsor`) client.get(endpoint, { params: { videoID: "getLockReason", category: "sponsor" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [ const expected = [
{ category: "sponsor", locked: 1, reason: "sponsor-reason" } { category: "sponsor", locked: 1, reason: "sponsor-reason" }
]; ];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get empty locks", (done: Done) => { it("Should be able to get empty locks", (done) => {
fetch(`${endpoint}?videoID=getLockReason&category=intro`) client.get(endpoint, { params: { videoID: "getLockReason", category: "intro" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [ const expected = [
{ category: "intro", locked: 0, reason: "" } { category: "intro", locked: 0, reason: "" }
]; ];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should get multiple locks with array", (done: Done) => { it("should get multiple locks with array", (done) => {
fetch(`${endpoint}?videoID=getLockReason&categories=["intro","sponsor"]`) client.get(endpoint, { params: { videoID: "getLockReason", categories: `["intro","sponsor"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [ const expected = [
{ category: "sponsor", locked: 1, reason: "sponsor-reason" }, { category: "sponsor", locked: 1, reason: "sponsor-reason" },
{ category: "intro", locked: 0, reason: "" } { category: "intro", locked: 0, reason: "" }
]; ];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should get multiple locks with repeated category", (done: Done) => { it("should get multiple locks with repeated category", (done) => {
fetch(`${endpoint}?videoID=getLockReason&category=interaction&category=music_offtopic&category=intro`) client.get(`${endpoint}?videoID=getLockReason&category=interaction&category=music_offtopic&category=intro`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [ const expected = [
{ category: "interaction", locked: 1, reason: "interaction-reason" }, { category: "interaction", locked: 1, reason: "interaction-reason" },
{ category: "music_offtopic", locked: 1, reason: "nonmusic-reason" }, { category: "music_offtopic", locked: 1, reason: "nonmusic-reason" },
{ category: "intro", locked: 0, reason: "" } { category: "intro", locked: 0, reason: "" }
]; ];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return all categories if none specified", (done: Done) => { it("should return all categories if none specified", (done) => {
fetch(`${endpoint}?videoID=getLockReason`) client.get(endpoint, { params: { videoID: "getLockReason" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
console.log(data);
const expected = [ const expected = [
{ category: "sponsor", locked: 1, reason: "sponsor-reason" }, { category: "sponsor", locked: 1, reason: "sponsor-reason" },
{ category: "interaction", locked: 1, reason: "interaction-reason" }, { category: "interaction", locked: 1, reason: "interaction-reason" },
@@ -102,14 +95,14 @@ describe("getLockReason", () => {
{ category: "outro", locked: 0, reason: "" }, { category: "outro", locked: 0, reason: "" },
{ category: "poi_highlight", locked: 0, reason: "" } { category: "poi_highlight", locked: 0, reason: "" }
]; ];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 400 if no videoID specified", (done: Done) => { it("should return 400 if no videoID specified", (done) => {
fetch(endpoint) client.get(endpoint)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();

View File

@@ -1,27 +1,27 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import { deepStrictEqual } from "assert";
import { client } from "../utils/httpClient";
const endpoint = "/api/getSavedTimeForUser";
describe("getSavedTimeForUser", () => { describe("getSavedTimeForUser", () => {
const user1 = "getSavedTimeForUserUser";
before(async () => { before(async () => {
const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES'; const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", "views", "shadowHidden") VALUES';
await db.prepare("run", `${startOfQuery}(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, await db.prepare("run", `${startOfQuery}(?, ?, ?, ?, ?, ?, ?, ?, ?)`,
["getSavedTimeForUser", 1, 11, 2, "abc1239999", getHash("testman"), 0, 50, "sponsor", 0, getHash("getSavedTimeForUser", 0)]); ["getSavedTimeForUser", 1, 11, 2, "gstfu0", getHash(user1), 0, 50, 0]);
return; return;
}); });
it("Should be able to get a 200", (done: Done) => { it("Should be able to get a 200", (done) => {
fetch(`${getbaseURL()}/api/getSavedTimeForUser?userID=testman`) client.get(endpoint, { params: { userID: user1 } })
.then(async res => { .then(res => {
const data = await res.json();
// (end-start)*minute * views // (end-start)*minute * views
const savedMinutes = ((11-1)/60) * 50; const savedMinutes = ((11-1)/60) * 50;
const expected = { const expected = {
timeSaved: savedMinutes timeSaved: savedMinutes
}; };
assert.deepStrictEqual(data, expected); deepStrictEqual(res.data, expected);
done(); done();
}) })
.catch((err) => done(err)); .catch((err) => done(err));

View File

@@ -1,42 +1,42 @@
import fetch from "node-fetch";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {Done, getbaseURL} from "../utils"; import { client } from "../utils/httpClient";
import assert from "assert"; import assert from "assert";
describe("getSearchSegments", () => { describe("getSearchSegments", () => {
const endpoint = "/api/searchSegments";
before(async () => { before(async () => {
const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "views", "locked", "hidden", "shadowHidden", "timeSubmitted", "UUID", "userID", "category", "actionType") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "views", "locked", "hidden", "shadowHidden", "timeSubmitted", "UUID", "userID", "category", "actionType") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
await db.prepare("run", query, ["searchTest0", 0, 1, 2, 0, 0, 0, 0, 1, "search-normal", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest0", 0, 1, 2, 0, 0, 0, 0, 1, "search-normal", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest0", 0, 2, -2, 0, 0, 0, 0, 2, "search-downvote", "testman", "selfpromo", "skip",]); await db.prepare("run", query, ["searchTest0", 0, 2, -2, 0, 0, 0, 0, 2, "search-downvote", "searchTestUser", "selfpromo", "skip",]);
await db.prepare("run", query, ["searchTest0", 0, 3, 1, 0, 1, 0, 0, 3, "search-locked", "testman", "interaction", "skip"]); await db.prepare("run", query, ["searchTest0", 0, 3, 1, 0, 1, 0, 0, 3, "search-locked", "searchTestUser", "interaction", "skip"]);
await db.prepare("run", query, ["searchTest0", 0, 4, 1, 0, 0, 1, 0, 4, "search-hidden", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest0", 0, 4, 1, 0, 0, 1, 0, 4, "search-hidden", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest0", 0, 5, 1, 0, 0, 0, 1, 5, "search-shadowhidden", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest0", 0, 5, 1, 0, 0, 0, 1, 5, "search-shadowhidden", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest1", 1, 2, 1, 5, 0, 0, 0, 6, "search-lowview", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest1", 1, 2, 1, 5, 0, 0, 0, 6, "search-lowview", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest1", 1, 3, 1, 50, 0, 0, 0, 7, "search-highview", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest1", 1, 3, 1, 50, 0, 0, 0, 7, "search-highview", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest2", 1, 4, -1, 0, 0, 0, 0, 8, "search-lowvote", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest2", 1, 4, -1, 0, 0, 0, 0, 8, "search-lowvote", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest2", 2, 3, 0, 0, 0, 0, 0, 9, "search-zerovote", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest2", 2, 3, 0, 0, 0, 0, 0, 9, "search-zerovote", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest2", 2, 4, 50, 0, 0, 0, 0, 10, "search-highvote", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest2", 2, 4, 50, 0, 0, 0, 0, 10, "search-highvote", "searchTestUser", "sponsor", "skip"]);
// page // page
await db.prepare("run", query, ["searchTest4", 3, 4, 1, 0, 0, 0, 0, 10, "search-page1-1", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 4, 1, 0, 0, 0, 0, 10, "search-page1-1", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 5, 1, 0, 0, 0, 0, 11, "search-page1-2", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 5, 1, 0, 0, 0, 0, 11, "search-page1-2", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 6, 1, 0, 0, 0, 0, 12, "search-page1-3", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 6, 1, 0, 0, 0, 0, 12, "search-page1-3", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 7, 1, 0, 0, 0, 0, 13, "search-page1-4", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 7, 1, 0, 0, 0, 0, 13, "search-page1-4", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 8, 1, 0, 0, 0, 0, 14, "search-page1-5", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 8, 1, 0, 0, 0, 0, 14, "search-page1-5", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 9, 1, 0, 0, 0, 0, 15, "search-page1-6", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 9, 1, 0, 0, 0, 0, 15, "search-page1-6", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 10, 1, 0, 0, 0, 0, 16, "search-page1-7", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 10, 1, 0, 0, 0, 0, 16, "search-page1-7", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 11, 1, 0, 0, 0, 0, 17, "search-page1-8", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 11, 1, 0, 0, 0, 0, 17, "search-page1-8", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 12, 1, 0, 0, 0, 0, 18, "search-page1-9", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 12, 1, 0, 0, 0, 0, 18, "search-page1-9", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 13, 1, 0, 0, 0, 0, 19, "search-page1-10", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 13, 1, 0, 0, 0, 0, 19, "search-page1-10", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 14, 1, 0, 0, 0, 0, 20, "search-page2-1", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 14, 1, 0, 0, 0, 0, 20, "search-page2-1", "searchTestUser", "sponsor", "skip"]);
await db.prepare("run", query, ["searchTest4", 3, 15, 1, 0, 0, 0, 0, 21, "search-page2-2", "testman", "sponsor", "skip"]); await db.prepare("run", query, ["searchTest4", 3, 15, 1, 0, 0, 0, 0, 21, "search-page2-2", "searchTestUser", "sponsor", "skip"]);
return; return;
}); });
it("Should be able to show all segments under searchTest0", (done: Done) => { it("Should be able to show all segments under searchTest0", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0`) client.get(endpoint, { params: { videoID: "searchTest0" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 5); assert.strictEqual(data.segmentCount, 5);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -50,11 +50,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter by category", (done: Done) => { it("Should be able to filter by category", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&category=selfpromo`) client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.segmentCount, 1);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -64,11 +64,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter by category", (done: Done) => { it("Should be able to filter by category", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&category=selfpromo`) client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.segmentCount, 1);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -78,11 +78,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter by lock status", (done: Done) => { it("Should be able to filter by lock status", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&locked=false`) client.get(endpoint, { params: { videoID: "searchTest0", locked: false } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 4); assert.strictEqual(data.segmentCount, 4);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -95,11 +95,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter by hide status", (done: Done) => { it("Should be able to filter by hide status", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&hidden=false`) client.get(endpoint, { params: { videoID: "searchTest0", hidden: false } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 4); assert.strictEqual(data.segmentCount, 4);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -112,11 +112,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter by ignored status", (done: Done) => { it("Should be able to filter by ignored status", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&ignored=false`) client.get(endpoint, { params: { videoID: "searchTest0", ignored: false } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 3); assert.strictEqual(data.segmentCount, 3);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -128,11 +128,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter segments by min views", (done: Done) => { it("Should be able to filter segments by min views", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest1&minViews=6`) client.get(endpoint, { params: { videoID: "searchTest1", minViews: 6 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.segmentCount, 1);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -142,11 +142,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter segments by max views", (done: Done) => { it("Should be able to filter segments by max views", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest1&maxViews=10`) client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.segmentCount, 1);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -156,11 +156,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter segments by min and max views", (done: Done) => { it("Should be able to filter segments by min and max views", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest1&maxViews=10&minViews=1`) client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10, minViews: 1 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.segmentCount, 1);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -170,11 +170,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter segments by min votes", (done: Done) => { it("Should be able to filter segments by min votes", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest2&minVotes=0`) client.get(endpoint, { params: { videoID: "searchTest2", minVotes: 0 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 2); assert.strictEqual(data.segmentCount, 2);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -185,11 +185,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter segments by max votes", (done: Done) => { it("Should be able to filter segments by max votes", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest2&maxVotes=10`) client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 2); assert.strictEqual(data.segmentCount, 2);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -200,11 +200,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to filter segments by both min and max votes", (done: Done) => { it("Should be able to filter segments by both min and max votes", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest2&maxVotes=10&minVotes=0`) client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10, minVotes: 0 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.segmentCount, 1);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -214,11 +214,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get first page of results", (done: Done) => { it("Should be able to get first page of results", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest4`) client.get(endpoint, { params: { videoID: "searchTest4" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 12); assert.strictEqual(data.segmentCount, 12);
assert.strictEqual(data.page, 0); assert.strictEqual(data.page, 0);
@@ -237,11 +237,11 @@ describe("getSearchSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get second page of results", (done: Done) => { it("Should be able to get second page of results", (done) => {
fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest4&page=1`) client.get(endpoint, { params: { videoID: "searchTest4", page: 1 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const segments = data.segments; const segments = data.segments;
assert.strictEqual(data.segmentCount, 12); assert.strictEqual(data.segmentCount, 12);
assert.strictEqual(data.page, 1); assert.strictEqual(data.page, 1);

View File

@@ -1,8 +1,7 @@
import fetch from "node-fetch";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {Done, getbaseURL, partialDeepEquals} from "../utils"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {getHash} from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const ENOENTID = "0".repeat(64); const ENOENTID = "0".repeat(64);
const upvotedID = `a${"0".repeat(63)}`; const upvotedID = `a${"0".repeat(63)}`;
@@ -26,181 +25,175 @@ const userAgents = {
blank: "" blank: ""
}; };
const endpoint = "/api/segmentInfo";
const singleUUIDLookup = (UUID: string) => client.get(endpoint, { params: { UUID } });
describe("getSegmentInfo", () => { describe("getSegmentInfo", () => {
before(async () => { before(async () => {
const insertQuery = `INSERT INTO const insertQuery = `INSERT INTO
"sponsorTimes"("videoID", "startTime", "endTime", "votes", "locked", "sponsorTimes"("videoID", "startTime", "endTime", "votes", "locked",
"UUID", "userID", "timeSubmitted", "views", "category", "service", "UUID", "userID", "timeSubmitted", "views", "hidden", "shadowHidden", "userAgent")
"videoDuration", "hidden", "shadowHidden", "hashedVideoID", "userAgent") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; await db.prepare("run", insertQuery, ["segmentInfoUpvoted", 1, 10, 2, 0, upvotedID, "segmentInfoUser", 0, 50, 0, 0, userAgents.vanced]);
await db.prepare("run", insertQuery, ["upvoted", 1, 10, 2, 0, upvotedID, "testman", 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash("upvoted", 1), userAgents.vanced]); await db.prepare("run", insertQuery, ["segmentInfoDownvoted", 1, 10, -2, 0, downvotedID, "segmentInfoUser", 0, 50, 0, 0, userAgents.meabot]);
await db.prepare("run", insertQuery, ["downvoted", 1, 10, -2, 0, downvotedID, "testman", 0, 50, "sponsor", "YouTube", 120, 0, 0, getHash("downvoted", 1), userAgents.meabot]); await db.prepare("run", insertQuery, ["segmentInfoLockedup", 1, 10, 2, 1, lockedupID, "segmentInfoUser", 0, 50, 0, 0, userAgents.mpv]);
await db.prepare("run", insertQuery, ["locked-up", 1, 10, 2, 1, lockedupID, "testman", 0, 50, "sponsor", "YouTube", 101, 0, 0, getHash("locked-up", 1), userAgents.mpv]); await db.prepare("run", insertQuery, ["segmentInfoInfvotes", 1, 10, 100000, 0, infvotesID, "segmentInfoUser", 0, 50, 0, 0, userAgents.nodesb]);
await db.prepare("run", insertQuery, ["infvotes", 1, 10, 100000, 0, infvotesID, "testman", 0, 50, "sponsor", "YouTube", 101, 0, 0, getHash("infvotes", 1), userAgents.nodesb]); await db.prepare("run", insertQuery, ["segmentInfoHidden", 1, 10, 2, 0, hiddenID, "segmentInfoUser", 0, 50, 1, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["hidden", 1, 10, 2, 0, hiddenID, "testman", 0, 50, "sponsor", "YouTube", 140, 1, 0, getHash("hidden", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoShadowhidden", 1, 10, 2, 0, shadowhiddenID, "segmentInfoUser", 0, 50, 0, 1, userAgents.blank]);
await db.prepare("run", insertQuery, ["shadowhidden", 1, 10, 2, 0, shadowhiddenID, "testman", 0, 50, "sponsor", "YouTube", 140, 0, 1, getHash("shadowhidden", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoLockedown", 1, 10, -2, 1, lockeddownID, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["locked-down", 1, 10, -2, 1, lockeddownID, "testman", 0, 50, "sponsor", "YouTube", 200, 0, 0, getHash("locked-down", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoOldID", 1, 10, 1, 0, oldID, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["oldID", 1, 10, 1, 0, oldID, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("oldID", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoUpvoted", 1, 2, 1, 0, fillerID1, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["filler", 1, 2, 1, 0, fillerID1, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("filler", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoFiller", 2, 3, 1, 0, fillerID2, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["filler", 2, 3, 1, 0, fillerID2, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("filler", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoFiller", 3, 4, 1, 0, fillerID3, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["filler", 3, 4, 1, 0, fillerID3, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("filler", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoFiller", 4, 5, 1, 0, fillerID4, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["filler", 4, 5, 1, 0, fillerID4, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("filler", 1), userAgents.blank]); await db.prepare("run", insertQuery, ["segmentInfoFiller", 5, 6, 1, 0, fillerID5, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]);
await db.prepare("run", insertQuery, ["filler", 5, 6, 1, 0, fillerID5, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("filler", 1), userAgents.blank]);
}); });
it("Should be able to retreive upvoted segment", (done: Done) => { it("Should be able to retreive upvoted segment", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${upvotedID}`) singleUUIDLookup(upvotedID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "upvoted", videoID: "segmentInfoUpvoted",
votes: 2, votes: 2,
userAgent: userAgents.vanced, userAgent: userAgents.vanced,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive downvoted segment", (done: Done) => { it("Should be able to retreive downvoted segment", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${downvotedID}`) singleUUIDLookup(downvotedID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "downvoted", videoID: "segmentInfoDownvoted",
votes: -2, votes: -2,
userAgent: userAgents.meabot, userAgent: userAgents.meabot,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive locked up segment", (done: Done) => { it("Should be able to retreive locked up segment", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${lockedupID}`) singleUUIDLookup(lockedupID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "locked-up", videoID: "segmentInfoLockedup",
locked: 1, locked: 1,
votes: 2, votes: 2,
userAgent: userAgents.mpv, userAgent: userAgents.mpv,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive infinite vote segment", (done: Done) => { it("Should be able to retreive infinite vote segment", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${infvotesID}`) singleUUIDLookup(infvotesID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "infvotes", videoID: "segmentInfoInfvotes",
votes: 100000, votes: 100000,
userAgent: userAgents.nodesb, userAgent: userAgents.nodesb,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive shadowhidden segment", (done: Done) => { it("Should be able to retreive shadowhidden segment", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${shadowhiddenID}`) singleUUIDLookup(shadowhiddenID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "shadowhidden", videoID: "segmentInfoShadowhidden",
shadowHidden: 1, shadowHidden: 1,
userAgent: userAgents.blank, userAgent: userAgents.blank,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive locked down segment", (done: Done) => { it("Should be able to retreive locked down segment", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${lockeddownID}`) singleUUIDLookup(lockeddownID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "locked-down", videoID: "segmentInfoLockedown",
locked: 1, locked: 1,
votes: -2, votes: -2,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive hidden segment", (done: Done) => { it("Should be able to retreive hidden segment", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${hiddenID}`) singleUUIDLookup(hiddenID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "hidden", videoID: "segmentInfoHidden",
hidden: 1, hidden: 1,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive segment with old ID", (done: Done) => { it("Should be able to retreive segment with old ID", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${oldID}`) singleUUIDLookup(oldID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "oldID", videoID: "segmentInfoOldID",
votes: 1, votes: 1,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive single segment in array", (done: Done) => { it("Should be able to retreive single segment in array", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}"]`) client.get(endpoint, { params: { UUIDs: `["${upvotedID}"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
videoID: "upvoted", videoID: "segmentInfoUpvoted",
votes: 2, votes: 2,
}]; }];
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive multiple segments in array", (done: Done) => { it("Should be able to retreive multiple segments in array", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}", "${downvotedID}"]`) client.get(endpoint, { params: { UUIDs: `["${upvotedID}", "${downvotedID}"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
videoID: "upvoted", videoID: "segmentInfoUpvoted",
votes: 2, votes: 2,
}, { }, {
videoID: "downvoted", videoID: "segmentInfoDownvoted",
votes: -2, votes: -2,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -210,13 +203,13 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be possible to send unexpected query parameters", (done: Done) => { it("Should be possible to send unexpected query parameters", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${upvotedID}&fakeparam=hello&category=sponsor`) client.get(endpoint, { params: { UUID: upvotedID, fakeparam: "hello", category: "sponsor" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
videoID: "upvoted", videoID: "segmentInfoUpvoted",
votes: 2, votes: 2,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -225,8 +218,8 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if array passed to UUID", (done: Done) => { it("Should return 400 if array passed to UUID", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=["${upvotedID}", "${downvotedID}"]`) client.get(`${endpoint}?UUID=["${upvotedID}", "${downvotedID}"]`)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -234,8 +227,8 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if bad array passed to UUIDs", (done: Done) => { it("Should return 400 if bad array passed to UUIDs", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=[not-quoted,not-quoted]`) client.get(`${endpoint}?UUIDs=[not-quoted,not-quoted]`)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -243,8 +236,8 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if bad UUID passed", (done: Done) => { it("Should return 400 if bad UUID passed", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=notarealuuid`) client.get(`${endpoint}?UUID=notarealuuid`)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -252,8 +245,8 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if bad UUIDs passed in array", (done: Done) => { it("Should return 400 if bad UUIDs passed in array", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["notarealuuid", "anotherfakeuuid"]`) client.get(`${endpoint}?UUIDs=["notarealuuid", "anotherfakeuuid"]`)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -261,13 +254,13 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return good UUID when mixed with bad UUIDs", (done: Done) => { it("Should return good UUID when mixed with bad UUIDs", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}", "anotherfakeuuid"]`) client.get(`${endpoint}?UUIDs=["${upvotedID}", "anotherfakeuuid"]`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
videoID: "upvoted", videoID: "segmentInfoUpvoted",
votes: 2, votes: 2,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -277,53 +270,52 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should cut off array at 10", function(done: Done) { it("Should cut off array at 10", function(done) {
this.timeout(10000); this.timeout(10000);
const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`; const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`;
fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=${filledIDArray}`) client.get(endpoint, { params: { UUIDs: filledIDArray } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 10); assert.strictEqual(data.length, 10);
assert.strictEqual(data[0].videoID, "upvoted"); assert.strictEqual(data[0].videoID, "segmentInfoUpvoted");
assert.strictEqual(data[0].votes, 2); assert.strictEqual(data[0].votes, 2);
assert.strictEqual(data[9].videoID, "filler"); assert.strictEqual(data[9].videoID, "segmentInfoFiller");
assert.strictEqual(data[9].UUID, fillerID4); assert.strictEqual(data[9].UUID, fillerID4);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not duplicate reponses", (done: Done) => { it("Should not duplicate reponses", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`) client.get(`${endpoint}?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); assert.strictEqual(res.data.length, 2);
assert.strictEqual(data.length, 2);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if UUID not found", (done: Done) => { it("Should return 400 if UUID not found", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${ENOENTID}`) client.get(endpoint, { params: { UUID: ENOENTID } })
.then(res => { .then(res => {
if (res.status !== 400) done(`non 400 respone code: ${res.status}`); if (res.status !== 400) done(`non 400 response code: ${res.status}`);
else done(); // pass else done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to retreive multiple segments with multiple parameters", (done: Done) => { it("Should be able to retreive multiple segments with multiple parameters", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${upvotedID}&UUID=${downvotedID}`) client.get(`${endpoint}?UUID=${upvotedID}&UUID=${downvotedID}`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
videoID: "upvoted", videoID: "segmentInfoUpvoted",
votes: 2, votes: 2,
}, { }, {
videoID: "downvoted", videoID: "segmentInfoDownvoted",
votes: -2, votes: -2,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -333,16 +325,15 @@ describe("getSegmentInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not parse repeated UUID if UUIDs present", (done: Done) => { it("Should not parse repeated UUID if UUIDs present", (done) => {
fetch(`${getbaseURL()}/api/segmentInfo?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`) client.get(`${endpoint}?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = [{ const expected = [{
videoID: "upvoted", videoID: "segmentInfoUpvoted",
votes: 2 votes: 2
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));

View File

@@ -1,6 +1,5 @@
import { getService } from "../../src/utils/getService"; import { getService } from "../../src/utils/getService";
import { Service } from "../../src/types/segments.model"; import { Service } from "../../src/types/segments.model";
import assert from "assert"; import assert from "assert";
describe("getService", () => { describe("getService", () => {

View File

@@ -1,57 +1,56 @@
import fetch from "node-fetch";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {Done, getbaseURL, partialDeepEquals} from "../utils"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {getHash} from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
describe("getSkipSegments", () => { describe("getSkipSegments", () => {
const endpoint = "/api/skipSegments";
before(async () => { before(async () => {
const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", views, category, "actionType", "service", "videoDuration", "hidden", "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "actionType", "service", "videoDuration", "hidden", "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
await db.prepare("run", query, ["testtesttest", 1, 11, 2, 0, "1-uuid-0", "testman", 0, 50, "sponsor", "skip", "YouTube", 100, 0, 0, getHash("testtesttest", 1)]); await db.prepare("run", query, ["getSkipSegmentID0", 1, 11, 2, 0, "uuid01", "testman", 0, 50, "sponsor", "skip", "YouTube", 100, 0, 0]);
await db.prepare("run", query, ["testtesttest2", 1, 11, 2, 0, "1-uuid-0-1", "testman", 0, 50, "sponsor", "skip", "PeerTube", 120, 0, 0, getHash("testtesttest2", 1)]); await db.prepare("run", query, ["getSkipSegmentID0", 12, 14, 2, 0, "uuid02", "testman", 0, 50, "sponsor", "mute", "YouTube", 100, 0, 0]);
await db.prepare("run", query, ["testtesttest", 12, 14, 2, 0, "1-uuid-0-2", "testman", 0, 50, "sponsor", "mute", "YouTube", 100, 0, 0, getHash("testtesttest", 1)]); await db.prepare("run", query, ["getSkipSegmentID0", 20, 33, 2, 0, "uuid03", "testman", 0, 50, "intro", "skip", "YouTube", 101, 0, 0]);
await db.prepare("run", query, ["testtesttest", 20, 33, 2, 0, "1-uuid-2", "testman", 0, 50, "intro", "skip", "YouTube", 101, 0, 0, getHash("testtesttest", 1)]); await db.prepare("run", query, ["getSkipSegmentID1", 1, 11, 2, 0, "uuid10", "testman", 0, 50, "sponsor", "skip", "PeerTube", 120, 0, 0]);
await db.prepare("run", query, ["testtesttest,test", 1, 11, 2, 0, "1-uuid-1", "testman", 0, 50, "sponsor", "skip", "YouTube", 140, 0, 0, getHash("testtesttest,test", 1)]); await db.prepare("run", query, ["getSkipSegmentID2", 1, 11, 2, 0, "uuid20", "testman", 0, 50, "sponsor", "skip", "YouTube", 140, 0, 0]);
await db.prepare("run", query, ["test3", 1, 11, 2, 0, "1-uuid-4", "testman", 0, 50, "sponsor", "skip", "YouTube", 200, 0, 0, getHash("test3", 1)]); await db.prepare("run", query, ["getSkipSegmentID3", 1, 11, 2, 0, "uuid30", "testman", 0, 50, "sponsor", "skip", "YouTube", 200, 0, 0]);
await db.prepare("run", query, ["test3", 7, 22, -3, 0, "1-uuid-5", "testman", 0, 50, "sponsor", "skip", "YouTube", 300, 0, 0, getHash("test3", 1)]); await db.prepare("run", query, ["getSkipSegmentID3", 7, 22, -3, 0, "uuid31", "testman", 0, 50, "sponsor", "skip", "YouTube", 300, 0, 0]);
await db.prepare("run", query, ["multiple", 1, 11, 2, 0, "1-uuid-6", "testman", 0, 50, "intro", "skip", "YouTube", 400, 0, 0, getHash("multiple", 1)]); await db.prepare("run", query, ["getSkipSegmentMultiple", 1, 11, 2, 0, "uuid40", "testman", 0, 50, "intro", "skip", "YouTube", 400, 0, 0]);
await db.prepare("run", query, ["multiple", 20, 33, 2, 0, "1-uuid-7", "testman", 0, 50, "intro", "skip", "YouTube", 500, 0, 0, getHash("multiple", 1)]); await db.prepare("run", query, ["getSkipSegmentMultiple", 20, 33, 2, 0, "uuid41", "testman", 0, 50, "intro", "skip", "YouTube", 500, 0, 0]);
await db.prepare("run", query, ["locked", 20, 33, 2, 1, "1-uuid-locked-8", "testman", 0, 50, "intro", "skip", "YouTube", 230, 0, 0, getHash("locked", 1)]); await db.prepare("run", query, ["getSkipSegmentLocked", 20, 33, 2, 1, "uuid50", "testman", 0, 50, "intro", "skip", "YouTube", 230, 0, 0]);
await db.prepare("run", query, ["locked", 20, 34, 100000, 0, "1-uuid-9", "testman", 0, 50, "intro", "skip", "YouTube", 190, 0, 0, getHash("locked", 1)]); await db.prepare("run", query, ["getSkipSegmentLocked", 20, 34, 100000, 0, "uuid51", "testman", 0, 50, "intro", "skip", "YouTube", 190, 0, 0]);
await db.prepare("run", query, ["onlyHiddenSegments", 20, 34, 100000, 0, "onlyHiddenSegments", "testman", 0, 50, "sponsor", "skip", "YouTube", 190, 1, 0, getHash("onlyHiddenSegments", 1)]); await db.prepare("run", query, ["getSkipSegmentID6", 20, 34, 100000, 0, "uuid60", "testman", 0, 50, "sponsor", "skip", "YouTube", 190, 1, 0]);
await db.prepare("run", query, ["requiredSegmentVid-raw", 60, 70, 2, 0, "requiredSegmentVid-raw-1", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)]); await db.prepare("run", query, ["requiredSegmentVid", 60, 70, 2, 0, "requiredSegmentVid1", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0]);
await db.prepare("run", query, ["requiredSegmentVid-raw", 60, 70, -2, 0, "requiredSegmentVid-raw-2", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)]); await db.prepare("run", query, ["requiredSegmentVid", 60, 70, -2, 0, "requiredSegmentVid2", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0]);
await db.prepare("run", query, ["requiredSegmentVid-raw", 80, 90, -2, 0, "requiredSegmentVid-raw-3", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)]); await db.prepare("run", query, ["requiredSegmentVid", 80, 90, -2, 0, "requiredSegmentVid3", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0]);
await db.prepare("run", query, ["requiredSegmentVid-raw", 80, 90, 2, 0, "requiredSegmentVid-raw-4", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)]); await db.prepare("run", query, ["requiredSegmentVid", 80, 90, 2, 0, "requiredSegmentVid4", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0]);
return; return;
}); });
it("Should be able to get a time by category 1", (done) => {
it("Should be able to get a time by category 1", (done: Done) => { client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor" } })
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor`) .then(res => {
.then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
assert.strictEqual(data[0].segment[0], 1); assert.strictEqual(data[0].segment[0], 1);
assert.strictEqual(data[0].segment[1], 11); assert.strictEqual(data[0].segment[1], 11);
assert.strictEqual(data[0].category, "sponsor"); assert.strictEqual(data[0].category, "sponsor");
assert.strictEqual(data[0].UUID, "1-uuid-0"); assert.strictEqual(data[0].UUID, "uuid01");
assert.strictEqual(data[0].videoDuration, 100); assert.strictEqual(data[0].videoDuration, 100);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a time by category and action type", (done: Done) => { it("Should be able to get a time by category and action type", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionType: "mute" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
segment: [12, 14], segment: [12, 14],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0-2", UUID: "uuid02",
videoDuration: 100 videoDuration: 100
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -61,18 +60,18 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a time by category and multiple action types", (done: Done) => { it("Should be able to get a time by category and getSkipSegmentMultiple action types", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute&actionType=skip`) client.get(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionType=mute&actionType=skip`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0", UUID: "uuid01",
videoDuration: 100 videoDuration: 100
}, { }, {
UUID: "1-uuid-0-2" UUID: "uuid02"
}]; }];
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -81,18 +80,18 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a time by category and multiple action types (JSON array)", (done: Done) => { it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&actionTypes=["mute","skip"]`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionTypes: `["mute","skip"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0", UUID: "uuid01",
videoDuration: 100 videoDuration: 100
}, { }, {
UUID: "1-uuid-0-2" UUID: "uuid02"
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -100,15 +99,15 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a time by category for a different service 1", (done: Done) => { it("Should be able to get a time by category for a different service 1", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest2&category=sponsor&service=PeerTube`) client.get(endpoint, { params: { videoID: "getSkipSegmentID1", category: "sponsor", service: "PeerTube" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0-1", UUID: "uuid10",
videoDuration: 120 videoDuration: 120
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -118,61 +117,61 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a time by category 2", (done: Done) => { it("Should be able to get a time by category 2", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=intro`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "intro" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [20, 33], segment: [20, 33],
category: "intro", category: "intro",
UUID: "1-uuid-2" UUID: "uuid03"
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
assert.strictEqual(data.length, 1);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a time by categories array", (done: Done) => { it("Should be able to get a time by categories array", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["sponsor"]`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0", UUID: "uuid01",
videoDuration: 100 videoDuration: 100
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
assert.strictEqual(data.length, 1);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a time by categories array 2", (done: Done) => { it("Should be able to get a time by categories array 2", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["intro"]`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["intro"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [20, 33], segment: [20, 33],
category: "intro", category: "intro",
UUID: "1-uuid-2", UUID: "uuid03",
videoDuration: 101 videoDuration: 101
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
assert.strictEqual(data.length, 1);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 404 if all submissions are hidden", (done: Done) => { it("Should return 404 if all submissions are hidden", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=onlyHiddenSegments`) client.get(endpoint, { params: { videoID: "getSkipSegmentID6" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -180,20 +179,20 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get multiple times by category", (done: Done) => { it("Should be able to get getSkipSegmentMultiple times by category", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=multiple&categories=["intro"]`) client.get(endpoint, { params: { videoID: "getSkipSegmentMultiple", categories: `["intro"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "intro", category: "intro",
UUID: "1-uuid-6", UUID: "uuid40",
}, { }, {
segment: [20, 33], segment: [20, 33],
category: "intro", category: "intro",
UUID: "1-uuid-7", UUID: "uuid41",
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -201,37 +200,20 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get multiple times by multiple categories", (done: Done) => { it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["sponsor", "intro"]`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor", "intro"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
const expected = [{
segment: [1, 11],
category: "sponsor",
UUID: "1-uuid-0",
}, {
segment: [20, 33],
category: "intro",
UUID: "1-uuid-2",
}];
assert.ok(partialDeepEquals(data, expected));
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
done();
})
.catch(err => done(err));
});
it("Should be possible to send unexpected query parameters", (done: Done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&fakeparam=hello&category=sponsor`)
.then(async res => {
assert.strictEqual(res.status, 200);
const data = await res.json();
assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0", UUID: "uuid01",
}, {
segment: [20, 33],
category: "intro",
UUID: "uuid03",
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -239,16 +221,16 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Low voted submissions should be hidden", (done: Done) => { it("Should be possible to send unexpected query parameters", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=test3&category=sponsor`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", fakeparam: "hello", category: "sponsor" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-4", UUID: "uuid01",
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -256,8 +238,25 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 404 if no segment found", (done: Done) => { it("Low voted submissions should be hidden", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=notarealvideo`) client.get(endpoint, { params: { videoID: "getSkipSegmentID3", category: "sponsor" } })
.then(res => {
assert.strictEqual(res.status, 200);
const data = res.data;
assert.strictEqual(data.length, 1);
const expected = [{
segment: [1, 11],
category: "sponsor",
UUID: "uuid30",
}];
assert.ok(partialDeepEquals(data, expected));
done();
})
.catch(err => done(err));
});
it("Should return 404 if no segment found", (done) => {
client.get(endpoint, { params: { videoID: "notarealvideo" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -265,8 +264,8 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if bad categories argument", (done: Done) => { it("Should return 400 if bad categories argument", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=[not-quoted,not-quoted]`) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `[not-quoted,not-quoted]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -274,16 +273,16 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able send a comma in a query param", (done: Done) => { it("Should be able send a comma in a query param", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest,test&category=sponsor`) client.get(endpoint, { params: { videoID: "getSkipSegmentID2", category: "sponsor" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-1", UUID: "uuid20",
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -291,16 +290,16 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should always get locked segment", (done: Done) => { it("Should always get getSkipSegmentLocked segment", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=locked&category=intro`) client.get(endpoint, { params: { videoID: "getSkipSegmentLocked", category: "intro" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [20, 33], segment: [20, 33],
category: "intro", category: "intro",
UUID: "1-uuid-locked-8", UUID: "uuid50",
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -308,20 +307,20 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get multiple categories with repeating parameters", (done: Done) => { it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&category=intro`) client.get(`${endpoint}?category=sponsor&category=intro`, { params: { videoID: "getSkipSegmentID0" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0", UUID: "uuid01",
}, { }, {
segment: [20, 33], segment: [20, 33],
category: "intro", category: "intro",
UUID: "1-uuid-2", UUID: "uuid03",
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -329,16 +328,16 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get, categories param overriding repeating category", (done: Done) => { it("Should be able to get, categories param overriding repeating category", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["sponsor"]&category=intro`) client.get(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor"]&category=intro`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segment: [1, 11], segment: [1, 11],
category: "sponsor", category: "sponsor",
UUID: "1-uuid-0", UUID: "uuid01",
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -346,16 +345,18 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get specific segments with requiredSegments", (done: Done) => { it("Should be able to get specific segments with requiredSegments", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegments=["requiredSegmentVid-raw-2","requiredSegmentVid-raw-3"]`) const required2 = "requiredSegmentVid2";
.then(async res => { const required3 = "requiredSegmentVid3";
client.get(endpoint, { params: { videoID: "requiredSegmentVid", requiredSegments: `["${required2}","${required3}"]` } })
.then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
const expected = [{ const expected = [{
UUID: "requiredSegmentVid-raw-2", UUID: required2,
}, { }, {
UUID: "requiredSegmentVid-raw-3", UUID: required3,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -363,16 +364,18 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get specific segments with repeating requiredSegment", (done: Done) => { it("Should be able to get specific segments with repeating requiredSegment", (done) => {
fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegment=requiredSegmentVid-raw-2&requiredSegment=requiredSegmentVid-raw-3`) const required2 = "requiredSegmentVid2";
.then(async res => { const required3 = "requiredSegmentVid3";
client.get(`${endpoint}?videoID=requiredSegmentVid&requiredSegment=${required2}&requiredSegment=${required3}`)
.then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
const expected = [{ const expected = [{
UUID: "requiredSegmentVid-raw-2", UUID: required2,
}, { }, {
UUID: "requiredSegmentVid-raw-3", UUID: required3,
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
done(); done();
@@ -380,9 +383,9 @@ describe("getSkipSegments", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get 400 if no videoID passed in", (done: Done) => { it("Should get 400 if no videoID passed in", (done) => {
fetch(`${getbaseURL()}/api/skipSegments`) client.get(endpoint)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })

View File

@@ -1,36 +1,39 @@
import fetch from "node-fetch";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {Done, getbaseURL, partialDeepEquals} from "../utils"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { ImportMock, } from "ts-mock-imports"; import { ImportMock, } from "ts-mock-imports";
import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi";
import { YouTubeApiMock } from "../youtubeMock"; import { YouTubeApiMock } from "../youtubeMock";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI");
const sinonStub = mockManager.mock("listVideos"); const sinonStub = mockManager.mock("listVideos");
sinonStub.callsFake(YouTubeApiMock.listVideos); sinonStub.callsFake(YouTubeApiMock.listVideos);
describe("getSkipSegmentsByHash", () => { describe("getSkipSegmentsByHash", () => {
const endpoint = "/api/skipSegments";
const getSegmentsByHash0Hash = "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910";
const requiredSegmentVidHash = "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61";
before(async () => { before(async () => {
const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "actionType", "service", "hidden", "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "actionType", "service", "hidden", "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
await db.prepare("run", query, ["getSegmentsByHash-0", 1, 10, 2, "getSegmentsByHash-0-0", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"]); await db.prepare("run", query, ["getSegmentsByHash-0", 1, 10, 2, "getSegmentsByHash-01", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, getSegmentsByHash0Hash]);
await db.prepare("run", query, ["getSegmentsByHash-0", 1, 10, 2, "getSegmentsByHash-0-0-1", "testman", 0, 50, "sponsor", "skip", "PeerTube", 0, 0, "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"]); await db.prepare("run", query, ["getSegmentsByHash-0", 1, 10, 2, "getSegmentsByHash-02", "testman", 0, 50, "sponsor", "skip", "PeerTube", 0, 0, getSegmentsByHash0Hash]);
await db.prepare("run", query, ["getSegmentsByHash-0", 20, 30, 2, "getSegmentsByHash-0-1", "testman", 100, 150, "intro", "skip", "YouTube", 0, 0, "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"]); await db.prepare("run", query, ["getSegmentsByHash-0", 20, 30, 2, "getSegmentsByHash-03", "testman", 100, 150, "intro", "skip", "YouTube", 0, 0, getSegmentsByHash0Hash]);
await db.prepare("run", query, ["getSegmentsByHash-0", 40, 50, 2, "getSegmentsByHash-0-2", "testman", 0, 50, "sponsor", "mute", "YouTube", 0, 0, "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"]); await db.prepare("run", query, ["getSegmentsByHash-0", 40, 50, 2, "getSegmentsByHash-04", "testman", 0, 50, "sponsor", "mute", "YouTube", 0, 0, getSegmentsByHash0Hash]);
await db.prepare("run", query, ["getSegmentsByHash-noMatchHash", 40, 50, 2, "getSegmentsByHash-noMatchHash", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "fdaffnoMatchHash"]); await db.prepare("run", query, ["getSegmentsByHash-noMatchHash", 40, 50, 2, "getSegmentsByHash-noMatchHash", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "fdaffnoMatchHash"]);
await db.prepare("run", query, ["getSegmentsByHash-1", 60, 70, 2, "getSegmentsByHash-1", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "3272fa85ee0927f6073ef6f07ad5f3146047c1abba794cfa364d65ab9921692b"]); await db.prepare("run", query, ["getSegmentsByHash-1", 60, 70, 2, "getSegmentsByHash-1", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "3272fa85ee0927f6073ef6f07ad5f3146047c1abba794cfa364d65ab9921692b"]);
await db.prepare("run", query, ["onlyHidden", 60, 70, 2, "onlyHidden", "testman", 0, 50, "sponsor", "skip", "YouTube", 1, 0, "f3a199e1af001d716cdc6599360e2b062c2d2b3fa2885f6d9d2fd741166cbbd3"]); await db.prepare("run", query, ["onlyHidden", 60, 70, 2, "onlyHidden", "testman", 0, 50, "sponsor", "skip", "YouTube", 1, 0, "f3a199e1af001d716cdc6599360e2b062c2d2b3fa2885f6d9d2fd741166cbbd3"]);
await db.prepare("run", query, ["highlightVid", 60, 60, 2, "highlightVid-1", "testman", 0, 50, "poi_highlight", "skip", "YouTube", 0, 0, getHash("highlightVid", 1)]); await db.prepare("run", query, ["highlightVid", 60, 60, 2, "highlightVid-1", "testman", 0, 50, "poi_highlight", "skip", "YouTube", 0, 0, getHash("highlightVid", 1)]);
await db.prepare("run", query, ["highlightVid", 70, 70, 2, "highlightVid-2", "testman", 0, 50, "poi_highlight", "skip", "YouTube", 0, 0, getHash("highlightVid", 1)]); await db.prepare("run", query, ["highlightVid", 70, 70, 2, "highlightVid-2", "testman", 0, 50, "poi_highlight", "skip", "YouTube", 0, 0, getHash("highlightVid", 1)]);
await db.prepare("run", query, ["requiredSegmentVid", 60, 70, 2, "requiredSegmentVid-1", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"]); await db.prepare("run", query, ["requiredSegmentVid", 60, 70, 2, "requiredSegmentVid-1", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, requiredSegmentVidHash]);
await db.prepare("run", query, ["requiredSegmentVid", 60, 70, -2, "requiredSegmentVid-2", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"]); await db.prepare("run", query, ["requiredSegmentVid", 60, 70, -2, "requiredSegmentVid-2", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, requiredSegmentVidHash]);
await db.prepare("run", query, ["requiredSegmentVid", 80, 90, -2, "requiredSegmentVid-3", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"]); await db.prepare("run", query, ["requiredSegmentVid", 80, 90, -2, "requiredSegmentVid-3", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, requiredSegmentVidHash]);
await db.prepare("run", query, ["requiredSegmentVid", 80, 90, 2, "requiredSegmentVid-4", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"]); await db.prepare("run", query, ["requiredSegmentVid", 80, 90, 2, "requiredSegmentVid-4", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, requiredSegmentVidHash]);
}); });
it("Should be able to get a 200", (done: Done) => { it("Should be able to get a 200", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/3272f?categories=["sponsor", "intro"]`) client.get(`${endpoint}/3272f`, { params: { categories: `["sponsor", "intro"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -38,46 +41,42 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 404 if no segments are found even if a video for the given hash is known", (done: Done) => { it("Should return 404 if no segments are found even if a video for the given hash is known", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/3272f?categories=["shilling"]`) client.get(`${endpoint}/3272f`, { params: { categories: `["shilling"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
const expected = "[]"; assert.equal(res.data.length, 0);
const body = await res.text();
assert.strictEqual(body, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get an empty array if no videos", (done: Done) => { it("Should be able to get an empty array if no videos", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/11111?categories=["shilling"]`) client.get(`${endpoint}/11111`, { params: { categories: `["shilling"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
const body = await res.text(); const body = res.data;
const expected = "[]"; assert.strictEqual(body.length, 0);
assert.strictEqual(JSON.parse(body).length, 0);
assert.strictEqual(body, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get an empty array if only hidden videos", (done: Done) => { it("Should be able to get an empty array if only hidden videos", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/f3a1?categories=["sponsor"]`) client.get(`${endpoint}/f3a1`, { params: { categories:`["sponsor"]` } })
.then(async res => { .then(res => {
if (res.status !== 404) done(`non 404 status code, was ${res.status}`); if (res.status !== 404) done(`non 404 status code, was ${res.status}`);
else { else {
const body = await res.text(); const body = res.data;
if (JSON.parse(body).length === 0 && body === "[]") done(); // pass if (body.length === 0) done(); // pass
else done("non empty array returned"); else done("non empty array returned");
} }
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 prefix too short", (done: Done) => { it("Should return 400 prefix too short", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/11?categories=["shilling"]`) client.get(`${endpoint}/11`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -85,10 +84,10 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 prefix too long", (done: Done) => { it("Should return 400 prefix too long", (done) => {
const prefix = "1".repeat(50); const prefix = "1".repeat(50);
assert.ok(prefix.length > 33, "failed to generate long enough string"); assert.ok(prefix.length > 33, "failed to generate long enough string");
fetch(`${getbaseURL()}/api/skipSegments/${prefix}?categories=["shilling"]`) client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -96,9 +95,9 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 404 prefix in range", (done: Done) => { it("Should return 404 prefix in range", (done) => {
const prefix = "1".repeat(5); const prefix = "1".repeat(5);
fetch(`${getbaseURL()}/api/skipSegments/${prefix}?categories=["shilling"]`) client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -106,8 +105,8 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 for no hash", (done: Done) => { it("Should return 400 for no hash", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/?categories=["shilling"]`) client.get(`${endpoint}`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -115,8 +114,8 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 for bad format categories", (done: Done) => { it("Should return 400 for bad format categories", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaf?categories=shilling`) client.get(`${endpoint}/fdaf`, { params: { categories: "shilling" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -124,11 +123,11 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get multiple videos", (done: Done) => { it("Should be able to get multiple videos", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaf?categories=["sponsor","intro"]`) client.get(`${endpoint}/fdaf`, { params: { categories: `["sponsor","intro"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
assert.strictEqual(data[0].segments.length, 2); assert.strictEqual(data[0].segments.length, 2);
assert.strictEqual(data[1].segments.length, 1); assert.strictEqual(data[1].segments.length, 1);
@@ -137,22 +136,22 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get 200 for no categories (default sponsor)", (done: Done) => { it("Should be able to get 200 for no categories (default sponsor)", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaf`) client.get(`${endpoint}/fdaf`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2);
const expected = [{ const expected = [{
segments: [{ segments: [{
category: "sponsor", category: "sponsor",
UUID: "getSegmentsByHash-0-0", UUID: "getSegmentsByHash-01",
}] }]
}, { }, {
segments: [{ segments: [{
category: "sponsor", category: "sponsor",
}] }]
}]; }];
assert.strictEqual(data.length, 2);
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
assert.strictEqual(data[0].segments.length, 1); assert.strictEqual(data[0].segments.length, 1);
assert.strictEqual(data[1].segments.length, 1); assert.strictEqual(data[1].segments.length, 1);
@@ -161,18 +160,18 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get 200 for no categories (default sponsor) with action type", (done: Done) => { it("Should be able to get 200 for no categories (default sponsor) with action type", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaf?actionType=skip`) client.get(`${endpoint}/fdaf`, { params: { actionType: "skip" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
assert.strictEqual(data[0].segments.length, 1); assert.strictEqual(data[0].segments.length, 1);
assert.strictEqual(data[1].segments.length, 1); assert.strictEqual(data[1].segments.length, 1);
const expected = [{ const expected = [{
segments: [{ segments: [{
category: "sponsor", category: "sponsor",
UUID: "getSegmentsByHash-0-0", UUID: "getSegmentsByHash-01",
}] }]
}, { }, {
segments: [{ segments: [{
@@ -185,20 +184,20 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get 200 for no categories (default sponsor) with multiple action types", (done: Done) => { it("Should be able to get 200 for no categories (default sponsor) with multiple action types", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaf?actionType=skip&actionType=mute`) client.get(`${endpoint}/fdaf?actionType=skip&actionType=mute`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
assert.strictEqual(data[0].segments.length, 2); assert.strictEqual(data[0].segments.length, 2);
assert.strictEqual(data[1].segments.length, 1); assert.strictEqual(data[1].segments.length, 1);
const expected = [{ const expected = [{
segments: [{ segments: [{
category: "sponsor", category: "sponsor",
UUID: "getSegmentsByHash-0-0", UUID: "getSegmentsByHash-01",
}, { }, {
UUID: "getSegmentsByHash-0-2", UUID: "getSegmentsByHash-04",
}] }]
}, { }, {
segments: [{ segments: [{
@@ -211,18 +210,18 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get 200 for no categories (default sponsor) with multiple action types (JSON array)", (done: Done) => { it("Should be able to get 200 for no categories (default sponsor) with multiple action types (JSON array)", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaf?actionTypes=["skip","mute"]`) client.get(`${endpoint}/fdaf?actionTypes=["skip","mute"]`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 2); assert.strictEqual(data.length, 2);
const expected = [{ const expected = [{
segments: [{ segments: [{
category: "sponsor", category: "sponsor",
UUID: "getSegmentsByHash-0-0", UUID: "getSegmentsByHash-01",
}, { }, {
UUID: "getSegmentsByHash-0-2", UUID: "getSegmentsByHash-04",
}] }]
}, { }, {
segments: [{ segments: [{
@@ -235,15 +234,15 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done: Done) => { it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaf?service=PeerTube`) client.get(`${endpoint}/fdaf`, { params: { service: "PeerTube" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segments: [{ segments: [{
UUID: "getSegmentsByHash-0-0-1" UUID: "getSegmentsByHash-02"
}] }]
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -253,11 +252,11 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should only return one segment when fetching highlight segments", (done: Done) => { it("Should only return one segment when fetching highlight segments", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/c962?category=poi_highlight`) client.get(`${endpoint}/c962`, { params: { category: "poi_highlight" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
assert.strictEqual(data[0].segments.length, 1); assert.strictEqual(data[0].segments.length, 1);
done(); done();
@@ -265,27 +264,21 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to post a segment and get it using endpoint", (done: Done) => { it("Should be able to post a segment and get it using endpoint", (done) => {
const testID = "abc123goodVideo"; const testID = "abc123goodVideo";
fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { client.post("/api/skipSegments", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userID: "test-qwertyuiopasdfghjklzxcvbnm", userID: "test-qwertyuiopasdfghjklzxcvbnm",
videoID: testID, videoID: testID,
segments: [{ segments: [{
segment: [13, 17], segment: [13, 17],
category: "sponsor", category: "sponsor",
}], }],
}),
}) })
.then(async () => { .then(() => {
fetch(`${getbaseURL()}/api/skipSegments/${getHash(testID, 1).substring(0, 3)}`) client.get(`${endpoint}/${getHash(testID, 1).substring(0, 3)}`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segments: [{ segments: [{
@@ -301,21 +294,21 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(`(post) ${err}`)); .catch(err => done(`(post) ${err}`));
}); });
it("Should be able to get multiple categories with repeating parameters", (done: Done) => { it("Should be able to get multiple categories with repeating parameters", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/fdaff4?&category=sponsor&category=intro`) client.get(`${endpoint}/fdaff4?&category=sponsor&category=intro`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segments: [{ segments: [{
segment: [1, 10], segment: [1, 10],
category: "sponsor", category: "sponsor",
UUID: "getSegmentsByHash-0-0", UUID: "getSegmentsByHash-01",
}, { }, {
segment: [20, 30], segment: [20, 30],
category: "intro", category: "intro",
UUID: "getSegmentsByHash-0-1", UUID: "getSegmentsByHash-03",
}] }]
}]; }];
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(data, expected));
@@ -324,11 +317,11 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get specific segments with requiredSegments", (done: Done) => { it("Should be able to get specific segments with requiredSegments", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]`) client.get(`${endpoint}/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
const expected = [{ const expected = [{
segments: [{ segments: [{
@@ -344,11 +337,11 @@ describe("getSkipSegmentsByHash", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get specific segments with repeating requiredSegment", (done: Done) => { it("Should be able to get specific segments with repeating requiredSegment", (done) => {
fetch(`${getbaseURL()}/api/skipSegments/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3`) client.get(`${endpoint}/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.strictEqual(data.length, 1); assert.strictEqual(data.length, 1);
assert.strictEqual(data[0].segments.length, 2); assert.strictEqual(data[0].segments.length, 2);
const expected = [{ const expected = [{

View File

@@ -1,20 +1,19 @@
import assert from "assert"; import assert from "assert";
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { client } from "../utils/httpClient";
let dbVersion: number; let dbVersion: number;
describe("getStatus", () => { describe("getStatus", () => {
const endpoint = "/api/status";
before(async () => { before(async () => {
dbVersion = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value; dbVersion = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value;
}); });
it("Should be able to get status", (done: Done) => { it("Should be able to get status", (done) => {
fetch(`${getbaseURL()}/api/status`) client.get(endpoint)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.ok(data.uptime); // uptime should be greater than 1s assert.ok(data.uptime); // uptime should be greater than 1s
assert.strictEqual(data.commit, "test"); assert.strictEqual(data.commit, "test");
assert.strictEqual(data.db, Number(dbVersion)); assert.strictEqual(data.db, Number(dbVersion));
@@ -25,57 +24,52 @@ describe("getStatus", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get uptime only", (done: Done) => { it("Should be able to get uptime only", (done) => {
fetch(`${getbaseURL()}/api/status/uptime`) client.get(`${endpoint}/uptime`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.text(); assert.ok(Number(res.data) >= 1); // uptime should be greater than 1s
assert.ok(Number(data) >= 1); // uptime should be greater than 1s
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get commit only", (done: Done) => { it("Should be able to get commit only", (done) => {
fetch(`${getbaseURL()}/api/status/commit`) client.get(`${endpoint}/commit`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.text(); assert.strictEqual(res.data, "test"); // commit should be test
assert.strictEqual(data, "test"); // commit should be test
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get db only", (done: Done) => { it("Should be able to get db only", (done) => {
fetch(`${getbaseURL()}/api/status/db`) client.get(`${endpoint}/db`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.text(); assert.strictEqual(Number(res.data), Number(dbVersion)); // commit should be test
assert.strictEqual(Number(data), Number(dbVersion)); // commit should be test
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get startTime only", (done: Done) => { it("Should be able to get startTime only", (done) => {
fetch(`${getbaseURL()}/api/status/startTime`) client.get(`${endpoint}/startTime`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.text();
const now = Date.now(); const now = Date.now();
assert.ok(Number(data) <= now); // startTime should be more than now assert.ok(Number(res.data) <= now); // startTime should be more than now
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get processTime only", (done: Done) => { it("Should be able to get processTime only", (done) => {
fetch(`${getbaseURL()}/api/status/processTime`) client.get(`${endpoint}/processTime`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.text(); assert.ok(Number(res.data) >= 0);
assert.ok(Number(data) >= 0);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));

View File

@@ -1,8 +1,11 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
import { AxiosResponse } from "axios";
const endpoint = "/api/userID";
const getUserName = (username: string): Promise<AxiosResponse> => client.get(endpoint, { params: { username } });
describe("getUserID", () => { describe("getUserID", () => {
before(async () => { before(async () => {
@@ -21,17 +24,17 @@ describe("getUserID", () => {
await db.prepare("run", insertUserNameQuery, [getHash("getuserid_user_12"), "a"]); await db.prepare("run", insertUserNameQuery, [getHash("getuserid_user_12"), "a"]);
}); });
it("Should be able to get a 200", (done: Done) => { it("Should be able to get a 200", (done) => {
fetch(`${getbaseURL()}/api/userID?username=fuzzy+user+01`) getUserName("fuzzy user 01")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a 400 (No username parameter)", (done: Done) => { it("Should be able to get a 400 (No username parameter)", (done) => {
fetch(`${getbaseURL()}/api/userID`) client.get(endpoint)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -39,17 +42,17 @@ describe("getUserID", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a 200 (username is public id)", (done: Done) => { it("Should be able to get a 200 (username is public id)", (done) => {
fetch(`${getbaseURL()}/api/userID?username=${getHash("getuserid_user_06")}`) client.get(endpoint, { params: { username: getHash("getuserid_user_06") } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a 400 (username longer than 64 chars)", (done: Done) => { it("Should be able to get a 400 (username longer than 64 chars)", (done) => {
fetch(`${getbaseURL()}/api/userID?username=${getHash("getuserid_user_06")}0`) client.get(endpoint, { params: { username: `${getHash("getuserid_user_06")}0` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -57,24 +60,23 @@ describe("getUserID", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get single username", (done: Done) => { it("Should be able to get single username", (done) => {
fetch(`${getbaseURL()}/api/userID?username=fuzzy+user+01`) client.get(endpoint, { params: { username: "fuzzy user 01" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "fuzzy user 01", userName: "fuzzy user 01",
userID: getHash("getuserid_user_01") userID: getHash("getuserid_user_01")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get multiple fuzzy user info from start", (done: Done) => { it("Should be able to get multiple fuzzy user info from start", (done) => {
fetch(`${getbaseURL()}/api/userID?username=fuzzy+user`) getUserName("fuzzy user")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "fuzzy user 01", userName: "fuzzy user 01",
@@ -83,16 +85,15 @@ describe("getUserID", () => {
userName: "fuzzy user 02", userName: "fuzzy user 02",
userID: getHash("getuserid_user_02") userID: getHash("getuserid_user_02")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get multiple fuzzy user info from middle", (done: Done) => { it("Should be able to get multiple fuzzy user info from middle", (done) => {
fetch(`${getbaseURL()}/api/userID?username=user`) getUserName("user")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "fuzzy user 01", userName: "fuzzy user 01",
@@ -104,48 +105,45 @@ describe("getUserID", () => {
userName: "specific user 03", userName: "specific user 03",
userID: getHash("getuserid_user_03") userID: getHash("getuserid_user_03")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get with public ID", (done: Done) => { it("Should be able to get with public ID", (done) => {
const userID = getHash("getuserid_user_06"); const userID = getHash("getuserid_user_06");
fetch(`${getbaseURL()}/api/userID?username=${userID}`) getUserName(userID)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: userID, userName: userID,
userID userID
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get with fuzzy public ID", (done: Done) => { it("Should be able to get with fuzzy public ID", (done) => {
const userID = getHash("getuserid_user_06"); const userID = getHash("getuserid_user_06");
fetch(`${getbaseURL()}/api/userID?username=${userID.substr(10,60)}`) getUserName(userID.substr(10,60))
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: userID, userName: userID,
userID userID
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get repeating username", (done: Done) => { it("Should be able to get repeating username", (done) => {
fetch(`${getbaseURL()}/api/userID?username=repeating`) getUserName("repeating")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "repeating", userName: "repeating",
@@ -154,16 +152,15 @@ describe("getUserID", () => {
userName: "repeating", userName: "repeating",
userID: getHash("getuserid_user_05") userID: getHash("getuserid_user_05")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get repeating fuzzy username", (done: Done) => { it("Should be able to get repeating fuzzy username", (done) => {
fetch(`${getbaseURL()}/api/userID?username=peat`) getUserName("peat")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "repeating", userName: "repeating",
@@ -172,45 +169,42 @@ describe("getUserID", () => {
userName: "repeating", userName: "repeating",
userID: getHash("getuserid_user_05") userID: getHash("getuserid_user_05")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should avoid ReDOS with _", (done: Done) => { it("should avoid ReDOS with _", (done) => {
fetch(`${getbaseURL()}/api/userID?username=_redos_`) getUserName("_redos_")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "_redos_", userName: "_redos_",
userID: getHash("getuserid_user_09") userID: getHash("getuserid_user_09")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should avoid ReDOS with %", (done: Done) => { it("should avoid ReDOS with %", (done) => {
fetch(`${getbaseURL()}/api/userID?username=%redos%`) getUserName("%redos%")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "%redos%", userName: "%redos%",
userID: getHash("getuserid_user_08") userID: getHash("getuserid_user_08")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 404 if escaped backslashes present", (done: Done) => { it("should return 404 if escaped backslashes present", (done) => {
fetch(`${getbaseURL()}/api/userID?username=%redos\\\\_`) getUserName("%redos\\\\_")
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -218,8 +212,8 @@ describe("getUserID", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 404 if backslashes present", (done: Done) => { it("should return 404 if backslashes present", (done) => {
fetch(`${getbaseURL()}/api/userID?username=\\%redos\\_`) getUserName(`\\%redos\\_`)
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -227,23 +221,22 @@ describe("getUserID", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return user if just backslashes", (done: Done) => { it("should return user if just backslashes", (done) => {
fetch(`${getbaseURL()}/api/userID?username=\\\\\\`) getUserName(`\\\\\\`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "\\\\\\", userName: "\\\\\\",
userID: getHash("getuserid_user_11") userID: getHash("getuserid_user_11")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should not allow usernames more than 64 characters", (done: Done) => { it("should not allow usernames more than 64 characters", (done) => {
fetch(`${getbaseURL()}/api/userID?username=${"0".repeat(65)}`) getUserName("0".repeat(65))
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -251,8 +244,8 @@ describe("getUserID", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should not allow usernames less than 3 characters", (done: Done) => { it("should not allow usernames less than 3 characters", (done) => {
fetch(`${getbaseURL()}/api/userID?username=aa`) getUserName("aa")
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -260,24 +253,23 @@ describe("getUserID", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should allow exact match", (done: Done) => { it("should allow exact match", (done) => {
fetch(`${getbaseURL()}/api/userID?username=a&exact=true`) client.get(endpoint, { params: { username: "a", exact: true } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "a", userName: "a",
userID: getHash("getuserid_user_12") userID: getHash("getuserid_user_12")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get repeating username with exact username", (done: Done) => { it("Should be able to get repeating username with exact username", (done) => {
fetch(`${getbaseURL()}/api/userID?username=repeating&exact=true`) client.get(endpoint, { params: { username: "repeating", exact: true } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "repeating", userName: "repeating",
@@ -286,16 +278,15 @@ describe("getUserID", () => {
userName: "repeating", userName: "repeating",
userID: getHash("getuserid_user_05") userID: getHash("getuserid_user_05")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not get exact unless explicitly set to true", (done: Done) => { it("Should not get exact unless explicitly set to true", (done) => {
fetch(`${getbaseURL()}/api/userID?username=user&exact=1`) client.get(endpoint, { params: { username: "user", exact: 1 } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
userName: "fuzzy user 01", userName: "fuzzy user 01",
@@ -307,15 +298,14 @@ describe("getUserID", () => {
userName: "specific user 03", userName: "specific user 03",
userID: getHash("getuserid_user_03") userID: getHash("getuserid_user_03")
}]; }];
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should return 400 if no username parameter specified", (done: Done) => { it("should return 400 if no username parameter specified", (done) => {
fetch(`${getbaseURL()}/api/userID`) client.get(endpoint)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();

View File

@@ -1,24 +1,26 @@
import fetch from "node-fetch"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {Done, getbaseURL, partialDeepEquals} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
describe("getUserInfo", () => { describe("getUserInfo", () => {
const endpoint = "/api/userInfo";
before(async () => { before(async () => {
const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)';
await db.prepare("run", insertUserNameQuery, [getHash("getuserinfo_user_01"), "Username user 01"]); await db.prepare("run", insertUserNameQuery, [getHash("getuserinfo_user_01"), "Username user 01"]);
const sponsorTimesQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const sponsorTimesQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
await db.prepare("run", sponsorTimesQuery, ["xxxyyyzzz", 1, 11, 2, "uuid000001", getHash("getuserinfo_user_01"), 1, 10, "sponsor", 0]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo0", 1, 11, 2, "uuid000001", getHash("getuserinfo_user_01"), 1, 10, "sponsor", 0]);
await db.prepare("run", sponsorTimesQuery, ["xxxyyyzzz", 1, 11, 2, "uuid000002", getHash("getuserinfo_user_01"), 2, 10, "sponsor", 0]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo0", 1, 11, 2, "uuid000002", getHash("getuserinfo_user_01"), 2, 10, "sponsor", 0]);
await db.prepare("run", sponsorTimesQuery, ["yyyxxxzzz", 1, 11, -1, "uuid000003", getHash("getuserinfo_user_01"), 3, 10, "sponsor", 0]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo1", 1, 11, -1, "uuid000003", getHash("getuserinfo_user_01"), 3, 10, "sponsor", 0]);
await db.prepare("run", sponsorTimesQuery, ["yyyxxxzzz", 1, 11, -2, "uuid000004", getHash("getuserinfo_user_01"), 4, 10, "sponsor", 1]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo1", 1, 11, -2, "uuid000004", getHash("getuserinfo_user_01"), 4, 10, "sponsor", 1]);
await db.prepare("run", sponsorTimesQuery, ["xzzzxxyyy", 1, 11, -5, "uuid000005", getHash("getuserinfo_user_01"), 5, 10, "sponsor", 1]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo2", 1, 11, -5, "uuid000005", getHash("getuserinfo_user_01"), 5, 10, "sponsor", 1]);
await db.prepare("run", sponsorTimesQuery, ["zzzxxxyyy", 1, 11, 2, "uuid000006", getHash("getuserinfo_user_02"), 6, 10, "sponsor", 0]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo0", 1, 11, 2, "uuid000007", getHash("getuserinfo_user_02"), 7, 10, "sponsor", 1]);
await db.prepare("run", sponsorTimesQuery, ["xxxyyyzzz", 1, 11, 2, "uuid000007", getHash("getuserinfo_user_02"), 7, 10, "sponsor", 1]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo0", 1, 11, 2, "uuid000008", getHash("getuserinfo_user_02"), 8, 10, "sponsor", 1]);
await db.prepare("run", sponsorTimesQuery, ["xxxyyyzzz", 1, 11, 2, "uuid000008", getHash("getuserinfo_user_02"), 8, 10, "sponsor", 1]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo0", 0, 36000, 2,"uuid000009", getHash("getuserinfo_user_03"), 8, 10, "sponsor", 0]);
await db.prepare("run", sponsorTimesQuery, ["xxxyyyzzz", 0, 36000, 2, "uuid000009", getHash("getuserinfo_user_03"), 8, 2, "sponsor", 0]); await db.prepare("run", sponsorTimesQuery, ["getUserInfo3", 1, 11, 2, "uuid000006", getHash("getuserinfo_user_02"), 6, 10, "sponsor", 0]);
const insertWarningQuery = 'INSERT INTO warnings ("userID", "issueTime", "issuerUserID", "enabled", "reason") VALUES (?, ?, ?, ?, ?)'; const insertWarningQuery = 'INSERT INTO warnings ("userID", "issueTime", "issuerUserID", "enabled", "reason") VALUES (?, ?, ?, ?, ?)';
await db.prepare("run", insertWarningQuery, [getHash("getuserinfo_warning_0"), 10, "getuserinfo_vip", 1, "warning0-0"]); await db.prepare("run", insertWarningQuery, [getHash("getuserinfo_warning_0"), 10, "getuserinfo_vip", 1, "warning0-0"]);
@@ -32,8 +34,8 @@ describe("getUserInfo", () => {
await db.prepare("run", insertBanQuery, [getHash("getuserinfo_ban_01")]); await db.prepare("run", insertBanQuery, [getHash("getuserinfo_ban_01")]);
}); });
it("Should be able to get a 200", (done: Done) => { it("Should be able to get a 200", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_01`) client.get(endpoint, { params: { userID: "getuserinfo_user_01" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -41,8 +43,8 @@ describe("getUserInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get a 400 (No userID parameter)", (done: Done) => { it("Should be able to get a 400 (No userID parameter)", (done) => {
fetch(`${getbaseURL()}/api/userInfo`) client.get(endpoint, { params: { userID: "" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -50,9 +52,9 @@ describe("getUserInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get user info", (done: Done) => { it("Should be able to get user info", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_01`) client.get(endpoint, { params: { userID: "getuserinfo_user_01" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
userName: "Username user 01", userName: "Username user 01",
@@ -68,98 +70,91 @@ describe("getUserInfo", () => {
warnings: 0, warnings: 0,
warningReason: "" warningReason: ""
}; };
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get warning data", (done: Done) => { it("Should get warning data", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_0&value=warnings`) client.get(endpoint, { params: { userID: "getuserinfo_warning_0", value: "warnings" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warnings: 1 warnings: 1
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get warning data with public ID", (done: Done) => { it("Should get warning data with public ID", (done) => {
fetch(`${getbaseURL()}/api/userInfo?publicUserID=${getHash("getuserinfo_warning_0")}&values=["warnings"]`) client.get(endpoint, { params: { publicUserID: getHash("getuserinfo_warning_0"), values: `["warnings"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warnings: 1 warnings: 1
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get multiple warnings", (done: Done) => { it("Should get multiple warnings", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_1&value=warnings`) client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warnings" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warnings: 2 warnings: 2
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not get warnings if none", (done: Done) => { it("Should not get warnings if none", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_2&value=warnings`) client.get(endpoint, { params: { userID: "getuserinfo_warning_2", value: "warnings" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warnings: 0, warnings: 0,
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should done(userID for userName (No userName set)", (done: Done) => { it("Should done(userID for userName (No userName set)", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_02&value=userName`) client.get(endpoint, { params: { userID: "getuserinfo_user_02", value: "userName" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
userName: "c2a28fd225e88f74945794ae85aef96001d4a1aaa1022c656f0dd48ac0a3ea0f" userName: "c2a28fd225e88f74945794ae85aef96001d4a1aaa1022c656f0dd48ac0a3ea0f"
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return null segment if none", (done: Done) => { it("Should return null segment if none", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_null&value=lastSegmentID`) client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); assert.strictEqual(res.data.lastSegmentID, null);
assert.strictEqual(data.lastSegmentID, null);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return zeroes if userid does not exist", (done: Done) => { it("Should return zeroes if userid does not exist", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_null&value=lastSegmentID`) client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" } })
.then(async res => { .then(res => {
const data = await res.json(); const data = res.data;
for (const value in data) { for (const value in data) {
if (data[value] === null && value !== "lastSegmentID") { if (data[value] === null && value !== "lastSegmentID") {
done(`returned null for ${value}`); done(`returned null for ${value}`);
@@ -170,115 +165,108 @@ describe("getUserInfo", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get warning reason from from single enabled warning", (done: Done) => { it("Should get warning reason from from single enabled warning", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_0&values=["warningReason"]`) client.get(endpoint, { params: { userID: "getuserinfo_warning_0", values: `["warningReason"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warningReason: "warning0-0", warningReason: "warning0-0",
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get most recent warning from two enabled warnings", (done: Done) => { it("Should get most recent warning from two enabled warnings", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_1&value=warningReason`) client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warningReason" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warningReason: "warning1-1" warningReason: "warning1-1"
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not get disabled warning", (done: Done) => { it("Should not get disabled warning", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_2&values=["warnings","warningReason"]`) client.get(endpoint, { params: { userID: "getuserinfo_warning_2", values: `["warnings","warningReason"]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warnings: 0, warnings: 0,
warningReason: "" warningReason: ""
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not get newer disabled warning", (done: Done) => { it("Should not get newer disabled warning", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_3&value=warnings&value=warningReason`) client.get(`${endpoint}?userID=getuserinfo_warning_3&value=warnings&value=warningReason`)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
warnings: 1, warnings: 1,
warningReason: "warning3-0" warningReason: "warning3-0"
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get 400 if bad values specified", (done: Done) => { it("Should get 400 if bad values specified", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_3&value=invalid-value`) client.get(endpoint, { params: { userID: "getuserinfo_warning_3", value: "invalid-value" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get ban data for banned user (only appears when specifically requested)", (done: Done) => { it("Should get ban data for banned user (only appears when specifically requested)", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_ban_01&value=banned`) client.get(endpoint, { params: { userID: "getuserinfo_ban_01", value: "banned" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
banned: true banned: true
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get ban data for unbanned user (only appears when specifically requested)", (done: Done) => { it("Should get ban data for unbanned user (only appears when specifically requested)", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_notban_01&value=banned`) client.get(endpoint, { params: { userID: "getuserinfo_notban_01", value: "banned" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
banned: false banned: false
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should throw 400 on bad json in values", (done: Done) => { it("Should throw 400 on bad json in values", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=x&values=[userID]`) client.get(endpoint, { params: { userID: "x", values: `[userID]` } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 200 on userID not found", (done: Done) => { it("Should return 200 on userID not found", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=notused-userid`) client.get(endpoint, { params: { userID: "notused-userid" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
minutesSaved: 0, minutesSaved: 0,
segmentCount: 0, segmentCount: 0,
@@ -290,21 +278,21 @@ describe("getUserInfo", () => {
reputation: 0, reputation: 0,
vip: false, vip: false,
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); // pass done(); // pass
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should only count long segments as 10 minutes", (done: Done) => { it("Should only count long segments as 10 minutes", (done) => {
fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_03`) client.get(endpoint, { params: { userID: "getuserinfo_user_03" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
userName: "807e0a5d0a62c9c4365fae3d403e4618a3226f231314a898fa1555a0e55eab9e", userName: "807e0a5d0a62c9c4365fae3d403e4618a3226f231314a898fa1555a0e55eab9e",
userID: "807e0a5d0a62c9c4365fae3d403e4618a3226f231314a898fa1555a0e55eab9e", userID: "807e0a5d0a62c9c4365fae3d403e4618a3226f231314a898fa1555a0e55eab9e",
minutesSaved: 20, minutesSaved: 100,
viewCount: 2, viewCount: 10,
ignoredViewCount: 0, ignoredViewCount: 0,
segmentCount: 1, segmentCount: 1,
ignoredSegmentCount: 0, ignoredSegmentCount: 0,
@@ -314,8 +302,7 @@ describe("getUserInfo", () => {
warnings: 0, warnings: 0,
warningReason: "" warningReason: ""
}; };
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));

View File

@@ -1,10 +1,11 @@
import fetch from "node-fetch"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {Done, getbaseURL, partialDeepEquals} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
describe("getUserStats", () => { describe("getUserStats", () => {
const endpoint = "/api/userStats";
before(async () => { before(async () => {
const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)';
await db.prepare("run", insertUserNameQuery, [getHash("getuserstats_user_01"), "Username user 01"]); await db.prepare("run", insertUserNameQuery, [getHash("getuserstats_user_01"), "Username user 01"]);
@@ -22,8 +23,8 @@ describe("getUserStats", () => {
}); });
it("Should be able to get a 400 (No userID parameter)", (done: Done) => { it("Should be able to get a 400 (No userID parameter)", (done) => {
fetch(`${getbaseURL()}/api/userStats`) client.get(endpoint)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -31,9 +32,9 @@ describe("getUserStats", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get all user info", (done: Done) => { it("Should be able to get all user info", (done) => {
fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01&fetchCategoryStats=true&fetchActionTypeStats=true`) client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchCategoryStats: true, fetchActionTypeStats: true } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
userName: "Username user 01", userName: "Username user 01",
@@ -57,18 +58,17 @@ describe("getUserStats", () => {
segmentCount: 8 segmentCount: 8
} }
}; };
const data = await res.json(); assert.ok(partialDeepEquals(res.data, expected));
assert.ok(partialDeepEquals(data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get all zeroes for invalid userid", (done: Done) => { it("Should be able to get all zeroes for invalid userid", (done) => {
fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_invalid`) client.get(endpoint, { params: { userID: "getuserstats_user_invalid" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
for (const value in data.overallStats) { for (const value in data.overallStats) {
if (data[value]) { if (data[value]) {
done(`returned non-zero for ${value}`); done(`returned non-zero for ${value}`);
@@ -79,11 +79,11 @@ describe("getUserStats", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get all zeroes for only ignored segments", (done: Done) => { it("Should be able to get all zeroes for only ignored segments", (done) => {
fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_02`) client.get(endpoint, { params: { userID: "getuserstats_user_02" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
for (const value in data.overallStats) { for (const value in data.overallStats) {
if (data[value]) { if (data[value]) {
done(`returned non-zero for ${value}`); done(`returned non-zero for ${value}`);
@@ -94,11 +94,11 @@ describe("getUserStats", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not get extra stats if not requested", (done: Done) => { it("Should not get extra stats if not requested", (done) => {
fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01`) client.get(endpoint, { params: { userID: "getuserstats_user_01" } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
// check for categoryCount // check for categoryCount
if (data.categoryCount || data.actionTypeCount) { if (data.categoryCount || data.actionTypeCount) {
done("returned extra stats"); done("returned extra stats");
@@ -108,11 +108,11 @@ describe("getUserStats", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get parts of extra stats if not requested", (done: Done) => { it("Should get parts of extra stats if not requested", (done) => {
fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01&fetchActionTypeStats=true`) client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchActionTypeStats: true } })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
// check for categoryCount // check for categoryCount
if (data.categoryCount && !data.actionTypeCount) { if (data.categoryCount && !data.actionTypeCount) {
done("returned extra stats"); done("returned extra stats");

View File

@@ -1,9 +1,8 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { LockCategory } from "../../src/types/segments.model"; import { LockCategory } from "../../src/types/segments.model";
import { client } from "../utils/httpClient";
const stringDeepEquals = (a: string[] ,b: string[]): boolean => { const stringDeepEquals = (a: string[] ,b: string[]): boolean => {
let result = true; let result = true;
@@ -13,23 +12,29 @@ const stringDeepEquals = (a: string[] ,b: string[]): boolean => {
return result; return result;
}; };
const endpoint = "/api/lockCategories";
const submitEndpoint = "/api/skipSegments";
const checkLockCategories = (videoID: string): Promise<LockCategory[]> => db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', [videoID]);
const lockVIPUser = "lockCategoriesRecordsVIPUser";
const lockVIPUserHash = getHash(lockVIPUser);
describe("lockCategoriesRecords", () => { describe("lockCategoriesRecords", () => {
before(async () => { before(async () => {
const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)';
await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-lockCategories")]); await db.prepare("run", insertVipUserQuery, [lockVIPUserHash]);
const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") VALUES (?, ?, ?, ?)'; const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") VALUES (?, ?, ?, ?)';
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "no-segments-video-id", "sponsor", "reason-1"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id", "sponsor", "reason-1"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "no-segments-video-id", "intro", "reason-1"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id", "intro", "reason-1"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "no-segments-video-id-1", "sponsor", "reason-2"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id-1", "sponsor", "reason-2"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "no-segments-video-id-1", "intro", "reason-2"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id-1", "intro", "reason-2"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "lockCategoryVideo", "sponsor", "reason-3"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "lockCategoryVideo", "sponsor", "reason-3"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "delete-record", "sponsor", "reason-4"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "delete-record", "sponsor", "reason-4"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "delete-record-1", "sponsor", "reason-5"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "delete-record-1", "sponsor", "reason-5"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "delete-record-1", "intro", "reason-5"]); await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "delete-record-1", "intro", "reason-5"]);
}); });
it("Should update the database version when starting the application", async () => { it("Should update the database version when starting the application", async () => {
@@ -37,10 +42,10 @@ describe("lockCategoriesRecords", () => {
assert.ok(version > 1); assert.ok(version > 1);
}); });
it("Should be able to submit categories not in video (http response)", (done: Done) => { it("Should be able to submit categories not in video (http response)", (done) => {
const json = { const json = {
videoID: "no-segments-video-id", videoID: "no-segments-video-id",
userID: "VIPUser-lockCategories", userID: "lockCategoriesRecordsVIPUser",
categories: [ categories: [
"outro", "outro",
"shilling", "shilling",
@@ -56,26 +61,20 @@ describe("lockCategoriesRecords", () => {
"shilling", "shilling",
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST", .then(res => {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json)
})
.then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); assert.deepStrictEqual(res.data, expected);
assert.deepStrictEqual(data, expected);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to submit categories not in video (sql check)", (done: Done) => { it("Should be able to submit categories not in video (sql check)", (done) => {
const videoID = "no-segments-video-id-1";
const json = { const json = {
videoID: "no-segments-video-id-1", videoID,
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"outro", "outro",
"shilling", "shilling",
@@ -85,25 +84,17 @@ describe("lockCategoriesRecords", () => {
"intro", "intro",
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json)
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ["no-segments-video-id-1"]) as LockCategory[]; const result = await checkLockCategories(videoID);
assert.strictEqual(result.length, 4); assert.strictEqual(result.length, 4);
const oldRecordNotChangeReason = result.filter(item => const oldRecordNotChangeReason = result.filter(item =>
item.reason === "reason-2" && ["sponsor", "intro"].includes(item.category) item.reason === "reason-2" && ["sponsor", "intro"].includes(item.category)
); );
const newRecordWithEmptyReason = result.filter(item => const newRecordWithEmptyReason = result.filter(item =>
item.reason === "" && ["outro", "shilling"].includes(item.category) item.reason === "" && ["outro", "shilling"].includes(item.category)
); );
assert.strictEqual(newRecordWithEmptyReason.length, 2); assert.strictEqual(newRecordWithEmptyReason.length, 2);
assert.strictEqual(oldRecordNotChangeReason.length, 2); assert.strictEqual(oldRecordNotChangeReason.length, 2);
done(); done();
@@ -111,10 +102,11 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to submit categories not in video with reason (http response)", (done: Done) => { it("Should be able to submit categories not in video with reason (http response)", (done) => {
const videoID = "no-segments-video-id";
const json = { const json = {
videoID: "no-segments-video-id", videoID,
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"outro", "outro",
"shilling", "shilling",
@@ -125,7 +117,6 @@ describe("lockCategoriesRecords", () => {
], ],
reason: "new reason" reason: "new reason"
}; };
const expected = { const expected = {
submitted: [ submitted: [
"outro", "outro",
@@ -134,26 +125,20 @@ describe("lockCategoriesRecords", () => {
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST", .then(res => {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json)
})
.then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); assert.deepStrictEqual(res.data.submitted, expected.submitted);
assert.deepStrictEqual(data.submitted, expected.submitted);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to submit categories not in video with reason (sql check)", (done: Done) => { it("Should be able to submit categories not in video with reason (sql check)", (done) => {
const videoID = "no-segments-video-id-1";
const json = { const json = {
videoID: "no-segments-video-id-1", videoID,
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"outro", "outro",
"shilling", "shilling",
@@ -171,16 +156,10 @@ describe("lockCategoriesRecords", () => {
"intro" "intro"
]; ];
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json)
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ["no-segments-video-id-1"]) as LockCategory[]; const result = await checkLockCategories(videoID);
assert.strictEqual(result.length, 4); assert.strictEqual(result.length, 4);
const newRecordWithNewReason = result.filter(item => const newRecordWithNewReason = result.filter(item =>
expectedWithNewReason.includes(item.category) && item.reason === "new reason" expectedWithNewReason.includes(item.category) && item.reason === "new reason"
@@ -196,87 +175,64 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to submit categories with _ in the category", (done: Done) => { it("Should be able to submit categories with _ in the category", (done) => {
const json = { const json = {
videoID: "underscore", videoID: "underscore",
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"word_word", "word_word",
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ["underscore"]); const result = await checkLockCategories("underscore");
assert.strictEqual(result.length, 1); assert.strictEqual(result.length, 1);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to submit categories with upper and lower case in the category", (done: Done) => { it("Should be able to submit categories with upper and lower case in the category", (done) => {
const json = { const json = {
videoID: "bothCases", videoID: "bothCases",
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"wordWord", "wordWord",
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ["bothCases"]); const result = await checkLockCategories("bothCases");
assert.strictEqual(result.length, 1); assert.strictEqual(result.length, 1);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to submit categories with $ in the category", (done: Done) => { it("Should not be able to submit categories with $ in the category", (done) => {
const videoID = "specialChar";
const json = { const json = {
videoID: "specialChar", videoID,
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"word&word", "word&word",
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ["specialChar"]); const result = await checkLockCategories(videoID);
assert.strictEqual(result.length, 0); assert.strictEqual(result.length, 0);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 for missing params", (done: Done) => { it("Should return 400 for missing params", (done) => {
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, {})
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -284,19 +240,13 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 for no categories", (done: Done) => { it("Should return 400 for no categories", (done) => {
const json: any = { const json: any = {
videoID: "test", videoID: "test",
userID: "test", userID: "test",
categories: [], categories: [],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -304,20 +254,14 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 for no userID", (done: Done) => { it("Should return 400 for no userID", (done) => {
const json: any = { const json: any = {
videoID: "test", videoID: "test",
userID: null, userID: null,
categories: ["sponsor"], categories: ["sponsor"],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -325,20 +269,14 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 for no videoID", (done: Done) => { it("Should return 400 for no videoID", (done) => {
const json: any = { const json: any = {
videoID: null, videoID: null,
userID: "test", userID: "test",
categories: ["sponsor"], categories: ["sponsor"],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -346,20 +284,14 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 object categories", (done: Done) => { it("Should return 400 object categories", (done) => {
const json = { const json = {
videoID: "test", videoID: "test",
userID: "test", userID: "test",
categories: {}, categories: {},
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -367,20 +299,14 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 bad format categories", (done: Done) => { it("Should return 400 bad format categories", (done) => {
const json = { const json = {
videoID: "test", videoID: "test",
userID: "test", userID: "test",
categories: "sponsor", categories: "sponsor",
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -388,7 +314,7 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 403 if user is not VIP", (done: Done) => { it("Should return 403 if user is not VIP", (done) => {
const json = { const json = {
videoID: "test", videoID: "test",
userID: "test", userID: "test",
@@ -397,13 +323,7 @@ describe("lockCategoriesRecords", () => {
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
@@ -411,50 +331,40 @@ describe("lockCategoriesRecords", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to delete a lockCategories record", (done: Done) => { it("Should be able to delete a lockCategories record", (done) => {
const videoID = "delete-record";
const json = { const json = {
videoID: "delete-record", videoID,
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"sponsor", "sponsor",
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.delete(endpoint, { data: json })
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ["delete-record"]); const result = await checkLockCategories(videoID);
assert.strictEqual(result.length, 0); assert.strictEqual(result.length, 0);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to delete one lockCategories record without removing another", (done: Done) => { it("Should be able to delete one lockCategories record without removing another", (done) => {
const videoID = "delete-record-1";
const json = { const json = {
videoID: "delete-record-1", videoID,
userID: "VIPUser-lockCategories", userID: lockVIPUser,
categories: [ categories: [
"sponsor", "sponsor",
], ],
}; };
fetch(`${getbaseURL()}/api/lockCategories`, { client.delete(endpoint, { data: json })
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ["delete-record-1"]); const result = await checkLockCategories(videoID);
assert.strictEqual(result.length, 1); assert.strictEqual(result.length, 1);
done(); done();
}) })
@@ -466,48 +376,37 @@ describe("lockCategoriesRecords", () => {
* Submission tests in this file do not check database records, only status codes. * Submission tests in this file do not check database records, only status codes.
* To test the submission code properly see ./test/cases/postSkipSegments.js * To test the submission code properly see ./test/cases/postSkipSegments.js
*/ */
const lockedVideoID = "lockCategoryVideo";
it("Should not be able to submit a segment to a video with a lock-category record (single submission)", (done: Done) => { const testSubmitUser = "testman42-qwertyuiopasdfghjklzxcvbnm";
fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { it("Should not be able to submit a segment to a video with a lock-category record (single submission)", (done) => {
method: "POST", client.post(submitEndpoint, {
headers: { userID: testSubmitUser,
"Content-Type": "application/json", videoID: lockedVideoID,
},
body: JSON.stringify({
userID: "testman42-qwertyuiopasdfghjklzxcvbnm",
videoID: "lockCategoryVideo",
segments: [{ segments: [{
segment: [20, 40], segment: [20, 40],
category: "sponsor", category: "sponsor",
}], }],
}),
}) })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to submit segments to a video where any of the submissions with a no-segment record", (done: Done) => { it("Should not be able to submit segments to a video where any of the submissions with a no-segment record", (done) => {
fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { client.post(submitEndpoint, {
method: "POST", userID: testSubmitUser,
headers: { videoID: lockedVideoID,
"Content-Type": "application/json",
},
body: JSON.stringify({
userID: "testman42-qwertyuiopasdfghjklzxcvbnm",
videoID: "lockCategoryVideo",
segments: [{ segments: [{
segment: [20, 40], segment: [20, 40],
category: "sponsor", category: "sponsor",
}, { }, {
segment: [50, 60], segment: [50, 60],
category: "intro", category: "intro",
}], }]
},),
}) })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
}) })
@@ -515,51 +414,39 @@ describe("lockCategoriesRecords", () => {
}); });
it("Should be able to submit a segment to a video with a different no-segment record", (done: Done) => { it("Should be able to submit a segment to a video with a different no-segment record", (done) => {
fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { client.post(submitEndpoint, {
method: "POST", userID: testSubmitUser,
headers: { videoID: lockedVideoID,
"Content-Type": "application/json",
},
body: JSON.stringify({
userID: "testman42-qwertyuiopasdfghjklzxcvbnm",
videoID: "lockCategoryVideo",
segments: [{ segments: [{
segment: [20, 40], segment: [20, 40],
category: "intro", category: "intro",
}], }],
}),
}) })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to submit a segment to a video with no no-segment records", (done: Done) => { it("Should be able to submit a segment to a video with no no-segment records", (done) => {
fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { client.post(submitEndpoint, {
method: "POST", userID: testSubmitUser,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userID: "testman42-qwertyuiopasdfghjklzxcvbnm",
videoID: "normalVideo", videoID: "normalVideo",
segments: [{ segments: [{
segment: [20, 40], segment: [20, 40],
category: "intro", category: "intro",
}], }],
}),
}) })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should be able to get existing category lock", (done: Done) => { it("should be able to get existing category lock", (done) => {
const expected = { const expected = {
categories: [ categories: [
"sponsor", "sponsor",
@@ -568,11 +455,10 @@ describe("lockCategoriesRecords", () => {
"shilling" "shilling"
], ],
}; };
client.get(endpoint, { params: { videoID: "no-segments-video-id" } })
fetch(`${getbaseURL()}/api/lockCategories?videoID=` + `no-segments-video-id`) .then(res => {
.then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json(); const data = res.data;
assert.ok(stringDeepEquals(data.categories, expected.categories)); assert.ok(stringDeepEquals(data.categories, expected.categories));
done(); done();
}) })

View File

@@ -1,18 +1,20 @@
import fetch from "node-fetch";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {Done, getbaseURL, partialDeepEquals} from "../utils"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {getHash} from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const endpoint = "/api/getVideoSponsorTimes";
const getOldSponsorTime = (videoID: string) => client.get(endpoint, { params: { videoID } });
describe("getVideoSponsorTime (Old get method)", () => { describe("getVideoSponsorTime (Old get method)", () => {
before(async () => { before(async () => {
const insertSponsorTimes = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const insertSponsorTimes = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
await db.prepare("run", insertSponsorTimes, ["old-testtesttest", 1, 11, 2, "uuid-0", "testman", 0, 50, "sponsor", 0, getHash("old-testtesttest", 1)]); await db.prepare("run", insertSponsorTimes, ["oldGetSponsorTime0", 1, 11, 2, "oldGetSponsorTime00", "oldGetSponsorTimeUser", 0, 50, "sponsor", 0]);
await db.prepare("run", insertSponsorTimes, ["old-testtesttest,test", 1, 11, 2, "uuid-1", "testman", 0, 50, "sponsor", 0, getHash("old-testtesttest,test", 1)]); await db.prepare("run", insertSponsorTimes, ["oldGetSponsorTime1,test", 1, 11, 2, "oldGetSponsorTime01", "oldGetSponsorTimeUser", 0, 50, "sponsor", 0]);
}); });
it("Should be able to get a time", (done: Done) => { it("Should be able to get a time", (done) => {
fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest`) getOldSponsorTime("oldGetSponsorTime0")
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -20,8 +22,8 @@ describe("getVideoSponsorTime (Old get method)", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 404 if no segment found", (done: Done) => { it("Should return 404 if no segment found", (done) => {
fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=notarealvideo`) getOldSponsorTime("notarealvideo")
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -30,8 +32,8 @@ describe("getVideoSponsorTime (Old get method)", () => {
}); });
it("Should be possible to send unexpected query parameters", (done: Done) => { it("Should be possible to send unexpected query parameters", (done) => {
fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest&fakeparam=hello`) client.get(endpoint, { params: { videoID: "oldGetSponsorTime0", fakeparam: "hello" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -39,30 +41,28 @@ describe("getVideoSponsorTime (Old get method)", () => {
.catch(() => done("couldn't callendpoint")); .catch(() => done("couldn't callendpoint"));
}); });
it("Should be able send a comma in a query param", (done: Done) => { it("Should be able send a comma in a query param", (done) => {
fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest,test`) getOldSponsorTime("oldGetSponsorTime1,test")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
UUIDs: ["uuid-1"], UUIDs: ["oldGetSponsorTime01"],
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to get the correct time", (done: Done) => { it("Should be able to get the correct time", (done) => {
fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest`) getOldSponsorTime("oldGetSponsorTime0")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await res.json();
const expected = { const expected = {
sponsorTimes: [[1, 11]], sponsorTimes: [[1, 11]],
UUIDs: ["uuid-0"] UUIDs: ["oldGetSponsorTime00"]
}; };
assert.ok(partialDeepEquals(data, expected)); assert.ok(partialDeepEquals(res.data, expected));
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));

View File

@@ -1,15 +1,18 @@
import fetch from "node-fetch"; import { partialDeepEquals } from "../utils/partialDeepEquals";import { db } from "../../src/databases/databases";
import {Done, getbaseURL, partialDeepEquals} from "../utils";
import {db} from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const videoID1 = "dQw4w9WgXcQ";
const videoID2 = "dQw4w9WgXcE";
const userID = "testtesttesttesttesttesttesttesttest";
const endpoint = "/api/postVideoSponsorTimes";
describe("postVideoSponsorTime (Old submission method)", () => { describe("postVideoSponsorTime (Old submission method)", () => {
it("Should be able to submit a time (GET)", (done: Done) => { it("Should be able to submit a time (GET)", (done) => {
fetch(`${getbaseURL() client.get(endpoint, { params: { videoID: videoID1, startTime: 1, endTime: 10, userID } })
}/api/postVideoSponsorTimes?videoID=dQw4w9WgXcQ&startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest`)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcQ"]); const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID1]);
const expected = { const expected = {
startTime: 1, startTime: 1,
endTime: 10, endTime: 10,
@@ -21,17 +24,15 @@ describe("postVideoSponsorTime (Old submission method)", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to submit a time (POST)", (done: Done) => { it("Should be able to submit a time (POST)", (done) => {
fetch(`${getbaseURL() client({
}/api/postVideoSponsorTimes?videoID=dQw4w9WgXcE&startTime=1&endTime=11&userID=testtesttesttesttesttesttesttesttest`, { url: endpoint,
method: "POST", params: { videoID: videoID2, startTime: 1, endTime: 11, userID },
headers: { method: "post",
"Content-Type": "application/json",
},
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcE"]); const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID2]);
const expected = { const expected = {
startTime: 1, startTime: 1,
endTime: 11, endTime: 11,
@@ -43,10 +44,9 @@ describe("postVideoSponsorTime (Old submission method)", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 for missing params", (done: Done) => { it("Should return 400 for missing params", (done) => {
fetch(`${getbaseURL() client.post(endpoint, { params: { startTime: 1, endTime: 10, userID } })
}/api/postVideoSponsorTimes?startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest`) .then(res => {
.then(async res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })

View File

@@ -1,21 +1,22 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const VIPUser = "clearCacheVIP";
const regularUser = "regular-user";
const endpoint = "/api/clearCache";
const postClearCache = (userID: string, videoID: string) => client({ method: "post", url: endpoint, params: { userID, videoID } });
describe("postClearCache", () => { describe("postClearCache", () => {
before(async () => { before(async () => {
await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES ('${getHash("clearing-vip")}')`); await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES ('${getHash(VIPUser)}')`);
const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES'; const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", "views", "category", "shadowHidden") VALUES';
await db.prepare("run", `${startOfQuery}('clear-test', 0, 1, 2, 'clear-uuid', 'testman', 0, 50, 'sponsor', 0, '" + getHash("clear-test", 1) + "')`); await db.prepare("run", `${startOfQuery}('clear-test', 0, 1, 2, 'clear-uuid', 'testman', 0, 50, 'sponsor', 0)`);
}); });
it("Should be able to clear cache for existing video", (done: Done) => { it("Should be able to clear cache for existing video", (done) => {
fetch(`${getbaseURL() postClearCache(VIPUser, "clear-test")
}/api/clearCache?userID=clearing-vip&videoID=clear-test`, {
method: "POST"
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -23,11 +24,8 @@ describe("postClearCache", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to clear cache for nonexistent video", (done: Done) => { it("Should be able to clear cache for nonexistent video", (done) => {
fetch(`${getbaseURL() postClearCache(VIPUser, "dne-video")
}/api/clearCache?userID=clearing-vip&videoID=dne-video`, {
method: "POST"
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -35,36 +33,27 @@ describe("postClearCache", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get 403 as non-vip", (done: Done) => { it("Should get 403 as non-vip", (done) => {
fetch(`${getbaseURL() postClearCache(regularUser, "clear-test")
}/api/clearCache?userID=regular-user&videoID=clear-tes`, { .then(res => {
method: "POST"
})
.then(async res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should give 400 with missing videoID", (done: Done) => { it("Should give 400 with missing videoID", (done) => {
fetch(`${getbaseURL() client.post(endpoint, { params: { userID: VIPUser } })
}/api/clearCache?userID=clearing-vip`, { .then(res => {
method: "POST"
})
.then(async res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should give 400 with missing userID", (done: Done) => { it("Should give 400 with missing userID", (done) => {
fetch(`${getbaseURL() client.post(endpoint, { params: { videoID: "clear-test" } })
}/api/clearCache?userID=clearing-vip`, { .then(res => {
method: "POST"
})
.then(async res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })

View File

@@ -1,9 +1,8 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { IDatabase } from "../../src/databases/IDatabase"; import { IDatabase } from "../../src/databases/IDatabase";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) { async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) {
const votes = 0, const votes = 0,
@@ -32,9 +31,9 @@ async function dbSponsorTimesCompareExpect(db: IDatabase, videoId: string, expec
describe("postPurgeAllSegments", function () { describe("postPurgeAllSegments", function () {
const privateVipUserID = "VIPUser-purgeAll"; const privateVipUserID = "VIPUser-purgeAll";
const route = "/api/purgeAllSegments";
const vipUserID = getHash(privateVipUserID); const vipUserID = getHash(privateVipUserID);
const baseURL = getbaseURL(); const endpoint = "/api/purgeAllSegments";
const postSegmentShift = (videoID: string, userID: string) => client.post(endpoint, { videoID, userID });
before(async function () { before(async function () {
// startTime and endTime get set in beforeEach for consistency // startTime and endTime get set in beforeEach for consistency
@@ -46,35 +45,17 @@ describe("postPurgeAllSegments", function () {
await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES (?)`, [vipUserID]); await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES (?)`, [vipUserID]);
}); });
it("Reject non-VIP user", function (done: Done) { it("Reject non-VIP user", function (done) {
fetch(`${baseURL}${route}`, { postSegmentShift("vsegpurge01", "segshift_randomuser001")
method: "POST", .then(res => {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegpurge01",
userID: "segshift_randomuser001",
}),
})
.then(async res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Purge all segments success", function (done: Done) { it("Purge all segments success", function (done) {
fetch(`${baseURL}${route}`, { postSegmentShift("vsegpurge01", privateVipUserID)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegpurge01",
userID: privateVipUserID,
}),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(await dbSponsorTimesCompareExpect(db, "vsegpurge01", 1) || await dbSponsorTimesCompareExpect(db, "vseg-not-purged01", 0)); done(await dbSponsorTimesCompareExpect(db, "vsegpurge01", 1) || await dbSponsorTimesCompareExpect(db, "vseg-not-purged01", 0));
@@ -82,14 +63,9 @@ describe("postPurgeAllSegments", function () {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if missing body", function (done: Done) { it("Should return 400 if missing body", function (done) {
fetch(`${baseURL}${route}`, { client.post(endpoint, {})
method: "POST", .then(res => {
headers: {
"Content-Type": "application/json",
}
})
.then(async res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +1,28 @@
import fetch from "node-fetch"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {Done, getbaseURL, partialDeepEquals} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
describe("postWarning", () => { describe("postWarning", () => {
// constants
const endpoint = "/api/warnUser";
const getWarning = (userID: string) => db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [userID]);
before(async () => { before(async () => {
await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES (?)`, [getHash("warning-vip")]); await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES (?)`, [getHash("warning-vip")]);
}); });
it("Should be able to create warning if vip (exp 200)", (done: Done) => { it("Should be able to create warning if vip (exp 200)", (done) => {
const json = { const json = {
issuerUserID: "warning-vip", issuerUserID: "warning-vip",
userID: "warning-0", userID: "warning-0",
reason: "warning-reason-0" reason: "warning-reason-0"
}; };
fetch(`${getbaseURL()}/api/warnUser`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [json.userID]); const row = await getWarning(json.userID);
const expected = { const expected = {
enabled: 1, enabled: 1,
issuerUserID: getHash(json.issuerUserID), issuerUserID: getHash(json.issuerUserID),
@@ -36,22 +34,16 @@ describe("postWarning", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be not be able to create a duplicate warning if vip", (done: Done) => { it("Should be not be able to create a duplicate warning if vip", (done) => {
const json = { const json = {
issuerUserID: "warning-vip", issuerUserID: "warning-vip",
userID: "warning-0", userID: "warning-0",
}; };
fetch(`${getbaseURL()}/api/warnUser`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 409); assert.strictEqual(res.status, 409);
const row = await db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled FROM warnings WHERE "userID" = ?`, [json.userID]); const row = await getWarning(json.userID);
const expected = { const expected = {
enabled: 1, enabled: 1,
issuerUserID: getHash(json.issuerUserID), issuerUserID: getHash(json.issuerUserID),
@@ -62,23 +54,17 @@ describe("postWarning", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to remove warning if vip", (done: Done) => { it("Should be able to remove warning if vip", (done) => {
const json = { const json = {
issuerUserID: "warning-vip", issuerUserID: "warning-vip",
userID: "warning-0", userID: "warning-0",
enabled: false enabled: false
}; };
fetch(`${getbaseURL()}/api/warnUser`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled FROM warnings WHERE "userID" = ?`, [json.userID]); const row = await getWarning(json.userID);
const expected = { const expected = {
enabled: 0 enabled: 0
}; };
@@ -88,19 +74,13 @@ describe("postWarning", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to create warning if not vip (exp 403)", (done: Done) => { it("Should not be able to create warning if not vip (exp 403)", (done) => {
const json = { const json = {
issuerUserID: "warning-not-vip", issuerUserID: "warning-not-vip",
userID: "warning-1", userID: "warning-1",
}; };
fetch(`${getbaseURL()}/api/warnUser`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
@@ -108,37 +88,26 @@ describe("postWarning", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should return 400 if missing body", (done: Done) => { it("Should return 400 if missing body", (done) => {
fetch(`${getbaseURL()}/api/warnUser`, { client.post(endpoint, {})
method: "POST", .then(res => {
headers: {
"Content-Type": "application/json",
}
})
.then(async res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should re-enable disabled warning", (done: Done) => { it("Should re-enable disabled warning", (done) => {
const json = { const json = {
issuerUserID: "warning-vip", issuerUserID: "warning-vip",
userID: "warning-0", userID: "warning-0",
enabled: true enabled: true
}; };
fetch(`${getbaseURL()}/api/warnUser`, { client.post(endpoint, json)
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(json),
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = await db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled FROM warnings WHERE "userID" = ?`, [json.userID]); const data = await getWarning(json.userID);
const expected = { const expected = {
enabled: 1 enabled: 1
}; };

View File

@@ -4,117 +4,128 @@ import { UserID } from "../../src/types/user.model";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { getReputation, calculateReputationFromMetrics } from "../../src/utils/reputation"; import { getReputation, calculateReputationFromMetrics } from "../../src/utils/reputation";
const userIDLowSubmissions = "reputation-lowsubmissions" as UserID;
const userIDHighDownvotes = "reputation-highdownvotes" as UserID;
const userIDHighNonSelfDownvotes = "reputation-highnonselfdownvotes" as UserID;
const userIDNewSubmissions = "reputation-newsubmissions" as UserID;
const userIDLowSum = "reputation-lowsum" as UserID;
const userIDHighRepBeforeManualVote = "reputation-oldhighrep" as UserID;
const userIDHighRep = "reputation-highrep" as UserID;
const userIDHighRepAndLocked = "reputation-highlockedrep" as UserID;
const userIDHaveMostUpvotedInLockedVideo = "reputation-mostupvotedaslocked" as UserID;
describe("reputation", () => { describe("reputation", () => {
// constants
const userIDLowSubmissions = "reputation-lowsubmissions" as UserID;
const userHashLowSubmissions = getHash(userIDLowSubmissions);
const userIDHighDownvotes = "reputation-highdownvotes" as UserID;
const userHashHighDownvotes = getHash(userIDHighDownvotes);
const userIDHighNonSelfDownvotes = "reputation-highnonselfdownvotes" as UserID;
const userHashHighNonSelfDownvotes = getHash(userIDHighNonSelfDownvotes);
const userIDNewSubmissions = "reputation-newsubmissions" as UserID;
const userHashNewSubmissions = getHash(userIDNewSubmissions);
const userIDLowSum = "reputation-lowsum" as UserID;
const userHashLowSum = getHash(userIDLowSum);
const userIDHighRepBeforeManualVote = "reputation-oldhighrep" as UserID;
const userHashHighRepBeforeManualVote = getHash(userIDHighRepBeforeManualVote);
const userIDHighRep = "reputation-highrep" as UserID;
const userHashHighRep = getHash(userIDHighRep);
const userIDHighRepAndLocked = "reputation-highlockedrep" as UserID;
const userHashHighAndLocked = getHash(userIDHighRepAndLocked);
const userIDHaveMostUpvotedInLockedVideo = "reputation-mostupvotedaslocked" as UserID;
const userHashHaveMostUpvotedInLockedVideo = getHash(userIDHaveMostUpvotedInLockedVideo);
before(async function() { before(async function() {
this.timeout(5000); // this preparation takes longer then usual this.timeout(5000); // this preparation takes longer then usual
const videoID = "reputation-videoID"; const videoID = "reputation-videoID";
const videoID2 = "reputation-videoID-2"; const videoID2 = "reputation-videoID-2";
const sponsorTimesInsertQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "service", "videoDuration", "hidden", "shadowHidden", "hashedVideoID") VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'; const sponsorTimesInsertQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "hidden", "shadowHidden") VALUES(?,?,?,?,?,?,?,?,?,?,?,?)';
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-0-uuid-0", getHash(userIDLowSubmissions), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-0-uuid-0", userHashLowSubmissions, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-0-uuid-1", getHash(userIDLowSubmissions), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-0-uuid-1", userHashLowSubmissions, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 100, 0, "reputation-0-uuid-2", getHash(userIDLowSubmissions), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 100, 0, "reputation-0-uuid-2", userHashLowSubmissions, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-1-uuid-0", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-1-uuid-0", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-1", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-1", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-2", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-2", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-3", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-3", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-4", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-4", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-1-uuid-5", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-1-uuid-5", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-uuid-6", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-uuid-6", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-uuid-7", getHash(userIDHighDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-uuid-7", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
// First video is considered a normal downvote, second is considered a self-downvote (ie. they didn't resubmit to fix their downvote) // First video is considered a normal downvote, second is considered a self-downvote (ie. they didn't resubmit to fix their downvote)
await db.prepare("run", sponsorTimesInsertQuery, [`${videoID}A`, 1, 11, 2, 0, "reputation-1-1-uuid-0", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [`${videoID}A`, 1, 11, 2, 0, "reputation-1-1-uuid-0", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
// Different category, same video // Different category, same video
await db.prepare("run", sponsorTimesInsertQuery, [`${videoID}A`, 1, 11, -2, 0, "reputation-1-1-uuid-1", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "intro", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [`${videoID}A`, 1, 11, -2, 0, "reputation-1-1-uuid-1", userHashHighNonSelfDownvotes, 1606240000000, 50, "intro", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-2", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-2", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-3", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-3", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-4", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-4", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-1-1-uuid-5", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-1-1-uuid-5", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-6", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-6", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-7", getHash(userIDHighNonSelfDownvotes), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-7", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-0", getHash(userIDNewSubmissions), Date.now(), 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-0", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-1", getHash(userIDNewSubmissions), Date.now(), 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-1", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-2", getHash(userIDNewSubmissions), Date.now(), 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-2", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-3", getHash(userIDNewSubmissions), Date.now(), 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-3", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-4", getHash(userIDNewSubmissions), Date.now(), 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-4", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-2-uuid-5", getHash(userIDNewSubmissions), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-2-uuid-5", userHashNewSubmissions, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-2-uuid-6", getHash(userIDNewSubmissions), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-2-uuid-6", userHashNewSubmissions, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-2-uuid-7", getHash(userIDNewSubmissions), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-2-uuid-7", userHashNewSubmissions, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-3-uuid-0", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-3-uuid-0", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 1, 0, "reputation-3-uuid-1", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 1, 0, "reputation-3-uuid-1", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-2", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-2", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-3", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-3", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 1, 0, "reputation-3-uuid-4", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 1, 0, "reputation-3-uuid-4", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-3-uuid-5", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-3-uuid-5", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-6", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-6", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-7", getHash(userIDLowSum), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-7", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-0", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-0", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-1", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-1", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-2", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-2", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-3", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-3", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-4", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-4", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-4-uuid-5", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-4-uuid-5", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-4-uuid-6", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-4-uuid-6", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-4-uuid-7", getHash(userIDHighRepBeforeManualVote), 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-4-uuid-7", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-0", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-0", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-1", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-1", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-2", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-2", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-3", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-3", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-4", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-4", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-5-uuid-5", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-5-uuid-5", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-5-uuid-6", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-5-uuid-6", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-5-uuid-7", getHash(userIDHighRep), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-5-uuid-7", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-0", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-0", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-1", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-1", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-2", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-2", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-3", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-3", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-6-uuid-4", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-6-uuid-4", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-6-uuid-5", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-6-uuid-5", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-6-uuid-6", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-6-uuid-6", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-6-uuid-7", getHash(userIDHighRepAndLocked), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-6-uuid-7", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]);
//Record has most upvoted //Record has most upvoted
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 5, 0, "reputation-7-uuid-0", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 5, 0, "reputation-7-uuid-0", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 101, 0, "reputation-7-uuid-1", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "intro", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 101, 0, "reputation-7-uuid-1", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "intro", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID2, 1, 11, 5, 0, "reputation-7-uuid-8", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID2, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID2, 1, 11, 5, 0, "reputation-7-uuid-8", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID2, 1, 11, 0, 0, "reputation-7-uuid-9", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID2, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID2, 1, 11, 0, 0, "reputation-7-uuid-9", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
// other segments // other segments
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-2", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-2", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-3", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-3", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-4", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-4", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-7-uuid-5", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-7-uuid-5", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-7-uuid-6", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-7-uuid-6", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-7-uuid-7", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-7-uuid-7", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]);
// lock video // lock video
const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)';
await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-getLockCategories")]); await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-getLockCategories")]);
const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "hashedVideoID") VALUES (?, ?, ?, ?)'; const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category") VALUES (?, ?, ?)';
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "sponsor", getHash(videoID, 1)]); await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "sponsor"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "intro", getHash(videoID, 1)]); await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "intro"]);
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID2, "sponsor", getHash(videoID2, 1)]); await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID2, "sponsor"]);
}); });
it("user in grace period", async () => { it("user in grace period", async () => {
assert.strictEqual(await getReputation(getHash(userIDLowSubmissions)), 0); const data = await getReputation(getHash(userIDLowSubmissions));
assert.strictEqual(data, 0);
}); });
it("user with high downvote ratio", async () => { it("user with high downvote ratio", async () => {
@@ -128,9 +139,9 @@ describe("reputation", () => {
oldUpvotedSubmissions: 1, oldUpvotedSubmissions: 1,
mostUpvotedInLockedVideoSum: 0 mostUpvotedInLockedVideoSum: 0
}; };
const data = await getReputation(getHash(userIDHighDownvotes));
assert.strictEqual(await getReputation(getHash(userIDHighDownvotes)), calculateReputationFromMetrics(metrics)); assert.strictEqual(data, calculateReputationFromMetrics(metrics));
assert.strictEqual(await getReputation(getHash(userIDHighDownvotes)), -2.125); assert.strictEqual(data, -2.125);
}); });
it("user with high non self downvote ratio", async () => { it("user with high non self downvote ratio", async () => {
@@ -144,20 +155,21 @@ describe("reputation", () => {
oldUpvotedSubmissions: 1, oldUpvotedSubmissions: 1,
mostUpvotedInLockedVideoSum: 0 mostUpvotedInLockedVideoSum: 0
}; };
assert.strictEqual(await getReputation(getHash(userIDHighNonSelfDownvotes)), calculateReputationFromMetrics(metrics)); const data = await getReputation(userHashHighNonSelfDownvotes);
assert.strictEqual(await getReputation(getHash(userIDHighNonSelfDownvotes)), -1.6428571428571428); assert.strictEqual(data, calculateReputationFromMetrics(metrics));
assert.strictEqual(data, -1.6428571428571428);
}); });
it("user with mostly new submissions", async () => { it("user with mostly new submissions", async () => {
assert.strictEqual(await getReputation(getHash(userIDNewSubmissions)), 0); assert.strictEqual(await getReputation(userHashNewSubmissions), 0);
}); });
it("user with not enough vote sum", async () => { it("user with not enough vote sum", async () => {
assert.strictEqual(await getReputation(getHash(userIDLowSum)), 0); assert.strictEqual(await getReputation(userHashLowSum), 0);
}); });
it("user with lots of old votes (before autovote was disabled) ", async () => { it("user with lots of old votes (before autovote was disabled) ", async () => {
assert.strictEqual(await getReputation(getHash(userIDHighRepBeforeManualVote)), 0); assert.strictEqual(await getReputation(userHashHighRepBeforeManualVote), 0);
}); });
it("user with high reputation", async () => { it("user with high reputation", async () => {
@@ -171,8 +183,9 @@ describe("reputation", () => {
oldUpvotedSubmissions: 5, oldUpvotedSubmissions: 5,
mostUpvotedInLockedVideoSum: 0 mostUpvotedInLockedVideoSum: 0
}; };
assert.strictEqual(await getReputation(getHash(userIDHighRep)), calculateReputationFromMetrics(metrics)); const data = await getReputation(userHashHighRep);
assert.strictEqual(await getReputation(getHash(userIDHighRep)), 0.19310344827586207); assert.strictEqual(data, calculateReputationFromMetrics(metrics));
assert.strictEqual(data, 0.19310344827586207);
}); });
it("user with high reputation and locked segments", async () => { it("user with high reputation and locked segments", async () => {
@@ -186,8 +199,9 @@ describe("reputation", () => {
oldUpvotedSubmissions: 5, oldUpvotedSubmissions: 5,
mostUpvotedInLockedVideoSum: 0 mostUpvotedInLockedVideoSum: 0
}; };
assert.strictEqual(await getReputation(getHash(userIDHighRepAndLocked)), calculateReputationFromMetrics(metrics)); const data = await getReputation(userHashHighAndLocked);
assert.strictEqual(await getReputation(getHash(userIDHighRepAndLocked)), 1.793103448275862); assert.strictEqual(data, calculateReputationFromMetrics(metrics));
assert.strictEqual(data, 1.793103448275862);
}); });
it("user with most upvoted segments in locked video", async () => { it("user with most upvoted segments in locked video", async () => {
@@ -201,8 +215,9 @@ describe("reputation", () => {
oldUpvotedSubmissions: 6, oldUpvotedSubmissions: 6,
mostUpvotedInLockedVideoSum: 2 mostUpvotedInLockedVideoSum: 2
}; };
assert.strictEqual(await getReputation(getHash(userIDHaveMostUpvotedInLockedVideo)), calculateReputationFromMetrics(metrics)); const data = await getReputation(userHashHaveMostUpvotedInLockedVideo);
assert.strictEqual(await getReputation(getHash(userIDHaveMostUpvotedInLockedVideo)), 6.158620689655172); assert.strictEqual(data, calculateReputationFromMetrics(metrics));
assert.strictEqual(data, 6.158620689655172);
}); });
}); });

View File

@@ -1,10 +1,11 @@
import fetch from "node-fetch";
import {Done, getbaseURL} from "../utils";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { IDatabase } from "../../src/databases/IDatabase"; import { IDatabase } from "../../src/databases/IDatabase";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
describe("segmentShift", function () {
// functions
async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) { async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) {
const votes = 0, const votes = 0,
userID = 0, userID = 0,
@@ -36,11 +37,15 @@ async function dbSponsorTimesCompareExpect(db: IDatabase, expect: any): Promise<
} }
} }
} }
// constants
describe("segmentShift", function () {
const privateVipUserID = "VIPUser-segmentShift"; const privateVipUserID = "VIPUser-segmentShift";
const vipUserID = getHash(privateVipUserID); const vipUserID = getHash(privateVipUserID);
const baseURL = getbaseURL(); const endpoint = "/api/segmentShift";
const postSegmentShift = (data: Record<string, any>) => client({
method: "POST",
url: endpoint,
data,
});
before(async function () { before(async function () {
// startTime and endTime get set in beforeEach for consistency // startTime and endTime get set in beforeEach for consistency
@@ -59,232 +64,171 @@ describe("segmentShift", function () {
await dbSponsorTimesSetByUUID(db, "vsegshifttest01uuid04", 120, 140); await dbSponsorTimesSetByUUID(db, "vsegshifttest01uuid04", 120, 140);
}); });
it("Reject none VIP user", function (done: Done) { it("Reject non VIP user", (done) => {
fetch(`${baseURL}/api/segmentShift`, { postSegmentShift({
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegshift01", videoID: "vsegshift01",
userID: "segshift_randomuser001", userID: "segshift_randomuser001",
startTime: 20, startTime: 20,
endTime: 30, endTime: 30,
}),
}) })
.then(async res => { .then(res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Shift is outside segments", function (done: Done) { it("Shift is outside segments", (done) => {
fetch(`${baseURL}/api/segmentShift`, { postSegmentShift({
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegshift01", videoID: "vsegshift01",
userID: privateVipUserID, userID: privateVipUserID,
startTime: 20, startTime: 20,
endTime: 30, endTime: 30,
}),
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expect = [ const expect = [{
{
UUID: "vsegshifttest01uuid01", UUID: "vsegshifttest01uuid01",
startTime: 0, startTime: 0,
endTime: 10, endTime: 10,
}, }, {
{
UUID: "vsegshifttest01uuid02", UUID: "vsegshifttest01uuid02",
startTime: 50, startTime: 50,
endTime: 80, endTime: 80,
}, }, {
{
UUID: "vsegshifttest01uuid03", UUID: "vsegshifttest01uuid03",
startTime: 30, startTime: 30,
endTime: 35, endTime: 35,
}, }, {
{
UUID: "vsegshifttest01uuid04", UUID: "vsegshifttest01uuid04",
startTime: 110, startTime: 110,
endTime: 130, endTime: 130,
}, }];
];
done(await dbSponsorTimesCompareExpect(db, expect)); done(await dbSponsorTimesCompareExpect(db, expect));
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Shift is inside segment", function (done: Done) { it("Shift is inside segment", (done) => {
fetch(`${baseURL}/api/segmentShift`, { postSegmentShift({
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegshift01", videoID: "vsegshift01",
userID: privateVipUserID, userID: privateVipUserID,
startTime: 65, startTime: 65,
endTime: 75, endTime: 75,
}),
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expect = [ const expect = [{
{
UUID: "vsegshifttest01uuid01", UUID: "vsegshifttest01uuid01",
startTime: 0, startTime: 0,
endTime: 10, endTime: 10,
}, }, {
{
UUID: "vsegshifttest01uuid02", UUID: "vsegshifttest01uuid02",
startTime: 60, startTime: 60,
endTime: 80, endTime: 80,
}, }, {
{
UUID: "vsegshifttest01uuid03", UUID: "vsegshifttest01uuid03",
startTime: 40, startTime: 40,
endTime: 45, endTime: 45,
}, }, {
{
UUID: "vsegshifttest01uuid04", UUID: "vsegshifttest01uuid04",
startTime: 110, startTime: 110,
endTime: 130, endTime: 130,
}, }];
];
done(await dbSponsorTimesCompareExpect(db, expect)); done(await dbSponsorTimesCompareExpect(db, expect));
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Shift is overlaping startTime of segment", function (done: Done) { it("Shift is overlaping startTime of segment", (done) => {
fetch(`${baseURL}/api/segmentShift`, { postSegmentShift({
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegshift01", videoID: "vsegshift01",
userID: privateVipUserID, userID: privateVipUserID,
startTime: 32, startTime: 32,
endTime: 42, endTime: 42,
}),
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expect = [ const expect = [{
{
UUID: "vsegshifttest01uuid01", UUID: "vsegshifttest01uuid01",
startTime: 0, startTime: 0,
endTime: 10, endTime: 10,
}, }, {
{
UUID: "vsegshifttest01uuid02", UUID: "vsegshifttest01uuid02",
startTime: 50, startTime: 50,
endTime: 80, endTime: 80,
}, }, {
{
UUID: "vsegshifttest01uuid03", UUID: "vsegshifttest01uuid03",
startTime: 32, startTime: 32,
endTime: 35, endTime: 35,
}, }, {
{
UUID: "vsegshifttest01uuid04", UUID: "vsegshifttest01uuid04",
startTime: 110, startTime: 110,
endTime: 130, endTime: 130,
}, }];
];
done(await dbSponsorTimesCompareExpect(db, expect)); done(await dbSponsorTimesCompareExpect(db, expect));
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Shift is overlaping endTime of segment", function (done: Done) { it("Shift is overlaping endTime of segment", (done) => {
fetch(`${baseURL}/api/segmentShift`, { postSegmentShift({
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegshift01", videoID: "vsegshift01",
userID: privateVipUserID, userID: privateVipUserID,
startTime: 85, startTime: 85,
endTime: 95, endTime: 95,
}),
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expect = [ const expect = [{
{
UUID: "vsegshifttest01uuid01", UUID: "vsegshifttest01uuid01",
startTime: 0, startTime: 0,
endTime: 10, endTime: 10,
}, }, {
{
UUID: "vsegshifttest01uuid02", UUID: "vsegshifttest01uuid02",
startTime: 60, startTime: 60,
endTime: 85, endTime: 85,
}, }, {
{
UUID: "vsegshifttest01uuid03", UUID: "vsegshifttest01uuid03",
startTime: 40, startTime: 40,
endTime: 45, endTime: 45,
}, }, {
{
UUID: "vsegshifttest01uuid04", UUID: "vsegshifttest01uuid04",
startTime: 110, startTime: 110,
endTime: 130, endTime: 130,
}, }];
];
done(await dbSponsorTimesCompareExpect(db, expect)); done(await dbSponsorTimesCompareExpect(db, expect));
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Shift is overlaping segment", function (done: Done) { it("Shift is overlaping segment", (done) => {
fetch(`${baseURL}/api/segmentShift`, { postSegmentShift({
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
videoID: "vsegshift01", videoID: "vsegshift01",
userID: privateVipUserID, userID: privateVipUserID,
startTime: 35, startTime: 35,
endTime: 55, endTime: 55,
}),
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expect = [ const expect = [{
{
UUID: "vsegshifttest01uuid01", UUID: "vsegshifttest01uuid01",
startTime: 0, startTime: 0,
endTime: 10, endTime: 10,
}, }, {
{
UUID: "vsegshifttest01uuid02", UUID: "vsegshifttest01uuid02",
startTime: 40, startTime: 40,
endTime: 70, endTime: 70,
}, }, {
{
UUID: "vsegshifttest01uuid03", UUID: "vsegshifttest01uuid03",
startTime: 40, startTime: 40,
endTime: 45, endTime: 45,
removed: true, removed: true,
}, }, {
{
UUID: "vsegshifttest01uuid04", UUID: "vsegshifttest01uuid04",
startTime: 100, startTime: 100,
endTime: 120, endTime: 120,
}, }];
];
done(await dbSponsorTimesCompareExpect(db, expect)); done(await dbSponsorTimesCompareExpect(db, expect));
}) })
.catch(err => done(err)); .catch(err => done(err));

View File

@@ -1,8 +1,7 @@
import fetch from "node-fetch";
import { Done, getbaseURL } from "../utils";
import { db, privateDB } from "../../src/databases/databases"; import { db, privateDB } from "../../src/databases/databases";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const adminPrivateUserID = "testUserId"; const adminPrivateUserID = "testUserId";
const user00PrivateUserID = "setUsername_00"; const user00PrivateUserID = "setUsername_00";
@@ -35,14 +34,14 @@ async function getUsernameInfo(userID: string): Promise<{ userName: string, lock
return row; return row;
} }
async function addLogUserNameChange(userID: string, newUserName: string, oldUserName = "") { function addLogUserNameChange(userID: string, newUserName: string, oldUserName = "") {
privateDB.prepare("run", privateDB.prepare("run",
`INSERT INTO "userNameLogs"("userID", "newUserName", "oldUserName", "updatedAt", "updatedByAdmin") VALUES(?, ?, ?, ?, ?)`, `INSERT INTO "userNameLogs"("userID", "newUserName", "oldUserName", "updatedAt", "updatedByAdmin") VALUES(?, ?, ?, ?, ?)`,
[getHash(userID), newUserName, oldUserName, new Date().getTime(), + true] [getHash(userID), newUserName, oldUserName, new Date().getTime(), + true]
); );
} }
async function getLastLogUserNameChange(userID: string) { function getLastLogUserNameChange(userID: string) {
return privateDB.prepare("get", `SELECT * FROM "userNameLogs" WHERE "userID" = ? ORDER BY "updatedAt" DESC LIMIT 1`, [getHash(userID)]); return privateDB.prepare("get", `SELECT * FROM "userNameLogs" WHERE "userID" = ? ORDER BY "updatedAt" DESC LIMIT 1`, [getHash(userID)]);
} }
@@ -51,7 +50,7 @@ function wellFormatUserName(userName: string) {
return userName.replace(/[\u0000-\u001F\u007F-\u009F]/g, ""); return userName.replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
} }
async function testUserNameChangelog(userID: string, newUserName: string, oldUserName: string, byAdmin: boolean, done: Done) { async function testUserNameChangelog(userID: string, newUserName: string, oldUserName: string, byAdmin: boolean, done: Mocha.Done) {
const log = await getLastLogUserNameChange(userID); const log = await getLastLogUserNameChange(userID);
assert.strictEqual(newUserName, log.newUserName); assert.strictEqual(newUserName, log.newUserName);
assert.strictEqual(oldUserName, log.oldUserName); assert.strictEqual(oldUserName, log.oldUserName);
@@ -59,6 +58,26 @@ async function testUserNameChangelog(userID: string, newUserName: string, oldUse
return done(); return done();
} }
const endpoint = "/api/setUsername";
const postSetUserName = (userID: string, username: string) => client({
method: "POST",
url: endpoint,
params: {
userID,
username,
}
});
const postSetUserNameAdmin = (userID: string, username: string, adminUserID: string) => client({
method: "POST",
url: endpoint,
params: {
userID,
username,
adminUserID,
}
});
describe("setUsername", () => { describe("setUsername", () => {
before(async () => { before(async () => {
await addUsername(getHash(user01PrivateUserID), username01, 0); await addUsername(getHash(user01PrivateUserID), username01, 0);
@@ -70,157 +89,147 @@ describe("setUsername", () => {
await addUsername(getHash(user07PrivateUserID), username07, 1); await addUsername(getHash(user07PrivateUserID), username07, 1);
}); });
it("Should be able to set username that has never been set", (done: Done) => { it("Should be able to set username that has never been set", (done) => {
fetch(`${getbaseURL()}/api/setUsername?userID=${user00PrivateUserID}&username=${username00}`, { postSetUserName(user00PrivateUserID, username00)
method: "POST",
})
.then(async res => { .then(async res => {
console.log(res.data);
const usernameInfo = await getUsernameInfo(getHash(user00PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user00PrivateUserID));
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(usernameInfo.userName, username00); assert.strictEqual(usernameInfo.userName, username00);
assert.notStrictEqual(usernameInfo.locked, 1, "username should not be locked"); assert.notStrictEqual(usernameInfo.locked, 1, "username should not be locked");
done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it("Should return 200", (done: Done) => { it("Should return 200", (done) => {
fetch(`${getbaseURL()}/api/setUsername?userID=${user01PrivateUserID}&username=Changed%20Username`, { const username = "Changed%20Username";
method: "POST", postSetUserName(user01PrivateUserID, username)
}) .then(res => {
.then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
testUserNameChangelog(user01PrivateUserID, decodeURIComponent("Changed%20Username"), username01, false, done); testUserNameChangelog(user01PrivateUserID, username, username01, false, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it('Should return 400 for missing param "userID"', (done: Done) => { it('Should return 400 for missing param "userID"', (done) => {
fetch(`${getbaseURL()}/api/setUsername?username=MyUsername`, { client({
method: "POST", method: "POST",
url: endpoint,
data: {
userName: "MyUsername"
}
}) })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it('Should return 400 for missing param "username"', (done: Done) => { it('Should return 400 for missing param "username"', (done) => {
fetch(`${getbaseURL()}/api/setUsername?userID=test`, { client({
method: "POST", method: "POST",
url: endpoint,
data: {
userID: "test"
}
}) })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it('Should return 400 for "username" longer then 64 characters', (done: Done) => { it('Should return 400 for "username" longer then 64 characters', (done) => {
const username65 = "0000000000000000000000000000000000000000000000000000000000000000X"; const username65 = "0000000000000000000000000000000000000000000000000000000000000000X";
fetch(`${getbaseURL()}/api/setUsername?userID=test&username=${encodeURIComponent(username65)}`, { postSetUserName("test", username65)
method: "POST",
})
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it('Should not change username if it contains "discord"', (done: Done) => { it('Should not change username if it contains "discord"', (done) => {
const newUsername = "discord.me"; const newUsername = "discord.me";
fetch(`${getbaseURL()}/api/setUsername?userID=${user02PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { postSetUserName(user02PrivateUserID, newUsername)
method: "POST",
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const userNameInfo = await getUsernameInfo(getHash(user02PrivateUserID)); const userNameInfo = await getUsernameInfo(getHash(user02PrivateUserID));
assert.notStrictEqual(userNameInfo.userName, newUsername); assert.notStrictEqual(userNameInfo.userName, newUsername);
done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it("Should be able to change username", (done: Done) => { it("Should be able to change username", (done) => {
const newUsername = "newUsername"; const newUsername = "newUsername";
fetch(`${getbaseURL()}/api/setUsername?userID=${user03PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { postSetUserName(user03PrivateUserID, newUsername)
method: "POST",
})
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user03PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user03PrivateUserID));
assert.strictEqual(usernameInfo.userName, newUsername, "Username should change"); assert.strictEqual(usernameInfo.userName, newUsername, "Username should change");
assert.notStrictEqual(usernameInfo.locked, 1, "Username should not be locked"); assert.notStrictEqual(usernameInfo.locked, 1, "Username should not be locked");
testUserNameChangelog(user03PrivateUserID, newUsername, username03, false, done); testUserNameChangelog(user03PrivateUserID, newUsername, username03, false, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it("Should not be able to change locked username", (done: Done) => { it("Should not be able to change locked username", (done) => {
const newUsername = "newUsername"; const newUsername = "newUsername";
fetch(`${getbaseURL()}/api/setUsername?userID=${user04PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { postSetUserName(user04PrivateUserID, newUsername)
method: "POST",
})
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user04PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user04PrivateUserID));
assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not be changed"); assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not be changed");
assert.strictEqual(usernameInfo.locked, 1, "username should be locked"); assert.strictEqual(usernameInfo.locked, 1, "username should be locked");
done(); done();
}) })
.catch((err) => done(`couldn't call endpoint: ${err}`)); .catch((err) => done(err));
}); });
it("Should filter out unicode control characters", (done: Done) => { it("Should filter out unicode control characters", (done) => {
const newUsername = "This\nUsername+has\tInvalid+Characters"; const newUsername = "This\nUsername+has\tInvalid+Characters";
fetch(`${getbaseURL()}/api/setUsername?userID=${user05PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { postSetUserName(user05PrivateUserID, newUsername)
method: "POST",
})
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user05PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user05PrivateUserID));
assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not contain control characters"); assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not contain control characters");
testUserNameChangelog(user05PrivateUserID, wellFormatUserName(newUsername), username05, false, done); testUserNameChangelog(user05PrivateUserID, wellFormatUserName(newUsername), username05, false, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it("Incorrect adminUserID should return 403", (done: Done) => { it("Incorrect adminUserID should return 403", (done) => {
const newUsername = "New Username"; const newUsername = "New Username";
fetch(`${getbaseURL()}/api/setUsername?adminUserID=invalidAdminID&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { postSetUserNameAdmin(getHash(user06PrivateUserID), newUsername,"invalidAdminID")
method: "POST", .then(res => {
})
.then(async res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it("Admin should be able to change username", (done: Done) => { it("Admin should be able to change username", (done) => {
const newUsername = "New Username"; const newUsername = "New Username";
fetch(`${getbaseURL()}/api/setUsername?adminUserID=${adminPrivateUserID}&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { postSetUserNameAdmin(getHash(user06PrivateUserID), newUsername, adminPrivateUserID)
method: "POST",
})
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID));
assert.strictEqual(usernameInfo.userName, newUsername, "username should be changed"); assert.strictEqual(usernameInfo.userName, newUsername, "username should be changed");
assert.strictEqual(usernameInfo.locked, 1, "Username should be locked"); assert.strictEqual(usernameInfo.locked, 1, "Username should be locked");
testUserNameChangelog(user06PrivateUserID, newUsername, username06, true, done); testUserNameChangelog(user06PrivateUserID, newUsername, username06, true, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
it("Admin should be able to change locked username", (done: Done) => { it("Admin should be able to change locked username", (done) => {
const newUsername = "New Username"; const newUsername = "New Username";
fetch(`${getbaseURL()}/api/setUsername?adminUserID=${adminPrivateUserID}&userID=${getHash(user07PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { postSetUserNameAdmin(getHash(user07PrivateUserID), newUsername, adminPrivateUserID)
method: "POST",
})
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID));
assert.strictEqual(usernameInfo.userName, newUsername, "Username should be changed"); assert.strictEqual(usernameInfo.userName, newUsername, "Username should be changed");
assert.strictEqual(usernameInfo.locked, 1, "Username should be locked"); assert.strictEqual(usernameInfo.locked, 1, "Username should be locked");
testUserNameChangelog(user07PrivateUserID, newUsername, username07, true, done); testUserNameChangelog(user07PrivateUserID, newUsername, username07, true, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch((err) => done(err));
}); });
}); });

View File

@@ -1,10 +1,17 @@
import fetch from "node-fetch";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {Done, getbaseURL} from "../utils";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { Category } from "../../src/types/segments.model";
import { client } from "../utils/httpClient";
describe("shadowBanUser", () => { describe("shadowBanUser", () => {
const getShadowBan = (userID: string) => db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, [userID]);
const getShadowBanSegments = (userID: string, status: number) => db.prepare("all", `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, [userID, status]);
const getShadowBanSegmentCategory = (userID: string, status: number): Promise<{shadowHidden: number, category: Category}[]> => db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, [userID, status]);
const endpoint = "/api/shadowBanUser";
const VIPuserID = "shadow-ban-vip";
before(async () => { before(async () => {
const insertQuery = `INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "service", "videoDuration", "hidden", "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; const insertQuery = `INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "service", "videoDuration", "hidden", "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
await db.prepare("run", insertQuery, ["testtesttest", 1, 11, 2, 0, "shadow-1-uuid-0", "shadowBanned", 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash("testtesttest", 1)]); await db.prepare("run", insertQuery, ["testtesttest", 1, 11, 2, 0, "shadow-1-uuid-0", "shadowBanned", 0, 50, "sponsor", "YouTube", 100, 0, 0, getHash("testtesttest", 1)]);
@@ -24,19 +31,23 @@ describe("shadowBanUser", () => {
await db.prepare("run", `INSERT INTO "shadowBannedUsers" ("userID") VALUES(?)`, ["shadowBanned3"]); await db.prepare("run", `INSERT INTO "shadowBannedUsers" ("userID") VALUES(?)`, ["shadowBanned3"]);
await db.prepare("run", `INSERT INTO "shadowBannedUsers" ("userID") VALUES(?)`, ["shadowBanned4"]); await db.prepare("run", `INSERT INTO "shadowBannedUsers" ("userID") VALUES(?)`, ["shadowBanned4"]);
await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES(?)`, [getHash("shadow-ban-vip")]); await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES(?)`, [getHash(VIPuserID)]);
}); });
it("Should be able to ban user and hide submissions", (done) => {
it("Should be able to ban user and hide submissions", (done: Done) => { const userID = "shadowBanned";
fetch(`${getbaseURL() client({
}/api/shadowBanUser?userID=shadowBanned&adminUserID=shadow-ban-vip`, { method: "POST",
method: "POST" url: endpoint,
params: {
userID,
adminUserID: VIPuserID,
}
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const videoRow = await db.prepare("all", `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned", 1]); const videoRow = await getShadowBanSegments(userID, 1);
const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned"]); const shadowRow = await getShadowBan(userID);
assert.ok(shadowRow); assert.ok(shadowRow);
assert.strictEqual(videoRow.length, 3); assert.strictEqual(videoRow.length, 3);
done(); done();
@@ -44,15 +55,22 @@ describe("shadowBanUser", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to unban user without unhiding submissions", (done: Done) => { it("Should be able to unban user without unhiding submissions", (done) => {
fetch(`${getbaseURL() const userID = "shadowBanned";
}/api/shadowBanUser?userID=shadowBanned&adminUserID=shadow-ban-vip&enabled=false&unHideOldSubmissions=false`, { client({
method: "POST" method: "POST",
url: endpoint,
params: {
userID,
adminUserID: VIPuserID,
enabled: false,
unHideOldSubmissions: false,
}
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const videoRow = await db.prepare("all", `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned", 1]); const videoRow = await getShadowBanSegments(userID, 1);
const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned"]); const shadowRow = await getShadowBan(userID);
assert.ok(!shadowRow); assert.ok(!shadowRow);
assert.strictEqual(videoRow.length, 3); assert.strictEqual(videoRow.length, 3);
done(); done();
@@ -60,15 +78,21 @@ describe("shadowBanUser", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to ban user and hide submissions from only some categories", (done: Done) => { it("Should be able to ban user and hide submissions from only some categories", (done) => {
fetch(`${getbaseURL() const userID = "shadowBanned2";
}/api/shadowBanUser?userID=shadowBanned2&adminUserID=shadow-ban-vip&categories=["sponsor"]`, { client({
method: "POST" method: "POST",
url: endpoint,
params: {
userID,
adminUserID: VIPuserID,
categories: `["sponsor"]`
}
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const videoRow: {category: string, shadowHidden: number}[] = (await db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned2", 1])); const videoRow = await getShadowBanSegmentCategory(userID, 1);
const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned2"]); const shadowRow = await getShadowBan(userID);
assert.ok(shadowRow); assert.ok(shadowRow);
assert.strictEqual(videoRow.length, 2); assert.strictEqual(videoRow.length, 2);
assert.strictEqual(videoRow.filter((elem) => elem.category === "sponsor").length, 2); assert.strictEqual(videoRow.filter((elem) => elem.category === "sponsor").length, 2);
@@ -77,15 +101,21 @@ describe("shadowBanUser", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to unban user and unhide submissions", (done: Done) => { it("Should be able to unban user and unhide submissions", (done) => {
fetch(`${getbaseURL() const userID = "shadowBanned2";
}/api/shadowBanUser?userID=shadowBanned2&adminUserID=shadow-ban-vip&enabled=false`, { client({
method: "POST" method: "POST",
url: endpoint,
params: {
userID,
adminUserID: VIPuserID,
enabled: false,
}
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const videoRow = await db.prepare("all", `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned2", 1]); const videoRow = await getShadowBanSegments(userID, 1);
const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned2"]); const shadowRow = await getShadowBan(userID);
assert.ok(!shadowRow); assert.ok(!shadowRow);
assert.strictEqual(videoRow?.length, 0); assert.strictEqual(videoRow?.length, 0);
done(); done();
@@ -93,15 +123,22 @@ describe("shadowBanUser", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to unban user and unhide some submissions", (done: Done) => { it("Should be able to unban user and unhide some submissions", (done) => {
fetch(`${getbaseURL() const userID = "shadowBanned3";
}/api/shadowBanUser?userID=shadowBanned3&adminUserID=shadow-ban-vip&enabled=false&categories=["sponsor"]`, { client({
method: "POST" method: "POST",
url: endpoint,
params: {
userID,
adminUserID: VIPuserID,
enabled: false,
categories: `["sponsor"]`
}
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const videoRow = await db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned3", 1]); const videoRow = await getShadowBanSegmentCategory(userID, 1);
const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned3"]); const shadowRow = await getShadowBan(userID);
assert.ok(!shadowRow); assert.ok(!shadowRow);
assert.strictEqual(videoRow.length, 1); assert.strictEqual(videoRow.length, 1);
assert.strictEqual(videoRow[0].category, "intro"); assert.strictEqual(videoRow[0].category, "intro");
@@ -110,15 +147,23 @@ describe("shadowBanUser", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should get 409 when re-shadowbanning user", (done: Done) => { it("Should get 409 when re-shadowbanning user", (done) => {
fetch(`${getbaseURL() const userID = "shadowBanned4";
}/api/shadowBanUser?userID=shadowBanned4&adminUserID=shadow-ban-vip&enabled=true&categories=["sponsor"]&unHideOldSubmissions=false`, { client({
method: "POST" method: "POST",
url: endpoint,
params: {
userID,
adminUserID: VIPuserID,
enabled: true,
categories: `["sponsor"]`,
unHideOldSubmissions: false
}
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 409); assert.strictEqual(res.status, 409);
const videoRow = await db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned4", 0]); const videoRow = await getShadowBanSegmentCategory(userID, 0);
const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned4"]); const shadowRow = await getShadowBan(userID);
assert.ok(shadowRow); // ban still exists assert.ok(shadowRow); // ban still exists
assert.strictEqual(videoRow.length, 1); // videos should not be hidden assert.strictEqual(videoRow.length, 1); // videos should not be hidden
assert.strictEqual(videoRow[0].category, "sponsor"); assert.strictEqual(videoRow[0].category, "sponsor");
@@ -127,15 +172,23 @@ describe("shadowBanUser", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to re-shadowban user to hide old submissions", (done: Done) => { it("Should be able to re-shadowban user to hide old submissions", (done) => {
fetch(`${getbaseURL() const userID = "shadowBanned4";
}/api/shadowBanUser?userID=shadowBanned4&adminUserID=shadow-ban-vip&enabled=true&categories=["sponsor"]&unHideOldSubmissions=true`, { client({
method: "POST" method: "POST",
url: endpoint,
params: {
userID,
adminUserID: VIPuserID,
enabled: true,
categories: `["sponsor"]`,
unHideOldSubmissions: true
}
}) })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const videoRow = await db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned4", 1]); const videoRow = await getShadowBanSegmentCategory(userID, 1);
const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned4"]); const shadowRow = await getShadowBan(userID);
assert.ok(shadowRow); // ban still exists assert.ok(shadowRow); // ban still exists
assert.strictEqual(videoRow.length, 1); // videos should be hidden assert.strictEqual(videoRow.length, 1); // videos should be hidden
assert.strictEqual(videoRow[0].category, "sponsor"); assert.strictEqual(videoRow[0].category, "sponsor");
@@ -143,5 +196,4 @@ describe("shadowBanUser", () => {
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
}); });

View File

@@ -1,9 +1,8 @@
import assert from "assert"; import assert from "assert";
import { partialDeepEquals } from "../utils/partialDeepEquals";
import { partialDeepEquals } from "../utils";
describe("Test utils ", () => { describe("Test utils ", () => {
it("objectContain", async () => { it("objectContain", () => {
assert(partialDeepEquals( assert(partialDeepEquals(
{ {
name: "John Wick", name: "John Wick",

View File

@@ -1,10 +1,21 @@
import fetch from "node-fetch";
import * as utils from "../utils";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { client } from "../utils/httpClient";
import assert from "assert"; import assert from "assert";
describe("unBan", () => { describe("unBan", () => {
const endpoint = "/api/shadowBanUser";
const VIPuser = "VIPUser-unBan";
const postUnBan = (userID: string, adminUserID: string, enabled: boolean) => client({
url: endpoint,
method: "POST",
params: {
userID,
adminUserID,
enabled
}
});
const videoIDUnBanCheck = (videoID: string, userID: string, status: number) => db.prepare("all", 'SELECT * FROM "sponsorTimes" WHERE "videoID" = ? AND "userID" = ? AND "shadowHidden" = ?', [videoID, userID, status]);
before(async () => { before(async () => {
const insertShadowBannedUserQuery = 'INSERT INTO "shadowBannedUsers" VALUES(?)'; const insertShadowBannedUserQuery = 'INSERT INTO "shadowBannedUsers" VALUES(?)';
await db.prepare("run", insertShadowBannedUserQuery, ["testMan-unBan"]); await db.prepare("run", insertShadowBannedUserQuery, ["testMan-unBan"]);
@@ -12,10 +23,10 @@ describe("unBan", () => {
await db.prepare("run", insertShadowBannedUserQuery, ["testEntity-unBan"]); await db.prepare("run", insertShadowBannedUserQuery, ["testEntity-unBan"]);
const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)';
await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-unBan")]); await db.prepare("run", insertVipUserQuery, [getHash(VIPuser)]);
const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category") VALUES(?, ?, ?)'; const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category") VALUES(?, ?, ?)';
await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-unBan"), "unBan-videoID-1", "sponsor"]); await db.prepare("run", insertLockCategoryQuery, [getHash(VIPuser), "unBan-videoID-1", "sponsor"]);
const insertSponsorTimeQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const insertSponsorTimeQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
await db.prepare("run", insertSponsorTimeQuery, ["unBan-videoID-0", 1, 11, 2, "unBan-uuid-0", "testMan-unBan", 0, 50, "sponsor", 1, getHash("unBan-videoID-0", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["unBan-videoID-0", 1, 11, 2, "unBan-uuid-0", "testMan-unBan", 0, 50, "sponsor", 1, getHash("unBan-videoID-0", 1)]);
@@ -25,16 +36,11 @@ describe("unBan", () => {
}); });
it("Should be able to unban a user and re-enable shadow banned segments", (done) => { it("Should be able to unban a user and re-enable shadow banned segments", (done) => {
fetch(`${utils.getbaseURL() const userID = "testMan-unBan";
}/api/shadowBanUser?userID=testMan-unBan&adminUserID=VIPUser-unBan&enabled=false`, { postUnBan(userID, VIPuser, false)
method: "POST",
headers: {
"Content-Type": "application/json",
},
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "sponsorTimes" WHERE "videoID" = ? AND "userID" = ? AND "shadowHidden" = ?', ["unBan-videoID-0", "testMan-unBan", 1]); const result = await videoIDUnBanCheck("unBan-videoID-0", userID, 1);
assert.strictEqual(result.length, 0); assert.strictEqual(result.length, 0);
done(); done();
}) })
@@ -42,16 +48,11 @@ describe("unBan", () => {
}); });
it("Should be able to unban a user and re-enable shadow banned segments without lockCategories entrys", (done) => { it("Should be able to unban a user and re-enable shadow banned segments without lockCategories entrys", (done) => {
fetch(`${utils.getbaseURL() const userID = "testWoman-unBan";
}/api/shadowBanUser?userID=testWoman-unBan&adminUserID=VIPUser-unBan&enabled=false`, { postUnBan(userID, VIPuser, false)
method: "POST",
headers: {
"Content-Type": "application/json",
},
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "sponsorTimes" WHERE "videoID" = ? AND "userID" = ? AND "shadowHidden" = ?', ["unBan-videoID-1", "testWoman-unBan", 1]); const result = await videoIDUnBanCheck("unBan-videoID-1", userID, 1);
assert.strictEqual(result.length, 1); assert.strictEqual(result.length, 1);
done(); done();
}) })
@@ -59,16 +60,11 @@ describe("unBan", () => {
}); });
it("Should be able to unban a user and re-enable shadow banned segments with a mix of lockCategories entrys", (done) => { it("Should be able to unban a user and re-enable shadow banned segments with a mix of lockCategories entrys", (done) => {
fetch(`${utils.getbaseURL() const userID = "testEntity-unBan";
}/api/shadowBanUser?userID=testEntity-unBan&adminUserID=VIPUser-unBan&enabled=false`, { postUnBan(userID, VIPuser, false)
method: "POST",
headers: {
"Content-Type": "application/json",
},
})
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const result = await db.prepare("all", 'SELECT * FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?', ["testEntity-unBan", 1]); const result = await db.prepare("all", 'SELECT * FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?', [userID, 1]);
assert.strictEqual(result.length, 1); assert.strictEqual(result.length, 1);
done(); done();
}) })

View File

@@ -1,16 +1,17 @@
import fetch from "node-fetch";
import { config } from "../../src/config"; import { config } from "../../src/config";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {Done, getbaseURL} from "../utils";
import { getHash } from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { ImportMock } from "ts-mock-imports"; import { ImportMock } from "ts-mock-imports";
import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi";
import { YouTubeApiMock } from "../youtubeMock"; import { YouTubeApiMock } from "../youtubeMock";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient";
const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI");
const sinonStub = mockManager.mock("listVideos"); const sinonStub = mockManager.mock("listVideos");
sinonStub.callsFake(YouTubeApiMock.listVideos); sinonStub.callsFake(YouTubeApiMock.listVideos);
const vipUser = "VIPUser";
const randomID2 = "randomID2";
describe("voteOnSponsorTime", () => { describe("voteOnSponsorTime", () => {
before(async () => { before(async () => {
@@ -21,31 +22,31 @@ describe("voteOnSponsorTime", () => {
const MILLISECONDS_IN_HOUR = 3600000; const MILLISECONDS_IN_HOUR = 3600000;
const warningExpireTime = MILLISECONDS_IN_HOUR * config.hoursAfterWarningExpires; const warningExpireTime = MILLISECONDS_IN_HOUR * config.hoursAfterWarningExpires;
const insertSponsorTimeQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", "views", "category", "shadowHidden", "hidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; const insertSponsorTimeQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", "views", "category", "shadowHidden", "hidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest", 1, 11, 2, "vote-uuid-0", "testman", 0, 50, "sponsor", 0, 0, getHash("vote-testtesttest", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest", 1, 11, 2, "vote-uuid-0", "testman", 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest2", 1, 11, 2, "vote-uuid-1", "testman", 0, 50, "sponsor", 0, 0, getHash("vote-testtesttest2", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest2", 1, 11, 2, "vote-uuid-1", "testman", 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest2", 1, 11, 10, "vote-uuid-1.5", "testman", 0, 50, "outro", 0, 0, getHash("vote-testtesttest2", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest2", 1, 11, 10, "vote-uuid-1.5", "testman", 0, 50, "outro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest2", 1, 11, 10, "vote-uuid-1.6", "testman", 0, 50, "interaction", 0, 0, getHash("vote-testtesttest2", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest2", 1, 11, 10, "vote-uuid-1.6", "testman", 0, 50, "interaction", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest3", 20, 33, 10, "vote-uuid-2", "testman", 0, 50, "intro", 0, 0, getHash("vote-testtesttest3", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest3", 20, 33, 10, "vote-uuid-2", "testman", 0, 50, "intro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest,test", 1, 11, 100, "vote-uuid-3", "testman", 0, 50, "sponsor", 0, 0, getHash("vote-testtesttest,test", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest,test", 1, 11, 100, "vote-uuid-3", "testman", 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-test3", 1, 11, 2, "vote-uuid-4", "testman", 0, 50, "sponsor", 0, 0, getHash("vote-test3", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-test3", 1, 11, 2, "vote-uuid-4", "testman", 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-test3", 7, 22, -3, "vote-uuid-5", "testman", 0, 50, "intro", 0, 0, getHash("vote-test3", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-test3", 7, 22, -3, "vote-uuid-5", "testman", 0, 50, "intro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-test3", 7, 22, -3, "vote-uuid-5_1", "testman", 0, 50, "intro", 0, 0, getHash("vote-test3", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-test3", 7, 22, -3, "vote-uuid-5_1", "testman", 0, 50, "intro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-multiple", 1, 11, 2, "vote-uuid-6", "testman", 0, 50, "intro", 0, 0, getHash("vote-multiple", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-multiple", 1, 11, 2, "vote-uuid-6", "testman", 0, 50, "intro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-multiple", 20, 33, 2, "vote-uuid-7", "testman", 0, 50, "intro", 0, 0, getHash("vote-multiple", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-multiple", 20, 33, 2, "vote-uuid-7", "testman", 0, 50, "intro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter", 1, 11, 2, "vote-uuid-8", getHash("randomID"), 0, 50, "sponsor", 0, 0, getHash("voter-submitter", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter", 1, 11, 2, "vote-uuid-8", getHash("randomID"), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter2", 1, 11, 2, "vote-uuid-9", getHash("randomID2"), 0, 50, "sponsor", 0, 0, getHash("voter-submitter2", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter2", 1, 11, 2, "vote-uuid-9", getHash(randomID2), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter2", 1, 11, 2, "vote-uuid-10", getHash("randomID3"), 0, 50, "sponsor", 0, 0, getHash("voter-submitter2", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter2", 1, 11, 2, "vote-uuid-10", getHash("randomID3"), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter2", 1, 11, 2, "vote-uuid-11", getHash("randomID4"), 0, 50, "sponsor", 0, 0, getHash("voter-submitter2", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["voter-submitter2", 1, 11, 2, "vote-uuid-11", getHash("randomID4"), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["own-submission-video", 1, 11, 500, "own-submission-uuid", getHash("own-submission-id"), 0, 50, "sponsor", 0, 0, getHash("own-submission-video", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["own-submission-video", 1, 11, 500, "own-submission-uuid", getHash("own-submission-id"), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["not-own-submission-video", 1, 11, 500, "not-own-submission-uuid", getHash("somebody-else-id"), 0, 50, "sponsor", 0, 0, getHash("not-own-submission-video", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["not-own-submission-video", 1, 11, 500, "not-own-submission-uuid", getHash("somebody-else-id"), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["incorrect-category", 1, 11, 500, "incorrect-category", getHash("somebody-else-id"), 0, 50, "sponsor", 0, 0, getHash("incorrect-category", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["incorrect-category", 1, 11, 500, "incorrect-category", getHash("somebody-else-id"), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["incorrect-category-change", 1, 11, 500, "incorrect-category-change", getHash("somebody-else-id"), 0, 50, "sponsor", 0, 0, getHash("incorrect-category-change", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["incorrect-category-change", 1, 11, 500, "incorrect-category-change", getHash("somebody-else-id"), 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest", 1, 11, 2, "warnvote-uuid-0", "testman", 0, 50, "sponsor", 0, 0, getHash("vote-testtesttest", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["vote-testtesttest", 1, 11, 2, "warnvote-uuid-0", "testman", 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["no-sponsor-segments-video", 1, 11, 2, "no-sponsor-segments-uuid-0", "no-sponsor-segments", 0, 50, "sponsor", 0, 0, getHash("no-sponsor-segments-video", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["no-sponsor-segments-video", 1, 11, 2, "no-sponsor-segments-uuid-0", "no-sponsor-segments", 0, 50, "sponsor", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["no-sponsor-segments-video", 1, 11, 2, "no-sponsor-segments-uuid-1", "no-sponsor-segments", 0, 50, "intro", 0, 0, getHash("no-sponsor-segments-video", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["no-sponsor-segments-video", 1, 11, 2, "no-sponsor-segments-uuid-1", "no-sponsor-segments", 0, 50, "intro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["segment-locking-video", 1, 11, 2, "segment-locking-uuid-1", "segment-locking-user", 0, 50, "intro", 0, 0, getHash("segment-locking-video", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["segment-locking-video", 1, 11, 2, "segment-locking-uuid-1", "segment-locking-user", 0, 50, "intro", 0, 0]);
await db.prepare("run", insertSponsorTimeQuery, ["segment-hidden-video", 1, 11, 2, "segment-hidden-uuid-1", "segment-hidden-user", 0, 50, "intro", 0, 1, getHash("segment-locking-video", 1)]); await db.prepare("run", insertSponsorTimeQuery, ["segment-hidden-video", 1, 11, 2, "segment-hidden-uuid-1", "segment-hidden-user", 0, 50, "intro", 0, 1]);
const insertWarningQuery = 'INSERT INTO "warnings" ("userID", "issueTime", "issuerUserID", "enabled") VALUES(?, ?, ?, ?)'; const insertWarningQuery = 'INSERT INTO "warnings" ("userID", "issueTime", "issuerUserID", "enabled") VALUES(?, ?, ?, ?)';
await db.prepare("run", insertWarningQuery, [warnUser01Hash, now, warnVip01Hash, 1]); await db.prepare("run", insertWarningQuery, [warnUser01Hash, now, warnVip01Hash, 1]);
@@ -58,127 +59,150 @@ describe("voteOnSponsorTime", () => {
await db.prepare("run", insertWarningQuery, [warnUser02Hash, (now - (warningExpireTime + 2000)), warnVip01Hash, 1]); await db.prepare("run", insertWarningQuery, [warnUser02Hash, (now - (warningExpireTime + 2000)), warnVip01Hash, 1]);
await db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash("VIPUser")]); await db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash(vipUser)]);
await db.prepare("run", 'INSERT INTO "shadowBannedUsers" ("userID") VALUES (?)', [getHash("randomID4")]); await db.prepare("run", 'INSERT INTO "shadowBannedUsers" ("userID") VALUES (?)', [getHash("randomID4")]);
await db.prepare("run", 'INSERT INTO "lockCategories" ("videoID", "userID", "category") VALUES (?, ?, ?)', ["no-sponsor-segments-video", "someUser", "sponsor"]); await db.prepare("run", 'INSERT INTO "lockCategories" ("videoID", "userID", "category") VALUES (?, ?, ?)', ["no-sponsor-segments-video", "someUser", "sponsor"]);
}); });
// constants
const endpoint = "/api/voteOnSponsorTime";
const postVote = (userID: string, UUID: string, type: number) => client({
method: "POST",
url: endpoint,
params: {
userID,
UUID,
type
}
});
const postVoteCategory = (userID: string, UUID: string, category: string) => client({
method: "POST",
url: endpoint,
params: {
userID,
UUID,
category
}
});
it("Should be able to upvote a segment", (done: Done) => { const getSegmentVotes = (UUID: string) => db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
fetch(`${getbaseURL() const getSegmentCategory = (UUID: string) => db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
}/api/voteOnSponsorTime?userID=randomID&UUID=vote-uuid-0&type=1`)
it("Should be able to upvote a segment", (done) => {
const UUID = "vote-uuid-0";
postVote("randomID", UUID, 1)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-0"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 3); assert.strictEqual(row.votes, 3);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to downvote a segment", (done: Done) => { it("Should be able to downvote a segment", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-2";
}/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=0`) postVote(randomID2, UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]); const row = await getSegmentVotes(UUID);
assert.ok(row.votes < 10); assert.ok(row.votes < 10);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to downvote the same segment when voting from a different user on the same IP", (done: Done) => { it("Should not be able to downvote the same segment when voting from a different user on the same IP", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-2";
}/api/voteOnSponsorTime?userID=randomID3&UUID=vote-uuid-2&type=0`) postVote("randomID3", UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 9); assert.strictEqual(row.votes, 9);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to downvote a segment if the user is shadow banned", (done: Done) => { it("Should not be able to downvote a segment if the user is shadow banned", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-1.6";
}/api/voteOnSponsorTime?userID=randomID4&UUID=vote-uuid-1.6&type=0`) postVote("randomID4", UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1.6"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 10); assert.strictEqual(row.votes, 10);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to upvote a segment if the user hasn't submitted yet", (done: Done) => { it("Should not be able to upvote a segment if the user hasn't submitted yet", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-1";
}/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1&type=1`) postVote("hasNotSubmittedID", UUID, 1)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 2); assert.strictEqual(row.votes, 2);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to downvote a segment if the user hasn't submitted yet", (done: Done) => { it("Should not be able to downvote a segment if the user hasn't submitted yet", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-1.5";
}/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1.5&type=0`) postVote("hasNotSubmittedID", UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1.5"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 10); assert.strictEqual(row.votes, 10);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("VIP should be able to completely downvote a segment", (done: Done) => { it("VIP should be able to completely downvote a segment", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-3";
}/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-3&type=0`) postVote(vipUser, UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-3"]); const row = await getSegmentVotes(UUID);
assert.ok(row.votes <= -2); assert.ok(row.votes <= -2);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should be able to completely downvote your own segment", (done: Done) => { it("should be able to completely downvote your own segment", (done) => {
fetch(`${getbaseURL() const UUID = "own-submission-uuid";
}/api/voteOnSponsorTime?userID=own-submission-id&UUID=own-submission-uuid&type=0`) postVote("own-submission-id", UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["own-submission-uuid"]); const row = await getSegmentVotes(UUID);
assert.ok(row.votes <= -2); assert.ok(row.votes <= -2);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("should not be able to completely downvote somebody elses segment", (done: Done) => { it("should not be able to completely downvote somebody elses segment", (done) => {
fetch(`${getbaseURL() const UUID = "not-own-submission-uuid";
}/api/voteOnSponsorTime?userID=randomID2&UUID=not-own-submission-uuid&type=0`) postVote(randomID2, UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["not-own-submission-uuid"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 499); assert.strictEqual(row.votes, 499);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to vote for a category and it should add your vote to the database", (done: Done) => { it("Should be able to vote for a category and it should add your vote to the database", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-4";
}/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=intro`) postVoteCategory(randomID2, UUID, "intro")
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-4"]); const row = await getSegmentCategory(UUID);
const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, ["vote-uuid-4"]); const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, [UUID]);
assert.strictEqual(row.category, "sponsor"); assert.strictEqual(row.category, "sponsor");
assert.strictEqual(categoryRows.length, 2); assert.strictEqual(categoryRows.length, 2);
assert.strictEqual(categoryRows[0].votes, 1); assert.strictEqual(categoryRows[0].votes, 1);
@@ -190,37 +214,37 @@ describe("voteOnSponsorTime", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not able to change to an invalid category", (done: Done) => { it("Should not able to change to an invalid category", (done) => {
fetch(`${getbaseURL() const UUID = "incorrect-category";
}/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=fakecategory`) postVoteCategory(randomID2, UUID, "fakecategory")
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category"]); const row = await getSegmentCategory(UUID);
assert.strictEqual(row.category, "sponsor"); assert.strictEqual(row.category, "sponsor");
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not able to change to highlight category", (done: Done) => { it("Should not able to change to highlight category", (done) => {
fetch(`${getbaseURL() const UUID = "incorrect-category";
}/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=highlight`) postVoteCategory(randomID2, UUID, "highlight")
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category"]); const row = await getSegmentCategory(UUID);
assert.strictEqual(row.category, "sponsor"); assert.strictEqual(row.category, "sponsor");
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to change your vote for a category and it should add your vote to the database", (done: Done) => { it("Should be able to change your vote for a category and it should add your vote to the database", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-4";
}/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=outro`) postVoteCategory(randomID2, UUID, "outro")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200, "Status code should be 200");
const submissionRow = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-4"]); const submissionRow = await getSegmentCategory(UUID);
const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, ["vote-uuid-4"]); const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, [UUID]);
let introVotes = 0; let introVotes = 0;
let outroVotes = 0; let outroVotes = 0;
let sponsorVotes = 0; let sponsorVotes = 0;
@@ -235,20 +259,17 @@ describe("voteOnSponsorTime", () => {
assert.strictEqual(outroVotes, 1); assert.strictEqual(outroVotes, 1);
assert.strictEqual(sponsorVotes, 1); assert.strictEqual(sponsorVotes, 1);
done(); done();
} else {
done(`Status code was ${res.status}`);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to change your vote to an invalid category", (done: Done) => { it("Should not be able to change your vote to an invalid category", (done) => {
const vote = (inputCat: string, assertCat: string, callback: Done) => { const UUID = "incorrect-category-change";
fetch(`${getbaseURL() const vote = (inputCat: string, assertCat: string, callback: Mocha.Done) => {
}/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category-change&category=${inputCat}`) postVoteCategory(randomID2, UUID, inputCat)
.then(async () => { .then(async () => {
const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category-change"]); const row = await getSegmentCategory(UUID);
assert.strictEqual(row.category, assertCat); assert.strictEqual(row.category, assertCat);
callback(); callback();
}) })
@@ -260,13 +281,13 @@ describe("voteOnSponsorTime", () => {
}); });
it("VIP should be able to vote for a category and it should immediately change", (done: Done) => { it("VIP should be able to vote for a category and it should immediately change", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-5";
}/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&category=outro`) postVoteCategory(vipUser, UUID, "outro")
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await getSegmentCategory(UUID);
const row2 = await db.prepare("get", `SELECT votes FROM "categoryVotes" WHERE "UUID" = ? and category = ?`, ["vote-uuid-5", "outro"]); const row2 = await db.prepare("get", `SELECT votes FROM "categoryVotes" WHERE "UUID" = ? and category = ?`, [UUID, "outro"]);
assert.strictEqual(row.category, "outro"); assert.strictEqual(row.category, "outro");
assert.strictEqual(row2.votes, 500); assert.strictEqual(row2.votes, 500);
done(); done();
@@ -274,160 +295,161 @@ describe("voteOnSponsorTime", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Submitter should be able to vote for a category and it should immediately change", (done: Done) => { it("Submitter should be able to vote for a category and it should immediately change", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-5_1";
}/api/voteOnSponsorTime?userID=testman&UUID=vote-uuid-5_1&category=outro`) postVoteCategory("testman", UUID, "outro")
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await getSegmentCategory("vote-uuid-5");
assert.strictEqual(row.category, "outro"); assert.strictEqual(row.category, "outro");
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to category-vote on an invalid UUID submission", (done: Done) => { it("Should not be able to category-vote on an invalid UUID submission", (done) => {
fetch(`${getbaseURL() const UUID = "invalid-uuid";
}/api/voteOnSponsorTime?userID=randomID3&UUID=invalid-uuid&category=intro`) postVoteCategory("randomID3", UUID, "intro")
.then(async res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it('Non-VIP should not be able to upvote "dead" submission', (done: Done) => { it('Non-VIP should not be able to upvote "dead" submission', (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-5";
}/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=1`) postVote(randomID2, UUID, 1)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, -3); assert.strictEqual(row.votes, -3);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it('Non-VIP should not be able to downvote "dead" submission', (done: Done) => { it('Non-VIP should not be able to downvote "dead" submission', (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-5";
}/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=0`) postVote(randomID2, UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, -3); assert.strictEqual(row.votes, -3);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it('VIP should be able to upvote "dead" submission', (done: Done) => { it('VIP should be able to upvote "dead" submission', (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-5";
}/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&type=1`) postVote(vipUser, UUID, 1)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await getSegmentVotes(UUID);
assert.ok(row.votes > -3); assert.ok(row.votes > -3);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to upvote a segment (Too many warning)", (done: Done) => { it("Should not be able to upvote a segment (Too many warning)", (done) => {
fetch(`${getbaseURL() const UUID = "warnvote-uuid-0";
}/api/voteOnSponsorTime?userID=warn-voteuser01&UUID=warnvote-uuid-0&type=1`) postVote("warn-voteuser01", UUID, 1)
.then(async res => { .then(res => {
assert.strictEqual(res.status, 403); assert.strictEqual(res.status, 403);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Non-VIP should not be able to downvote on a segment with no-segments category", (done: Done) => { it("Non-VIP should not be able to downvote on a segment with no-segments category", (done) => {
fetch(`${getbaseURL() const UUID = "no-sponsor-segments-uuid-0";
}/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=0`) postVote("randomID", UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["no-sponsor-segments-uuid-0"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 2); assert.strictEqual(row.votes, 2);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Non-VIP should be able to upvote on a segment with no-segments category", (done: Done) => { it("Non-VIP should be able to upvote on a segment with no-segments category", (done) => {
fetch(`${getbaseURL() const UUID = "no-sponsor-segments-uuid-0";
}/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=1`) postVote("randomID", UUID, 1)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["no-sponsor-segments-uuid-0"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 3); assert.strictEqual(row.votes, 3);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Non-VIP should not be able to category vote on a segment with no-segments category", (done: Done) => { it("Non-VIP should not be able to category vote on a segment with no-segments category", (done) => {
fetch(`${getbaseURL() const UUID = "no-sponsor-segments-uuid-0";
}/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&category=outro`) postVoteCategory("randomID", UUID, "outro")
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["no-sponsor-segments-uuid-0"]); const row = await getSegmentCategory(UUID);
assert.strictEqual(row.category, "sponsor"); assert.strictEqual(row.category, "sponsor");
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("VIP upvote should lock segment", (done: Done) => { it("VIP upvote should lock segment", (done) => {
fetch(`${getbaseURL() const UUID = "segment-locking-uuid-1";
}/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=1`) postVote(vipUser, UUID, 1)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-locking-uuid-1"]); const row = await db.prepare("get", `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
assert.strictEqual(row.locked, 1); assert.strictEqual(row.locked, 1);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("VIP downvote should unlock segment", (done: Done) => { it("VIP downvote should unlock segment", (done) => {
fetch(`${getbaseURL() const UUID = "segment-locking-uuid-1";
}/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=0`) postVote(vipUser, UUID, 0)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-locking-uuid-1"]); const row = await db.prepare("get", `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
assert.strictEqual(row.locked, 0); assert.strictEqual(row.locked, 0);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("VIP upvote should unhide segment", (done: Done) => { it("VIP upvote should unhide segment", (done) => {
fetch(`${getbaseURL() const UUID = "segment-hidden-uuid-1";
}/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-hidden-uuid-1&type=1`) postVote(vipUser, UUID, 1)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "hidden" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-hidden-uuid-1"]); const row = await db.prepare("get", `SELECT "hidden" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
assert.strictEqual(row.hidden, 0); assert.strictEqual(row.hidden, 0);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should be able to undo-vote a segment", (done: Done) => { it("Should be able to undo-vote a segment", (done) => {
fetch(`${getbaseURL() const UUID = "vote-uuid-2";
}/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=20`) postVote(randomID2, UUID, 20)
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]); const row = await getSegmentVotes(UUID);
assert.strictEqual(row.votes, 10); assert.strictEqual(row.votes, 10);
done(); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to vote with type 10", (done: Done) => { it("Should not be able to vote with type 10", (done) => {
fetch(`${getbaseURL() }/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=10`) const UUID = "segment-locking-uuid-1";
postVote(vipUser, UUID, 10)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -435,8 +457,9 @@ describe("voteOnSponsorTime", () => {
.catch(err => done(err)); .catch(err => done(err));
}); });
it("Should not be able to vote with type 11", (done: Done) => { it("Should not be able to vote with type 11", (done) => {
fetch(`${getbaseURL() }/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=11`) const UUID = "segment-locking-uuid-1";
postVote(vipUser, UUID, 11)
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();

9
test/utils/httpClient.ts Normal file
View File

@@ -0,0 +1,9 @@
import { config } from "../../src/config";
import axios, { AxiosRequestConfig } from "axios";
const defaultConfig: AxiosRequestConfig = {
baseURL: `http://localhost:${config.port}`,
validateStatus: (status) => status < 500
};
export const client = axios.create(defaultConfig);

View File

@@ -1,19 +1,10 @@
import {config} from "../src/config"; import { Logger } from "../../src/utils/logger";
import { Logger } from "../src/utils/logger";
export function getbaseURL(): string { function printActualExpected(actual: Record<string, any>, expected: Record<string, any>): void {
return `http://localhost:${config.port}`; Logger.error(`Actual: ${JSON.stringify(actual)}`);
Logger.error(`Expected: ${JSON.stringify(expected)}`);
} }
/**
* Duplicated from Mocha types. TypeScript doesn't infer that type by itself for some reason.
*/
export type Done = (err?: any) => void;
/**
*
* Check object contains expected properties
*/
export const partialDeepEquals = (actual: Record<string, any>, expected: Record<string, any>, print = true): boolean => { export const partialDeepEquals = (actual: Record<string, any>, expected: Record<string, any>, print = true): boolean => {
// loop over key, value of expected // loop over key, value of expected
for (const [ key, value ] of Object.entries(expected)) { for (const [ key, value ] of Object.entries(expected)) {
@@ -21,20 +12,13 @@ export const partialDeepEquals = (actual: Record<string, any>, expected: Record<
if (Array.isArray(value) || typeof value === "object") { if (Array.isArray(value) || typeof value === "object") {
if (!partialDeepEquals(actual?.[key], value, false)) { if (!partialDeepEquals(actual?.[key], value, false)) {
if (print) printActualExpected(actual, expected); if (print) printActualExpected(actual, expected);
return false; return false;
} }
} }
else if (actual?.[key] !== value) { else if (actual?.[key] !== value) {
if (print) printActualExpected(actual, expected); if (print) printActualExpected(actual, expected);
return false; return false;
} }
} }
return true; return true;
}; };
function printActualExpected(actual: Record<string, any>, expected: Record<string, any>): void {
Logger.error(`Actual: ${JSON.stringify(actual)}`);
Logger.error(`Expected: ${JSON.stringify(expected)}`);
}

View File

@@ -1,6 +1,7 @@
import { APIVideoData, APIVideoInfo } from "../src/types/youtubeApi.model"; import { APIVideoData, APIVideoInfo } from "../src/types/youtubeApi.model";
export class YouTubeApiMock { export class YouTubeApiMock {
// eslint-disable-next-line require-await
static async listVideos(videoID: string): Promise<APIVideoInfo> { static async listVideos(videoID: string): Promise<APIVideoInfo> {
const obj = { const obj = {
id: videoID id: videoID