From 6e55f9d979df997d68a8353f5ab625ec3323b758 Mon Sep 17 00:00:00 2001 From: Michael C Date: Sat, 4 Sep 2021 19:23:43 -0400 Subject: [PATCH 01/14] everything up to purgeAllSegments --- test/cases/downvoteSegmentArchiveJob.ts | 115 ++++++++++---------- test/cases/getHash.ts | 24 ++-- test/cases/getIsUserVIP.ts | 8 +- test/cases/getLockCategories.ts | 19 ++-- test/cases/getLockCategoriesByHash.ts | 50 +++++---- test/cases/getSavedTimeForUser.ts | 12 +- test/cases/getSearchSegments.ts | 44 ++++---- test/cases/getSegmentInfo.ts | 70 ++++++------ test/cases/getSkipSegments.ts | 139 ++++++++++++------------ test/cases/getSkipSegmentsByHash.ts | 36 +++--- test/cases/getUserInfo.ts | 23 ++-- test/cases/lockCategoriesRecords.ts | 36 +++--- test/cases/oldGetSponsorTime.ts | 19 ++-- test/cases/oldSubmitSponsorTimes.ts | 14 ++- test/cases/postClearCache.ts | 19 ++-- 15 files changed, 320 insertions(+), 308 deletions(-) diff --git a/test/cases/downvoteSegmentArchiveJob.ts b/test/cases/downvoteSegmentArchiveJob.ts index f98ea0d..07e6342 100644 --- a/test/cases/downvoteSegmentArchiveJob.ts +++ b/test/cases/downvoteSegmentArchiveJob.ts @@ -1,40 +1,43 @@ -import assert from "assert"; - +import {strictEqual, ok} from "assert"; import { db } from "../../src/databases/databases"; -import { getHash } from "../../src/utils/getHash"; import { archiveDownvoteSegment } from "../../src/cronjob/downvoteSegmentArchiveJob"; 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 = [ - ["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)], - ["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)], - ["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)], - ["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)], - ["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, "dsaj00", "dsajUser", dec2021, 0, 0, 0], + ["dsajVideo0", 0, 0, 2, 0, "dsaj01", "dsajUser", dec2021, 0, 0, 0], + ["dsajVideo0", 0, 0, 2, 0, "dsaj02", "dsajUser", dec2021, 0, 0, 0], + ["dsajVideo0", 0, 0, 2, 0, "dsaj03", "dsajUser", dec2021, 0, 0, 0], + ["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)], - ["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, 2, 0, "dsaj10", "dsajUser", dec2021, 0, 0, 0], + ["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)], - ["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, 2, 0, "dsaj20", "dsajUser", dec2021, 0, 0, 0], + ["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)], - ["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, 2, 1, "dsaj30", "dsajUser", dec2021, 0, 0, 0], + ["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)], - ["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)], - ["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)], - ["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, "dsaj50", "dsajUser", dec2021, 0, 0, 0], + ["dsajVideo5", 0, 0, -1, 0, "dsaj51", "dsajUser", dec2021, 0, 0, 0], + ["dsajVideo5", 0, 0, -2, 0, "dsaj52", "dsajUser", nov2021, 0, 0, 0], + ["dsajVideo5", 0, 0, 2, 0, "dsaj53", "dsajUser", dec2021, 0, 0, 0] ]; describe("downvoteSegmentArchiveJob", () => { 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) { - await db.prepare("run", query, records[i]); + for (const record of records) { + await db.prepare("run", query, record); } return; @@ -42,7 +45,7 @@ describe("downvoteSegmentArchiveJob", () => { 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; - 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 () => { @@ -50,12 +53,10 @@ describe("downvoteSegmentArchiveJob", () => { await db.prepare("run", 'DELETE FROM "archivedSponsorTimes"'); }); - const getArchivedSegment = (): Promise => { - return db.prepare("all", 'SELECT * FROM "archivedSponsorTimes"'); - }; + const getArchivedSegment = (): Promise => db.prepare("all", 'SELECT * FROM "archivedSponsorTimes"'); - const getSegmentsInMainTable = (dayLimit: number, voteLimit: number, now: number): Promise => { - return db.prepare( + const getSegmentsInMainTable = (dayLimit: number, voteLimit: number, now: number): Promise => + db.prepare( "all", 'SELECT * FROM "sponsorTimes" WHERE "votes" < ? AND (? - "timeSubmitted") > ?', [ @@ -64,109 +65,107 @@ describe("downvoteSegmentArchiveJob", () => { dayLimit * 86400000, ] ); - }; - const countSegmentInMainTable = (): Promise => { - return db.prepare( + const countSegmentInMainTable = (): Promise => + db.prepare( "get", 'SELECT COUNT(*) as count FROM "sponsorTimes"' ).then(res => res.count); - }; it("Should archive all records match", async () => { const dayLimit = 20; const voteLimit = 0; - const time = new Date("December 17, 2022").getTime(); + const time = dec2022; 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 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 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 - 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 () => { const dayLimit = 20; const voteLimit = -1; - const time = new Date("December 17, 2022").getTime(); + const time = dec2022; const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); - assert.strictEqual(res, 0, ""); + strictEqual(res, 0, ""); // check segments in archived table 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 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 - 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 () => { const dayLimit = 30; const voteLimit = -2; - const time = new Date("December 17, 2021").getTime(); + const time = dec2021; const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); - assert.strictEqual(res, 0, ""); + strictEqual(res, 0, ""); // check segments in archived table 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 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 - 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 () => { const dayLimit = 300; const voteLimit = -2; - const time = new Date("December 17, 2022").getTime(); + const time = dec2022; const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); - assert.strictEqual(res, 0, ""); + strictEqual(res, 0, ""); // check segments in archived table 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 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 - 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 () => { const dayLimit = 300; const voteLimit = -2; - const time = new Date("December 17, 2021").getTime(); + const time = dec2021; const res = await archiveDownvoteSegment(dayLimit, voteLimit, time); - assert.strictEqual(res, 0, ""); + strictEqual(res, 0, ""); // check segments in archived table 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 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 - 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"); }); }); diff --git a/test/cases/getHash.ts b/test/cases/getHash.ts index 27df1e9..9643351 100644 --- a/test/cases/getHash.ts +++ b/test/cases/getHash.ts @@ -1,33 +1,33 @@ import {getHash} from "../../src/utils/getHash"; -import assert from "assert"; +import {notStrictEqual, strictEqual} from "assert"; describe("getHash", () => { it("Should not output the input string", () => { - assert(getHash("test") !== "test"); - assert(getHash("test", -1) !== "test"); - assert(getHash("test", 0) !== "test"); - assert(getHash("test", null) !== "test"); + notStrictEqual(getHash("test"), "test"); + notStrictEqual(getHash("test", -1), "test"); + notStrictEqual(getHash("test", 0), "test"); + notStrictEqual(getHash("test", null), "test"); }); 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", () => { - assert.strictEqual(getHash("vid", 1), "1ff838dc6ca9680d88455341118157d59a055fe6d0e3870f9c002847bebe4663"); + strictEqual(getHash("vid", 1), "1ff838dc6ca9680d88455341118157d59a055fe6d0e3870f9c002847bebe4663"); }); it("Should take a variable number of passes", () => { - assert.strictEqual(getHash("test", 1), "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"); - assert.strictEqual(getHash("test", 2), "7b3d979ca8330a94fa7e9e1b466d8b99e0bcdea1ec90596c0dcc8d7ef6b4300c"); - assert.strictEqual(getHash("test", 3), "5b24f7aa99f1e1da5698a4f91ae0f4b45651a1b625c61ed669dd25ff5b937972"); + strictEqual(getHash("test", 1), "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"); + strictEqual(getHash("test", 2), "7b3d979ca8330a94fa7e9e1b466d8b99e0bcdea1ec90596c0dcc8d7ef6b4300c"); + strictEqual(getHash("test", 3), "5b24f7aa99f1e1da5698a4f91ae0f4b45651a1b625c61ed669dd25ff5b937972"); }); 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", () => { - assert.strictEqual(getHash("test", -1), ""); + strictEqual(getHash("test", -1), ""); }); }); diff --git a/test/cases/getIsUserVIP.ts b/test/cases/getIsUserVIP.ts index 81ee48a..c8bce73 100644 --- a/test/cases/getIsUserVIP.ts +++ b/test/cases/getIsUserVIP.ts @@ -6,11 +6,11 @@ import assert from "assert"; describe("getIsUserVIP", () => { before((done: Done) => { - db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash("supertestman")]).then(done); + db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash("isUserVIPVIP")]).then(done); }); it("Should be able to get a 200", (done: Done) => { - fetch(`${getbaseURL()}/api/isUserVIP?userID=supertestman`) + fetch(`${getbaseURL()}/api/isUserVIP?userID=isUserVIPVIP`) .then(res => { assert.strictEqual(res.status, 200, "response should be 200"); done(); @@ -29,7 +29,7 @@ describe("getIsUserVIP", () => { }); it("Should say a VIP is a VIP", (done: Done) => { - fetch(`${getbaseURL()}/api/isUserVIP?userID=supertestman`) + fetch(`${getbaseURL()}/api/isUserVIP?userID=isUserVIPVIP`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -40,7 +40,7 @@ describe("getIsUserVIP", () => { }); it("Should say a normal user is not a VIP", (done: Done) => { - fetch(`${getbaseURL()}/api/isUserVIP?userID=regulartestman`) + fetch(`${getbaseURL()}/api/isUserVIP?userID=isUserVIPNormal`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); diff --git a/test/cases/getLockCategories.ts b/test/cases/getLockCategories.ts index 3db2733..55830f0 100644 --- a/test/cases/getLockCategories.ts +++ b/test/cases/getLockCategories.ts @@ -8,25 +8,24 @@ import assert from "assert"; describe("getLockCategories", () => { before(async () => { 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 (?, ?, ?, ?)'; - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLock-1", "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", "sponsor", "1-short"]); + 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 () => { const version = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value; - if (version > 20) return; - else return `Version isn't greater than 20. Version is ${version}`; + assert.ok(version > 20, `Version isn't greater than 20. Version is ${version}`); }); it("Should be able to get multiple locks", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock-1`) + fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock1`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -44,7 +43,7 @@ describe("getLockCategories", () => { }); it("Should be able to get single locks", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock-2`) + fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock2`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -61,7 +60,7 @@ describe("getLockCategories", () => { }); it("should return 404 if no lock exists", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock-0`) + fetch(`${getbaseURL()}/api/lockCategories?videoID=getLockNull`) .then(res => { assert.strictEqual(res.status, 404); done(); diff --git a/test/cases/getLockCategoriesByHash.ts b/test/cases/getLockCategoriesByHash.ts index d6ce0b2..cc7e605 100644 --- a/test/cases/getLockCategoriesByHash.ts +++ b/test/cases/getLockCategoriesByHash.ts @@ -4,22 +4,24 @@ import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; +const fakeHash = "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35"; + describe("getLockCategoriesByHash", () => { before(async () => { 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 (?, ?, ?, ?, ?)'; - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLockHash-1", "sponsor", "1-reason-short", "67a654898fda3a5541774aea345796c7709982bb6018cb08d22a18eeddccc1d0"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "getLockHash-1", "interaction", "1-reason-longer", "67a654898fda3a5541774aea345796c7709982bb6018cb08d22a18eeddccc1d0"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "getLockHash1", "sponsor", "1-reason-short", getHash("getLockHash1", 1)]); + 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("VIPUser-getLockCategories"), "fakehash-2", "intro", "fake2-longer-reason", "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), "fakehash-2", "preview", "fake2-short", "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "fakehash-1", "outro", "fake1-reason", fakeHash]); + await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "fakehash-2", "intro", "fake2-longer-reason", fakeHash]); + await db.prepare("run", insertLockCategoryQuery, [getHash("getLockCategoriesHashVIP"), "fakehash-2", "preview", "fake2-short", fakeHash]); }); it("Database should be greater or equal to version 20", async () => { @@ -30,13 +32,15 @@ describe("getLockCategoriesByHash", () => { }); it("Should be able to get multiple locks in one object", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/67a65`) + const videoID = "getLockHash1"; + const hash = getHash(videoID, 1); + fetch(`${getbaseURL()}/api/lockCategories/${hash.substring(0,4)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "getLockHash-1", - hash: getHash("getLockHash-1", 1), + videoID, + hash, categories: [ "sponsor", "interaction" @@ -50,13 +54,15 @@ describe("getLockCategoriesByHash", () => { }); it("Should be able to get single lock", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/dff09`) + const videoID = "getLockHash2"; + const hash = getHash(videoID, 1); + fetch(`${getbaseURL()}/api/lockCategories/${hash.substring(0,6)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "getLockHash-2", - hash: getHash("getLockHash-2", 1), + videoID, + hash, categories: [ "preview" ], @@ -69,13 +75,15 @@ describe("getLockCategoriesByHash", () => { }); it("Should be able to get by half full hash", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/bf1b122fd5630e0df8626d00c4a95c58`) + const videoID = "getLockHash3"; + const hash = getHash(videoID, 1); + fetch(`${getbaseURL()}/api/lockCategories/${hash.substring(0,32)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "getLockHash-3", - hash: getHash("getLockHash-3", 1), + videoID, + hash, categories: [ "nonmusic" ], @@ -88,20 +96,20 @@ describe("getLockCategoriesByHash", () => { }); it("Should be able to get multiple by similar hash with multiple categories", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/b05a`) + fetch(`${getbaseURL()}/api/lockCategories/${fakeHash.substring(0,5)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ videoID: "fakehash-1", - hash: "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35", + hash: fakeHash, categories: [ "outro" ], reason: "fake1-reason" }, { videoID: "fakehash-2", - hash: "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450", + hash: fakeHash, categories: [ "intro", "preview" @@ -142,7 +150,7 @@ describe("getLockCategoriesByHash", () => { }); it("should return 400 if full hash sent", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35`) + fetch(`${getbaseURL()}/api/lockCategories/${fakeHash}`) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getSavedTimeForUser.ts b/test/cases/getSavedTimeForUser.ts index 2a0f49f..c41bef4 100644 --- a/test/cases/getSavedTimeForUser.ts +++ b/test/cases/getSavedTimeForUser.ts @@ -2,18 +2,18 @@ import fetch from "node-fetch"; import {Done, getbaseURL} from "../utils"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; -import assert from "assert"; +import {deepStrictEqual} from "assert"; describe("getSavedTimeForUser", () => { before(async () => { - const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES'; - await db.prepare("run", `${startOfQuery}(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ["getSavedTimeForUser", 1, 11, 2, "abc1239999", getHash("testman"), 0, 50, "sponsor", 0, getHash("getSavedTimeForUser", 0)]); + const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", "views", "shadowHidden") VALUES'; + await db.prepare("run", `${startOfQuery}(?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ["getSavedTimeForUser", 1, 11, 2, "gstfu0", getHash("getSavedTimeForUserUser"), 0, 50, 0]); return; }); it("Should be able to get a 200", (done: Done) => { - fetch(`${getbaseURL()}/api/getSavedTimeForUser?userID=testman`) + fetch(`${getbaseURL()}/api/getSavedTimeForUser?userID=getSavedTimeForUserUser`) .then(async res => { const data = await res.json(); // (end-start)*minute * views @@ -21,7 +21,7 @@ describe("getSavedTimeForUser", () => { const expected = { timeSaved: savedMinutes }; - assert.deepStrictEqual(data, expected); + deepStrictEqual(data, expected); done(); }) .catch((err) => done(err)); diff --git a/test/cases/getSearchSegments.ts b/test/cases/getSearchSegments.ts index 8f3aa61..61cabae 100644 --- a/test/cases/getSearchSegments.ts +++ b/test/cases/getSearchSegments.ts @@ -6,29 +6,29 @@ import assert from "assert"; describe("getSearchSegments", () => { before(async () => { 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, 2, -2, 0, 0, 0, 0, 2, "search-downvote", "testman", "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, 4, 1, 0, 0, 1, 0, 4, "search-hidden", "testman", "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, ["searchTest1", 1, 2, 1, 5, 0, 0, 0, 6, "search-lowview", "testman", "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, ["searchTest2", 1, 4, -1, 0, 0, 0, 0, 8, "search-lowvote", "testman", "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, 4, 50, 0, 0, 0, 0, 10, "search-highvote", "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", "searchTestUser", "selfpromo", "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", "searchTestUser", "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", "searchTestUser", "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", "searchTestUser", "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", "searchTestUser", "sponsor", "skip"]); // 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, 5, 1, 0, 0, 0, 0, 11, "search-page1-2", "testman", "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, 7, 1, 0, 0, 0, 0, 13, "search-page1-4", "testman", "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, 9, 1, 0, 0, 0, 0, 15, "search-page1-6", "testman", "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, 11, 1, 0, 0, 0, 0, 17, "search-page1-8", "testman", "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, 13, 1, 0, 0, 0, 0, 19, "search-page1-10", "testman", "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, 15, 1, 0, 0, 0, 0, 21, "search-page2-2", "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", "searchTestUser", "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", "searchTestUser", "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", "searchTestUser", "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", "searchTestUser", "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", "searchTestUser", "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", "searchTestUser", "sponsor", "skip"]); return; }); diff --git a/test/cases/getSegmentInfo.ts b/test/cases/getSegmentInfo.ts index b398665..f3e069b 100644 --- a/test/cases/getSegmentInfo.ts +++ b/test/cases/getSegmentInfo.ts @@ -1,7 +1,6 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; import {Done, getbaseURL, partialDeepEquals} from "../utils"; -import {getHash} from "../../src/utils/getHash"; import assert from "assert"; const ENOENTID = "0".repeat(64); @@ -30,22 +29,21 @@ describe("getSegmentInfo", () => { before(async () => { const insertQuery = `INSERT INTO "sponsorTimes"("videoID", "startTime", "endTime", "votes", "locked", - "UUID", "userID", "timeSubmitted", "views", "category", "service", - "videoDuration", "hidden", "shadowHidden", "hashedVideoID", "userAgent") - VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; - 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, ["downvoted", 1, 10, -2, 0, downvotedID, "testman", 0, 50, "sponsor", "YouTube", 120, 0, 0, getHash("downvoted", 1), userAgents.meabot]); - 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, ["infvotes", 1, 10, 100000, 0, infvotesID, "testman", 0, 50, "sponsor", "YouTube", 101, 0, 0, getHash("infvotes", 1), userAgents.nodesb]); - 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, ["shadowhidden", 1, 10, 2, 0, shadowhiddenID, "testman", 0, 50, "sponsor", "YouTube", 140, 0, 1, getHash("shadowhidden", 1), 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, ["oldID", 1, 10, 1, 0, oldID, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("oldID", 1), 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, ["filler", 2, 3, 1, 0, fillerID2, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("filler", 1), 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, ["filler", 4, 5, 1, 0, fillerID4, "testman", 0, 50, "sponsor", "YouTube", 300, 0, 0, getHash("filler", 1), 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]); + "UUID", "userID", "timeSubmitted", "views", "hidden", "shadowHidden", "userAgent") + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; + await db.prepare("run", insertQuery, ["segmentInfoUpvoted", 1, 10, 2, 0, upvotedID, "segmentInfoUser", 0, 50, 0, 0, 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, ["segmentInfoLockedup", 1, 10, 2, 1, lockedupID, "segmentInfoUser", 0, 50, 0, 0, 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, ["segmentInfoHidden", 1, 10, 2, 0, hiddenID, "segmentInfoUser", 0, 50, 1, 0, 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, ["segmentInfoLockedown", 1, 10, -2, 1, lockeddownID, "segmentInfoUser", 0, 50, 0, 0, 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, ["segmentInfoUpvoted", 1, 2, 1, 0, fillerID1, "segmentInfoUser", 0, 50, 0, 0, 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, ["segmentInfoFiller", 3, 4, 1, 0, fillerID3, "segmentInfoUser", 0, 50, 0, 0, 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, ["segmentInfoFiller", 5, 6, 1, 0, fillerID5, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]); }); it("Should be able to retreive upvoted segment", (done: Done) => { @@ -54,7 +52,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "upvoted", + videoID: "segmentInfoUpvoted", votes: 2, userAgent: userAgents.vanced, }]; @@ -70,7 +68,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "downvoted", + videoID: "segmentInfoDownvoted", votes: -2, userAgent: userAgents.meabot, }]; @@ -86,7 +84,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "locked-up", + videoID: "segmentInfoLockedup", locked: 1, votes: 2, userAgent: userAgents.mpv, @@ -103,7 +101,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "infvotes", + videoID: "segmentInfoInfvotes", votes: 100000, userAgent: userAgents.nodesb, }]; @@ -119,7 +117,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "shadowhidden", + videoID: "segmentInfoShadowhidden", shadowHidden: 1, userAgent: userAgents.blank, }]; @@ -135,7 +133,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "locked-down", + videoID: "segmentInfoLockedown", locked: 1, votes: -2, }]; @@ -151,7 +149,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "hidden", + videoID: "segmentInfoHidden", hidden: 1, }]; assert.ok(partialDeepEquals(data, expected)); @@ -166,7 +164,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "oldID", + videoID: "segmentInfoOldID", votes: 1, }]; assert.ok(partialDeepEquals(data, expected)); @@ -181,7 +179,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "upvoted", + videoID: "segmentInfoUpvoted", votes: 2, }]; assert.strictEqual(data.length, 1); @@ -197,10 +195,10 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "upvoted", + videoID: "segmentInfoUpvoted", votes: 2, }, { - videoID: "downvoted", + videoID: "segmentInfoDownvoted", votes: -2, }]; assert.ok(partialDeepEquals(data, expected)); @@ -216,7 +214,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "upvoted", + videoID: "segmentInfoUpvoted", votes: 2, }]; assert.ok(partialDeepEquals(data, expected)); @@ -267,7 +265,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "upvoted", + videoID: "segmentInfoUpvoted", votes: 2, }]; assert.ok(partialDeepEquals(data, expected)); @@ -285,9 +283,9 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); 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[9].videoID, "filler"); + assert.strictEqual(data[9].videoID, "segmentInfoFiller"); assert.strictEqual(data[9].UUID, fillerID4); done(); }) @@ -308,7 +306,7 @@ describe("getSegmentInfo", () => { it("Should return 400 if UUID not found", (done: Done) => { fetch(`${getbaseURL()}/api/segmentInfo?UUID=${ENOENTID}`) .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 }) .catch(err => done(err)); @@ -320,10 +318,10 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "upvoted", + videoID: "segmentInfoUpvoted", votes: 2, }, { - videoID: "downvoted", + videoID: "segmentInfoDownvoted", votes: -2, }]; assert.ok(partialDeepEquals(data, expected)); @@ -339,7 +337,7 @@ describe("getSegmentInfo", () => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ - videoID: "upvoted", + videoID: "segmentInfoUpvoted", votes: 2 }]; assert.ok(partialDeepEquals(data, expected)); diff --git a/test/cases/getSkipSegments.ts b/test/cases/getSkipSegments.ts index ff1edb7..92a9ec1 100644 --- a/test/cases/getSkipSegments.ts +++ b/test/cases/getSkipSegments.ts @@ -1,34 +1,33 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; import {Done, getbaseURL, partialDeepEquals} from "../utils"; -import {getHash} from "../../src/utils/getHash"; import assert from "assert"; describe("getSkipSegments", () => { before(async () => { - const query = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", views, category, "actionType", "service", "videoDuration", "hidden", "shadowHidden", "hashedVideoID") 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, ["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, ["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, ["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, ["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, ["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, ["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, ["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, ["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, ["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, ["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, ["onlyHiddenSegments", 20, 34, 100000, 0, "onlyHiddenSegments", "testman", 0, 50, "sponsor", "skip", "YouTube", 190, 1, 0, getHash("onlyHiddenSegments", 1)]); - 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-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-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-raw", 80, 90, 2, 0, "requiredSegmentVid-raw-4", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0, getHash("requiredSegmentVid-raw", 1)]); + 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, ["getSkipSegmentID0", 1, 11, 2, 0, "uuid01", "testman", 0, 50, "sponsor", "skip", "YouTube", 100, 0, 0]); + 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, ["getSkipSegmentID0", 20, 33, 2, 0, "uuid03", "testman", 0, 50, "intro", "skip", "YouTube", 101, 0, 0]); + 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, ["getSkipSegmentID2", 1, 11, 2, 0, "uuid20", "testman", 0, 50, "sponsor", "skip", "YouTube", 140, 0, 0]); + 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, ["getSkipSegmentID3", 7, 22, -3, 0, "uuid31", "testman", 0, 50, "sponsor", "skip", "YouTube", 300, 0, 0]); + 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, ["getSkipSegmentMultiple", 20, 33, 2, 0, "uuid41", "testman", 0, 50, "intro", "skip", "YouTube", 500, 0, 0]); + 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, ["getSkipSegmentLocked", 20, 34, 100000, 0, "uuid51", "testman", 0, 50, "intro", "skip", "YouTube", 190, 0, 0]); + 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", 60, 70, 2, 0, "requiredSegmentVid1", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0]); + 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", 80, 90, -2, 0, "requiredSegmentVid3", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0]); + await db.prepare("run", query, ["requiredSegmentVid", 80, 90, 2, 0, "requiredSegmentVid4", "testman", 0, 50, "sponsor", "skip", "YouTube", 0, 0, 0]); return; }); it("Should be able to get a time by category 1", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -36,7 +35,7 @@ describe("getSkipSegments", () => { assert.strictEqual(data[0].segment[0], 1); assert.strictEqual(data[0].segment[1], 11); 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); done(); }) @@ -44,14 +43,14 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category and action type", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&actionType=mute`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [12, 14], category: "sponsor", - UUID: "1-uuid-0-2", + UUID: "uuid02", videoDuration: 100 }]; assert.ok(partialDeepEquals(data, expected)); @@ -61,18 +60,18 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get a time by category and multiple action types", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute&actionType=skip`) + it("Should be able to get a time by category and getSkipSegmentMultiple action types", (done: Done) => { + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&actionType=mute&actionType=skip`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0", + UUID: "uuid01", videoDuration: 100 }, { - UUID: "1-uuid-0-2" + UUID: "uuid02" }]; assert.strictEqual(data.length, 2); assert.ok(partialDeepEquals(data, expected)); @@ -81,18 +80,18 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get a time by category and multiple action types (JSON array)", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&actionTypes=["mute","skip"]`) + it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done: Done) => { + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&actionTypes=["mute","skip"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0", + UUID: "uuid01", videoDuration: 100 }, { - UUID: "1-uuid-0-2" + UUID: "uuid02" }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -101,14 +100,14 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category for a different service 1", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest2&category=sponsor&service=PeerTube`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID1&category=sponsor&service=PeerTube`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0-1", + UUID: "uuid10", videoDuration: 120 }]; assert.ok(partialDeepEquals(data, expected)); @@ -119,14 +118,14 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category 2", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=intro`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [20, 33], category: "intro", - UUID: "1-uuid-2" + UUID: "uuid03" }]; assert.ok(partialDeepEquals(data, expected)); assert.strictEqual(data.length, 1); @@ -136,14 +135,14 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by categories array", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["sponsor"]`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["sponsor"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0", + UUID: "uuid01", videoDuration: 100 }]; assert.ok(partialDeepEquals(data, expected)); @@ -154,14 +153,14 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by categories array 2", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["intro"]`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["intro"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [20, 33], category: "intro", - UUID: "1-uuid-2", + UUID: "uuid03", videoDuration: 101 }]; assert.ok(partialDeepEquals(data, expected)); @@ -172,7 +171,7 @@ describe("getSkipSegments", () => { }); it("Should return 404 if all submissions are hidden", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=onlyHiddenSegments`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID6`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -180,40 +179,40 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get multiple times by category", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=multiple&categories=["intro"]`) + it("Should be able to get getSkipSegmentMultiple times by category", (done: Done) => { + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentMultiple&categories=["intro"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); - assert.strictEqual(data.length, 2); const expected = [{ segment: [1, 11], category: "intro", - UUID: "1-uuid-6", + UUID: "uuid40", }, { segment: [20, 33], category: "intro", - UUID: "1-uuid-7", + UUID: "uuid41", }]; assert.ok(partialDeepEquals(data, expected)); + assert.strictEqual(data.length, 2); done(); }) .catch(err => done(err)); }); - it("Should be able to get multiple times by multiple categories", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["sponsor", "intro"]`) + it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done: Done) => { + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["sponsor", "intro"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0", + UUID: "uuid01", }, { segment: [20, 33], category: "intro", - UUID: "1-uuid-2", + UUID: "uuid03", }]; assert.ok(partialDeepEquals(data, expected)); assert.strictEqual(data.length, 2); @@ -223,7 +222,7 @@ describe("getSkipSegments", () => { }); it("Should be possible to send unexpected query parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&fakeparam=hello&category=sponsor`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&fakeparam=hello&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -231,7 +230,7 @@ describe("getSkipSegments", () => { const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0", + UUID: "uuid01", }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -240,7 +239,7 @@ describe("getSkipSegments", () => { }); it("Low voted submissions should be hidden", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=test3&category=sponsor`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID3&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -248,7 +247,7 @@ describe("getSkipSegments", () => { const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-4", + UUID: "uuid30", }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -266,7 +265,7 @@ describe("getSkipSegments", () => { }); it("Should return 400 if bad categories argument", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=[not-quoted,not-quoted]`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=[not-quoted,not-quoted]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -275,7 +274,7 @@ describe("getSkipSegments", () => { }); it("Should be able send a comma in a query param", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest,test&category=sponsor`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID2&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -283,7 +282,7 @@ describe("getSkipSegments", () => { const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-1", + UUID: "uuid20", }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -291,8 +290,8 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should always get locked segment", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=locked&category=intro`) + it("Should always get getSkipSegmentLocked segment", (done: Done) => { + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentLocked&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -300,7 +299,7 @@ describe("getSkipSegments", () => { const expected = [{ segment: [20, 33], category: "intro", - UUID: "1-uuid-locked-8", + UUID: "uuid50", }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -308,8 +307,8 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get multiple categories with repeating parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&category=sponsor&category=intro`) + it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done: Done) => { + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -317,11 +316,11 @@ describe("getSkipSegments", () => { const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0", + UUID: "uuid01", }, { segment: [20, 33], category: "intro", - UUID: "1-uuid-2", + UUID: "uuid03", }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -330,7 +329,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get, categories param overriding repeating category", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=testtesttest&categories=["sponsor"]&category=intro`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["sponsor"]&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -338,7 +337,7 @@ describe("getSkipSegments", () => { const expected = [{ segment: [1, 11], category: "sponsor", - UUID: "1-uuid-0", + UUID: "uuid01", }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -347,15 +346,15 @@ describe("getSkipSegments", () => { }); it("Should be able to get specific segments with requiredSegments", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegments=["requiredSegmentVid-raw-2","requiredSegmentVid-raw-3"]`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid&requiredSegments=["requiredSegmentVid2","requiredSegmentVid3"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); assert.strictEqual(data.length, 2); const expected = [{ - UUID: "requiredSegmentVid-raw-2", + UUID: "requiredSegmentVid2", }, { - UUID: "requiredSegmentVid-raw-3", + UUID: "requiredSegmentVid3", }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -364,15 +363,15 @@ describe("getSkipSegments", () => { }); it("Should be able to get specific segments with repeating requiredSegment", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegment=requiredSegmentVid-raw-2&requiredSegment=requiredSegmentVid-raw-3`) + fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid&requiredSegment=requiredSegmentVid2&requiredSegment=requiredSegmentVid3`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); assert.strictEqual(data.length, 2); const expected = [{ - UUID: "requiredSegmentVid-raw-2", + UUID: "requiredSegmentVid2", }, { - UUID: "requiredSegmentVid-raw-3", + UUID: "requiredSegmentVid3", }]; assert.ok(partialDeepEquals(data, expected)); done(); diff --git a/test/cases/getSkipSegmentsByHash.ts b/test/cases/getSkipSegmentsByHash.ts index 40e7d5e..d5627a4 100644 --- a/test/cases/getSkipSegmentsByHash.ts +++ b/test/cases/getSkipSegmentsByHash.ts @@ -12,21 +12,23 @@ const sinonStub = mockManager.mock("listVideos"); sinonStub.callsFake(YouTubeApiMock.listVideos); describe("getSkipSegmentsByHash", () => { + const getSegmentsByHash0Hash = "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"; + const requiredSegmentVidHash = "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"; before(async () => { 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-0-0-1", "testman", 0, 50, "sponsor", "skip", "PeerTube", 0, 0, "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"]); - 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", 40, 50, 2, "getSegmentsByHash-0-2", "testman", 0, 50, "sponsor", "mute", "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-02", "testman", 0, 50, "sponsor", "skip", "PeerTube", 0, 0, getSegmentsByHash0Hash]); + 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-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-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, ["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, ["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-2", "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, "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"]); - 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", 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, requiredSegmentVidHash]); + 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, requiredSegmentVidHash]); }); it("Should be able to get a 200", (done: Done) => { @@ -146,7 +148,7 @@ describe("getSkipSegmentsByHash", () => { const expected = [{ segments: [{ category: "sponsor", - UUID: "getSegmentsByHash-0-0", + UUID: "getSegmentsByHash-01", }] }, { segments: [{ @@ -172,7 +174,7 @@ describe("getSkipSegmentsByHash", () => { const expected = [{ segments: [{ category: "sponsor", - UUID: "getSegmentsByHash-0-0", + UUID: "getSegmentsByHash-01", }] }, { segments: [{ @@ -196,9 +198,9 @@ describe("getSkipSegmentsByHash", () => { const expected = [{ segments: [{ category: "sponsor", - UUID: "getSegmentsByHash-0-0", + UUID: "getSegmentsByHash-01", }, { - UUID: "getSegmentsByHash-0-2", + UUID: "getSegmentsByHash-04", }] }, { segments: [{ @@ -220,9 +222,9 @@ describe("getSkipSegmentsByHash", () => { const expected = [{ segments: [{ category: "sponsor", - UUID: "getSegmentsByHash-0-0", + UUID: "getSegmentsByHash-01", }, { - UUID: "getSegmentsByHash-0-2", + UUID: "getSegmentsByHash-04", }] }, { segments: [{ @@ -243,7 +245,7 @@ describe("getSkipSegmentsByHash", () => { assert.strictEqual(data.length, 1); const expected = [{ segments: [{ - UUID: "getSegmentsByHash-0-0-1" + UUID: "getSegmentsByHash-02" }] }]; assert.ok(partialDeepEquals(data, expected)); @@ -311,11 +313,11 @@ describe("getSkipSegmentsByHash", () => { segments: [{ segment: [1, 10], category: "sponsor", - UUID: "getSegmentsByHash-0-0", + UUID: "getSegmentsByHash-01", }, { segment: [20, 30], category: "intro", - UUID: "getSegmentsByHash-0-1", + UUID: "getSegmentsByHash-03", }] }]; assert.ok(partialDeepEquals(data, expected)); diff --git a/test/cases/getUserInfo.ts b/test/cases/getUserInfo.ts index e0a4d65..7d88abf 100644 --- a/test/cases/getUserInfo.ts +++ b/test/cases/getUserInfo.ts @@ -10,15 +10,16 @@ describe("getUserInfo", () => { 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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - await db.prepare("run", sponsorTimesQuery, ["xxxyyyzzz", 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, ["yyyxxxzzz", 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, ["xzzzxxyyy", 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, ["xxxyyyzzz", 1, 11, 2, "uuid000007", getHash("getuserinfo_user_02"), 7, 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, ["xxxyyyzzz", 0, 36000, 2, "uuid000009", getHash("getuserinfo_user_03"), 8, 2, "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, ["getUserInfo0", 1, 11, 2, "uuid000002", getHash("getuserinfo_user_01"), 2, 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, ["getUserInfo1", 1, 11, -2, "uuid000004", getHash("getuserinfo_user_01"), 4, 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, ["getUserInfo0", 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, ["getUserInfo0", 0, 36000, 2,"uuid000009", getHash("getuserinfo_user_03"), 8, 10, "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 (?, ?, ?, ?, ?)'; await db.prepare("run", insertWarningQuery, [getHash("getuserinfo_warning_0"), 10, "getuserinfo_vip", 1, "warning0-0"]); @@ -303,8 +304,8 @@ describe("getUserInfo", () => { const expected = { userName: "807e0a5d0a62c9c4365fae3d403e4618a3226f231314a898fa1555a0e55eab9e", userID: "807e0a5d0a62c9c4365fae3d403e4618a3226f231314a898fa1555a0e55eab9e", - minutesSaved: 20, - viewCount: 2, + minutesSaved: 100, + viewCount: 10, ignoredViewCount: 0, segmentCount: 1, ignoredSegmentCount: 0, diff --git a/test/cases/lockCategoriesRecords.ts b/test/cases/lockCategoriesRecords.ts index 3a16307..d00f078 100644 --- a/test/cases/lockCategoriesRecords.ts +++ b/test/cases/lockCategoriesRecords.ts @@ -16,20 +16,20 @@ const stringDeepEquals = (a: string[] ,b: string[]): boolean => { describe("lockCategoriesRecords", () => { before(async () => { const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; - await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-lockCategories")]); + await db.prepare("run", insertVipUserQuery, [getHash("lockCategoriesRecordsVIPUser")]); 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, [getHash("VIPUser-lockCategories"), "no-segments-video-id", "intro", "reason-1"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "no-segments-video-id", "sponsor", "reason-1"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "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, [getHash("VIPUser-lockCategories"), "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, [getHash("lockCategoriesRecordsVIPUser"), "no-segments-video-id-1", "sponsor", "reason-2"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "no-segments-video-id-1", "intro", "reason-2"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "lockCategoryVideo", "sponsor", "reason-3"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "delete-record", "sponsor", "reason-4"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "delete-record", "sponsor", "reason-4"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-lockCategories"), "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, [getHash("lockCategoriesRecordsVIPUser"), "delete-record-1", "sponsor", "reason-5"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "delete-record-1", "intro", "reason-5"]); }); it("Should update the database version when starting the application", async () => { @@ -40,7 +40,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories not in video (http response)", (done: Done) => { const json = { videoID: "no-segments-video-id", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "outro", "shilling", @@ -75,7 +75,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories not in video (sql check)", (done: Done) => { const json = { videoID: "no-segments-video-id-1", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "outro", "shilling", @@ -114,7 +114,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories not in video with reason (http response)", (done: Done) => { const json = { videoID: "no-segments-video-id", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "outro", "shilling", @@ -153,7 +153,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories not in video with reason (sql check)", (done: Done) => { const json = { videoID: "no-segments-video-id-1", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "outro", "shilling", @@ -199,7 +199,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories with _ in the category", (done: Done) => { const json = { videoID: "underscore", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "word_word", ], @@ -223,7 +223,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories with upper and lower case in the category", (done: Done) => { const json = { videoID: "bothCases", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "wordWord", ], @@ -247,7 +247,7 @@ describe("lockCategoriesRecords", () => { it("Should not be able to submit categories with $ in the category", (done: Done) => { const json = { videoID: "specialChar", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "word&word", ], @@ -414,7 +414,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to delete a lockCategories record", (done: Done) => { const json = { videoID: "delete-record", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "sponsor", ], @@ -439,7 +439,7 @@ describe("lockCategoriesRecords", () => { it("Should be able to delete one lockCategories record without removing another", (done: Done) => { const json = { videoID: "delete-record-1", - userID: "VIPUser-lockCategories", + userID: "lockCategoriesRecordsVIPUser", categories: [ "sponsor", ], diff --git a/test/cases/oldGetSponsorTime.ts b/test/cases/oldGetSponsorTime.ts index ef0bcf5..46cfe2f 100644 --- a/test/cases/oldGetSponsorTime.ts +++ b/test/cases/oldGetSponsorTime.ts @@ -1,18 +1,17 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; import {Done, getbaseURL, partialDeepEquals} from "../utils"; -import {getHash} from "../../src/utils/getHash"; import assert from "assert"; describe("getVideoSponsorTime (Old get method)", () => { before(async () => { - const insertSponsorTimes = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") 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, ["old-testtesttest,test", 1, 11, 2, "uuid-1", "testman", 0, 50, "sponsor", 0, getHash("old-testtesttest,test", 1)]); + const insertSponsorTimes = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; + await db.prepare("run", insertSponsorTimes, ["oldGetSponsorTime0", 1, 11, 2, "oldGetSponsorTime00", "oldGetSponsorTimeUser", 0, 50, "sponsor", 0]); + 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) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest`) + fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime0`) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -31,7 +30,7 @@ describe("getVideoSponsorTime (Old get method)", () => { it("Should be possible to send unexpected query parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest&fakeparam=hello`) + fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime0&fakeparam=hello`) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -40,12 +39,12 @@ describe("getVideoSponsorTime (Old get method)", () => { }); it("Should be able send a comma in a query param", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest,test`) + fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime1,test`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = { - UUIDs: ["uuid-1"], + UUIDs: ["oldGetSponsorTime01"], }; assert.ok(partialDeepEquals(data, expected)); done(); @@ -54,13 +53,13 @@ describe("getVideoSponsorTime (Old get method)", () => { }); it("Should be able to get the correct time", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=old-testtesttest`) + fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime0`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); const expected = { sponsorTimes: [[1, 11]], - UUIDs: ["uuid-0"] + UUIDs: ["oldGetSponsorTime00"] }; assert.ok(partialDeepEquals(data, expected)); done(); diff --git a/test/cases/oldSubmitSponsorTimes.ts b/test/cases/oldSubmitSponsorTimes.ts index fac3555..ac1c0a4 100644 --- a/test/cases/oldSubmitSponsorTimes.ts +++ b/test/cases/oldSubmitSponsorTimes.ts @@ -3,13 +3,17 @@ import {Done, getbaseURL, partialDeepEquals} from "../utils"; import {db} from "../../src/databases/databases"; import assert from "assert"; +const videoID1 = "dQw4w9WgXcQ"; +const videoID2 = "dQw4w9WgXcE"; +const userID = "testtesttesttesttesttesttesttesttest"; + describe("postVideoSponsorTime (Old submission method)", () => { it("Should be able to submit a time (GET)", (done: Done) => { fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=dQw4w9WgXcQ&startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest`) + }/api/postVideoSponsorTimes?videoID=${videoID1}&startTime=1&endTime=10&userID=${userID}`) .then(async res => { 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 = { startTime: 1, endTime: 10, @@ -23,7 +27,7 @@ describe("postVideoSponsorTime (Old submission method)", () => { it("Should be able to submit a time (POST)", (done: Done) => { fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=dQw4w9WgXcE&startTime=1&endTime=11&userID=testtesttesttesttesttesttesttesttest`, { + }/api/postVideoSponsorTimes?videoID=${videoID2}&startTime=1&endTime=11&userID=${userID}`, { method: "POST", headers: { "Content-Type": "application/json", @@ -31,7 +35,7 @@ describe("postVideoSponsorTime (Old submission method)", () => { }) .then(async res => { 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 = { startTime: 1, endTime: 11, @@ -45,7 +49,7 @@ describe("postVideoSponsorTime (Old submission method)", () => { it("Should return 400 for missing params", (done: Done) => { fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest`) + }/api/postVideoSponsorTimes?startTime=1&endTime=10&userID=${userID}`) .then(async res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/postClearCache.ts b/test/cases/postClearCache.ts index 43e450b..46a9718 100644 --- a/test/cases/postClearCache.ts +++ b/test/cases/postClearCache.ts @@ -4,16 +4,19 @@ import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; +const VIPUser = "clearCacheVIP"; +const regularUser = "regular-user"; + describe("postClearCache", () => { before(async () => { - await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES ('${getHash("clearing-vip")}')`); - const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") 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", `INSERT INTO "vipUsers" ("userID") VALUES ('${getHash(VIPUser)}')`); + 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)`); }); it("Should be able to clear cache for existing video", (done: Done) => { fetch(`${getbaseURL() - }/api/clearCache?userID=clearing-vip&videoID=clear-test`, { + }/api/clearCache?userID=${VIPUser}&videoID=clear-test`, { method: "POST" }) .then(res => { @@ -25,7 +28,7 @@ describe("postClearCache", () => { it("Should be able to clear cache for nonexistent video", (done: Done) => { fetch(`${getbaseURL() - }/api/clearCache?userID=clearing-vip&videoID=dne-video`, { + }/api/clearCache?userID=${VIPUser}&videoID=dne-video`, { method: "POST" }) .then(res => { @@ -37,7 +40,7 @@ describe("postClearCache", () => { it("Should get 403 as non-vip", (done: Done) => { fetch(`${getbaseURL() - }/api/clearCache?userID=regular-user&videoID=clear-tes`, { + }/api/clearCache?userID=${regularUser}&videoID=clear-tes`, { method: "POST" }) .then(async res => { @@ -49,7 +52,7 @@ describe("postClearCache", () => { it("Should give 400 with missing videoID", (done: Done) => { fetch(`${getbaseURL() - }/api/clearCache?userID=clearing-vip`, { + }/api/clearCache?userID=${VIPUser}`, { method: "POST" }) .then(async res => { @@ -61,7 +64,7 @@ describe("postClearCache", () => { it("Should give 400 with missing userID", (done: Done) => { fetch(`${getbaseURL() - }/api/clearCache?userID=clearing-vip`, { + }/api/clearCache?userID=${VIPUser}`, { method: "POST" }) .then(async res => { From 870ade6fa9abc44daad3e1c0a9d9bdef3a641f2e Mon Sep 17 00:00:00 2001 From: Michael C Date: Thu, 16 Sep 2021 20:44:12 -0400 Subject: [PATCH 02/14] postSkipSegments --- test/cases/postSkipSegments.ts | 491 +++++++++++++++------------------ test/utils.ts | 9 +- 2 files changed, 236 insertions(+), 264 deletions(-) diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index 0fef115..75ae64a 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -1,7 +1,7 @@ import fetch from "node-fetch"; import {config} from "../../src/config"; import {getHash} from "../../src/utils/getHash"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; +import {Done, getbaseURL, partialDeepEquals, postJSON} from "../utils"; import {db} from "../../src/databases/databases"; import {ImportMock} from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; @@ -12,19 +12,40 @@ const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const sinonStub = mockManager.mock("listVideos"); sinonStub.callsFake(YouTubeApiMock.listVideos); +// Constant and helpers +const submitUserOne = `PostSkipUser1${".".repeat(18)}`; +const submitUserTwo = `PostSkipUser2${".".repeat(18)}`; +const submitUserThree = `PostSkipUser3${".".repeat(18)}`; + +const warnUser01 = "warn-user01-qwertyuiopasdfghjklzxcvbnm"; +const warnUser01Hash = getHash(warnUser01); +const warnUser02 = "warn-user02-qwertyuiopasdfghjklzxcvbnm"; +const warnUser02Hash = getHash(warnUser02); +const warnUser03 = "warn-user03-qwertyuiopasdfghjklzxcvbnm"; +const warnUser03Hash = getHash(warnUser03); +const warnUser04 = "warn-user04-qwertyuiopasdfghjklzxcvbnm"; +const warnUser04Hash = getHash(warnUser04); + +const submitUserOneHash = getHash(submitUserOne); +const submitVIPuser = `VIPPostSkipUser${".".repeat(16)}`; +const warnVideoID = "dQw4w9WgXcF"; +const badInputVideoID = "dQw4w9WgXcQ"; + +const queryDatabase = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); +const queryDatabaseActionType = async(videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); +const queryDatabaseDuration = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); + +const endpoint = `${getbaseURL()}/api/skipSegments`; + describe("postSkipSegments", () => { before(() => { const insertSponsorTimeQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - db.prepare("run", insertSponsorTimeQuery, ["80percent_video", 0, 1000, 0, "80percent-uuid-0", getHash("testtesttesttesttesttesttesttesttest"), 0, 0, "interaction", 0, "80percent_video"]); - db.prepare("run", insertSponsorTimeQuery, ["80percent_video", 1001, 1005, 0, "80percent-uuid-1", getHash("testtesttesttesttesttesttesttesttest"), 0, 0, "interaction", 0, "80percent_video"]); - db.prepare("run", insertSponsorTimeQuery, ["80percent_video", 0, 5000, -2, "80percent-uuid-2", getHash("testtesttesttesttesttesttesttesttest"), 0, 0, "interaction", 0, "80percent_video"]); + db.prepare("run", insertSponsorTimeQuery, ["80percent_video", 0, 1000, 0, "80percent-uuid-0", submitUserOneHash, 0, 0, "interaction", 0, "80percent_video"]); + db.prepare("run", insertSponsorTimeQuery, ["80percent_video", 1001, 1005, 0, "80percent-uuid-1", submitUserOneHash, 0, 0, "interaction", 0, "80percent_video"]); + db.prepare("run", insertSponsorTimeQuery, ["80percent_video", 0, 5000, -2, "80percent-uuid-2", submitUserOneHash, 0, 0, "interaction", 0, "80percent_video"]); const now = Date.now(); const warnVip01Hash = getHash("warn-vip01-qwertyuiopasdfghjklzxcvbnm"); - const warnUser01Hash = getHash("warn-user01-qwertyuiopasdfghjklzxcvbnm"); - const warnUser02Hash = getHash("warn-user02-qwertyuiopasdfghjklzxcvbnm"); - const warnUser03Hash = getHash("warn-user03-qwertyuiopasdfghjklzxcvbnm"); - const warnUser04Hash = getHash("warn-user04-qwertyuiopasdfghjklzxcvbnm"); const reason01 = "Reason01"; const reason02 = ""; const reason03 = "Reason03"; @@ -32,39 +53,40 @@ describe("postSkipSegments", () => { const MILLISECONDS_IN_HOUR = 3600000; const warningExpireTime = MILLISECONDS_IN_HOUR * config.hoursAfterWarningExpires; - const insertWarningQuery = 'INSERT INTO warnings ("userID", "issueTime", "issuerUserID", "enabled", "reason") VALUES(?, ?, ?, ?, ?)'; - db.prepare("run", insertWarningQuery, [warnUser01Hash, now, warnVip01Hash, 1, reason01]); - db.prepare("run", insertWarningQuery, [warnUser01Hash, (now - 1000), warnVip01Hash, 1, reason01]); - db.prepare("run", insertWarningQuery, [warnUser01Hash, (now - 2000), warnVip01Hash, 1, reason01]); - db.prepare("run", insertWarningQuery, [warnUser01Hash, (now - 3601000), warnVip01Hash, 1, reason01]); - db.prepare("run", insertWarningQuery, [warnUser02Hash, now, warnVip01Hash, 1, reason02]); - db.prepare("run", insertWarningQuery, [warnUser02Hash, now, warnVip01Hash, 1, reason02]); - db.prepare("run", insertWarningQuery, [warnUser02Hash, (now - (warningExpireTime + 1000)), warnVip01Hash, 1, reason02]); - db.prepare("run", insertWarningQuery, [warnUser02Hash, (now - (warningExpireTime + 2000)), warnVip01Hash, 1, reason02]); - db.prepare("run", insertWarningQuery, [warnUser03Hash, now, warnVip01Hash, 0, reason03]); - db.prepare("run", insertWarningQuery, [warnUser03Hash, (now - 1000), warnVip01Hash, 0, reason03]); - db.prepare("run", insertWarningQuery, [warnUser03Hash, (now - 2000), warnVip01Hash, 1, reason03]); - db.prepare("run", insertWarningQuery, [warnUser03Hash, (now - 3601000), warnVip01Hash, 1, reason03]); - db.prepare("run", insertWarningQuery, [warnUser04Hash, now, warnVip01Hash, 0, reason04]); - db.prepare("run", insertWarningQuery, [warnUser04Hash, (now - 1000), warnVip01Hash, 0, reason04]); - db.prepare("run", insertWarningQuery, [warnUser04Hash, (now - 2000), warnVip01Hash, 1, reason04]); - db.prepare("run", insertWarningQuery, [warnUser04Hash, (now - 3601000), warnVip01Hash, 1, reason04]); + const insertWarningQuery = 'INSERT INTO warnings ("userID", "issuerUserID", "enabled", "reason", issueTime) VALUES(?, ?, ?, ?, ?)'; + // User 1 + db.prepare("run", insertWarningQuery, [warnUser01Hash, warnVip01Hash, 1, reason01, now]); + db.prepare("run", insertWarningQuery, [warnUser01Hash, warnVip01Hash, 1, reason01, (now - 1000)]); + db.prepare("run", insertWarningQuery, [warnUser01Hash, warnVip01Hash, 1, reason01, (now - 2000)]); + db.prepare("run", insertWarningQuery, [warnUser01Hash, warnVip01Hash, 1, reason01, (now - 3601000)]); + // User 2 + db.prepare("run", insertWarningQuery, [warnUser02Hash, warnVip01Hash, 1, reason02, now]); + db.prepare("run", insertWarningQuery, [warnUser02Hash, warnVip01Hash, 1, reason02, now]); + db.prepare("run", insertWarningQuery, [warnUser02Hash, warnVip01Hash, 1, reason02, (now - (warningExpireTime + 1000))]); + db.prepare("run", insertWarningQuery, [warnUser02Hash, warnVip01Hash, 1, reason02, (now - (warningExpireTime + 2000))]); + // User 3 + db.prepare("run", insertWarningQuery, [warnUser03Hash, warnVip01Hash, 0, reason03, now]); + db.prepare("run", insertWarningQuery, [warnUser03Hash, warnVip01Hash, 0, reason03, (now - 1000)]); + db.prepare("run", insertWarningQuery, [warnUser03Hash, warnVip01Hash, 1, reason03, (now - 2000)]); + db.prepare("run", insertWarningQuery, [warnUser03Hash, warnVip01Hash, 1, reason03, (now - 3601000)]); + // User 4 + db.prepare("run", insertWarningQuery, [warnUser04Hash, warnVip01Hash, 0, reason04, now]); + db.prepare("run", insertWarningQuery, [warnUser04Hash, warnVip01Hash, 0, reason04, (now - 1000)]); + db.prepare("run", insertWarningQuery, [warnUser04Hash, warnVip01Hash, 1, reason04, (now - 2000)]); + db.prepare("run", insertWarningQuery, [warnUser04Hash, warnVip01Hash, 1, reason04, (now - 3601000)]); const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; - db.prepare("run", insertVipUserQuery, [getHash("VIPUserSubmissionVIPUserSubmissionVIPUserSubmission")]); + db.prepare("run", insertVipUserQuery, [getHash(submitVIPuser)]); }); it("Should be able to submit a single time (Params method)", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=dQw4w9WgXcR&startTime=2&endTime=10&userID=testtesttesttesttesttesttesttesttest&category=sponsor`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXcR"; + fetch(`${endpoint}?videoID=${videoID}&startTime=2&endTime=10&userID=${submitUserOne}&category=sponsor`, { + method: "POST" }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcR"]); + const row = await queryDatabase(videoID); const expected = { startTime: 2, endTime: 10, @@ -77,14 +99,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit a single time (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXcF"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcF", + userID: submitUserOne, + videoID, segments: [{ segment: [0, 10], category: "sponsor", @@ -93,7 +113,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcF"]); + const row = await queryDatabase(videoID); const expected = { startTime: 0, endTime: 10, @@ -107,14 +127,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit a single time with an action type (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXcV"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcV", + userID: submitUserOne, + videoID, segments: [{ segment: [0, 10], category: "sponsor", @@ -124,7 +142,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcV"]); + const row = await queryDatabaseActionType(videoID); const expected = { startTime: 0, endTime: 10, @@ -138,14 +156,12 @@ describe("postSkipSegments", () => { }); it("Should not be able to submit an intro with mute action type (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXpQ"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXpQ", + userID: submitUserOne, + videoID, segments: [{ segment: [0, 10], category: "intro", @@ -155,7 +171,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 400); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXpQ"]); + const row = await queryDatabaseActionType(videoID); assert.strictEqual(row, undefined); done(); }) @@ -163,14 +179,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit a single time with a duration from the YouTube API (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXZX"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXZX", + userID: submitUserOne, + videoID, videoDuration: 100, segments: [{ segment: [0, 10], @@ -180,7 +194,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXZX"]); + const row = await queryDatabaseDuration(videoID); const expected = { startTime: 0, endTime: 10, @@ -194,14 +208,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit a single time with a precise duration close to the one from the YouTube API (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXZH"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXZH", + userID: submitUserOne, + videoID, videoDuration: 4980.20, segments: [{ segment: [1, 10], @@ -211,7 +223,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXZH"]); + const row = await queryDatabaseDuration(videoID); const expected = { startTime: 1, endTime: 10, @@ -226,14 +238,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit a single time with a duration in the body (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "noDuration"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "noDuration", + userID: submitUserOne, + videoID, videoDuration: 100, segments: [{ segment: [0, 10], @@ -243,7 +253,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, ["noDuration"]); + const row = await queryDatabaseDuration(videoID); const expected = { startTime: 0, endTime: 10, @@ -258,18 +268,16 @@ describe("postSkipSegments", () => { }); it("Should be able to submit with a new duration, and hide old submissions and remove segment locks", async () => { + const videoID = "noDuration"; await db.prepare("run", `INSERT INTO "lockCategories" ("userID", "videoID", "category") - VALUES(?, ?, ?)`, [getHash("VIPUser-lockCategories"), "noDuration", "sponsor"]); + VALUES(?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "sponsor"]); try { - const res = await fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const res = await fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "noDuration", + userID: submitUserOne, + videoID, videoDuration: 100, segments: [{ segment: [1, 10], @@ -278,11 +286,11 @@ describe("postSkipSegments", () => { }), }); assert.strictEqual(res.status, 200); - const lockCategoriesRow = await db.prepare("get", `SELECT * from "lockCategories" WHERE videoID = ?`, ["noDuration"]); + const lockCategoriesRow = await db.prepare("get", `SELECT * from "lockCategories" WHERE videoID = ?`, [videoID]); const videoRows = await db.prepare("all", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" - FROM "sponsorTimes" WHERE "videoID" = ? AND hidden = 0`, ["noDuration"]); + FROM "sponsorTimes" WHERE "videoID" = ? AND hidden = 0`, [videoID]); const hiddenVideoRows = await db.prepare("all", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" - FROM "sponsorTimes" WHERE "videoID" = ? AND hidden = 1`, ["noDuration"]); + FROM "sponsorTimes" WHERE "videoID" = ? AND hidden = 1`, [videoID]); assert.ok(!lockCategoriesRow); const expected = { startTime: 1, @@ -300,8 +308,8 @@ describe("postSkipSegments", () => { }); it("Should still not be allowed if youtube thinks duration is 0", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=noDuration&startTime=30&endTime=10000&userID=testtesttesttesttesttesttesttesttesting`, { + const videoID= "noDuration"; + fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=10000&userID=${submitUserThree}&category=sponsor`, { method: "POST", }) .then(async res => { @@ -312,14 +320,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit a single time under a different service (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXcG"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcG", + userID: submitUserOne, + videoID, service: "PeerTube", segments: [{ segment: [0, 10], @@ -329,7 +335,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "service" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcG"]); + const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "service" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); const expected = { startTime: 0, endTime: 10, @@ -344,14 +350,12 @@ describe("postSkipSegments", () => { }); it("VIP submission should start locked", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "vipuserIDSubmission"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "VIPUserSubmissionVIPUserSubmissionVIPUserSubmission", - videoID: "vipuserIDSubmission", + userID: submitVIPuser, + videoID, segments: [{ segment: [0, 10], category: "sponsor", @@ -360,7 +364,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["vipuserIDSubmission"]); + const row = await queryDatabase(videoID); const expected = { startTime: 0, endTime: 10, @@ -374,14 +378,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit multiple times (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "dQw4w9WgXcT"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcT", + userID: submitUserOne, + videoID, segments: [{ segment: [3, 10], category: "sponsor", @@ -393,7 +395,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const rows = await db.prepare("all", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcT"]); + const rows = await db.prepare("all", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); const expected = [{ startTime: 3, endTime: 10, @@ -410,14 +412,12 @@ describe("postSkipSegments", () => { }).timeout(5000); it("Should allow multiple times if total is under 80% of video(JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "L_jWHffIx5E"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "L_jWHffIx5E", + userID: submitUserOne, + videoID, segments: [{ segment: [3, 3000], category: "sponsor", @@ -435,7 +435,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const rows = await db.prepare("all", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ? and "votes" > -1`, ["L_jWHffIx5E"]); + const rows = await db.prepare("all", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ? and "votes" > -1`, [videoID]); const expected = [{ startTime: 3, endTime: 3000, @@ -460,14 +460,12 @@ describe("postSkipSegments", () => { }).timeout(5000); it("Should reject multiple times if total is over 80% of video (JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "n9rIGdXnSJc"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "n9rIGdXnSJc", + userID: submitUserOne, + videoID, segments: [{ segment: [0, 2000], category: "interaction", @@ -485,7 +483,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 403); - const rows = await db.prepare("all", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ? and "votes" > -1`, ["n9rIGdXnSJc"]); + const rows = await db.prepare("all", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ? and "votes" > -1`, [videoID]); assert.deepStrictEqual(rows, []); done(); }) @@ -493,14 +491,12 @@ describe("postSkipSegments", () => { }).timeout(5000); it("Should reject multiple times if total is over 80% of video including previosuly submitted times(JSON method)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const videoID = "80percent_video"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "80percent_video", + userID: submitUserOne, + videoID, segments: [{ segment: [2000, 4000], category: "sponsor", @@ -528,7 +524,7 @@ describe("postSkipSegments", () => { startTime: 4050, endTime: 4750 }]; - const rows = await db.prepare("all", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ? and "votes" > -1`, ["80percent_video"]); + const rows = await queryDatabase(videoID); assert.notDeepStrictEqual(rows, expected); done(); }) @@ -536,8 +532,8 @@ describe("postSkipSegments", () => { }).timeout(5000); it("Should be accepted if a non-sponsor is less than 1 second", (done: Done) => { - fetch(`${getbaseURL() - }/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting&category=intro`, { + const videoID = "qqwerty"; + fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30.5&userID=${submitUserTwo}&category=intro`, { method: "POST", }) .then(res => { @@ -548,8 +544,8 @@ describe("postSkipSegments", () => { }); it("Should be rejected if segment starts and ends at the same time", (done: Done) => { - fetch(`${getbaseURL() - }/api/skipSegments?videoID=qqwerty&startTime=90&endTime=90&userID=testtesttesttesttesttesttesttesttesting&category=intro`, { + const videoID = "qqwerty"; + fetch(`${endpoint}?videoID=${videoID}&startTime=90&endTime=90&userID=${submitUserTwo}&category=intro`, { method: "POST", }) .then(res => { @@ -560,8 +556,8 @@ describe("postSkipSegments", () => { }); it("Should be accepted if highlight segment starts and ends at the same time", (done: Done) => { - fetch(`${getbaseURL() - }/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30&userID=testtesttesttesttesttesttesttesttesting&category=poi_highlight`, { + const videoID = "qqwerty"; + fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30&userID=${submitUserTwo}&category=poi_highlight`, { method: "POST", }) .then(res => { @@ -572,8 +568,8 @@ describe("postSkipSegments", () => { }); it("Should be rejected if highlight segment doesn't start and end at the same time", (done: Done) => { - fetch(`${getbaseURL() - }/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting&category=poi_highlight`, { + const videoID = "qqwerty"; + fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30.5&userID=${submitUserTwo}&category=poi_highlight`, { method: "POST", }) .then(res => { @@ -584,8 +580,8 @@ describe("postSkipSegments", () => { }); it("Should be rejected if a sponsor is less than 1 second", (done: Done) => { - fetch(`${getbaseURL() - }/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting`, { + const videoID = "qqwerty"; + fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30.5&userID=${submitUserTwo}`, { method: "POST", }) .then(res => { @@ -596,34 +592,37 @@ describe("postSkipSegments", () => { }); it("Should be rejected if over 80% of the video", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=qqwerty&startTime=30&endTime=1000000&userID=testtesttesttesttesttesttesttesttesting`) - .then(res => { + const videoID = "qqwerty"; + fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=1000000&userID=${submitUserTwo}&category=sponsor`, { + method: "POST", + }) + .then( async res => { assert.strictEqual(res.status, 403); + console.log(res.text()); done(); }) .catch(err => done(err)); }); it("Should be rejected if NB's predicted probability is <70%.", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=LevkAjUE6d4&startTime=40&endTime=60&userID=testtesttesttesttesttesttesttesttesting`) - .then(res => { + const videoID = "LevkAjUE6d4"; + fetch(`${endpoint}?videoID=${videoID}&startTime=40&endTime=60&userID=${submitUserTwo}&category=sponsor`, { + method: "POST", + }) + .then(async res => { assert.strictEqual(res.status, 200); + console.log(res.text()); done(); }) .catch(err => done(err)); }); it("Should be rejected with custom message if user has to many active warnings", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "warn-user01-qwertyuiopasdfghjklzxcvbnm", - videoID: "dQw4w9WgXcF", + userID: warnUser01, + videoID: warnVideoID, segments: [{ segment: [0, 10], category: "sponsor", @@ -634,11 +633,10 @@ describe("postSkipSegments", () => { assert.strictEqual(res.status, 403); const errorMessage = await res.text(); const reason = "Reason01"; - const userID = "09dee632bfbb1acc9fda3169cc14b46e459b45cee4f4449be305590e612b5eb7"; const expected = "Submission rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes" + " that are not malicious, and we just want to clarify the rules. " + "Could you please send a message in discord.gg/SponsorBlock or matrix.to/#/#sponsor:ajay.app so we can further help you? " - + `Your userID is ${userID}.\n\nWarning reason: '${reason}'`; + + `Your userID is ${warnUser01Hash}.\n\nWarning reason: '${reason}'`; assert.strictEqual(errorMessage, expected); done(); @@ -647,14 +645,11 @@ describe("postSkipSegments", () => { }); it("Should be accepted if user has some active warnings", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "warn-user02-qwertyuiopasdfghjklzxcvbnm", - videoID: "dQw4w9WgXcF", + userID: warnUser02, + videoID: warnVideoID, segments: [{ segment: [50, 60], category: "sponsor", @@ -673,14 +668,11 @@ describe("postSkipSegments", () => { }); it("Should be accepted if user has some warnings removed", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "warn-user03-qwertyuiopasdfghjklzxcvbnm", - videoID: "dQw4w9WgXcF", + userID: warnUser03, + videoID: warnVideoID, segments: [{ segment: [53, 60], category: "sponsor", @@ -699,8 +691,7 @@ describe("postSkipSegments", () => { }); it("Should return 400 for missing params (Params method)", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?startTime=9&endTime=10&userID=testtesttesttesttesttesttesttesttest`, { + fetch(`${endpoint}?startTime=9&endTime=10&userID=${submitUserOne}`, { method: "POST", }) .then(async res => { @@ -711,14 +702,11 @@ describe("postSkipSegments", () => { }); it("Should be rejected with default message if user has to many active warnings", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "warn-user01-qwertyuiopasdfghjklzxcvbnm", - videoID: "dQw4w9WgXcF", + userID: warnUser01, + videoID: warnVideoID, segments: [{ segment: [0, 10], category: "sponsor", @@ -735,13 +723,10 @@ describe("postSkipSegments", () => { }); it("Should return 400 for missing params (JSON method) 1", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", + userID: submitUserOne, segments: [{ segment: [9, 10], category: "sponsor", @@ -758,14 +743,11 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); it("Should return 400 for missing params (JSON method) 2", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcQ", + userID: submitUserOne, + videoID: badInputVideoID, }), }) .then(res => { @@ -775,14 +757,11 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); it("Should return 400 for missing params (JSON method) 3", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcQ", + userID: submitUserOne, + videoID: badInputVideoID, segments: [{ segment: [0], category: "sponsor", @@ -799,14 +778,11 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); it("Should return 400 for missing params (JSON method) 4", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcQ", + userID: submitUserOne, + videoID: badInputVideoID, segments: [{ segment: [9, 10], }, { @@ -822,14 +798,11 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); it("Should return 400 for missing params (JSON method) 5", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "dQw4w9WgXcQ", + userID: submitUserOne, + videoID: badInputVideoID, }), }) .then(res => { @@ -840,18 +813,16 @@ describe("postSkipSegments", () => { }); it("Should return 403 and custom reason for submiting in lockedCategory", async () => { + const videoID = "lockedVideo"; await db.prepare("run", `INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") - VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), "lockedVideo", "sponsor", "Custom Reason"]); + VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "sponsor", "Custom Reason"]); try { - const res = await fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const res = await fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "lockedVideo", + userID: submitUserOne, + videoID, segments: [{ segment: [1, 10], category: "sponsor", @@ -868,18 +839,16 @@ describe("postSkipSegments", () => { }); it("Should return 403 for submiting in lockedCategory", async () => { + const videoID = "lockedVideo1"; await db.prepare("run", `INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") - VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), "lockedVideo1", "intro", ""]); + VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "intro", ""]); try { - const res = await fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const res = await fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "lockedVideo1", + userID: submitUserOne, + videoID, segments: [{ segment: [1, 10], category: "intro", @@ -896,14 +865,14 @@ describe("postSkipSegments", () => { }).timeout(5000); it("Should be able to submit with custom user-agent 1", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { + fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "com.google.android.youtube/5.0" }, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", + userID: submitUserOne, videoID: "userAgent-1", segments: [{ segment: [0, 10], @@ -926,14 +895,14 @@ describe("postSkipSegments", () => { }); it("Should be able to submit with empty user-agent", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { + fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "" }, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", + userID: submitUserOne, videoID: "userAgent-3", segments: [{ segment: [0, 10], @@ -956,13 +925,13 @@ describe("postSkipSegments", () => { }); it("Should be able to submit with custom userAgent in body", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { + fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", + userID: submitUserOne, videoID: "userAgent-4", segments: [{ segment: [0, 10], @@ -986,14 +955,12 @@ describe("postSkipSegments", () => { }); it("Should be able to submit with commas in timestamps", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json" - }, + const videoID = "commas-1"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "commas-1", + userID: submitUserOne, + videoID, segments: [{ segment: ["0,2", "10,392"], category: "sponsor", @@ -1002,7 +969,7 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["commas-1"]); + const row = await queryDatabase(videoID); const expected = { startTime: 0.2, endTime: 10.392 @@ -1014,8 +981,8 @@ describe("postSkipSegments", () => { }); it("Should be rejected if a POI is at less than 1 second", (done: Done) => { - fetch(`${getbaseURL() - }/api/skipSegments?videoID=qqwerty&startTime=0.5&endTime=0.5&category=poi_highlight&userID=testtesttesttesttesttesttesttesttesting`, { + const videoID = "qqwerty"; + fetch(`${endpoint}?videoID=${videoID}&startTime=0.5&endTime=0.5&category=poi_highlight&userID=${submitUserTwo}`, { method: "POST", }) .then(res => { @@ -1026,14 +993,12 @@ describe("postSkipSegments", () => { }); it("Should not be able to submit with colons in timestamps", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json" - }, + const videoID = "colon-1"; + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testtesttesttesttesttesttesttesttest", - videoID: "colon-1", + userID: submitUserOne, + videoID, segments: [{ segment: ["0:2.000", "3:10.392"], category: "sponsor", diff --git a/test/utils.ts b/test/utils.ts index 3636151..6bebf00 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -37,4 +37,11 @@ export const partialDeepEquals = (actual: Record, expected: Record< function printActualExpected(actual: Record, expected: Record): void { Logger.error(`Actual: ${JSON.stringify(actual)}`); Logger.error(`Expected: ${JSON.stringify(expected)}`); -} \ No newline at end of file +} + +export const postJSON = { + method: "POST", + headers: { + "Content-Type": "application/json", + }, +}; \ No newline at end of file From 7cef510b29abf1adbda85d1e10de8353517697e6 Mon Sep 17 00:00:00 2001 From: Michael C Date: Thu, 16 Sep 2021 20:50:59 -0400 Subject: [PATCH 03/14] quoted --- test/cases/postSkipSegments.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index 75ae64a..bc967ee 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -53,7 +53,7 @@ describe("postSkipSegments", () => { const MILLISECONDS_IN_HOUR = 3600000; const warningExpireTime = MILLISECONDS_IN_HOUR * config.hoursAfterWarningExpires; - const insertWarningQuery = 'INSERT INTO warnings ("userID", "issuerUserID", "enabled", "reason", issueTime) VALUES(?, ?, ?, ?, ?)'; + const insertWarningQuery = 'INSERT INTO warnings ("userID", "issuerUserID", "enabled", "reason", "issueTime") VALUES(?, ?, ?, ?, ?)'; // User 1 db.prepare("run", insertWarningQuery, [warnUser01Hash, warnVip01Hash, 1, reason01, now]); db.prepare("run", insertWarningQuery, [warnUser01Hash, warnVip01Hash, 1, reason01, (now - 1000)]); From e7d55d1e1b1a69a4a97a2ea8ed136aeac39c15da Mon Sep 17 00:00:00 2001 From: Michael C Date: Thu, 16 Sep 2021 23:05:16 -0400 Subject: [PATCH 04/14] everything after postClearCache --- test/cases/postClearCache.ts | 16 +- test/cases/postPurgeAllSegments.ts | 26 +-- test/cases/postSkipSegments.ts | 52 +++-- test/cases/postWarning.ts | 56 ++---- test/cases/reputation.ts | 213 ++++++++++---------- test/cases/segmentShift.ts | 302 +++++++++++++---------------- test/cases/setUsername.ts | 25 +-- test/cases/shadowBanUser.ts | 68 ++++--- test/cases/unBan.ts | 42 ++-- test/cases/voteOnSponsorTime.ts | 224 ++++++++++----------- 10 files changed, 482 insertions(+), 542 deletions(-) diff --git a/test/cases/postClearCache.ts b/test/cases/postClearCache.ts index 46a9718..8fc7516 100644 --- a/test/cases/postClearCache.ts +++ b/test/cases/postClearCache.ts @@ -6,6 +6,7 @@ import assert from "assert"; const VIPUser = "clearCacheVIP"; const regularUser = "regular-user"; +const endpoint = `${getbaseURL()}/api/clearCache`; describe("postClearCache", () => { before(async () => { @@ -15,8 +16,7 @@ describe("postClearCache", () => { }); it("Should be able to clear cache for existing video", (done: Done) => { - fetch(`${getbaseURL() - }/api/clearCache?userID=${VIPUser}&videoID=clear-test`, { + fetch(`${endpoint}?userID=${VIPUser}&videoID=clear-test`, { method: "POST" }) .then(res => { @@ -27,8 +27,7 @@ describe("postClearCache", () => { }); it("Should be able to clear cache for nonexistent video", (done: Done) => { - fetch(`${getbaseURL() - }/api/clearCache?userID=${VIPUser}&videoID=dne-video`, { + fetch(`${endpoint}?userID=${VIPUser}&videoID=dne-video`, { method: "POST" }) .then(res => { @@ -39,8 +38,7 @@ describe("postClearCache", () => { }); it("Should get 403 as non-vip", (done: Done) => { - fetch(`${getbaseURL() - }/api/clearCache?userID=${regularUser}&videoID=clear-tes`, { + fetch(`${endpoint}?userID=${regularUser}&videoID=clear-tes`, { method: "POST" }) .then(async res => { @@ -51,8 +49,7 @@ describe("postClearCache", () => { }); it("Should give 400 with missing videoID", (done: Done) => { - fetch(`${getbaseURL() - }/api/clearCache?userID=${VIPUser}`, { + fetch(`${endpoint}?userID=${VIPUser}`, { method: "POST" }) .then(async res => { @@ -63,8 +60,7 @@ describe("postClearCache", () => { }); it("Should give 400 with missing userID", (done: Done) => { - fetch(`${getbaseURL() - }/api/clearCache?userID=${VIPUser}`, { + fetch(`${endpoint}?userID=${VIPUser}`, { method: "POST" }) .then(async res => { diff --git a/test/cases/postPurgeAllSegments.ts b/test/cases/postPurgeAllSegments.ts index 5c93cd1..f8e68ed 100644 --- a/test/cases/postPurgeAllSegments.ts +++ b/test/cases/postPurgeAllSegments.ts @@ -1,5 +1,5 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import {Done, getbaseURL, postJSON} from "../utils"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import {IDatabase} from "../../src/databases/IDatabase"; @@ -32,9 +32,8 @@ async function dbSponsorTimesCompareExpect(db: IDatabase, videoId: string, expec describe("postPurgeAllSegments", function () { const privateVipUserID = "VIPUser-purgeAll"; - const route = "/api/purgeAllSegments"; const vipUserID = getHash(privateVipUserID); - const baseURL = getbaseURL(); + const endpoint = `${getbaseURL()}/api/purgeAllSegments`; before(async function () { // startTime and endTime get set in beforeEach for consistency @@ -47,11 +46,8 @@ describe("postPurgeAllSegments", function () { }); it("Reject non-VIP user", function (done: Done) { - fetch(`${baseURL}${route}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegpurge01", userID: "segshift_randomuser001", @@ -65,11 +61,8 @@ describe("postPurgeAllSegments", function () { }); it("Purge all segments success", function (done: Done) { - fetch(`${baseURL}${route}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegpurge01", userID: privateVipUserID, @@ -83,12 +76,7 @@ describe("postPurgeAllSegments", function () { }); it("Should return 400 if missing body", function (done: Done) { - fetch(`${baseURL}${route}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - } - }) + fetch(endpoint, { ...postJSON }) .then(async res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index bc967ee..0c7369d 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -12,32 +12,32 @@ const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const sinonStub = mockManager.mock("listVideos"); sinonStub.callsFake(YouTubeApiMock.listVideos); -// Constant and helpers -const submitUserOne = `PostSkipUser1${".".repeat(18)}`; -const submitUserTwo = `PostSkipUser2${".".repeat(18)}`; -const submitUserThree = `PostSkipUser3${".".repeat(18)}`; - -const warnUser01 = "warn-user01-qwertyuiopasdfghjklzxcvbnm"; -const warnUser01Hash = getHash(warnUser01); -const warnUser02 = "warn-user02-qwertyuiopasdfghjklzxcvbnm"; -const warnUser02Hash = getHash(warnUser02); -const warnUser03 = "warn-user03-qwertyuiopasdfghjklzxcvbnm"; -const warnUser03Hash = getHash(warnUser03); -const warnUser04 = "warn-user04-qwertyuiopasdfghjklzxcvbnm"; -const warnUser04Hash = getHash(warnUser04); - -const submitUserOneHash = getHash(submitUserOne); -const submitVIPuser = `VIPPostSkipUser${".".repeat(16)}`; -const warnVideoID = "dQw4w9WgXcF"; -const badInputVideoID = "dQw4w9WgXcQ"; - -const queryDatabase = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); -const queryDatabaseActionType = async(videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); -const queryDatabaseDuration = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); - -const endpoint = `${getbaseURL()}/api/skipSegments`; - describe("postSkipSegments", () => { +// Constant and helpers + const submitUserOne = `PostSkipUser1${".".repeat(18)}`; + const submitUserTwo = `PostSkipUser2${".".repeat(18)}`; + const submitUserThree = `PostSkipUser3${".".repeat(18)}`; + + const warnUser01 = "warn-user01-qwertyuiopasdfghjklzxcvbnm"; + const warnUser01Hash = getHash(warnUser01); + const warnUser02 = "warn-user02-qwertyuiopasdfghjklzxcvbnm"; + const warnUser02Hash = getHash(warnUser02); + const warnUser03 = "warn-user03-qwertyuiopasdfghjklzxcvbnm"; + const warnUser03Hash = getHash(warnUser03); + const warnUser04 = "warn-user04-qwertyuiopasdfghjklzxcvbnm"; + const warnUser04Hash = getHash(warnUser04); + + const submitUserOneHash = getHash(submitUserOne); + const submitVIPuser = `VIPPostSkipUser${".".repeat(16)}`; + const warnVideoID = "dQw4w9WgXcF"; + const badInputVideoID = "dQw4w9WgXcQ"; + + const queryDatabase = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); + const queryDatabaseActionType = async(videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); + const queryDatabaseDuration = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); + + const endpoint = `${getbaseURL()}/api/skipSegments`; + before(() => { const insertSponsorTimeQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; db.prepare("run", insertSponsorTimeQuery, ["80percent_video", 0, 1000, 0, "80percent-uuid-0", submitUserOneHash, 0, 0, "interaction", 0, "80percent_video"]); @@ -598,7 +598,6 @@ describe("postSkipSegments", () => { }) .then( async res => { assert.strictEqual(res.status, 403); - console.log(res.text()); done(); }) .catch(err => done(err)); @@ -611,7 +610,6 @@ describe("postSkipSegments", () => { }) .then(async res => { assert.strictEqual(res.status, 200); - console.log(res.text()); done(); }) .catch(err => done(err)); diff --git a/test/cases/postWarning.ts b/test/cases/postWarning.ts index 1cdd6f6..0f6cc80 100644 --- a/test/cases/postWarning.ts +++ b/test/cases/postWarning.ts @@ -1,10 +1,14 @@ import fetch from "node-fetch"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; +import {Done, getbaseURL, partialDeepEquals, postJSON} from "../utils"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; describe("postWarning", () => { + // constants + const endpoint = `${getbaseURL()}/api/warnUser`; + const getWarning = async (userID: string) => await db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [userID]); + before(async () => { await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES (?)`, [getHash("warning-vip")]); }); @@ -15,16 +19,13 @@ describe("postWarning", () => { userID: "warning-0", reason: "warning-reason-0" }; - fetch(`${getbaseURL()}/api/warnUser`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(async res => { 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 = { enabled: 1, issuerUserID: getHash(json.issuerUserID), @@ -42,16 +43,13 @@ describe("postWarning", () => { userID: "warning-0", }; - fetch(`${getbaseURL()}/api/warnUser`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(async res => { 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 = { enabled: 1, issuerUserID: getHash(json.issuerUserID), @@ -69,16 +67,13 @@ describe("postWarning", () => { enabled: false }; - fetch(`${getbaseURL()}/api/warnUser`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(async res => { 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 = { enabled: 0 }; @@ -94,11 +89,8 @@ describe("postWarning", () => { userID: "warning-1", }; - fetch(`${getbaseURL()}/api/warnUser`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(res => { @@ -109,12 +101,7 @@ describe("postWarning", () => { }); it("Should return 400 if missing body", (done: Done) => { - fetch(`${getbaseURL()}/api/warnUser`, { - method: "POST", - headers: { - "Content-Type": "application/json", - } - }) + fetch(endpoint, postJSON) .then(async res => { assert.strictEqual(res.status, 400); done(); @@ -129,16 +116,13 @@ describe("postWarning", () => { enabled: true }; - fetch(`${getbaseURL()}/api/warnUser`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(async res => { 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 = { enabled: 1 }; diff --git a/test/cases/reputation.ts b/test/cases/reputation.ts index 3bd11ca..b06c0a9 100644 --- a/test/cases/reputation.ts +++ b/test/cases/reputation.ts @@ -4,117 +4,128 @@ import { UserID } from "../../src/types/user.model"; import { getHash } from "../../src/utils/getHash"; 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", () => { + // 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() { this.timeout(5000); // this preparation takes longer then usual const videoID = "reputation-videoID"; 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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'; - 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-1", 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", getHash(userIDLowSubmissions), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); + 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", userHashLowSubmissions, 1606240000000, 50, "sponsor", 0, 0]); + 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", 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-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-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-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-4", 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", 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", 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", 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", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); + 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", 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) - 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 - 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, 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-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-4", 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", 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", 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", 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-1", userHashHighNonSelfDownvotes, 1606240000000, 50, "intro", 0, 0]); + 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", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); + 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", 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-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-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-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-4", getHash(userIDNewSubmissions), Date.now(), 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID, 1)]); - 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, 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-7", getHash(userIDNewSubmissions), 1606240000000, 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", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]); + 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", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]); + 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", userHashNewSubmissions, 1606240000000, 50, "sponsor", 0, 0]); + 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", 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, 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, 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-3", 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", 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", 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", 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", 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", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); + 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", 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-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-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-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-4", 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", 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", 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", 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", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); + 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", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); + 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", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); + 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", 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-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-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-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-4", 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", 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", 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", 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", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); + 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", 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-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-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-3", 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", 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", 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", 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", 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", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); //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, 101, 0, "reputation-7-uuid-1", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "intro", "YouTube", 100, 0, 0, getHash(videoID, 1)]); - 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, 0, 0, "reputation-7-uuid-9", getHash(userIDHaveMostUpvotedInLockedVideo), 1606240000000, 50, "sponsor", "YouTube", 100, 0, 0, getHash(videoID2, 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", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "intro", 0, 0]); + 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", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); // 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-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-4", 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", 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", 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", 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", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); + 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", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); // lock video const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-getLockCategories")]); - const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "hashedVideoID") VALUES (?, ?, ?, ?)'; - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "sponsor", getHash(videoID, 1)]); - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "intro", getHash(videoID, 1)]); - await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID2, "sponsor", getHash(videoID2, 1)]); + const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category") VALUES (?, ?, ?)'; + await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "sponsor"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "intro"]); + await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID2, "sponsor"]); }); 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 () => { @@ -128,9 +139,9 @@ describe("reputation", () => { oldUpvotedSubmissions: 1, mostUpvotedInLockedVideoSum: 0 }; - - assert.strictEqual(await getReputation(getHash(userIDHighDownvotes)), calculateReputationFromMetrics(metrics)); - assert.strictEqual(await getReputation(getHash(userIDHighDownvotes)), -2.125); + const data = await getReputation(getHash(userIDHighDownvotes)); + assert.strictEqual(data, calculateReputationFromMetrics(metrics)); + assert.strictEqual(data, -2.125); }); it("user with high non self downvote ratio", async () => { @@ -144,20 +155,21 @@ describe("reputation", () => { oldUpvotedSubmissions: 1, mostUpvotedInLockedVideoSum: 0 }; - assert.strictEqual(await getReputation(getHash(userIDHighNonSelfDownvotes)), calculateReputationFromMetrics(metrics)); - assert.strictEqual(await getReputation(getHash(userIDHighNonSelfDownvotes)), -1.6428571428571428); + const data = await getReputation(userHashHighNonSelfDownvotes); + assert.strictEqual(data, calculateReputationFromMetrics(metrics)); + assert.strictEqual(data, -1.6428571428571428); }); 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 () => { - 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 () => { - assert.strictEqual(await getReputation(getHash(userIDHighRepBeforeManualVote)), 0); + assert.strictEqual(await getReputation(userHashHighRepBeforeManualVote), 0); }); it("user with high reputation", async () => { @@ -171,8 +183,9 @@ describe("reputation", () => { oldUpvotedSubmissions: 5, mostUpvotedInLockedVideoSum: 0 }; - assert.strictEqual(await getReputation(getHash(userIDHighRep)), calculateReputationFromMetrics(metrics)); - assert.strictEqual(await getReputation(getHash(userIDHighRep)), 0.19310344827586207); + const data = await getReputation(userHashHighRep); + assert.strictEqual(data, calculateReputationFromMetrics(metrics)); + assert.strictEqual(data, 0.19310344827586207); }); it("user with high reputation and locked segments", async () => { @@ -186,8 +199,9 @@ describe("reputation", () => { oldUpvotedSubmissions: 5, mostUpvotedInLockedVideoSum: 0 }; - assert.strictEqual(await getReputation(getHash(userIDHighRepAndLocked)), calculateReputationFromMetrics(metrics)); - assert.strictEqual(await getReputation(getHash(userIDHighRepAndLocked)), 1.793103448275862); + const data = await getReputation(userHashHighAndLocked); + assert.strictEqual(data, calculateReputationFromMetrics(metrics)); + assert.strictEqual(data, 1.793103448275862); }); it("user with most upvoted segments in locked video", async () => { @@ -201,8 +215,9 @@ describe("reputation", () => { oldUpvotedSubmissions: 6, mostUpvotedInLockedVideoSum: 2 }; - assert.strictEqual(await getReputation(getHash(userIDHaveMostUpvotedInLockedVideo)), calculateReputationFromMetrics(metrics)); - assert.strictEqual(await getReputation(getHash(userIDHaveMostUpvotedInLockedVideo)), 6.158620689655172); + const data = await getReputation(userHashHaveMostUpvotedInLockedVideo); + assert.strictEqual(data, calculateReputationFromMetrics(metrics)); + assert.strictEqual(data, 6.158620689655172); }); }); diff --git a/test/cases/segmentShift.ts b/test/cases/segmentShift.ts index 9889af0..164fba2 100644 --- a/test/cases/segmentShift.ts +++ b/test/cases/segmentShift.ts @@ -1,46 +1,47 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import {Done, getbaseURL, postJSON} from "../utils"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import {IDatabase} from "../../src/databases/IDatabase"; import assert from "assert"; -async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) { - const votes = 0, - userID = 0, - timeSubmitted = 0, - views = 0, - shadowHidden = 0, - hashedVideoID = `hash_${UUID}`; - await db.prepare("run", `INSERT INTO - "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", - "userID", "timeSubmitted", "views", "category", "shadowHidden", "hashedVideoID") - VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - [videoID, startTime, endTime, votes, UUID, userID, timeSubmitted, views, category, shadowHidden, hashedVideoID]); -} +describe("segmentShift", function () { + // functions + async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) { + const votes = 0, + userID = 0, + timeSubmitted = 0, + views = 0, + shadowHidden = 0, + hashedVideoID = `hash_${UUID}`; + await db.prepare("run", `INSERT INTO + "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", + "userID", "timeSubmitted", "views", "category", "shadowHidden", "hashedVideoID") + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [videoID, startTime, endTime, votes, UUID, userID, timeSubmitted, views, category, shadowHidden, hashedVideoID]); + } -async function dbSponsorTimesSetByUUID(db: IDatabase, UUID: string, startTime: number, endTime: number) { - await db.prepare("run", `UPDATE "sponsorTimes" SET "startTime" = ?, "endTime" = ? WHERE "UUID" = ?`, [startTime, endTime, UUID]); -} + async function dbSponsorTimesSetByUUID(db: IDatabase, UUID: string, startTime: number, endTime: number) { + await db.prepare("run", `UPDATE "sponsorTimes" SET "startTime" = ?, "endTime" = ? WHERE "UUID" = ?`, [startTime, endTime, UUID]); + } -async function dbSponsorTimesCompareExpect(db: IDatabase, expect: any): Promise { - for (let i = 0, len = expect.length; i < len; i++) { - const expectSeg = expect[i]; - const seg = await db.prepare("get", `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "UUID" = ?`, [expectSeg.UUID]); - if ("removed" in expect) { - assert.ok(expect.removed); - assert.strictEqual(seg.votes, -2); - assert.deepStrictEqual(seg, expectSeg); - assert.strictEqual(seg.startTime, expectSeg.startTime); - assert.strictEqual(seg.endTime, expectSeg.endTime); + async function dbSponsorTimesCompareExpect(db: IDatabase, expect: any): Promise { + for (let i = 0, len = expect.length; i < len; i++) { + const expectSeg = expect[i]; + const seg = await db.prepare("get", `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "UUID" = ?`, [expectSeg.UUID]); + if ("removed" in expect) { + assert.ok(expect.removed); + assert.strictEqual(seg.votes, -2); + assert.deepStrictEqual(seg, expectSeg); + assert.strictEqual(seg.startTime, expectSeg.startTime); + assert.strictEqual(seg.endTime, expectSeg.endTime); + } } } -} - -describe("segmentShift", function () { + // constants const privateVipUserID = "VIPUser-segmentShift"; const vipUserID = getHash(privateVipUserID); - const baseURL = getbaseURL(); + const endpoint = `${getbaseURL()}/api/segmentShift`; before(async function () { // startTime and endTime get set in beforeEach for consistency @@ -60,11 +61,8 @@ describe("segmentShift", function () { }); it("Reject none VIP user", function (done: Done) { - fetch(`${baseURL}/api/segmentShift`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegshift01", userID: "segshift_randomuser001", @@ -80,11 +78,8 @@ describe("segmentShift", function () { }); it("Shift is outside segments", function (done: Done) { - fetch(`${baseURL}/api/segmentShift`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegshift01", userID: privateVipUserID, @@ -94,39 +89,31 @@ describe("segmentShift", function () { }) .then(async res => { assert.strictEqual(res.status, 200); - const expect = [ - { - UUID: "vsegshifttest01uuid01", - startTime: 0, - endTime: 10, - }, - { - UUID: "vsegshifttest01uuid02", - startTime: 50, - endTime: 80, - }, - { - UUID: "vsegshifttest01uuid03", - startTime: 30, - endTime: 35, - }, - { - UUID: "vsegshifttest01uuid04", - startTime: 110, - endTime: 130, - }, - ]; + const expect = [{ + UUID: "vsegshifttest01uuid01", + startTime: 0, + endTime: 10, + }, { + UUID: "vsegshifttest01uuid02", + startTime: 50, + endTime: 80, + }, { + UUID: "vsegshifttest01uuid03", + startTime: 30, + endTime: 35, + }, { + UUID: "vsegshifttest01uuid04", + startTime: 110, + endTime: 130, + }]; done(await dbSponsorTimesCompareExpect(db, expect)); }) .catch(err => done(err)); }); it("Shift is inside segment", function (done: Done) { - fetch(`${baseURL}/api/segmentShift`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegshift01", userID: privateVipUserID, @@ -136,39 +123,31 @@ describe("segmentShift", function () { }) .then(async res => { assert.strictEqual(res.status, 200); - const expect = [ - { - UUID: "vsegshifttest01uuid01", - startTime: 0, - endTime: 10, - }, - { - UUID: "vsegshifttest01uuid02", - startTime: 60, - endTime: 80, - }, - { - UUID: "vsegshifttest01uuid03", - startTime: 40, - endTime: 45, - }, - { - UUID: "vsegshifttest01uuid04", - startTime: 110, - endTime: 130, - }, - ]; + const expect = [{ + UUID: "vsegshifttest01uuid01", + startTime: 0, + endTime: 10, + }, { + UUID: "vsegshifttest01uuid02", + startTime: 60, + endTime: 80, + }, { + UUID: "vsegshifttest01uuid03", + startTime: 40, + endTime: 45, + }, { + UUID: "vsegshifttest01uuid04", + startTime: 110, + endTime: 130, + }]; done(await dbSponsorTimesCompareExpect(db, expect)); }) .catch(err => done(err)); }); it("Shift is overlaping startTime of segment", function (done: Done) { - fetch(`${baseURL}/api/segmentShift`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegshift01", userID: privateVipUserID, @@ -178,39 +157,31 @@ describe("segmentShift", function () { }) .then(async res => { assert.strictEqual(res.status, 200); - const expect = [ - { - UUID: "vsegshifttest01uuid01", - startTime: 0, - endTime: 10, - }, - { - UUID: "vsegshifttest01uuid02", - startTime: 50, - endTime: 80, - }, - { - UUID: "vsegshifttest01uuid03", - startTime: 32, - endTime: 35, - }, - { - UUID: "vsegshifttest01uuid04", - startTime: 110, - endTime: 130, - }, - ]; + const expect = [{ + UUID: "vsegshifttest01uuid01", + startTime: 0, + endTime: 10, + }, { + UUID: "vsegshifttest01uuid02", + startTime: 50, + endTime: 80, + }, { + UUID: "vsegshifttest01uuid03", + startTime: 32, + endTime: 35, + }, { + UUID: "vsegshifttest01uuid04", + startTime: 110, + endTime: 130, + }]; done(await dbSponsorTimesCompareExpect(db, expect)); }) .catch(err => done(err)); }); it("Shift is overlaping endTime of segment", function (done: Done) { - fetch(`${baseURL}/api/segmentShift`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegshift01", userID: privateVipUserID, @@ -220,39 +191,31 @@ describe("segmentShift", function () { }) .then(async res => { assert.strictEqual(res.status, 200); - const expect = [ - { - UUID: "vsegshifttest01uuid01", - startTime: 0, - endTime: 10, - }, - { - UUID: "vsegshifttest01uuid02", - startTime: 60, - endTime: 85, - }, - { - UUID: "vsegshifttest01uuid03", - startTime: 40, - endTime: 45, - }, - { - UUID: "vsegshifttest01uuid04", - startTime: 110, - endTime: 130, - }, - ]; + const expect = [{ + UUID: "vsegshifttest01uuid01", + startTime: 0, + endTime: 10, + }, { + UUID: "vsegshifttest01uuid02", + startTime: 60, + endTime: 85, + }, { + UUID: "vsegshifttest01uuid03", + startTime: 40, + endTime: 45, + }, { + UUID: "vsegshifttest01uuid04", + startTime: 110, + endTime: 130, + }]; done(await dbSponsorTimesCompareExpect(db, expect)); }) .catch(err => done(err)); }); it("Shift is overlaping segment", function (done: Done) { - fetch(`${baseURL}/api/segmentShift`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({ videoID: "vsegshift01", userID: privateVipUserID, @@ -262,29 +225,24 @@ describe("segmentShift", function () { }) .then(async res => { assert.strictEqual(res.status, 200); - const expect = [ - { - UUID: "vsegshifttest01uuid01", - startTime: 0, - endTime: 10, - }, - { - UUID: "vsegshifttest01uuid02", - startTime: 40, - endTime: 70, - }, - { - UUID: "vsegshifttest01uuid03", - startTime: 40, - endTime: 45, - removed: true, - }, - { - UUID: "vsegshifttest01uuid04", - startTime: 100, - endTime: 120, - }, - ]; + const expect = [{ + UUID: "vsegshifttest01uuid01", + startTime: 0, + endTime: 10, + }, { + UUID: "vsegshifttest01uuid02", + startTime: 40, + endTime: 70, + }, { + UUID: "vsegshifttest01uuid03", + startTime: 40, + endTime: 45, + removed: true, + }, { + UUID: "vsegshifttest01uuid04", + startTime: 100, + endTime: 120, + }]; done(await dbSponsorTimesCompareExpect(db, expect)); }) .catch(err => done(err)); diff --git a/test/cases/setUsername.ts b/test/cases/setUsername.ts index c9000c0..c0927aa 100644 --- a/test/cases/setUsername.ts +++ b/test/cases/setUsername.ts @@ -60,6 +60,7 @@ async function testUserNameChangelog(userID: string, newUserName: string, oldUse } describe("setUsername", () => { + const endpoint = `${getbaseURL()}/api/setUsername`; before(async () => { await addUsername(getHash(user01PrivateUserID), username01, 0); await addUsername(getHash(user02PrivateUserID), username02, 0); @@ -71,7 +72,7 @@ describe("setUsername", () => { }); it("Should be able to set username that has never been set", (done: Done) => { - fetch(`${getbaseURL()}/api/setUsername?userID=${user00PrivateUserID}&username=${username00}`, { + fetch(`${endpoint}?userID=${user00PrivateUserID}&username=${username00}`, { method: "POST", }) .then(async res => { @@ -85,7 +86,7 @@ describe("setUsername", () => { }); it("Should return 200", (done: Done) => { - fetch(`${getbaseURL()}/api/setUsername?userID=${user01PrivateUserID}&username=Changed%20Username`, { + fetch(`${endpoint}?userID=${user01PrivateUserID}&username=Changed%20Username`, { method: "POST", }) .then(async res => { @@ -96,7 +97,7 @@ describe("setUsername", () => { }); it('Should return 400 for missing param "userID"', (done: Done) => { - fetch(`${getbaseURL()}/api/setUsername?username=MyUsername`, { + fetch(`${endpoint}?username=MyUsername`, { method: "POST", }) .then(res => { @@ -107,7 +108,7 @@ describe("setUsername", () => { }); it('Should return 400 for missing param "username"', (done: Done) => { - fetch(`${getbaseURL()}/api/setUsername?userID=test`, { + fetch(`${endpoint}?userID=test`, { method: "POST", }) .then(res => { @@ -119,7 +120,7 @@ describe("setUsername", () => { it('Should return 400 for "username" longer then 64 characters', (done: Done) => { const username65 = "0000000000000000000000000000000000000000000000000000000000000000X"; - fetch(`${getbaseURL()}/api/setUsername?userID=test&username=${encodeURIComponent(username65)}`, { + fetch(`${endpoint}?userID=test&username=${encodeURIComponent(username65)}`, { method: "POST", }) .then(res => { @@ -131,7 +132,7 @@ describe("setUsername", () => { it('Should not change username if it contains "discord"', (done: Done) => { const newUsername = "discord.me"; - fetch(`${getbaseURL()}/api/setUsername?userID=${user02PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { + fetch(`${endpoint}?userID=${user02PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { method: "POST", }) .then(async res => { @@ -145,7 +146,7 @@ describe("setUsername", () => { it("Should be able to change username", (done: Done) => { const newUsername = "newUsername"; - fetch(`${getbaseURL()}/api/setUsername?userID=${user03PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { + fetch(`${endpoint}?userID=${user03PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { method: "POST", }) .then(async () => { @@ -159,7 +160,7 @@ describe("setUsername", () => { it("Should not be able to change locked username", (done: Done) => { const newUsername = "newUsername"; - fetch(`${getbaseURL()}/api/setUsername?userID=${user04PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { + fetch(`${endpoint}?userID=${user04PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { method: "POST", }) .then(async () => { @@ -173,7 +174,7 @@ describe("setUsername", () => { it("Should filter out unicode control characters", (done: Done) => { const newUsername = "This\nUsername+has\tInvalid+Characters"; - fetch(`${getbaseURL()}/api/setUsername?userID=${user05PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { + fetch(`${endpoint}?userID=${user05PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { method: "POST", }) .then(async () => { @@ -186,7 +187,7 @@ describe("setUsername", () => { it("Incorrect adminUserID should return 403", (done: Done) => { const newUsername = "New Username"; - fetch(`${getbaseURL()}/api/setUsername?adminUserID=invalidAdminID&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { + fetch(`${endpoint}?adminUserID=invalidAdminID&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { method: "POST", }) .then(async res => { @@ -198,7 +199,7 @@ describe("setUsername", () => { it("Admin should be able to change username", (done: Done) => { const newUsername = "New Username"; - fetch(`${getbaseURL()}/api/setUsername?adminUserID=${adminPrivateUserID}&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { + fetch(`${endpoint}?adminUserID=${adminPrivateUserID}&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { method: "POST", }) .then(async () => { @@ -212,7 +213,7 @@ describe("setUsername", () => { it("Admin should be able to change locked username", (done: Done) => { const newUsername = "New Username"; - fetch(`${getbaseURL()}/api/setUsername?adminUserID=${adminPrivateUserID}&userID=${getHash(user07PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { + fetch(`${endpoint}?adminUserID=${adminPrivateUserID}&userID=${getHash(user07PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { method: "POST", }) .then(async () => { diff --git a/test/cases/shadowBanUser.ts b/test/cases/shadowBanUser.ts index 56cf15f..0b91206 100644 --- a/test/cases/shadowBanUser.ts +++ b/test/cases/shadowBanUser.ts @@ -3,8 +3,16 @@ import {db} from "../../src/databases/databases"; import {Done, getbaseURL} from "../utils"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; +import { Category } from "../../src/types/segments.model"; describe("shadowBanUser", () => { + const endpoint = `${getbaseURL()}/api/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 VIPuserID = "shadow-ban-vip"; + before(async () => { 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)]); @@ -24,19 +32,18 @@ describe("shadowBanUser", () => { 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 "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: Done) => { - fetch(`${getbaseURL() - }/api/shadowBanUser?userID=shadowBanned&adminUserID=shadow-ban-vip`, { + const userID = "shadowBanned"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}`, { method: "POST" }) .then(async res => { assert.strictEqual(res.status, 200); - const videoRow = await db.prepare("all", `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned", 1]); - const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned"]); + const videoRow = await getShadowBanSegments(userID, 1); + const shadowRow = await getShadowBan(userID); assert.ok(shadowRow); assert.strictEqual(videoRow.length, 3); done(); @@ -45,14 +52,14 @@ describe("shadowBanUser", () => { }); it("Should be able to unban user without unhiding submissions", (done: Done) => { - fetch(`${getbaseURL() - }/api/shadowBanUser?userID=shadowBanned&adminUserID=shadow-ban-vip&enabled=false&unHideOldSubmissions=false`, { + const userID = "shadowBanned"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=false&unHideOldSubmissions=false`, { method: "POST" }) .then(async res => { assert.strictEqual(res.status, 200); - const videoRow = await db.prepare("all", `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned", 1]); - const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned"]); + const videoRow = await getShadowBanSegments(userID, 1); + const shadowRow = await getShadowBan(userID); assert.ok(!shadowRow); assert.strictEqual(videoRow.length, 3); done(); @@ -61,14 +68,14 @@ describe("shadowBanUser", () => { }); it("Should be able to ban user and hide submissions from only some categories", (done: Done) => { - fetch(`${getbaseURL() - }/api/shadowBanUser?userID=shadowBanned2&adminUserID=shadow-ban-vip&categories=["sponsor"]`, { + const userID = "shadowBanned2"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&categories=["sponsor"]`, { method: "POST" }) .then(async res => { 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 shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned2"]); + const videoRow = await getShadowBanSegmentCategory(userID, 1); + const shadowRow = await getShadowBan(userID); assert.ok(shadowRow); assert.strictEqual(videoRow.length, 2); assert.strictEqual(videoRow.filter((elem) => elem.category === "sponsor").length, 2); @@ -78,14 +85,14 @@ describe("shadowBanUser", () => { }); it("Should be able to unban user and unhide submissions", (done: Done) => { - fetch(`${getbaseURL() - }/api/shadowBanUser?userID=shadowBanned2&adminUserID=shadow-ban-vip&enabled=false`, { + const userID = "shadowBanned2"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=false`, { method: "POST" }) .then(async res => { assert.strictEqual(res.status, 200); - const videoRow = await db.prepare("all", `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned2", 1]); - const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned2"]); + const videoRow = await getShadowBanSegments(userID, 1); + const shadowRow = await getShadowBan(userID); assert.ok(!shadowRow); assert.strictEqual(videoRow?.length, 0); done(); @@ -94,14 +101,14 @@ describe("shadowBanUser", () => { }); it("Should be able to unban user and unhide some submissions", (done: Done) => { - fetch(`${getbaseURL() - }/api/shadowBanUser?userID=shadowBanned3&adminUserID=shadow-ban-vip&enabled=false&categories=["sponsor"]`, { + const userID = "shadowBanned3"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=false&categories=["sponsor"]`, { method: "POST" }) .then(async res => { assert.strictEqual(res.status, 200); - const videoRow = await db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned3", 1]); - const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned3"]); + const videoRow = await getShadowBanSegmentCategory(userID, 1); + const shadowRow = await getShadowBan(userID); assert.ok(!shadowRow); assert.strictEqual(videoRow.length, 1); assert.strictEqual(videoRow[0].category, "intro"); @@ -111,14 +118,14 @@ describe("shadowBanUser", () => { }); it("Should get 409 when re-shadowbanning user", (done: Done) => { - fetch(`${getbaseURL() - }/api/shadowBanUser?userID=shadowBanned4&adminUserID=shadow-ban-vip&enabled=true&categories=["sponsor"]&unHideOldSubmissions=false`, { + const userID = "shadowBanned4"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=true&categories=["sponsor"]&unHideOldSubmissions=false`, { method: "POST" }) .then(async res => { assert.strictEqual(res.status, 409); - const videoRow = await db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned4", 0]); - const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned4"]); + const videoRow = await getShadowBanSegmentCategory(userID, 0); + const shadowRow = await getShadowBan(userID); assert.ok(shadowRow); // ban still exists assert.strictEqual(videoRow.length, 1); // videos should not be hidden assert.strictEqual(videoRow[0].category, "sponsor"); @@ -128,14 +135,14 @@ describe("shadowBanUser", () => { }); it("Should be able to re-shadowban user to hide old submissions", (done: Done) => { - fetch(`${getbaseURL() - }/api/shadowBanUser?userID=shadowBanned4&adminUserID=shadow-ban-vip&enabled=true&categories=["sponsor"]&unHideOldSubmissions=true`, { + const userID = "shadowBanned4"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=true&categories=["sponsor"]&unHideOldSubmissions=true`, { method: "POST" }) .then(async res => { assert.strictEqual(res.status, 200); - const videoRow = await db.prepare("all", `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned4", 1]); - const shadowRow = await db.prepare("get", `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned4"]); + const videoRow = await getShadowBanSegmentCategory(userID, 1); + const shadowRow = await getShadowBan(userID); assert.ok(shadowRow); // ban still exists assert.strictEqual(videoRow.length, 1); // videos should be hidden assert.strictEqual(videoRow[0].category, "sponsor"); @@ -143,5 +150,4 @@ describe("shadowBanUser", () => { }) .catch(err => done(err)); }); - }); diff --git a/test/cases/unBan.ts b/test/cases/unBan.ts index acba7e5..3de23dc 100644 --- a/test/cases/unBan.ts +++ b/test/cases/unBan.ts @@ -1,10 +1,13 @@ import fetch from "node-fetch"; -import * as utils from "../utils"; +import { getbaseURL, postJSON } from "../utils"; import { getHash } from "../../src/utils/getHash"; import { db } from "../../src/databases/databases"; import assert from "assert"; describe("unBan", () => { + const endpoint = `${getbaseURL()}/api/shadowBanUser`; + const VIPuser = "VIPUser-unBan"; + 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 () => { const insertShadowBannedUserQuery = 'INSERT INTO "shadowBannedUsers" VALUES(?)'; await db.prepare("run", insertShadowBannedUserQuery, ["testMan-unBan"]); @@ -12,10 +15,10 @@ describe("unBan", () => { await db.prepare("run", insertShadowBannedUserQuery, ["testEntity-unBan"]); 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(?, ?, ?)'; - 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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 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 +28,13 @@ describe("unBan", () => { }); it("Should be able to unban a user and re-enable shadow banned segments", (done) => { - fetch(`${utils.getbaseURL() - }/api/shadowBanUser?userID=testMan-unBan&adminUserID=VIPUser-unBan&enabled=false`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const userID = "testMan-unBan"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuser}&enabled=false`, { + ...postJSON }) .then(async res => { 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); done(); }) @@ -42,16 +42,13 @@ describe("unBan", () => { }); it("Should be able to unban a user and re-enable shadow banned segments without lockCategories entrys", (done) => { - fetch(`${utils.getbaseURL() - }/api/shadowBanUser?userID=testWoman-unBan&adminUserID=VIPUser-unBan&enabled=false`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const userID = "testWoman-unBan"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuser}&enabled=false`, { + ...postJSON }) .then(async res => { 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); done(); }) @@ -59,16 +56,13 @@ describe("unBan", () => { }); it("Should be able to unban a user and re-enable shadow banned segments with a mix of lockCategories entrys", (done) => { - fetch(`${utils.getbaseURL() - }/api/shadowBanUser?userID=testEntity-unBan&adminUserID=VIPUser-unBan&enabled=false`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + const userID = "testEntity-unBan"; + fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuser}&enabled=false`, { + ...postJSON }) .then(async res => { 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); done(); }) diff --git a/test/cases/voteOnSponsorTime.ts b/test/cases/voteOnSponsorTime.ts index 765f038..1167605 100644 --- a/test/cases/voteOnSponsorTime.ts +++ b/test/cases/voteOnSponsorTime.ts @@ -21,31 +21,31 @@ describe("voteOnSponsorTime", () => { const MILLISECONDS_IN_HOUR = 3600000; 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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - 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-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, 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.6", "testman", 0, 50, "interaction", 0, 0, getHash("vote-testtesttest2", 1)]); - 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-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-test3", 1, 11, 2, "vote-uuid-4", "testman", 0, 50, "sponsor", 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, getHash("vote-test3", 1)]); - 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-multiple", 1, 11, 2, "vote-uuid-6", "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, getHash("vote-multiple", 1)]); - 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-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-10", getHash("randomID3"), 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, getHash("voter-submitter2", 1)]); - 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, ["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, ["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-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, ["vote-testtesttest", 1, 11, 2, "warnvote-uuid-0", "testman", 0, 50, "sponsor", 0, 0, getHash("vote-testtesttest", 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, 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, getHash("no-sponsor-segments-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, 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, getHash("segment-locking-video", 1)]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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]); + 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(?, ?, ?, ?)'; await db.prepare("run", insertWarningQuery, [warnUser01Hash, now, warnVip01Hash, 1]); @@ -63,13 +63,17 @@ describe("voteOnSponsorTime", () => { await db.prepare("run", 'INSERT INTO "lockCategories" ("videoID", "userID", "category") VALUES (?, ?, ?)', ["no-sponsor-segments-video", "someUser", "sponsor"]); }); + // constants + const endpoint = `${getbaseURL()}/api/voteOnSponsorTime`; + const getSegmentVotes = (UUID: string) => db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]); + const getSegmentCategory = (UUID: string) => db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]); it("Should be able to upvote a segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID&UUID=vote-uuid-0&type=1`) + const UUID = "vote-uuid-0"; + fetch(`${endpoint}?userID=randomID&UUID=${UUID}&type=1`) .then(async res => { 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); done(); }) @@ -77,11 +81,11 @@ describe("voteOnSponsorTime", () => { }); it("Should be able to downvote a segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=0`) + const UUID = "vote-uuid-2"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=0`) .then(async res => { 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); done(); }) @@ -89,11 +93,11 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to downvote the same segment when voting from a different user on the same IP", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID3&UUID=vote-uuid-2&type=0`) + const UUID = "vote-uuid-2"; + fetch(`${endpoint}?userID=randomID3&UUID=${UUID}&type=0`) .then(async res => { 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); done(); }) @@ -101,11 +105,10 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to downvote a segment if the user is shadow banned", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID4&UUID=vote-uuid-1.6&type=0`) + fetch(`${endpoint}?userID=randomID4&UUID=vote-uuid-1.6&type=0`) .then(async res => { 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("vote-uuid-1.6"); assert.strictEqual(row.votes, 10); done(); }) @@ -113,11 +116,10 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to upvote a segment if the user hasn't submitted yet", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1&type=1`) + fetch(`${endpoint}?userID=hasNotSubmittedID&UUID=vote-uuid-1&type=1`) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1"]); + const row = await getSegmentVotes("vote-uuid-1"); assert.strictEqual(row.votes, 2); done(); }) @@ -125,11 +127,10 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to downvote a segment if the user hasn't submitted yet", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1.5&type=0`) + fetch(`${endpoint}?userID=hasNotSubmittedID&UUID=vote-uuid-1.5&type=0`) .then(async res => { 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("vote-uuid-1.5"); assert.strictEqual(row.votes, 10); done(); }) @@ -137,11 +138,10 @@ describe("voteOnSponsorTime", () => { }); it("VIP should be able to completely downvote a segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-3&type=0`) + fetch(`${endpoint}?userID=VIPUser&UUID=vote-uuid-3&type=0`) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-3"]); + const row = await getSegmentVotes("vote-uuid-3"); assert.ok(row.votes <= -2); done(); }) @@ -149,11 +149,10 @@ describe("voteOnSponsorTime", () => { }); it("should be able to completely downvote your own segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=own-submission-id&UUID=own-submission-uuid&type=0`) + fetch(`${endpoint}?userID=own-submission-id&UUID=own-submission-uuid&type=0`) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["own-submission-uuid"]); + const row = await getSegmentVotes("own-submission-uuid"); assert.ok(row.votes <= -2); done(); }) @@ -161,11 +160,10 @@ describe("voteOnSponsorTime", () => { }); it("should not be able to completely downvote somebody elses segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=not-own-submission-uuid&type=0`) + fetch(`${endpoint}?userID=randomID2&UUID=not-own-submission-uuid&type=0`) .then(async res => { 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("not-own-submission-uuid"); assert.strictEqual(row.votes, 499); done(); }) @@ -173,12 +171,12 @@ describe("voteOnSponsorTime", () => { }); it("Should be able to vote for a category and it should add your vote to the database", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=intro`) + const UUID = "vote-uuid-4"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-4"]); - const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, ["vote-uuid-4"]); + const row = await getSegmentCategory(UUID); + const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, [UUID]); assert.strictEqual(row.category, "sponsor"); assert.strictEqual(categoryRows.length, 2); assert.strictEqual(categoryRows[0].votes, 1); @@ -191,11 +189,11 @@ describe("voteOnSponsorTime", () => { }); it("Should not able to change to an invalid category", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=fakecategory`) + const UUID = "incorrect-category"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=fakecategory`) .then(async res => { 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"); done(); }) @@ -203,11 +201,11 @@ describe("voteOnSponsorTime", () => { }); it("Should not able to change to highlight category", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=highlight`) + const UUID = "incorrect-category"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=highlight`) .then(async res => { 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"); done(); }) @@ -215,12 +213,12 @@ describe("voteOnSponsorTime", () => { }); it("Should be able to change your vote for a category and it should add your vote to the database", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=outro`) + const UUID = "vote-uuid-4"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=outro`) .then(async res => { if (res.status === 200) { - const submissionRow = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-4"]); - const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, ["vote-uuid-4"]); + const submissionRow = await getSegmentCategory(UUID); + const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, [UUID]); let introVotes = 0; let outroVotes = 0; let sponsorVotes = 0; @@ -244,11 +242,11 @@ describe("voteOnSponsorTime", () => { it("Should not be able to change your vote to an invalid category", (done: Done) => { + const UUID = "incorrect-category-change"; const vote = (inputCat: string, assertCat: string, callback: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category-change&category=${inputCat}`) + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=${inputCat}`) .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); callback(); }) @@ -261,12 +259,12 @@ describe("voteOnSponsorTime", () => { it("VIP should be able to vote for a category and it should immediately change", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&category=outro`) + const UUID = "vote-uuid-5"; + fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&category=outro`) .then(async res => { assert.strictEqual(res.status, 200); - const row = await db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); - const row2 = await db.prepare("get", `SELECT votes FROM "categoryVotes" WHERE "UUID" = ? and category = ?`, ["vote-uuid-5", "outro"]); + const row = await getSegmentCategory(UUID); + const row2 = await db.prepare("get", `SELECT votes FROM "categoryVotes" WHERE "UUID" = ? and category = ?`, [UUID, "outro"]); assert.strictEqual(row.category, "outro"); assert.strictEqual(row2.votes, 500); done(); @@ -275,11 +273,11 @@ describe("voteOnSponsorTime", () => { }); it("Submitter should be able to vote for a category and it should immediately change", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=testman&UUID=vote-uuid-5_1&category=outro`) + const UUID = "vote-uuid-5_1"; + fetch(`${endpoint}?userID=testman&UUID=${UUID}&category=outro`) .then(async res => { 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"); done(); }) @@ -287,8 +285,8 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to category-vote on an invalid UUID submission", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID3&UUID=invalid-uuid&category=intro`) + const UUID = "invalid-uuid"; + fetch(`${endpoint}?userID=randomID3&UUID=${UUID}&category=intro`) .then(async res => { assert.strictEqual(res.status, 400); done(); @@ -297,11 +295,11 @@ describe("voteOnSponsorTime", () => { }); it('Non-VIP should not be able to upvote "dead" submission', (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=1`) + const UUID = "vote-uuid-5"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=1`) .then(async res => { 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); done(); }) @@ -309,11 +307,11 @@ describe("voteOnSponsorTime", () => { }); it('Non-VIP should not be able to downvote "dead" submission', (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=0`) + const UUID = "vote-uuid-5"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=0`) .then(async res => { 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); done(); }) @@ -321,11 +319,11 @@ describe("voteOnSponsorTime", () => { }); it('VIP should be able to upvote "dead" submission', (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&type=1`) + const UUID = "vote-uuid-5"; + fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=1`) .then(async res => { 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); done(); }) @@ -333,8 +331,8 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to upvote a segment (Too many warning)", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=warn-voteuser01&UUID=warnvote-uuid-0&type=1`) + const UUID = "warnvote-uuid-0"; + fetch(`${endpoint}?userID=warn-voteuser01&UUID=${UUID}&type=1`) .then(async res => { assert.strictEqual(res.status, 403); done(); @@ -343,11 +341,11 @@ describe("voteOnSponsorTime", () => { }); it("Non-VIP should not be able to downvote on a segment with no-segments category", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=0`) + const UUID = "no-sponsor-segments-uuid-0"; + fetch(`${endpoint}?userID=randomID&UUID=${UUID}&type=0`) .then(async res => { 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); done(); }) @@ -355,11 +353,11 @@ describe("voteOnSponsorTime", () => { }); it("Non-VIP should be able to upvote on a segment with no-segments category", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=1`) + const UUID = "no-sponsor-segments-uuid-0"; + fetch(`${endpoint}?userID=randomID&UUID=${UUID}&type=1`) .then(async res => { 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); done(); }) @@ -367,11 +365,11 @@ describe("voteOnSponsorTime", () => { }); it("Non-VIP should not be able to category vote on a segment with no-segments category", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&category=outro`) + const UUID = "no-sponsor-segments-uuid-0"; + fetch(`${endpoint}?userID=randomID&UUID=${UUID}&category=outro`) .then(async res => { 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"); done(); }) @@ -379,11 +377,11 @@ describe("voteOnSponsorTime", () => { }); it("VIP upvote should lock segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=1`) + const UUID = "segment-locking-uuid-1"; + fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=1`) .then(async res => { 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); done(); }) @@ -391,11 +389,11 @@ describe("voteOnSponsorTime", () => { }); it("VIP downvote should unlock segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=0`) + const UUID = "segment-locking-uuid-1"; + fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=0`) .then(async res => { 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); done(); }) @@ -403,11 +401,11 @@ describe("voteOnSponsorTime", () => { }); it("VIP upvote should unhide segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-hidden-uuid-1&type=1`) + const UUID = "segment-hidden-uuid-1"; + fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=1`) .then(async res => { 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); done(); }) @@ -415,11 +413,11 @@ describe("voteOnSponsorTime", () => { }); it("Should be able to undo-vote a segment", (done: Done) => { - fetch(`${getbaseURL() - }/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=20`) + const UUID = "vote-uuid-2"; + fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=20`) .then(async res => { 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); done(); }) @@ -427,7 +425,8 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to vote with type 10", (done: Done) => { - fetch(`${getbaseURL() }/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=10`) + const UUID = "segment-locking-uuid-1"; + fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=10`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -436,7 +435,8 @@ describe("voteOnSponsorTime", () => { }); it("Should not be able to vote with type 11", (done: Done) => { - fetch(`${getbaseURL() }/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=11`) + const UUID = "segment-locking-uuid-1"; + fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=11`) .then(res => { assert.strictEqual(res.status, 400); done(); From 9e9fcd47c00bfe04dbdebbed852cb5b9dd71a5b5 Mon Sep 17 00:00:00 2001 From: Michael C Date: Thu, 16 Sep 2021 23:59:19 -0400 Subject: [PATCH 05/14] finished other tests --- test/cases/getIsUserVIP.ts | 13 +- test/cases/getLockCategories.ts | 9 +- test/cases/getLockCategoriesByHash.ts | 21 +-- test/cases/getSavedTimeForUser.ts | 3 +- test/cases/getSearchSegments.ts | 29 ++-- test/cases/getSegmentInfo.ts | 43 ++--- test/cases/getSkipSegments.ts | 57 ++++--- test/cases/getSkipSegmentsByHash.ts | 48 +++--- test/cases/getStatus.ts | 13 +- test/cases/getUserID.ts | 45 ++--- test/cases/getUserInfo.ts | 41 ++--- test/cases/lockCategoriesRecords.ts | 228 +++++++++++--------------- test/cases/oldGetSponsorTime.ts | 6 +- 13 files changed, 263 insertions(+), 293 deletions(-) diff --git a/test/cases/getIsUserVIP.ts b/test/cases/getIsUserVIP.ts index c8bce73..d380eea 100644 --- a/test/cases/getIsUserVIP.ts +++ b/test/cases/getIsUserVIP.ts @@ -5,12 +5,13 @@ import {getHash} from "../../src/utils/getHash"; import assert from "assert"; describe("getIsUserVIP", () => { - before((done: Done) => { - db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash("isUserVIPVIP")]).then(done); + const endpoint = `${getbaseURL()}/api/isUserVIP`; + before(() => { + db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash("isUserVIPVIP")]); }); it("Should be able to get a 200", (done: Done) => { - fetch(`${getbaseURL()}/api/isUserVIP?userID=isUserVIPVIP`) + fetch(`${endpoint}?userID=isUserVIPVIP`) .then(res => { assert.strictEqual(res.status, 200, "response should be 200"); done(); @@ -20,7 +21,7 @@ describe("getIsUserVIP", () => { it("Should get a 400 if no userID", (done: Done) => { - fetch(`${getbaseURL()}/api/isUserVIP`) + fetch(endpoint) .then(res => { assert.strictEqual(res.status, 400, "response should be 400"); done(); @@ -29,7 +30,7 @@ describe("getIsUserVIP", () => { }); it("Should say a VIP is a VIP", (done: Done) => { - fetch(`${getbaseURL()}/api/isUserVIP?userID=isUserVIPVIP`) + fetch(`${endpoint}?userID=isUserVIPVIP`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -40,7 +41,7 @@ describe("getIsUserVIP", () => { }); it("Should say a normal user is not a VIP", (done: Done) => { - fetch(`${getbaseURL()}/api/isUserVIP?userID=isUserVIPNormal`) + fetch(`${endpoint}?userID=isUserVIPNormal`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); diff --git a/test/cases/getLockCategories.ts b/test/cases/getLockCategories.ts index 55830f0..a70b5e7 100644 --- a/test/cases/getLockCategories.ts +++ b/test/cases/getLockCategories.ts @@ -6,6 +6,7 @@ import assert from "assert"; describe("getLockCategories", () => { + const endpoint = `${getbaseURL()}/api/lockCategories`; before(async () => { const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; await db.prepare("run", insertVipUserQuery, [getHash("getLockCategoriesVIP")]); @@ -25,7 +26,7 @@ describe("getLockCategories", () => { }); it("Should be able to get multiple locks", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock1`) + fetch(`${endpoint}?videoID=getLock1`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -43,7 +44,7 @@ describe("getLockCategories", () => { }); it("Should be able to get single locks", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories?videoID=getLock2`) + fetch(`${endpoint}?videoID=getLock2`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -60,7 +61,7 @@ describe("getLockCategories", () => { }); it("should return 404 if no lock exists", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories?videoID=getLockNull`) + fetch(`${endpoint}?videoID=getLockNull`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -69,7 +70,7 @@ describe("getLockCategories", () => { }); it("should return 400 if no videoID specified", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories`) + fetch(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getLockCategoriesByHash.ts b/test/cases/getLockCategoriesByHash.ts index cc7e605..7cfeb6a 100644 --- a/test/cases/getLockCategoriesByHash.ts +++ b/test/cases/getLockCategoriesByHash.ts @@ -7,6 +7,7 @@ import assert from "assert"; const fakeHash = "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35"; describe("getLockCategoriesByHash", () => { + const endpoint = `${getbaseURL()}/api/lockCategories`; before(async () => { const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; await db.prepare("run", insertVipUserQuery, [getHash("getLockCategoriesHashVIP")]); @@ -34,7 +35,7 @@ describe("getLockCategoriesByHash", () => { it("Should be able to get multiple locks in one object", (done: Done) => { const videoID = "getLockHash1"; const hash = getHash(videoID, 1); - fetch(`${getbaseURL()}/api/lockCategories/${hash.substring(0,4)}`) + fetch(`${endpoint}/${hash.substring(0,4)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -56,7 +57,7 @@ describe("getLockCategoriesByHash", () => { it("Should be able to get single lock", (done: Done) => { const videoID = "getLockHash2"; const hash = getHash(videoID, 1); - fetch(`${getbaseURL()}/api/lockCategories/${hash.substring(0,6)}`) + fetch(`${endpoint}/${hash.substring(0,6)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -77,7 +78,7 @@ describe("getLockCategoriesByHash", () => { it("Should be able to get by half full hash", (done: Done) => { const videoID = "getLockHash3"; const hash = getHash(videoID, 1); - fetch(`${getbaseURL()}/api/lockCategories/${hash.substring(0,32)}`) + fetch(`${endpoint}/${hash.substring(0,32)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -96,7 +97,7 @@ describe("getLockCategoriesByHash", () => { }); it("Should be able to get multiple by similar hash with multiple categories", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/${fakeHash.substring(0,5)}`) + fetch(`${endpoint}/${fakeHash.substring(0,5)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -123,7 +124,7 @@ describe("getLockCategoriesByHash", () => { }); it("should return 404 once hash prefix varies", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/b05aa`) + fetch(`${endpoint}/b05aa`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -132,7 +133,7 @@ describe("getLockCategoriesByHash", () => { }); it("should return 404 if no lock exists", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/aaaaaa`) + fetch(`${endpoint}/aaaaaa`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -141,7 +142,7 @@ describe("getLockCategoriesByHash", () => { }); it("should return 400 if no videoID specified", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/`) + fetch(`${endpoint}/`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -150,7 +151,7 @@ describe("getLockCategoriesByHash", () => { }); it("should return 400 if full hash sent", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/${fakeHash}`) + fetch(`${endpoint}/${fakeHash}`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -159,7 +160,7 @@ describe("getLockCategoriesByHash", () => { }); it("should return 400 if hash too short", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/00`) + fetch(`${endpoint}/00`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -168,7 +169,7 @@ describe("getLockCategoriesByHash", () => { }); it("should return 400 if no hash specified", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories/`) + fetch(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getSavedTimeForUser.ts b/test/cases/getSavedTimeForUser.ts index c41bef4..6d11409 100644 --- a/test/cases/getSavedTimeForUser.ts +++ b/test/cases/getSavedTimeForUser.ts @@ -5,6 +5,7 @@ import {getHash} from "../../src/utils/getHash"; import {deepStrictEqual} from "assert"; describe("getSavedTimeForUser", () => { + const endpoint = `${getbaseURL()}/api/getSavedTimeForUser`; before(async () => { const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", "views", "shadowHidden") VALUES'; await db.prepare("run", `${startOfQuery}(?, ?, ?, ?, ?, ?, ?, ?, ?)`, @@ -13,7 +14,7 @@ describe("getSavedTimeForUser", () => { }); it("Should be able to get a 200", (done: Done) => { - fetch(`${getbaseURL()}/api/getSavedTimeForUser?userID=getSavedTimeForUserUser`) + fetch(`${endpoint}?userID=getSavedTimeForUserUser`) .then(async res => { const data = await res.json(); // (end-start)*minute * views diff --git a/test/cases/getSearchSegments.ts b/test/cases/getSearchSegments.ts index 61cabae..481fb25 100644 --- a/test/cases/getSearchSegments.ts +++ b/test/cases/getSearchSegments.ts @@ -4,6 +4,7 @@ import {Done, getbaseURL} from "../utils"; import assert from "assert"; describe("getSearchSegments", () => { + const endpoint = `${getbaseURL()}/api/searchSegments`; before(async () => { 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", "searchTestUser", "sponsor", "skip"]); @@ -33,7 +34,7 @@ describe("getSearchSegments", () => { }); it("Should be able to show all segments under searchTest0", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0`) + fetch(`${endpoint}?videoID=searchTest0`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -51,7 +52,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by category", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&category=selfpromo`) + fetch(`${endpoint}?videoID=searchTest0&category=selfpromo`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -65,7 +66,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by category", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&category=selfpromo`) + fetch(`${endpoint}?videoID=searchTest0&category=selfpromo`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -79,7 +80,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by lock status", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&locked=false`) + fetch(`${endpoint}?videoID=searchTest0&locked=false`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -96,7 +97,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by hide status", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&hidden=false`) + fetch(`${endpoint}?videoID=searchTest0&hidden=false`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -113,7 +114,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by ignored status", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest0&ignored=false`) + fetch(`${endpoint}?videoID=searchTest0&ignored=false`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -129,7 +130,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by min views", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest1&minViews=6`) + fetch(`${endpoint}?videoID=searchTest1&minViews=6`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -143,7 +144,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by max views", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest1&maxViews=10`) + fetch(`${endpoint}?videoID=searchTest1&maxViews=10`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -157,7 +158,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by min and max views", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest1&maxViews=10&minViews=1`) + fetch(`${endpoint}?videoID=searchTest1&maxViews=10&minViews=1`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -171,7 +172,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by min votes", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest2&minVotes=0`) + fetch(`${endpoint}?videoID=searchTest2&minVotes=0`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -186,7 +187,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by max votes", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest2&maxVotes=10`) + fetch(`${endpoint}?videoID=searchTest2&maxVotes=10`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -201,7 +202,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by both min and max votes", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest2&maxVotes=10&minVotes=0`) + fetch(`${endpoint}?videoID=searchTest2&maxVotes=10&minVotes=0`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -215,7 +216,7 @@ describe("getSearchSegments", () => { }); it("Should be able to get first page of results", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest4`) + fetch(`${endpoint}?videoID=searchTest4`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -238,7 +239,7 @@ describe("getSearchSegments", () => { }); it("Should be able to get second page of results", (done: Done) => { - fetch(`${getbaseURL()}/api/searchSegments?videoID=searchTest4&page=1`) + fetch(`${endpoint}?videoID=searchTest4&page=1`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); diff --git a/test/cases/getSegmentInfo.ts b/test/cases/getSegmentInfo.ts index f3e069b..2bc1d57 100644 --- a/test/cases/getSegmentInfo.ts +++ b/test/cases/getSegmentInfo.ts @@ -26,6 +26,7 @@ const userAgents = { }; describe("getSegmentInfo", () => { + const endpoint = `${getbaseURL()}/api/segmentInfo`; before(async () => { const insertQuery = `INSERT INTO "sponsorTimes"("videoID", "startTime", "endTime", "votes", "locked", @@ -47,7 +48,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive upvoted segment", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${upvotedID}`) + fetch(`${endpoint}?UUID=${upvotedID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -63,7 +64,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive downvoted segment", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${downvotedID}`) + fetch(`${endpoint}?UUID=${downvotedID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -79,7 +80,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive locked up segment", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${lockedupID}`) + fetch(`${endpoint}?UUID=${lockedupID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -96,7 +97,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive infinite vote segment", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${infvotesID}`) + fetch(`${endpoint}?UUID=${infvotesID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -112,7 +113,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive shadowhidden segment", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${shadowhiddenID}`) + fetch(`${endpoint}?UUID=${shadowhiddenID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -128,7 +129,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive locked down segment", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${lockeddownID}`) + fetch(`${endpoint}?UUID=${lockeddownID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -144,7 +145,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive hidden segment", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${hiddenID}`) + fetch(`${endpoint}?UUID=${hiddenID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -159,7 +160,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive segment with old ID", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${oldID}`) + fetch(`${endpoint}?UUID=${oldID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -174,7 +175,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive single segment in array", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}"]`) + fetch(`${endpoint}?UUIDs=["${upvotedID}"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -190,7 +191,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive multiple segments in array", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}", "${downvotedID}"]`) + fetch(`${endpoint}?UUIDs=["${upvotedID}", "${downvotedID}"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -209,7 +210,7 @@ describe("getSegmentInfo", () => { }); it("Should be possible to send unexpected query parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${upvotedID}&fakeparam=hello&category=sponsor`) + fetch(`${endpoint}?UUID=${upvotedID}&fakeparam=hello&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -224,7 +225,7 @@ describe("getSegmentInfo", () => { }); it("Should return 400 if array passed to UUID", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=["${upvotedID}", "${downvotedID}"]`) + fetch(`${endpoint}?UUID=["${upvotedID}", "${downvotedID}"]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -233,7 +234,7 @@ describe("getSegmentInfo", () => { }); it("Should return 400 if bad array passed to UUIDs", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=[not-quoted,not-quoted]`) + fetch(`${endpoint}?UUIDs=[not-quoted,not-quoted]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -242,7 +243,7 @@ describe("getSegmentInfo", () => { }); it("Should return 400 if bad UUID passed", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=notarealuuid`) + fetch(`${endpoint}?UUID=notarealuuid`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -251,7 +252,7 @@ describe("getSegmentInfo", () => { }); it("Should return 400 if bad UUIDs passed in array", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["notarealuuid", "anotherfakeuuid"]`) + fetch(`${endpoint}?UUIDs=["notarealuuid", "anotherfakeuuid"]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -260,7 +261,7 @@ describe("getSegmentInfo", () => { }); it("Should return good UUID when mixed with bad UUIDs", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}", "anotherfakeuuid"]`) + fetch(`${endpoint}?UUIDs=["${upvotedID}", "anotherfakeuuid"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -278,7 +279,7 @@ describe("getSegmentInfo", () => { it("Should cut off array at 10", function(done: Done) { this.timeout(10000); const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`; - fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=${filledIDArray}`) + fetch(`${endpoint}?UUIDs=${filledIDArray}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -293,7 +294,7 @@ describe("getSegmentInfo", () => { }); it("Should not duplicate reponses", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`) + fetch(`${endpoint}?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -304,7 +305,7 @@ describe("getSegmentInfo", () => { }); it("Should return 400 if UUID not found", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${ENOENTID}`) + fetch(`${endpoint}?UUID=${ENOENTID}`) .then(res => { if (res.status !== 400) done(`non 400 response code: ${res.status}`); else done(); // pass @@ -313,7 +314,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive multiple segments with multiple parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${upvotedID}&UUID=${downvotedID}`) + fetch(`${endpoint}?UUID=${upvotedID}&UUID=${downvotedID}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -332,7 +333,7 @@ describe("getSegmentInfo", () => { }); it("Should not parse repeated UUID if UUIDs present", (done: Done) => { - fetch(`${getbaseURL()}/api/segmentInfo?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`) + fetch(`${endpoint}?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); diff --git a/test/cases/getSkipSegments.ts b/test/cases/getSkipSegments.ts index 92a9ec1..bcd8b23 100644 --- a/test/cases/getSkipSegments.ts +++ b/test/cases/getSkipSegments.ts @@ -4,6 +4,7 @@ import {Done, getbaseURL, partialDeepEquals} from "../utils"; import assert from "assert"; describe("getSkipSegments", () => { + const endpoint = `${getbaseURL()}/api/skipSegments`; before(async () => { 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, ["getSkipSegmentID0", 1, 11, 2, 0, "uuid01", "testman", 0, 50, "sponsor", "skip", "YouTube", 100, 0, 0]); @@ -27,7 +28,7 @@ describe("getSkipSegments", () => { it("Should be able to get a time by category 1", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -43,7 +44,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category and action type", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&actionType=mute`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionType=mute`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -61,7 +62,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category and getSkipSegmentMultiple action types", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&actionType=mute&actionType=skip`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionType=mute&actionType=skip`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -81,7 +82,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&actionTypes=["mute","skip"]`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionTypes=["mute","skip"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -100,7 +101,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category for a different service 1", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID1&category=sponsor&service=PeerTube`) + fetch(`${endpoint}?videoID=getSkipSegmentID1&category=sponsor&service=PeerTube`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -118,7 +119,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category 2", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=intro`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -135,7 +136,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by categories array", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["sponsor"]`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -153,7 +154,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by categories array 2", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["intro"]`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["intro"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -171,7 +172,7 @@ describe("getSkipSegments", () => { }); it("Should return 404 if all submissions are hidden", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID6`) + fetch(`${endpoint}?videoID=getSkipSegmentID6`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -180,7 +181,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get getSkipSegmentMultiple times by category", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentMultiple&categories=["intro"]`) + fetch(`${endpoint}?videoID=getSkipSegmentMultiple&categories=["intro"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -201,7 +202,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["sponsor", "intro"]`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor", "intro"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -222,7 +223,7 @@ describe("getSkipSegments", () => { }); it("Should be possible to send unexpected query parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&fakeparam=hello&category=sponsor`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&fakeparam=hello&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -239,7 +240,7 @@ describe("getSkipSegments", () => { }); it("Low voted submissions should be hidden", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID3&category=sponsor`) + fetch(`${endpoint}?videoID=getSkipSegmentID3&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -256,7 +257,7 @@ describe("getSkipSegments", () => { }); it("Should return 404 if no segment found", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=notarealvideo`) + fetch(`${endpoint}?videoID=notarealvideo`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -265,7 +266,7 @@ describe("getSkipSegments", () => { }); it("Should return 400 if bad categories argument", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=[not-quoted,not-quoted]`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=[not-quoted,not-quoted]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -274,7 +275,7 @@ describe("getSkipSegments", () => { }); it("Should be able send a comma in a query param", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID2&category=sponsor`) + fetch(`${endpoint}?videoID=getSkipSegmentID2&category=sponsor`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -291,7 +292,7 @@ describe("getSkipSegments", () => { }); it("Should always get getSkipSegmentLocked segment", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentLocked&category=intro`) + fetch(`${endpoint}?videoID=getSkipSegmentLocked&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -308,7 +309,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&category=sponsor&category=intro`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -329,7 +330,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get, categories param overriding repeating category", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=getSkipSegmentID0&categories=["sponsor"]&category=intro`) + fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor"]&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -346,15 +347,17 @@ describe("getSkipSegments", () => { }); it("Should be able to get specific segments with requiredSegments", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid&requiredSegments=["requiredSegmentVid2","requiredSegmentVid3"]`) + const required2 = "requiredSegmentVid2"; + const required3 = "requiredSegmentVid3"; + fetch(`${endpoint}?videoID=requiredSegmentVid&requiredSegments=["${required2}","${required3}"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); assert.strictEqual(data.length, 2); const expected = [{ - UUID: "requiredSegmentVid2", + UUID: required2, }, { - UUID: "requiredSegmentVid3", + UUID: required3, }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -363,15 +366,17 @@ describe("getSkipSegments", () => { }); it("Should be able to get specific segments with repeating requiredSegment", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments?videoID=requiredSegmentVid&requiredSegment=requiredSegmentVid2&requiredSegment=requiredSegmentVid3`) + const required2 = "requiredSegmentVid2"; + const required3 = "requiredSegmentVid3"; + fetch(`${endpoint}?videoID=requiredSegmentVid&requiredSegment=${required2}&requiredSegment=${required3}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); assert.strictEqual(data.length, 2); const expected = [{ - UUID: "requiredSegmentVid2", + UUID: required2, }, { - UUID: "requiredSegmentVid3", + UUID: required3, }]; assert.ok(partialDeepEquals(data, expected)); done(); @@ -380,7 +385,7 @@ describe("getSkipSegments", () => { }); it("Should get 400 if no videoID passed in", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments`) + fetch(`${endpoint}`) .then(async res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getSkipSegmentsByHash.ts b/test/cases/getSkipSegmentsByHash.ts index d5627a4..b3e1459 100644 --- a/test/cases/getSkipSegmentsByHash.ts +++ b/test/cases/getSkipSegmentsByHash.ts @@ -1,6 +1,6 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; +import {Done, getbaseURL, partialDeepEquals, postJSON} from "../utils"; import {getHash} from "../../src/utils/getHash"; import {ImportMock,} from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; @@ -12,6 +12,7 @@ const sinonStub = mockManager.mock("listVideos"); sinonStub.callsFake(YouTubeApiMock.listVideos); describe("getSkipSegmentsByHash", () => { + const endpoint = `${getbaseURL()}/api/skipSegments`; const getSegmentsByHash0Hash = "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"; const requiredSegmentVidHash = "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"; before(async () => { @@ -32,7 +33,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get a 200", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/3272f?categories=["sponsor", "intro"]`) + fetch(`${endpoint}/3272f?categories=["sponsor", "intro"]`) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -41,7 +42,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 404 if no segments are found even if a video for the given hash is known", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/3272f?categories=["shilling"]`) + fetch(`${endpoint}/3272f?categories=["shilling"]`) .then(async res => { assert.strictEqual(res.status, 404); const expected = "[]"; @@ -53,7 +54,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get an empty array if no videos", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/11111?categories=["shilling"]`) + fetch(`${endpoint}/11111?categories=["shilling"]`) .then(async res => { assert.strictEqual(res.status, 404); const body = await res.text(); @@ -66,7 +67,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get an empty array if only hidden videos", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/f3a1?categories=["sponsor"]`) + fetch(`${endpoint}/f3a1?categories=["sponsor"]`) .then(async res => { if (res.status !== 404) done(`non 404 status code, was ${res.status}`); else { @@ -79,7 +80,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 400 prefix too short", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/11?categories=["shilling"]`) + fetch(`${endpoint}/11?categories=["shilling"]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -90,7 +91,7 @@ describe("getSkipSegmentsByHash", () => { it("Should return 400 prefix too long", (done: Done) => { const prefix = "1".repeat(50); assert.ok(prefix.length > 33, "failed to generate long enough string"); - fetch(`${getbaseURL()}/api/skipSegments/${prefix}?categories=["shilling"]`) + fetch(`${endpoint}/${prefix}?categories=["shilling"]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -100,7 +101,7 @@ describe("getSkipSegmentsByHash", () => { it("Should return 404 prefix in range", (done: Done) => { const prefix = "1".repeat(5); - fetch(`${getbaseURL()}/api/skipSegments/${prefix}?categories=["shilling"]`) + fetch(`${endpoint}/${prefix}?categories=["shilling"]`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -109,7 +110,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 400 for no hash", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/?categories=["shilling"]`) + fetch(`${endpoint}/?categories=["shilling"]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -118,7 +119,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 400 for bad format categories", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaf?categories=shilling`) + fetch(`${endpoint}/fdaf?categories=shilling`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -127,7 +128,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get multiple videos", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaf?categories=["sponsor","intro"]`) + fetch(`${endpoint}/fdaf?categories=["sponsor","intro"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -140,7 +141,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get 200 for no categories (default sponsor)", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaf`) + fetch(`${endpoint}/fdaf`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -164,7 +165,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get 200 for no categories (default sponsor) with action type", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaf?actionType=skip`) + fetch(`${endpoint}/fdaf?actionType=skip`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -188,7 +189,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get 200 for no categories (default sponsor) with multiple action types", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaf?actionType=skip&actionType=mute`) + fetch(`${endpoint}/fdaf?actionType=skip&actionType=mute`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -214,7 +215,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get 200 for no categories (default sponsor) with multiple action types (JSON array)", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaf?actionTypes=["skip","mute"]`) + fetch(`${endpoint}/fdaf?actionTypes=["skip","mute"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -238,7 +239,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaf?service=PeerTube`) + fetch(`${endpoint}/fdaf?service=PeerTube`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -256,7 +257,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should only return one segment when fetching highlight segments", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/c962?category=poi_highlight`) + fetch(`${endpoint}/c962?category=poi_highlight`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -270,10 +271,7 @@ describe("getSkipSegmentsByHash", () => { it("Should be able to post a segment and get it using endpoint", (done: Done) => { const testID = "abc123goodVideo"; fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + ...postJSON, body: JSON.stringify({ userID: "test-qwertyuiopasdfghjklzxcvbnm", videoID: testID, @@ -284,7 +282,7 @@ describe("getSkipSegmentsByHash", () => { }), }) .then(async () => { - fetch(`${getbaseURL()}/api/skipSegments/${getHash(testID, 1).substring(0, 3)}`) + fetch(`${endpoint}/${getHash(testID, 1).substring(0, 3)}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -304,7 +302,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get multiple categories with repeating parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/fdaff4?&category=sponsor&category=intro`) + fetch(`${endpoint}/fdaff4?&category=sponsor&category=intro`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -327,7 +325,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get specific segments with requiredSegments", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]`) + fetch(`${endpoint}/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -347,7 +345,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get specific segments with repeating requiredSegment", (done: Done) => { - fetch(`${getbaseURL()}/api/skipSegments/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3`) + fetch(`${endpoint}/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); diff --git a/test/cases/getStatus.ts b/test/cases/getStatus.ts index b8be1be..7860e95 100644 --- a/test/cases/getStatus.ts +++ b/test/cases/getStatus.ts @@ -6,12 +6,13 @@ import {db} from "../../src/databases/databases"; let dbVersion: number; describe("getStatus", () => { + const endpoint = `${getbaseURL()}/api/status`; before(async () => { dbVersion = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value; }); it("Should be able to get status", (done: Done) => { - fetch(`${getbaseURL()}/api/status`) + fetch(endpoint) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -26,7 +27,7 @@ describe("getStatus", () => { }); it("Should be able to get uptime only", (done: Done) => { - fetch(`${getbaseURL()}/api/status/uptime`) + fetch(`${endpoint}/uptime`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.text(); @@ -37,7 +38,7 @@ describe("getStatus", () => { }); it("Should be able to get commit only", (done: Done) => { - fetch(`${getbaseURL()}/api/status/commit`) + fetch(`${endpoint}/commit`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.text(); @@ -48,7 +49,7 @@ describe("getStatus", () => { }); it("Should be able to get db only", (done: Done) => { - fetch(`${getbaseURL()}/api/status/db`) + fetch(`${endpoint}/db`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.text(); @@ -59,7 +60,7 @@ describe("getStatus", () => { }); it("Should be able to get startTime only", (done: Done) => { - fetch(`${getbaseURL()}/api/status/startTime`) + fetch(`${endpoint}/startTime`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.text(); @@ -71,7 +72,7 @@ describe("getStatus", () => { }); it("Should be able to get processTime only", (done: Done) => { - fetch(`${getbaseURL()}/api/status/processTime`) + fetch(`${endpoint}/processTime`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.text(); diff --git a/test/cases/getUserID.ts b/test/cases/getUserID.ts index bf85cf0..a4dfece 100644 --- a/test/cases/getUserID.ts +++ b/test/cases/getUserID.ts @@ -5,6 +5,7 @@ import {getHash} from "../../src/utils/getHash"; import assert from "assert"; describe("getUserID", () => { + const endpoint = `${getbaseURL()}/api/userID`; before(async () => { const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; await db.prepare("run", insertUserNameQuery, [getHash("getuserid_user_01"), "fuzzy user 01"]); @@ -22,7 +23,7 @@ describe("getUserID", () => { }); it("Should be able to get a 200", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=fuzzy+user+01`) + fetch(`${endpoint}?username=fuzzy+user+01`) .then(async res => { assert.strictEqual(res.status, 200); done(); @@ -31,7 +32,7 @@ describe("getUserID", () => { }); it("Should be able to get a 400 (No username parameter)", (done: Done) => { - fetch(`${getbaseURL()}/api/userID`) + fetch(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -40,7 +41,7 @@ describe("getUserID", () => { }); it("Should be able to get a 200 (username is public id)", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=${getHash("getuserid_user_06")}`) + fetch(`${endpoint}?username=${getHash("getuserid_user_06")}`) .then(async res => { assert.strictEqual(res.status, 200); done(); @@ -49,7 +50,7 @@ describe("getUserID", () => { }); it("Should be able to get a 400 (username longer than 64 chars)", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=${getHash("getuserid_user_06")}0`) + fetch(`${endpoint}?username=${getHash("getuserid_user_06")}0`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -58,7 +59,7 @@ describe("getUserID", () => { }); it("Should be able to get single username", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=fuzzy+user+01`) + fetch(`${endpoint}?username=fuzzy+user+01`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -73,7 +74,7 @@ describe("getUserID", () => { }); it("Should be able to get multiple fuzzy user info from start", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=fuzzy+user`) + fetch(`${endpoint}?username=fuzzy+user`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -91,7 +92,7 @@ describe("getUserID", () => { }); it("Should be able to get multiple fuzzy user info from middle", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=user`) + fetch(`${endpoint}?username=user`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -113,7 +114,7 @@ describe("getUserID", () => { it("Should be able to get with public ID", (done: Done) => { const userID = getHash("getuserid_user_06"); - fetch(`${getbaseURL()}/api/userID?username=${userID}`) + fetch(`${endpoint}?username=${userID}`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -129,7 +130,7 @@ describe("getUserID", () => { it("Should be able to get with fuzzy public ID", (done: Done) => { const userID = getHash("getuserid_user_06"); - fetch(`${getbaseURL()}/api/userID?username=${userID.substr(10,60)}`) + fetch(`${endpoint}?username=${userID.substr(10,60)}`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -144,7 +145,7 @@ describe("getUserID", () => { }); it("Should be able to get repeating username", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=repeating`) + fetch(`${endpoint}?username=repeating`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -162,7 +163,7 @@ describe("getUserID", () => { }); it("Should be able to get repeating fuzzy username", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=peat`) + fetch(`${endpoint}?username=peat`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -180,7 +181,7 @@ describe("getUserID", () => { }); it("should avoid ReDOS with _", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=_redos_`) + fetch(`${endpoint}?username=_redos_`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -195,7 +196,7 @@ describe("getUserID", () => { }); it("should avoid ReDOS with %", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=%redos%`) + fetch(`${endpoint}?username=%redos%`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -210,7 +211,7 @@ describe("getUserID", () => { }); it("should return 404 if escaped backslashes present", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=%redos\\\\_`) + fetch(`${endpoint}?username=%redos\\\\_`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -219,7 +220,7 @@ describe("getUserID", () => { }); it("should return 404 if backslashes present", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=\\%redos\\_`) + fetch(`${endpoint}?username=\\%redos\\_`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -228,7 +229,7 @@ describe("getUserID", () => { }); it("should return user if just backslashes", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=\\\\\\`) + fetch(`${endpoint}?username=\\\\\\`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -243,7 +244,7 @@ describe("getUserID", () => { }); it("should not allow usernames more than 64 characters", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=${"0".repeat(65)}`) + fetch(`${endpoint}?username=${"0".repeat(65)}`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -252,7 +253,7 @@ describe("getUserID", () => { }); it("should not allow usernames less than 3 characters", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=aa`) + fetch(`${endpoint}?username=aa`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -261,7 +262,7 @@ describe("getUserID", () => { }); it("should allow exact match", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=a&exact=true`) + fetch(`${endpoint}?username=a&exact=true`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -276,7 +277,7 @@ describe("getUserID", () => { }); it("Should be able to get repeating username with exact username", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=repeating&exact=true`) + fetch(`${endpoint}?username=repeating&exact=true`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -294,7 +295,7 @@ describe("getUserID", () => { }); it("Should not get exact unless explicitly set to true", (done: Done) => { - fetch(`${getbaseURL()}/api/userID?username=user&exact=1`) + fetch(`${endpoint}?username=user&exact=1`) .then(async res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -315,7 +316,7 @@ describe("getUserID", () => { }); it("should return 400 if no username parameter specified", (done: Done) => { - fetch(`${getbaseURL()}/api/userID`) + fetch(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getUserInfo.ts b/test/cases/getUserInfo.ts index 7d88abf..b87dfd3 100644 --- a/test/cases/getUserInfo.ts +++ b/test/cases/getUserInfo.ts @@ -5,6 +5,7 @@ import {getHash} from "../../src/utils/getHash"; import assert from "assert"; describe("getUserInfo", () => { + const endpoint = `${getbaseURL()}/api/userInfo`; before(async () => { const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; await db.prepare("run", insertUserNameQuery, [getHash("getuserinfo_user_01"), "Username user 01"]); @@ -34,7 +35,7 @@ describe("getUserInfo", () => { }); it("Should be able to get a 200", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_01`) + fetch(`${endpoint}?userID=getuserinfo_user_01`) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -43,7 +44,7 @@ describe("getUserInfo", () => { }); it("Should be able to get a 400 (No userID parameter)", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo`) + fetch(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -52,7 +53,7 @@ describe("getUserInfo", () => { }); it("Should be able to get user info", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_01`) + fetch(`${endpoint}?userID=getuserinfo_user_01`) .then(async res => { assert.strictEqual(res.status, 200); const expected = { @@ -77,7 +78,7 @@ describe("getUserInfo", () => { }); it("Should get warning data", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_0&value=warnings`) + fetch(`${endpoint}?userID=getuserinfo_warning_0&value=warnings`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -91,7 +92,7 @@ describe("getUserInfo", () => { }); it("Should get warning data with public ID", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?publicUserID=${getHash("getuserinfo_warning_0")}&values=["warnings"]`) + fetch(`${endpoint}?publicUserID=${getHash("getuserinfo_warning_0")}&values=["warnings"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -105,7 +106,7 @@ describe("getUserInfo", () => { }); it("Should get multiple warnings", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_1&value=warnings`) + fetch(`${endpoint}?userID=getuserinfo_warning_1&value=warnings`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -119,7 +120,7 @@ describe("getUserInfo", () => { }); it("Should not get warnings if none", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_2&value=warnings`) + fetch(`${endpoint}?userID=getuserinfo_warning_2&value=warnings`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -133,7 +134,7 @@ describe("getUserInfo", () => { }); it("Should done(userID for userName (No userName set)", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_02&value=userName`) + fetch(`${endpoint}?userID=getuserinfo_user_02&value=userName`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -147,7 +148,7 @@ describe("getUserInfo", () => { }); it("Should return null segment if none", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_null&value=lastSegmentID`) + fetch(`${endpoint}?userID=getuserinfo_null&value=lastSegmentID`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -158,7 +159,7 @@ describe("getUserInfo", () => { }); it("Should return zeroes if userid does not exist", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_null&value=lastSegmentID`) + fetch(`${endpoint}?userID=getuserinfo_null&value=lastSegmentID`) .then(async res => { const data = await res.json(); for (const value in data) { @@ -172,7 +173,7 @@ describe("getUserInfo", () => { }); it("Should get warning reason from from single enabled warning", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_0&values=["warningReason"]`) + fetch(`${endpoint}?userID=getuserinfo_warning_0&values=["warningReason"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -186,7 +187,7 @@ describe("getUserInfo", () => { }); it("Should get most recent warning from two enabled warnings", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_1&value=warningReason`) + fetch(`${endpoint}?userID=getuserinfo_warning_1&value=warningReason`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -200,7 +201,7 @@ describe("getUserInfo", () => { }); it("Should not get disabled warning", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_2&values=["warnings","warningReason"]`) + fetch(`${endpoint}?userID=getuserinfo_warning_2&values=["warnings","warningReason"]`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -215,7 +216,7 @@ describe("getUserInfo", () => { }); it("Should not get newer disabled warning", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_3&value=warnings&value=warningReason`) + fetch(`${endpoint}?userID=getuserinfo_warning_3&value=warnings&value=warningReason`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -230,7 +231,7 @@ describe("getUserInfo", () => { }); it("Should get 400 if bad values specified", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_warning_3&value=invalid-value`) + fetch(`${endpoint}?userID=getuserinfo_warning_3&value=invalid-value`) .then(async res => { assert.strictEqual(res.status, 400); done(); // pass @@ -239,7 +240,7 @@ describe("getUserInfo", () => { }); it("Should get ban data for banned user (only appears when specifically requested)", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_ban_01&value=banned`) + fetch(`${endpoint}?userID=getuserinfo_ban_01&value=banned`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -253,7 +254,7 @@ describe("getUserInfo", () => { }); it("Should get ban data for unbanned user (only appears when specifically requested)", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_notban_01&value=banned`) + fetch(`${endpoint}?userID=getuserinfo_notban_01&value=banned`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -267,7 +268,7 @@ describe("getUserInfo", () => { }); it("Should throw 400 on bad json in values", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=x&values=[userID]`) + fetch(`${endpoint}?userID=x&values=[userID]`) .then(async res => { assert.strictEqual(res.status, 400); done(); // pass @@ -276,7 +277,7 @@ describe("getUserInfo", () => { }); it("Should return 200 on userID not found", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=notused-userid`) + fetch(`${endpoint}?userID=notused-userid`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -298,7 +299,7 @@ describe("getUserInfo", () => { }); it("Should only count long segments as 10 minutes", (done: Done) => { - fetch(`${getbaseURL()}/api/userInfo?userID=getuserinfo_user_03`) + fetch(`${endpoint}?userID=getuserinfo_user_03`) .then(async res => { assert.strictEqual(res.status, 200); const expected = { diff --git a/test/cases/lockCategoriesRecords.ts b/test/cases/lockCategoriesRecords.ts index d00f078..3bdbf03 100644 --- a/test/cases/lockCategoriesRecords.ts +++ b/test/cases/lockCategoriesRecords.ts @@ -1,9 +1,9 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import {Done, getbaseURL, postJSON} from "../utils"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; -import {LockCategory} from "../../src/types/segments.model"; +import {LockCategory } from "../../src/types/segments.model"; const stringDeepEquals = (a: string[] ,b: string[]): boolean => { let result = true; @@ -13,23 +13,29 @@ const stringDeepEquals = (a: string[] ,b: string[]): boolean => { return result; }; +const endpoint = `${getbaseURL()}/api/lockCategories`; +const submitEndpoint = `${getbaseURL()}/api/skipSegments`; +const checkLockCategories = (videoID: string): Promise => db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', [videoID]); +const lockVIPUser = "lockCategoriesRecordsVIPUser"; +const lockVIPUserHash = getHash(lockVIPUser); + describe("lockCategoriesRecords", () => { before(async () => { const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; - await db.prepare("run", insertVipUserQuery, [getHash("lockCategoriesRecordsVIPUser")]); + await db.prepare("run", insertVipUserQuery, [lockVIPUserHash]); const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") VALUES (?, ?, ?, ?)'; - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "no-segments-video-id", "sponsor", "reason-1"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "no-segments-video-id", "intro", "reason-1"]); + await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id", "sponsor", "reason-1"]); + await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id", "intro", "reason-1"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "no-segments-video-id-1", "sponsor", "reason-2"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "no-segments-video-id-1", "intro", "reason-2"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "lockCategoryVideo", "sponsor", "reason-3"]); + await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id-1", "sponsor", "reason-2"]); + await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "no-segments-video-id-1", "intro", "reason-2"]); + await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "lockCategoryVideo", "sponsor", "reason-3"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "delete-record", "sponsor", "reason-4"]); + await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "delete-record", "sponsor", "reason-4"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "delete-record-1", "sponsor", "reason-5"]); - await db.prepare("run", insertLockCategoryQuery, [getHash("lockCategoriesRecordsVIPUser"), "delete-record-1", "intro", "reason-5"]); + await db.prepare("run", insertLockCategoryQuery, [lockVIPUserHash, "delete-record-1", "sponsor", "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 () => { @@ -56,11 +62,8 @@ describe("lockCategoriesRecords", () => { "shilling", ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json) }) .then(async res => { @@ -73,9 +76,10 @@ describe("lockCategoriesRecords", () => { }); it("Should be able to submit categories not in video (sql check)", (done: Done) => { + const videoID = "no-segments-video-id-1"; const json = { - videoID: "no-segments-video-id-1", - userID: "lockCategoriesRecordsVIPUser", + videoID, + userID: lockVIPUser, categories: [ "outro", "shilling", @@ -85,25 +89,20 @@ describe("lockCategoriesRecords", () => { "intro", ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json) }) .then(async res => { 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); const oldRecordNotChangeReason = result.filter(item => item.reason === "reason-2" && ["sponsor", "intro"].includes(item.category) ); - const newRecordWithEmptyReason = result.filter(item => item.reason === "" && ["outro", "shilling"].includes(item.category) ); - assert.strictEqual(newRecordWithEmptyReason.length, 2); assert.strictEqual(oldRecordNotChangeReason.length, 2); done(); @@ -112,9 +111,10 @@ describe("lockCategoriesRecords", () => { }); it("Should be able to submit categories not in video with reason (http response)", (done: Done) => { + const videoID = "no-segments-video-id"; const json = { - videoID: "no-segments-video-id", - userID: "lockCategoriesRecordsVIPUser", + videoID, + userID: lockVIPUser, categories: [ "outro", "shilling", @@ -134,11 +134,8 @@ describe("lockCategoriesRecords", () => { ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json) }) .then(async res => { @@ -151,9 +148,10 @@ describe("lockCategoriesRecords", () => { }); it("Should be able to submit categories not in video with reason (sql check)", (done: Done) => { + const videoID = "no-segments-video-id-1"; const json = { - videoID: "no-segments-video-id-1", - userID: "lockCategoriesRecordsVIPUser", + videoID, + userID: lockVIPUser, categories: [ "outro", "shilling", @@ -171,16 +169,13 @@ describe("lockCategoriesRecords", () => { "intro" ]; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json) }) .then(async res => { 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); const newRecordWithNewReason = result.filter(item => expectedWithNewReason.includes(item.category) && item.reason === "new reason" @@ -199,21 +194,18 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories with _ in the category", (done: Done) => { const json = { videoID: "underscore", - userID: "lockCategoriesRecordsVIPUser", + userID: lockVIPUser, categories: [ "word_word", ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(async res => { 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); done(); }) @@ -223,21 +215,18 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit categories with upper and lower case in the category", (done: Done) => { const json = { videoID: "bothCases", - userID: "lockCategoriesRecordsVIPUser", + userID: lockVIPUser, categories: [ "wordWord", ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(async res => { 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); done(); }) @@ -245,24 +234,22 @@ describe("lockCategoriesRecords", () => { }); it("Should not be able to submit categories with $ in the category", (done: Done) => { + const videoID = "specialChar"; const json = { - videoID: "specialChar", - userID: "lockCategoriesRecordsVIPUser", + videoID, + userID: lockVIPUser, categories: [ "word&word", ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(async res => { 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); done(); }) @@ -270,11 +257,8 @@ describe("lockCategoriesRecords", () => { }); it("Should return 400 for missing params", (done: Done) => { - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify({}), }) .then(res => { @@ -290,11 +274,8 @@ describe("lockCategoriesRecords", () => { userID: "test", categories: [], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(res => { @@ -311,11 +292,8 @@ describe("lockCategoriesRecords", () => { categories: ["sponsor"], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(res => { @@ -332,11 +310,8 @@ describe("lockCategoriesRecords", () => { categories: ["sponsor"], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(res => { @@ -353,11 +328,8 @@ describe("lockCategoriesRecords", () => { categories: {}, }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(res => { @@ -374,11 +346,8 @@ describe("lockCategoriesRecords", () => { categories: "sponsor", }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(res => { @@ -397,11 +366,8 @@ describe("lockCategoriesRecords", () => { ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(endpoint, { + ...postJSON, body: JSON.stringify(json), }) .then(res => { @@ -412,15 +378,16 @@ describe("lockCategoriesRecords", () => { }); it("Should be able to delete a lockCategories record", (done: Done) => { + const videoID = "delete-record"; const json = { - videoID: "delete-record", - userID: "lockCategoriesRecordsVIPUser", + videoID, + userID: lockVIPUser, categories: [ "sponsor", ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { + fetch(endpoint, { method: "DELETE", headers: { "Content-Type": "application/json", @@ -429,7 +396,7 @@ describe("lockCategoriesRecords", () => { }) .then(async res => { 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); done(); }) @@ -437,15 +404,16 @@ describe("lockCategoriesRecords", () => { }); it("Should be able to delete one lockCategories record without removing another", (done: Done) => { + const videoID = "delete-record-1"; const json = { - videoID: "delete-record-1", - userID: "lockCategoriesRecordsVIPUser", + videoID, + userID: lockVIPUser, categories: [ "sponsor", ], }; - fetch(`${getbaseURL()}/api/lockCategories`, { + fetch(endpoint, { method: "DELETE", headers: { "Content-Type": "application/json", @@ -454,7 +422,7 @@ describe("lockCategoriesRecords", () => { }) .then(async res => { 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); done(); }) @@ -466,16 +434,14 @@ describe("lockCategoriesRecords", () => { * Submission tests in this file do not check database records, only status codes. * To test the submission code properly see ./test/cases/postSkipSegments.js */ - + const lockedVideoID = "lockCategoryVideo"; + const testSubmitUser = "testman42-qwertyuiopasdfghjklzxcvbnm"; it("Should not be able to submit a segment to a video with a lock-category record (single submission)", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(submitEndpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testman42-qwertyuiopasdfghjklzxcvbnm", - videoID: "lockCategoryVideo", + userID: testSubmitUser, + videoID: lockedVideoID, segments: [{ segment: [20, 40], category: "sponsor", @@ -490,14 +456,11 @@ describe("lockCategoriesRecords", () => { }); it("Should not be able to submit segments to a video where any of the submissions with a no-segment record", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(submitEndpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testman42-qwertyuiopasdfghjklzxcvbnm", - videoID: "lockCategoryVideo", + userID: testSubmitUser, + videoID: lockedVideoID, segments: [{ segment: [20, 40], category: "sponsor", @@ -516,14 +479,11 @@ describe("lockCategoriesRecords", () => { it("Should be able to submit a segment to a video with a different no-segment record", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(submitEndpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testman42-qwertyuiopasdfghjklzxcvbnm", - videoID: "lockCategoryVideo", + userID: testSubmitUser, + videoID: lockedVideoID, segments: [{ segment: [20, 40], category: "intro", @@ -538,13 +498,10 @@ describe("lockCategoriesRecords", () => { }); it("Should be able to submit a segment to a video with no no-segment records", (done: Done) => { - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + fetch(submitEndpoint, { + ...postJSON, body: JSON.stringify({ - userID: "testman42-qwertyuiopasdfghjklzxcvbnm", + userID: testSubmitUser, videoID: "normalVideo", segments: [{ segment: [20, 40], @@ -568,8 +525,7 @@ describe("lockCategoriesRecords", () => { "shilling" ], }; - - fetch(`${getbaseURL()}/api/lockCategories?videoID=` + `no-segments-video-id`) + fetch(`${endpoint}?videoID=no-segments-video-id`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); diff --git a/test/cases/oldGetSponsorTime.ts b/test/cases/oldGetSponsorTime.ts index 46cfe2f..70fca97 100644 --- a/test/cases/oldGetSponsorTime.ts +++ b/test/cases/oldGetSponsorTime.ts @@ -3,6 +3,8 @@ import {db} from "../../src/databases/databases"; import {Done, getbaseURL, partialDeepEquals} from "../utils"; import assert from "assert"; +const endpoint = `${getbaseURL()}/api/getVideoSponsorTimes`; + describe("getVideoSponsorTime (Old get method)", () => { before(async () => { const insertSponsorTimes = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; @@ -11,7 +13,7 @@ describe("getVideoSponsorTime (Old get method)", () => { }); it("Should be able to get a time", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime0`) + fetch(`${endpoint}?videoID=oldGetSponsorTime0`) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -20,7 +22,7 @@ describe("getVideoSponsorTime (Old get method)", () => { }); it("Should return 404 if no segment found", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=notarealvideo`) + fetch(`${endpoint}?videoID=notarealvideo`) .then(res => { assert.strictEqual(res.status, 404); done(); From 802dd501630946317516b86051ed022bbe70babe Mon Sep 17 00:00:00 2001 From: Michael C Date: Fri, 17 Sep 2021 00:01:29 -0400 Subject: [PATCH 06/14] naming --- test/cases/getIsUserVIP.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/cases/getIsUserVIP.ts b/test/cases/getIsUserVIP.ts index d380eea..fc0784e 100644 --- a/test/cases/getIsUserVIP.ts +++ b/test/cases/getIsUserVIP.ts @@ -4,14 +4,17 @@ import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; +const endpoint = `${getbaseURL()}/api/isUserVIP`; +const VIPUser = "isUserVIPVIP"; +const normalUser = "isUserVIPNormal"; + describe("getIsUserVIP", () => { - const endpoint = `${getbaseURL()}/api/isUserVIP`; before(() => { - db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash("isUserVIPVIP")]); + db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash(VIPUser)]); }); it("Should be able to get a 200", (done: Done) => { - fetch(`${endpoint}?userID=isUserVIPVIP`) + fetch(`${endpoint}?userID=${VIPUser}`) .then(res => { assert.strictEqual(res.status, 200, "response should be 200"); done(); @@ -30,7 +33,7 @@ describe("getIsUserVIP", () => { }); it("Should say a VIP is a VIP", (done: Done) => { - fetch(`${endpoint}?userID=isUserVIPVIP`) + fetch(`${endpoint}?userID=${VIPUser}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); @@ -41,7 +44,7 @@ describe("getIsUserVIP", () => { }); it("Should say a normal user is not a VIP", (done: Done) => { - fetch(`${endpoint}?userID=isUserVIPNormal`) + fetch(`${endpoint}?userID=${normalUser}`) .then(async res => { assert.strictEqual(res.status, 200); const data = await res.json(); From d4d9f2d4d700a4e09db675427215ce5cc263dce3 Mon Sep 17 00:00:00 2001 From: Michael C Date: Fri, 17 Sep 2021 00:03:42 -0400 Subject: [PATCH 07/14] remove unnecessary async await --- test/cases/postSkipSegments.ts | 6 +++--- test/cases/postWarning.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index 0c7369d..b2f4faf 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -32,9 +32,9 @@ describe("postSkipSegments", () => { const warnVideoID = "dQw4w9WgXcF"; const badInputVideoID = "dQw4w9WgXcQ"; - const queryDatabase = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); - const queryDatabaseActionType = async(videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); - const queryDatabaseDuration = async (videoID: string) => await db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); + const queryDatabase = (videoID: string) => db.prepare("get", `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); + const queryDatabaseActionType = (videoID: string) => db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); + const queryDatabaseDuration = (videoID: string) => db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); const endpoint = `${getbaseURL()}/api/skipSegments`; diff --git a/test/cases/postWarning.ts b/test/cases/postWarning.ts index 0f6cc80..02b09d0 100644 --- a/test/cases/postWarning.ts +++ b/test/cases/postWarning.ts @@ -7,7 +7,7 @@ import assert from "assert"; describe("postWarning", () => { // constants const endpoint = `${getbaseURL()}/api/warnUser`; - const getWarning = async (userID: string) => await db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [userID]); + const getWarning = (userID: string) => db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [userID]); before(async () => { await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES (?)`, [getHash("warning-vip")]); From 5758f6512df7f6d08da0da2185aa9f09c8b00c03 Mon Sep 17 00:00:00 2001 From: Michael C Date: Tue, 21 Sep 2021 02:02:17 -0400 Subject: [PATCH 08/14] move utils to seperate files and folder, update imports --- test/cases/getIsUserVIP.ts | 3 +- test/cases/getLockCategories.ts | 3 +- test/cases/getLockCategoriesByHash.ts | 3 +- test/cases/getSavedTimeForUser.ts | 3 +- test/cases/getSearchSegments.ts | 3 +- test/cases/getSegmentInfo.ts | 4 +- test/cases/getSkipSegments.ts | 4 +- test/cases/getSkipSegmentsByHash.ts | 4 +- test/cases/getStatus.ts | 4 +- test/cases/getUserID.ts | 3 +- test/cases/getUserInfo.ts | 4 +- test/cases/getUserStats.ts | 126 ++++++++++++++++++ test/cases/lockCategoriesRecords.ts | 3 +- test/cases/oldGetSponsorTime.ts | 4 +- test/cases/oldSubmitSponsorTimes.ts | 5 +- test/cases/postClearCache.ts | 3 +- test/cases/postPurgeAllSegments.ts | 3 +- test/cases/postSkipSegments.ts | 4 +- test/cases/postWarning.ts | 4 +- test/cases/segmentShift.ts | 3 +- test/cases/setUsername.ts | 3 +- test/cases/shadowBanUser.ts | 3 +- test/cases/testUtils.ts | 3 +- test/cases/unBan.ts | 3 +- test/cases/voteOnSponsorTime.ts | 3 +- test/utils/getBaseURL.ts | 5 + test/{utils.ts => utils/partialDeepEquals.ts} | 31 +---- test/utils/utils.ts | 11 ++ 28 files changed, 201 insertions(+), 54 deletions(-) create mode 100644 test/cases/getUserStats.ts create mode 100644 test/utils/getBaseURL.ts rename test/{utils.ts => utils/partialDeepEquals.ts} (64%) create mode 100644 test/utils/utils.ts diff --git a/test/cases/getIsUserVIP.ts b/test/cases/getIsUserVIP.ts index fc0784e..0639066 100644 --- a/test/cases/getIsUserVIP.ts +++ b/test/cases/getIsUserVIP.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {getbaseURL, Done} from "../utils"; +import { Done} from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; diff --git a/test/cases/getLockCategories.ts b/test/cases/getLockCategories.ts index a70b5e7..f04f89e 100644 --- a/test/cases/getLockCategories.ts +++ b/test/cases/getLockCategories.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; diff --git a/test/cases/getLockCategoriesByHash.ts b/test/cases/getLockCategoriesByHash.ts index 7cfeb6a..84dad63 100644 --- a/test/cases/getLockCategoriesByHash.ts +++ b/test/cases/getLockCategoriesByHash.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; diff --git a/test/cases/getSavedTimeForUser.ts b/test/cases/getSavedTimeForUser.ts index 6d11409..59ac2fc 100644 --- a/test/cases/getSavedTimeForUser.ts +++ b/test/cases/getSavedTimeForUser.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import {deepStrictEqual} from "assert"; diff --git a/test/cases/getSearchSegments.ts b/test/cases/getSearchSegments.ts index 481fb25..80416c5 100644 --- a/test/cases/getSearchSegments.ts +++ b/test/cases/getSearchSegments.ts @@ -1,6 +1,7 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import assert from "assert"; describe("getSearchSegments", () => { diff --git a/test/cases/getSegmentInfo.ts b/test/cases/getSegmentInfo.ts index 2bc1d57..7a075b7 100644 --- a/test/cases/getSegmentInfo.ts +++ b/test/cases/getSegmentInfo.ts @@ -1,6 +1,8 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; const ENOENTID = "0".repeat(64); diff --git a/test/cases/getSkipSegments.ts b/test/cases/getSkipSegments.ts index bcd8b23..4d6afa8 100644 --- a/test/cases/getSkipSegments.ts +++ b/test/cases/getSkipSegments.ts @@ -1,6 +1,8 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; describe("getSkipSegments", () => { diff --git a/test/cases/getSkipSegmentsByHash.ts b/test/cases/getSkipSegmentsByHash.ts index b3e1459..d97c888 100644 --- a/test/cases/getSkipSegmentsByHash.ts +++ b/test/cases/getSkipSegmentsByHash.ts @@ -1,6 +1,8 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL, partialDeepEquals, postJSON} from "../utils"; +import { Done, postJSON } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; import {getHash} from "../../src/utils/getHash"; import {ImportMock,} from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; diff --git a/test/cases/getStatus.ts b/test/cases/getStatus.ts index 7860e95..a58c0b2 100644 --- a/test/cases/getStatus.ts +++ b/test/cases/getStatus.ts @@ -1,7 +1,7 @@ import assert from "assert"; import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; - +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; let dbVersion: number; diff --git a/test/cases/getUserID.ts b/test/cases/getUserID.ts index a4dfece..2e031c4 100644 --- a/test/cases/getUserID.ts +++ b/test/cases/getUserID.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; diff --git a/test/cases/getUserInfo.ts b/test/cases/getUserInfo.ts index b87dfd3..d73f880 100644 --- a/test/cases/getUserInfo.ts +++ b/test/cases/getUserInfo.ts @@ -1,5 +1,7 @@ import fetch from "node-fetch"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; diff --git a/test/cases/getUserStats.ts b/test/cases/getUserStats.ts new file mode 100644 index 0000000..64336d1 --- /dev/null +++ b/test/cases/getUserStats.ts @@ -0,0 +1,126 @@ +import fetch from "node-fetch"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import assert from "assert"; + +describe("getUserStats", () => { + before(async () => { + const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; + await db.prepare("run", insertUserNameQuery, [getHash("getuserstats_user_01"), "Username user 01"]); + + const sponsorTimesQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, 0, "getuserstatsuuid1", getHash("getuserstats_user_01"), 1, 1, "sponsor", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, 0, "getuserstatsuuid2", getHash("getuserstats_user_01"), 2, 2, "selfpromo", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, 0, "getuserstatsuuid3", getHash("getuserstats_user_01"), 3, 3, "interaction", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, 0, "getuserstatsuuid4", getHash("getuserstats_user_01"), 4, 4, "intro", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, 0, "getuserstatsuuid5", getHash("getuserstats_user_01"), 5, 5, "outro", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, 0, "getuserstatsuuid6", getHash("getuserstats_user_01"), 6, 6, "preview", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, 0, "getuserstatsuuid7", getHash("getuserstats_user_01"), 7, 7, "music_offtopic", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 11, 11, 0, "getuserstatsuuid8", getHash("getuserstats_user_01"), 8, 8, "poi_highlight", 0]); + await db.prepare("run", sponsorTimesQuery, ["getuserstats1", 0, 60, -2, "getuserstatsuuid9", getHash("getuserstats_user_02"), 8, 2, "sponsor", 0]); + + }); + + it("Should be able to get a 400 (No userID parameter)", (done: Done) => { + fetch(`${getbaseURL()}/api/userStats`) + .then(res => { + assert.strictEqual(res.status, 400); + done(); + }) + .catch(err => done(err)); + }); + + it("Should be able to get all user info", (done: Done) => { + fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01&fetchCategoryStats=true&fetchActionTypeStats=true`) + .then(async res => { + assert.strictEqual(res.status, 200); + const expected = { + userName: "Username user 01", + userID: getHash("getuserstats_user_01"), + categoryCount: { + sponsor: 1, + selfpromo: 1, + interaction: 1, + intro: 1, + outro: 1, + preview: 1, + music_offtopic: 1, + poi_highlight: 1, + }, + actionTypeCount: { + mute: 0, + skip: 8 + }, + overallStats: { + minutesSaved: 28, + segmentCount: 8 + } + }; + const data = await res.json(); + assert.ok(partialDeepEquals(data, expected)); + done(); + }) + .catch(err => done(err)); + }); + + it("Should be able to get all zeroes for invalid userid", (done: Done) => { + fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_invalid`) + .then(async res => { + assert.strictEqual(res.status, 200); + const data = await res.json(); + for (const value in data.overallStats) { + if (data[value]) { + done(`returned non-zero for ${value}`); + } + } + done(); + }) + .catch(err => done(err)); + }); + + it("Should be able to get all zeroes for only ignored segments", (done: Done) => { + fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_02`) + .then(async res => { + assert.strictEqual(res.status, 200); + const data = await res.json(); + for (const value in data.overallStats) { + if (data[value]) { + done(`returned non-zero for ${value}`); + } + } + done(); + }) + .catch(err => done(err)); + }); + + it("Should not get extra stats if not requested", (done: Done) => { + fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01`) + .then(async res => { + assert.strictEqual(res.status, 200); + const data = await res.json(); + // check for categoryCount + if (data.categoryCount || data.actionTypeCount) { + done("returned extra stats"); + } + done(); + }) + .catch(err => done(err)); + }); + + it("Should get parts of extra stats if not requested", (done: Done) => { + fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01&fetchActionTypeStats=true`) + .then(async res => { + assert.strictEqual(res.status, 200); + const data = await res.json(); + // check for categoryCount + if (data.categoryCount && !data.actionTypeCount) { + done("returned extra stats"); + } + done(); + }) + .catch(err => done(err)); + }); +}); diff --git a/test/cases/lockCategoriesRecords.ts b/test/cases/lockCategoriesRecords.ts index 3bdbf03..e1949f5 100644 --- a/test/cases/lockCategoriesRecords.ts +++ b/test/cases/lockCategoriesRecords.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL, postJSON} from "../utils"; +import { Done, postJSON } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; diff --git a/test/cases/oldGetSponsorTime.ts b/test/cases/oldGetSponsorTime.ts index 70fca97..756ec0b 100644 --- a/test/cases/oldGetSponsorTime.ts +++ b/test/cases/oldGetSponsorTime.ts @@ -1,6 +1,8 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; const endpoint = `${getbaseURL()}/api/getVideoSponsorTimes`; diff --git a/test/cases/oldSubmitSponsorTimes.ts b/test/cases/oldSubmitSponsorTimes.ts index ac1c0a4..2c0ea9e 100644 --- a/test/cases/oldSubmitSponsorTimes.ts +++ b/test/cases/oldSubmitSponsorTimes.ts @@ -1,6 +1,7 @@ import fetch from "node-fetch"; -import {Done, getbaseURL, partialDeepEquals} from "../utils"; -import {db} from "../../src/databases/databases"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals";import {db} from "../../src/databases/databases"; import assert from "assert"; const videoID1 = "dQw4w9WgXcQ"; diff --git a/test/cases/postClearCache.ts b/test/cases/postClearCache.ts index 8fc7516..d1d71d6 100644 --- a/test/cases/postClearCache.ts +++ b/test/cases/postClearCache.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; diff --git a/test/cases/postPurgeAllSegments.ts b/test/cases/postPurgeAllSegments.ts index f8e68ed..dc34ce3 100644 --- a/test/cases/postPurgeAllSegments.ts +++ b/test/cases/postPurgeAllSegments.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL, postJSON} from "../utils"; +import {Done, postJSON} from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import {IDatabase} from "../../src/databases/IDatabase"; diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index b2f4faf..ea77d23 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -1,7 +1,9 @@ import fetch from "node-fetch"; import {config} from "../../src/config"; import {getHash} from "../../src/utils/getHash"; -import {Done, getbaseURL, partialDeepEquals, postJSON} from "../utils"; +import { Done, postJSON } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; import {db} from "../../src/databases/databases"; import {ImportMock} from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; diff --git a/test/cases/postWarning.ts b/test/cases/postWarning.ts index 02b09d0..2dedef5 100644 --- a/test/cases/postWarning.ts +++ b/test/cases/postWarning.ts @@ -1,5 +1,7 @@ import fetch from "node-fetch"; -import {Done, getbaseURL, partialDeepEquals, postJSON} from "../utils"; +import { Done, postJSON } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; diff --git a/test/cases/segmentShift.ts b/test/cases/segmentShift.ts index 164fba2..430710b 100644 --- a/test/cases/segmentShift.ts +++ b/test/cases/segmentShift.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL, postJSON} from "../utils"; +import {Done, postJSON} from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import {IDatabase} from "../../src/databases/IDatabase"; diff --git a/test/cases/setUsername.ts b/test/cases/setUsername.ts index c0927aa..75f87dd 100644 --- a/test/cases/setUsername.ts +++ b/test/cases/setUsername.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import { Done, getbaseURL } from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import { db, privateDB } from "../../src/databases/databases"; import { getHash } from "../../src/utils/getHash"; import assert from "assert"; diff --git a/test/cases/shadowBanUser.ts b/test/cases/shadowBanUser.ts index 0b91206..d167fd8 100644 --- a/test/cases/shadowBanUser.ts +++ b/test/cases/shadowBanUser.ts @@ -1,6 +1,7 @@ import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; import { Category } from "../../src/types/segments.model"; diff --git a/test/cases/testUtils.ts b/test/cases/testUtils.ts index 4b3f87a..f60156a 100644 --- a/test/cases/testUtils.ts +++ b/test/cases/testUtils.ts @@ -1,6 +1,5 @@ import assert from "assert"; - -import { partialDeepEquals } from "../utils"; +import { partialDeepEquals } from "../utils/partialDeepEquals"; describe("Test utils ", () => { it("objectContain", async () => { diff --git a/test/cases/unBan.ts b/test/cases/unBan.ts index 3de23dc..cb34d0b 100644 --- a/test/cases/unBan.ts +++ b/test/cases/unBan.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import { getbaseURL, postJSON } from "../utils"; +import { postJSON } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import { getHash } from "../../src/utils/getHash"; import { db } from "../../src/databases/databases"; import assert from "assert"; diff --git a/test/cases/voteOnSponsorTime.ts b/test/cases/voteOnSponsorTime.ts index 1167605..5929f94 100644 --- a/test/cases/voteOnSponsorTime.ts +++ b/test/cases/voteOnSponsorTime.ts @@ -1,7 +1,8 @@ import fetch from "node-fetch"; import {config} from "../../src/config"; import {db} from "../../src/databases/databases"; -import {Done, getbaseURL} from "../utils"; +import { Done } from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {ImportMock} from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; diff --git a/test/utils/getBaseURL.ts b/test/utils/getBaseURL.ts new file mode 100644 index 0000000..3632cb4 --- /dev/null +++ b/test/utils/getBaseURL.ts @@ -0,0 +1,5 @@ +import { config } from "../../src/config"; + +export function getbaseURL(): string { + return `http://localhost:${config.port}`; +} \ No newline at end of file diff --git a/test/utils.ts b/test/utils/partialDeepEquals.ts similarity index 64% rename from test/utils.ts rename to test/utils/partialDeepEquals.ts index 6bebf00..6571794 100644 --- a/test/utils.ts +++ b/test/utils/partialDeepEquals.ts @@ -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 { - return `http://localhost:${config.port}`; +function printActualExpected(actual: Record, expected: Record): void { + 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, expected: Record, print = true): boolean => { // loop over key, value of expected for (const [ key, value ] of Object.entries(expected)) { @@ -21,27 +12,13 @@ export const partialDeepEquals = (actual: Record, expected: Record< if (Array.isArray(value) || typeof value === "object") { if (!partialDeepEquals(actual?.[key], value, false)) { if (print) printActualExpected(actual, expected); - return false; } } else if (actual?.[key] !== value) { if (print) printActualExpected(actual, expected); - return false; } } return true; -}; - -function printActualExpected(actual: Record, expected: Record): void { - Logger.error(`Actual: ${JSON.stringify(actual)}`); - Logger.error(`Expected: ${JSON.stringify(expected)}`); -} - -export const postJSON = { - method: "POST", - headers: { - "Content-Type": "application/json", - }, }; \ No newline at end of file diff --git a/test/utils/utils.ts b/test/utils/utils.ts new file mode 100644 index 0000000..4bbb8f4 --- /dev/null +++ b/test/utils/utils.ts @@ -0,0 +1,11 @@ +/** + * Duplicated from Mocha types. TypeScript doesn't infer that type by itself for some reason. + */ +export type Done = (err?: any) => void; + +export const postJSON = { + method: "POST", + headers: { + "Content-Type": "application/json", + }, +}; \ No newline at end of file From c779c2c19e1e18279b15361a56abdc9d80a626ab Mon Sep 17 00:00:00 2001 From: Michael C Date: Wed, 22 Sep 2021 17:50:06 -0400 Subject: [PATCH 09/14] everything to postClearCache --- package-lock.json | 41 +++++ package.json | 1 + src/middleware/userCounter.ts | 4 +- src/routes/getTotalStats.ts | 8 +- test/cases/getIsUserVIP.ts | 33 ++-- test/cases/getLockCategories.ts | 34 ++-- test/cases/getLockCategoriesByHash.ts | 72 ++++---- test/cases/getSavedTimeForUser.ts | 18 +- test/cases/getSearchSegments.ts | 118 +++++++------ test/cases/getSegmentInfo.ts | 168 +++++++++--------- test/cases/getService.ts | 1 - test/cases/getSkipSegments.ts | 179 ++++++++++--------- test/cases/getSkipSegmentsByHash.ts | 171 +++++++++--------- test/cases/getStatus.ts | 59 +++---- test/cases/getUserID.ts | 166 +++++++++--------- test/cases/getUserInfo.ts | 169 ++++++++---------- test/cases/getUserStats.ts | 50 +++--- test/cases/lockCategoriesRecords.ts | 239 +++++++++----------------- test/cases/oldGetSponsorTime.ts | 37 ++-- test/cases/oldSubmitSponsorTimes.ts | 29 ++-- test/utils/httpClient.ts | 13 ++ 21 files changed, 750 insertions(+), 860 deletions(-) create mode 100644 test/utils/httpClient.ts diff --git a/package-lock.json b/package-lock.json index 25dccee..ff8c266 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "@ajayyy/lru-diskcache": "^1.1.9", "@types/request": "^2.48.7", + "axios": "^0.21.4", "better-sqlite3": "^7.4.3", "cron": "^1.8.2", "express": "^4.17.1", @@ -1111,6 +1112,14 @@ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" }, + "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": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", @@ -2570,6 +2579,25 @@ "integrity": "sha512-XprP7lDrVT+kE2c2YlfiV+IfS9zxukiIOvNamPNsImNhXadSsQEbosItdL9bUQlCZXR13SvPk20BjWSWLA7m4A==", "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": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz", @@ -6660,6 +6688,14 @@ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" }, + "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": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", @@ -7785,6 +7821,11 @@ "integrity": "sha512-XprP7lDrVT+kE2c2YlfiV+IfS9zxukiIOvNamPNsImNhXadSsQEbosItdL9bUQlCZXR13SvPk20BjWSWLA7m4A==", "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": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz", diff --git a/package.json b/package.json index 04103ed..5a2caa6 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "dependencies": { "@ajayyy/lru-diskcache": "^1.1.9", "@types/request": "^2.48.7", + "axios": "^0.21.4", "better-sqlite3": "^7.4.3", "cron": "^1.8.2", "express": "^4.17.1", diff --git a/src/middleware/userCounter.ts b/src/middleware/userCounter.ts index 0818a9e..a941cf5 100644 --- a/src/middleware/userCounter.ts +++ b/src/middleware/userCounter.ts @@ -1,4 +1,4 @@ -import fetch from "node-fetch"; +import axios from "axios"; import {Logger} from "../utils/logger"; import {config} from "../config"; import {getIP} from "../utils/getIP"; @@ -6,7 +6,7 @@ import {getHash} from "../utils/getHash"; import {NextFunction, Request, Response} from "express"; 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}`)); next(); diff --git a/src/routes/getTotalStats.ts b/src/routes/getTotalStats.ts index 4db4601..2fe7af7 100644 --- a/src/routes/getTotalStats.ts +++ b/src/routes/getTotalStats.ts @@ -2,6 +2,7 @@ import {db} from "../databases/databases"; import {config} from "../config"; import {Request, Response} from "express"; import fetch from "node-fetch"; +import axios from "axios"; import {Logger} from "../utils/logger"; // A cache of the number of chrome web store users @@ -44,10 +45,9 @@ export async function getTotalStats(req: Request, res: Response): Promise function updateExtensionUsers() { if (config.userCounterURL) { - fetch(`${config.userCounterURL}/api/v1/userCount`) - .then(res => res.json()) - .then(data => { - apiUsersCache = Math.max(apiUsersCache, data.userCount); + axios.get(`${config.userCounterURL}/api/v1/userCount`) + .then(res => { + apiUsersCache = Math.max(apiUsersCache, res.data.userCount); }) .catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`)); } diff --git a/test/cases/getIsUserVIP.ts b/test/cases/getIsUserVIP.ts index 0639066..be03fac 100644 --- a/test/cases/getIsUserVIP.ts +++ b/test/cases/getIsUserVIP.ts @@ -1,21 +1,20 @@ -import fetch from "node-fetch"; -import { Done} from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; +import { client } from "../utils/httpClient"; import assert from "assert"; -const endpoint = `${getbaseURL()}/api/isUserVIP`; const VIPUser = "isUserVIPVIP"; const normalUser = "isUserVIPNormal"; +const endpoint = "/api/isUserVIP"; +const vipUserRequest = (userID: string) => client.get(endpoint, { params: { userID }}); describe("getIsUserVIP", () => { before(() => { db.prepare("run", 'INSERT INTO "vipUsers" ("userID") VALUES (?)', [getHash(VIPUser)]); }); - it("Should be able to get a 200", (done: Done) => { - fetch(`${endpoint}?userID=${VIPUser}`) + it("Should be able to get a 200", (done) => { + vipUserRequest(VIPUser) .then(res => { assert.strictEqual(res.status, 200, "response should be 200"); done(); @@ -24,8 +23,8 @@ describe("getIsUserVIP", () => { }); - it("Should get a 400 if no userID", (done: Done) => { - fetch(endpoint) + it("Should get a 400 if no userID", (done) => { + client.get(endpoint) .then(res => { assert.strictEqual(res.status, 400, "response should be 400"); done(); @@ -33,23 +32,21 @@ describe("getIsUserVIP", () => { .catch(err => done(err)); }); - it("Should say a VIP is a VIP", (done: Done) => { - fetch(`${endpoint}?userID=${VIPUser}`) - .then(async res => { + it("Should say a VIP is a VIP", (done) => { + vipUserRequest(VIPUser) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - assert.strictEqual(data.vip, true); + assert.strictEqual(res.data.vip, true); done(); }) .catch(err => done(err)); }); - it("Should say a normal user is not a VIP", (done: Done) => { - fetch(`${endpoint}?userID=${normalUser}`) - .then(async res => { + it("Should say a normal user is not a VIP", (done) => { + vipUserRequest(normalUser) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - assert.strictEqual(data.vip, false); + assert.strictEqual(res.data.vip, false); done(); }) .catch(err => done(err)); diff --git a/test/cases/getLockCategories.ts b/test/cases/getLockCategories.ts index f04f89e..128efdd 100644 --- a/test/cases/getLockCategories.ts +++ b/test/cases/getLockCategories.ts @@ -1,13 +1,11 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; - +import { client } from "../utils/httpClient"; +const endpoint = "/api/lockCategories"; +const getLockCategories = (videoID: string) => client.get(endpoint, { params: { videoID } }); describe("getLockCategories", () => { - const endpoint = `${getbaseURL()}/api/lockCategories`; before(async () => { const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; await db.prepare("run", insertVipUserQuery, [getHash("getLockCategoriesVIP")]); @@ -26,11 +24,10 @@ describe("getLockCategories", () => { assert.ok(version > 20, `Version isn't greater than 20. Version is ${version}`); }); - it("Should be able to get multiple locks", (done: Done) => { - fetch(`${endpoint}?videoID=getLock1`) - .then(async res => { + it("Should be able to get multiple locks", (done) => { + getLockCategories("getLock1") + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { categories: [ "sponsor", @@ -38,31 +35,30 @@ describe("getLockCategories", () => { ], reason: "1-longer-reason" }; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get single locks", (done: Done) => { - fetch(`${endpoint}?videoID=getLock2`) - .then(async res => { + it("Should be able to get single locks", (done) => { + getLockCategories("getLock2") + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { categories: [ "preview" ], reason: "2-reason" }; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should return 404 if no lock exists", (done: Done) => { - fetch(`${endpoint}?videoID=getLockNull`) + it("should return 404 if no lock exists", (done) => { + getLockCategories("getLockNull") .then(res => { assert.strictEqual(res.status, 404); done(); @@ -70,8 +66,8 @@ describe("getLockCategories", () => { .catch(err => done(err)); }); - it("should return 400 if no videoID specified", (done: Done) => { - fetch(endpoint) + it("should return 400 if no videoID specified", (done) => { + client.get(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getLockCategoriesByHash.ts b/test/cases/getLockCategoriesByHash.ts index 84dad63..63ab2a3 100644 --- a/test/cases/getLockCategoriesByHash.ts +++ b/test/cases/getLockCategoriesByHash.ts @@ -1,14 +1,13 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; 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", () => { - const endpoint = `${getbaseURL()}/api/lockCategories`; before(async () => { const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; await db.prepare("run", insertVipUserQuery, [getHash("getLockCategoriesHashVIP")]); @@ -33,13 +32,12 @@ describe("getLockCategoriesByHash", () => { `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) => { const videoID = "getLockHash1"; const hash = getHash(videoID, 1); - fetch(`${endpoint}/${hash.substring(0,4)}`) - .then(async res => { + getLockCategories(hash.substring(0,4)) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID, hash, @@ -49,19 +47,18 @@ describe("getLockCategoriesByHash", () => { ], reason: "1-reason-longer" }]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get single lock", (done: Done) => { + it("Should be able to get single lock", (done) => { const videoID = "getLockHash2"; const hash = getHash(videoID, 1); - fetch(`${endpoint}/${hash.substring(0,6)}`) - .then(async res => { + getLockCategories(hash.substring(0,6)) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID, hash, @@ -70,19 +67,18 @@ describe("getLockCategoriesByHash", () => { ], reason: "2-reason" }]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .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) => { const videoID = "getLockHash3"; const hash = getHash(videoID, 1); - fetch(`${endpoint}/${hash.substring(0,32)}`) - .then(async res => { + getLockCategories(hash.substring(0,32)) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID, hash, @@ -91,17 +87,16 @@ describe("getLockCategoriesByHash", () => { ], reason: "3-reason" }]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get multiple by similar hash with multiple categories", (done: Done) => { - fetch(`${endpoint}/${fakeHash.substring(0,5)}`) - .then(async res => { + it("Should be able to get multiple by similar hash with multiple categories", (done) => { + getLockCategories(fakeHash.substring(0,5)) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "fakehash-1", hash: fakeHash, @@ -118,14 +113,14 @@ describe("getLockCategoriesByHash", () => { ], reason: "fake2-longer-reason" }]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should return 404 once hash prefix varies", (done: Done) => { - fetch(`${endpoint}/b05aa`) + it("should return 404 once hash prefix varies", (done) => { + getLockCategories("b05aa") .then(res => { assert.strictEqual(res.status, 404); done(); @@ -133,8 +128,8 @@ describe("getLockCategoriesByHash", () => { .catch(err => done(err)); }); - it("should return 404 if no lock exists", (done: Done) => { - fetch(`${endpoint}/aaaaaa`) + it("should return 404 if no lock exists", (done) => { + getLockCategories("aaaaaa") .then(res => { assert.strictEqual(res.status, 404); done(); @@ -142,8 +137,8 @@ describe("getLockCategoriesByHash", () => { .catch(err => done(err)); }); - it("should return 400 if no videoID specified", (done: Done) => { - fetch(`${endpoint}/`) + it("should return 400 if full hash sent", (done) => { + getLockCategories(fakeHash) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -151,8 +146,8 @@ describe("getLockCategoriesByHash", () => { .catch(err => done(err)); }); - it("should return 400 if full hash sent", (done: Done) => { - fetch(`${endpoint}/${fakeHash}`) + it("should return 400 if hash too short", (done) => { + getLockCategories("00") .then(res => { assert.strictEqual(res.status, 400); done(); @@ -160,17 +155,8 @@ describe("getLockCategoriesByHash", () => { .catch(err => done(err)); }); - it("should return 400 if hash too short", (done: Done) => { - fetch(`${endpoint}/00`) - .then(res => { - assert.strictEqual(res.status, 400); - done(); - }) - .catch(err => done(err)); - }); - - it("should return 400 if no hash specified", (done: Done) => { - fetch(endpoint) + it("should return 400 if no hash specified", (done) => { + getLockCategories("") .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getSavedTimeForUser.ts b/test/cases/getSavedTimeForUser.ts index 59ac2fc..7fd27cd 100644 --- a/test/cases/getSavedTimeForUser.ts +++ b/test/cases/getSavedTimeForUser.ts @@ -1,29 +1,27 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import {deepStrictEqual} from "assert"; +import { client } from "../utils/httpClient"; +const endpoint = "/api/getSavedTimeForUser"; describe("getSavedTimeForUser", () => { - const endpoint = `${getbaseURL()}/api/getSavedTimeForUser`; + const user1 = "getSavedTimeForUserUser"; before(async () => { const startOfQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", "views", "shadowHidden") VALUES'; await db.prepare("run", `${startOfQuery}(?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ["getSavedTimeForUser", 1, 11, 2, "gstfu0", getHash("getSavedTimeForUserUser"), 0, 50, 0]); + ["getSavedTimeForUser", 1, 11, 2, "gstfu0", getHash(user1), 0, 50, 0]); return; }); - it("Should be able to get a 200", (done: Done) => { - fetch(`${endpoint}?userID=getSavedTimeForUserUser`) - .then(async res => { - const data = await res.json(); + it("Should be able to get a 200", (done) => { + client.get(endpoint, { params: { userID: user1 }}) + .then(res => { // (end-start)*minute * views const savedMinutes = ((11-1)/60) * 50; const expected = { timeSaved: savedMinutes }; - deepStrictEqual(data, expected); + deepStrictEqual(res.data, expected); done(); }) .catch((err) => done(err)); diff --git a/test/cases/getSearchSegments.ts b/test/cases/getSearchSegments.ts index 80416c5..9a9be1e 100644 --- a/test/cases/getSearchSegments.ts +++ b/test/cases/getSearchSegments.ts @@ -1,11 +1,9 @@ -import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; +import { client } from "../utils/httpClient"; import assert from "assert"; describe("getSearchSegments", () => { - const endpoint = `${getbaseURL()}/api/searchSegments`; + const endpoint = "/api/searchSegments"; before(async () => { 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", "searchTestUser", "sponsor", "skip"]); @@ -34,11 +32,11 @@ describe("getSearchSegments", () => { return; }); - it("Should be able to show all segments under searchTest0", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest0`) - .then(async res => { + it("Should be able to show all segments under searchTest0", (done) => { + client.get(endpoint, { params: { videoID: "searchTest0" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 5); assert.strictEqual(data.page, 0); @@ -52,11 +50,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter by category", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest0&category=selfpromo`) - .then(async res => { + it("Should be able to filter by category", (done) => { + client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.page, 0); @@ -66,11 +64,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter by category", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest0&category=selfpromo`) - .then(async res => { + it("Should be able to filter by category", (done) => { + client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.page, 0); @@ -80,11 +78,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter by lock status", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest0&locked=false`) - .then(async res => { + it("Should be able to filter by lock status", (done) => { + client.get(endpoint, { params: { videoID: "searchTest0", locked: false }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 4); assert.strictEqual(data.page, 0); @@ -97,11 +95,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter by hide status", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest0&hidden=false`) - .then(async res => { + it("Should be able to filter by hide status", (done) => { + client.get(endpoint, { params: { videoID: "searchTest0", hidden: false }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 4); assert.strictEqual(data.page, 0); @@ -114,11 +112,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter by ignored status", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest0&ignored=false`) - .then(async res => { + it("Should be able to filter by ignored status", (done) => { + client.get(endpoint, { params: { videoID: "searchTest0", ignored: false }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 3); assert.strictEqual(data.page, 0); @@ -130,11 +128,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter segments by min views", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest1&minViews=6`) - .then(async res => { + it("Should be able to filter segments by min views", (done) => { + client.get(endpoint, { params: { videoID: "searchTest1", minViews: 6 }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.page, 0); @@ -144,11 +142,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter segments by max views", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest1&maxViews=10`) - .then(async res => { + it("Should be able to filter segments by max views", (done) => { + client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10 }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.page, 0); @@ -158,11 +156,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter segments by min and max views", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest1&maxViews=10&minViews=1`) - .then(async res => { + it("Should be able to filter segments by min and max views", (done) => { + client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10, minViews: 1 }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.page, 0); @@ -172,11 +170,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter segments by min votes", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest2&minVotes=0`) - .then(async res => { + it("Should be able to filter segments by min votes", (done) => { + client.get(endpoint, { params: { videoID: "searchTest2", minVotes: 0 }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 2); assert.strictEqual(data.page, 0); @@ -187,11 +185,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter segments by max votes", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest2&maxVotes=10`) - .then(async res => { + it("Should be able to filter segments by max votes", (done) => { + client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10 }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 2); assert.strictEqual(data.page, 0); @@ -202,11 +200,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to filter segments by both min and max votes", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest2&maxVotes=10&minVotes=0`) - .then(async res => { + it("Should be able to filter segments by both min and max votes", (done) => { + client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10, minVotes: 0 }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 1); assert.strictEqual(data.page, 0); @@ -216,11 +214,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to get first page of results", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest4`) - .then(async res => { + it("Should be able to get first page of results", (done) => { + client.get(endpoint, { params: { videoID: "searchTest4" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 12); assert.strictEqual(data.page, 0); @@ -239,11 +237,11 @@ describe("getSearchSegments", () => { .catch(err => done(err)); }); - it("Should be able to get second page of results", (done: Done) => { - fetch(`${endpoint}?videoID=searchTest4&page=1`) - .then(async res => { + it("Should be able to get second page of results", (done) => { + client.get(endpoint, { params: { videoID: "searchTest4", page: 1 }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const segments = data.segments; assert.strictEqual(data.segmentCount, 12); assert.strictEqual(data.page, 1); diff --git a/test/cases/getSegmentInfo.ts b/test/cases/getSegmentInfo.ts index 7a075b7..6153ab0 100644 --- a/test/cases/getSegmentInfo.ts +++ b/test/cases/getSegmentInfo.ts @@ -1,9 +1,7 @@ -import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; +import { client } from "../utils/httpClient"; const ENOENTID = "0".repeat(64); const upvotedID = `a${"0".repeat(63)}`; @@ -27,8 +25,10 @@ const userAgents = { blank: "" }; +const endpoint = "/api/segmentInfo"; +const singleUUIDLookup = (UUID: string) => client.get(endpoint, { params: { UUID } }); + describe("getSegmentInfo", () => { - const endpoint = `${getbaseURL()}/api/segmentInfo`; before(async () => { const insertQuery = `INSERT INTO "sponsorTimes"("videoID", "startTime", "endTime", "votes", "locked", @@ -49,154 +49,146 @@ describe("getSegmentInfo", () => { await db.prepare("run", insertQuery, ["segmentInfoFiller", 5, 6, 1, 0, fillerID5, "segmentInfoUser", 0, 50, 0, 0, userAgents.blank]); }); - it("Should be able to retreive upvoted segment", (done: Done) => { - fetch(`${endpoint}?UUID=${upvotedID}`) - .then(async res => { + it("Should be able to retreive upvoted segment", (done) => { + singleUUIDLookup(upvotedID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoUpvoted", votes: 2, userAgent: userAgents.vanced, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive downvoted segment", (done: Done) => { - fetch(`${endpoint}?UUID=${downvotedID}`) - .then(async res => { + it("Should be able to retreive downvoted segment", (done) => { + singleUUIDLookup(downvotedID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoDownvoted", votes: -2, userAgent: userAgents.meabot, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive locked up segment", (done: Done) => { - fetch(`${endpoint}?UUID=${lockedupID}`) - .then(async res => { + it("Should be able to retreive locked up segment", (done) => { + singleUUIDLookup(lockedupID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoLockedup", locked: 1, votes: 2, userAgent: userAgents.mpv, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive infinite vote segment", (done: Done) => { - fetch(`${endpoint}?UUID=${infvotesID}`) - .then(async res => { + it("Should be able to retreive infinite vote segment", (done) => { + singleUUIDLookup(infvotesID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoInfvotes", votes: 100000, userAgent: userAgents.nodesb, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive shadowhidden segment", (done: Done) => { - fetch(`${endpoint}?UUID=${shadowhiddenID}`) - .then(async res => { + it("Should be able to retreive shadowhidden segment", (done) => { + singleUUIDLookup(shadowhiddenID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoShadowhidden", shadowHidden: 1, userAgent: userAgents.blank, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive locked down segment", (done: Done) => { - fetch(`${endpoint}?UUID=${lockeddownID}`) - .then(async res => { + it("Should be able to retreive locked down segment", (done) => { + singleUUIDLookup(lockeddownID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoLockedown", locked: 1, votes: -2, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive hidden segment", (done: Done) => { - fetch(`${endpoint}?UUID=${hiddenID}`) - .then(async res => { + it("Should be able to retreive hidden segment", (done) => { + singleUUIDLookup(hiddenID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoHidden", hidden: 1, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive segment with old ID", (done: Done) => { - fetch(`${endpoint}?UUID=${oldID}`) - .then(async res => { + it("Should be able to retreive segment with old ID", (done) => { + singleUUIDLookup(oldID) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoOldID", votes: 1, }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive single segment in array", (done: Done) => { - fetch(`${endpoint}?UUIDs=["${upvotedID}"]`) - .then(async res => { + it("Should be able to retreive single segment in array", (done) => { + client.get(endpoint, { params: { UUIDs: `["${upvotedID}"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ videoID: "segmentInfoUpvoted", votes: 2, }]; assert.strictEqual(data.length, 1); - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to retreive multiple segments in array", (done: Done) => { - fetch(`${endpoint}?UUIDs=["${upvotedID}", "${downvotedID}"]`) - .then(async res => { + it("Should be able to retreive multiple segments in array", (done) => { + client.get(endpoint, { params: { UUIDs: `["${upvotedID}", "${downvotedID}"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ videoID: "segmentInfoUpvoted", votes: 2, @@ -211,11 +203,11 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should be possible to send unexpected query parameters", (done: Done) => { - fetch(`${endpoint}?UUID=${upvotedID}&fakeparam=hello&category=sponsor`) - .then(async res => { + it("Should be possible to send unexpected query parameters", (done) => { + client.get(endpoint, { params: { UUID: upvotedID, fakeparam: "hello", category: "sponsor" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ videoID: "segmentInfoUpvoted", votes: 2, @@ -226,8 +218,8 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should return 400 if array passed to UUID", (done: Done) => { - fetch(`${endpoint}?UUID=["${upvotedID}", "${downvotedID}"]`) + it("Should return 400 if array passed to UUID", (done) => { + client.get(`${endpoint}?UUID=["${upvotedID}", "${downvotedID}"]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -235,8 +227,8 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should return 400 if bad array passed to UUIDs", (done: Done) => { - fetch(`${endpoint}?UUIDs=[not-quoted,not-quoted]`) + it("Should return 400 if bad array passed to UUIDs", (done) => { + client.get(`${endpoint}?UUIDs=[not-quoted,not-quoted]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -244,8 +236,8 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should return 400 if bad UUID passed", (done: Done) => { - fetch(`${endpoint}?UUID=notarealuuid`) + it("Should return 400 if bad UUID passed", (done) => { + client.get(`${endpoint}?UUID=notarealuuid`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -253,8 +245,8 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should return 400 if bad UUIDs passed in array", (done: Done) => { - fetch(`${endpoint}?UUIDs=["notarealuuid", "anotherfakeuuid"]`) + it("Should return 400 if bad UUIDs passed in array", (done) => { + client.get(`${endpoint}?UUIDs=["notarealuuid", "anotherfakeuuid"]`) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -262,11 +254,11 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should return good UUID when mixed with bad UUIDs", (done: Done) => { - fetch(`${endpoint}?UUIDs=["${upvotedID}", "anotherfakeuuid"]`) - .then(async res => { + it("Should return good UUID when mixed with bad UUIDs", (done) => { + client.get(`${endpoint}?UUIDs=["${upvotedID}", "anotherfakeuuid"]`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ videoID: "segmentInfoUpvoted", votes: 2, @@ -278,13 +270,13 @@ describe("getSegmentInfo", () => { .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); const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`; - fetch(`${endpoint}?UUIDs=${filledIDArray}`) - .then(async res => { + client.get(endpoint, { params: { UUIDs: filledIDArray }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 10); assert.strictEqual(data[0].videoID, "segmentInfoUpvoted"); assert.strictEqual(data[0].votes, 2); @@ -295,19 +287,18 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should not duplicate reponses", (done: Done) => { - fetch(`${endpoint}?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`) - .then(async res => { + it("Should not duplicate reponses", (done) => { + client.get(`${endpoint}?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - assert.strictEqual(data.length, 2); + assert.strictEqual(res.data.length, 2); done(); }) .catch(err => done(err)); }); - it("Should return 400 if UUID not found", (done: Done) => { - fetch(`${endpoint}?UUID=${ENOENTID}`) + it("Should return 400 if UUID not found", (done) => { + client.get(endpoint, { params: { UUID: ENOENTID }}) .then(res => { if (res.status !== 400) done(`non 400 response code: ${res.status}`); else done(); // pass @@ -315,11 +306,11 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should be able to retreive multiple segments with multiple parameters", (done: Done) => { - fetch(`${endpoint}?UUID=${upvotedID}&UUID=${downvotedID}`) - .then(async res => { + it("Should be able to retreive multiple segments with multiple parameters", (done) => { + client.get(`${endpoint}?UUID=${upvotedID}&UUID=${downvotedID}`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ videoID: "segmentInfoUpvoted", votes: 2, @@ -334,16 +325,15 @@ describe("getSegmentInfo", () => { .catch(err => done(err)); }); - it("Should not parse repeated UUID if UUIDs present", (done: Done) => { - fetch(`${endpoint}?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`) - .then(async res => { + it("Should not parse repeated UUID if UUIDs present", (done) => { + client.get(`${endpoint}?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [{ videoID: "segmentInfoUpvoted", votes: 2 }]; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); diff --git a/test/cases/getService.ts b/test/cases/getService.ts index a223247..a2d6c88 100644 --- a/test/cases/getService.ts +++ b/test/cases/getService.ts @@ -1,6 +1,5 @@ import { getService } from "../../src/utils/getService"; import { Service } from "../../src/types/segments.model"; - import assert from "assert"; describe("getService", () => { diff --git a/test/cases/getSkipSegments.ts b/test/cases/getSkipSegments.ts index 4d6afa8..f13ae1b 100644 --- a/test/cases/getSkipSegments.ts +++ b/test/cases/getSkipSegments.ts @@ -1,12 +1,10 @@ -import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; +import { client } from "../utils/httpClient"; describe("getSkipSegments", () => { - const endpoint = `${getbaseURL()}/api/skipSegments`; + const endpoint = "/api/skipSegments"; before(async () => { 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, ["getSkipSegmentID0", 1, 11, 2, 0, "uuid01", "testman", 0, 50, "sponsor", "skip", "YouTube", 100, 0, 0]); @@ -28,12 +26,11 @@ describe("getSkipSegments", () => { return; }); - - it("Should be able to get a time by category 1", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor`) - .then(async res => { + it("Should be able to get a time by category 1", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); assert.strictEqual(data[0].segment[0], 1); assert.strictEqual(data[0].segment[1], 11); @@ -45,11 +42,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get a time by category and action type", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionType=mute`) - .then(async res => { + it("Should be able to get a time by category and action type", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionType: "mute" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ segment: [12, 14], category: "sponsor", @@ -63,11 +60,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get a time by category and getSkipSegmentMultiple action types", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionType=mute&actionType=skip`) - .then(async res => { + it("Should be able to get a time by category and getSkipSegmentMultiple action types", (done) => { + client.get(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionType=mute&actionType=skip`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ segment: [1, 11], category: "sponsor", @@ -83,11 +80,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&actionTypes=["mute","skip"]`) - .then(async res => { + it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionTypes: `["mute","skip"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ segment: [1, 11], category: "sponsor", @@ -102,11 +99,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get a time by category for a different service 1", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID1&category=sponsor&service=PeerTube`) - .then(async res => { + it("Should be able to get a time by category for a different service 1", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID1", category: "sponsor", service: "PeerTube" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; const expected = [{ segment: [1, 11], category: "sponsor", @@ -120,28 +117,29 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get a time by category 2", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&category=intro`) - .then(async res => { + it("Should be able to get a time by category 2", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "intro" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; + assert.strictEqual(data.length, 1); const expected = [{ segment: [20, 33], category: "intro", UUID: "uuid03" }]; assert.ok(partialDeepEquals(data, expected)); - assert.strictEqual(data.length, 1); done(); }) .catch(err => done(err)); }); - it("Should be able to get a time by categories array", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor"]`) - .then(async res => { + it("Should be able to get a time by categories array", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; + assert.strictEqual(data.length, 1); const expected = [{ segment: [1, 11], category: "sponsor", @@ -149,17 +147,17 @@ describe("getSkipSegments", () => { videoDuration: 100 }]; assert.ok(partialDeepEquals(data, expected)); - assert.strictEqual(data.length, 1); done(); }) .catch(err => done(err)); }); - it("Should be able to get a time by categories array 2", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["intro"]`) - .then(async res => { + it("Should be able to get a time by categories array 2", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["intro"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; + assert.strictEqual(data.length, 1); const expected = [{ segment: [20, 33], category: "intro", @@ -167,14 +165,13 @@ describe("getSkipSegments", () => { videoDuration: 101 }]; assert.ok(partialDeepEquals(data, expected)); - assert.strictEqual(data.length, 1); done(); }) .catch(err => done(err)); }); - it("Should return 404 if all submissions are hidden", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID6`) + it("Should return 404 if all submissions are hidden", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID6" }}) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -182,11 +179,12 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get getSkipSegmentMultiple times by category", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentMultiple&categories=["intro"]`) - .then(async res => { + it("Should be able to get getSkipSegmentMultiple times by category", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentMultiple", categories: `["intro"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; + assert.strictEqual(data.length, 2); const expected = [{ segment: [1, 11], category: "intro", @@ -197,17 +195,17 @@ describe("getSkipSegments", () => { UUID: "uuid41", }]; assert.ok(partialDeepEquals(data, expected)); - assert.strictEqual(data.length, 2); done(); }) .catch(err => done(err)); }); - it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor", "intro"]`) - .then(async res => { + it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor", "intro"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; + assert.strictEqual(data.length, 2); const expected = [{ segment: [1, 11], category: "sponsor", @@ -218,17 +216,16 @@ describe("getSkipSegments", () => { UUID: "uuid03", }]; assert.ok(partialDeepEquals(data, expected)); - assert.strictEqual(data.length, 2); done(); }) .catch(err => done(err)); }); - it("Should be possible to send unexpected query parameters", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&fakeparam=hello&category=sponsor`) - .then(async res => { + it("Should be possible to send unexpected query parameters", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", fakeparam: "hello", category: "sponsor" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segment: [1, 11], @@ -241,11 +238,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Low voted submissions should be hidden", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID3&category=sponsor`) - .then(async res => { + it("Low voted submissions should be hidden", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID3", category: "sponsor" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segment: [1, 11], @@ -258,8 +255,8 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should return 404 if no segment found", (done: Done) => { - fetch(`${endpoint}?videoID=notarealvideo`) + it("Should return 404 if no segment found", (done) => { + client.get(endpoint, { params: { videoID: "notarealvideo" }}) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -267,8 +264,8 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should return 400 if bad categories argument", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=[not-quoted,not-quoted]`) + it("Should return 400 if bad categories argument", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `[not-quoted,not-quoted]` }}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -276,11 +273,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able send a comma in a query param", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID2&category=sponsor`) - .then(async res => { + it("Should be able send a comma in a query param", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentID2", category: "sponsor" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segment: [1, 11], @@ -293,11 +290,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should always get getSkipSegmentLocked segment", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentLocked&category=intro`) - .then(async res => { + it("Should always get getSkipSegmentLocked segment", (done) => { + client.get(endpoint, { params: { videoID: "getSkipSegmentLocked", category: "intro" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segment: [20, 33], @@ -310,11 +307,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&category=sponsor&category=intro`) - .then(async res => { + it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done) => { + client.get(`${endpoint}?category=sponsor&category=intro`, { params: { videoID: "getSkipSegmentID0" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 2); const expected = [{ segment: [1, 11], @@ -331,11 +328,11 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to get, categories param overriding repeating category", (done: Done) => { - fetch(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor"]&category=intro`) - .then(async res => { + it("Should be able to get, categories param overriding repeating category", (done) => { + client.get(`${endpoint}?videoID=getSkipSegmentID0&categories=["sponsor"]&category=intro`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segment: [1, 11], @@ -348,13 +345,13 @@ describe("getSkipSegments", () => { .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) => { const required2 = "requiredSegmentVid2"; const required3 = "requiredSegmentVid3"; - fetch(`${endpoint}?videoID=requiredSegmentVid&requiredSegments=["${required2}","${required3}"]`) - .then(async res => { + client.get(endpoint, { params: { videoID: "requiredSegmentVid", requiredSegments: `["${required2}","${required3}"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 2); const expected = [{ UUID: required2, @@ -367,13 +364,13 @@ describe("getSkipSegments", () => { .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) => { const required2 = "requiredSegmentVid2"; const required3 = "requiredSegmentVid3"; - fetch(`${endpoint}?videoID=requiredSegmentVid&requiredSegment=${required2}&requiredSegment=${required3}`) - .then(async res => { + client.get(`${endpoint}?videoID=requiredSegmentVid&requiredSegment=${required2}&requiredSegment=${required3}`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 2); const expected = [{ UUID: required2, @@ -386,9 +383,9 @@ describe("getSkipSegments", () => { .catch(err => done(err)); }); - it("Should get 400 if no videoID passed in", (done: Done) => { - fetch(`${endpoint}`) - .then(async res => { + it("Should get 400 if no videoID passed in", (done) => { + client.get(endpoint) + .then(res => { assert.strictEqual(res.status, 400); done(); }) diff --git a/test/cases/getSkipSegmentsByHash.ts b/test/cases/getSkipSegmentsByHash.ts index d97c888..bc9efff 100644 --- a/test/cases/getSkipSegmentsByHash.ts +++ b/test/cases/getSkipSegmentsByHash.ts @@ -1,20 +1,18 @@ -import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import { Done, postJSON } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import {getHash} from "../../src/utils/getHash"; import {ImportMock,} from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; import {YouTubeApiMock} from "../youtubeMock"; import assert from "assert"; +import { client } from "../utils/httpClient"; const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const sinonStub = mockManager.mock("listVideos"); sinonStub.callsFake(YouTubeApiMock.listVideos); describe("getSkipSegmentsByHash", () => { - const endpoint = `${getbaseURL()}/api/skipSegments`; + const endpoint = "/api/skipSegments"; const getSegmentsByHash0Hash = "fdaff4dee1043451faa7398324fb63d8618ebcd11bddfe0491c488db12c6c910"; const requiredSegmentVidHash = "d51822c3f681e07aef15a8855f52ad12db9eb9cf059e65b16b64c43359557f61"; before(async () => { @@ -34,8 +32,8 @@ describe("getSkipSegmentsByHash", () => { 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) => { - fetch(`${endpoint}/3272f?categories=["sponsor", "intro"]`) + it("Should be able to get a 200", (done) => { + client.get(`${endpoint}/3272f`, { params: { categories: `["sponsor", "intro"]` }}) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -43,46 +41,42 @@ describe("getSkipSegmentsByHash", () => { .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) => { - fetch(`${endpoint}/3272f?categories=["shilling"]`) - .then(async res => { + it("Should return 404 if no segments are found even if a video for the given hash is known", (done) => { + client.get(`${endpoint}/3272f`, { params: { categories: `["shilling"]` }}) + .then(res => { assert.strictEqual(res.status, 404); - const expected = "[]"; - const body = await res.text(); - assert.strictEqual(body, expected); + assert.equal(res.data.length, 0); done(); }) .catch(err => done(err)); }); - it("Should be able to get an empty array if no videos", (done: Done) => { - fetch(`${endpoint}/11111?categories=["shilling"]`) - .then(async res => { + it("Should be able to get an empty array if no videos", (done) => { + client.get(`${endpoint}/11111`, { params: { categories: `["shilling"]` }}) + .then(res => { assert.strictEqual(res.status, 404); - const body = await res.text(); - const expected = "[]"; - assert.strictEqual(JSON.parse(body).length, 0); - assert.strictEqual(body, expected); + const body = res.data; + assert.strictEqual(body.length, 0); done(); }) .catch(err => done(err)); }); - it("Should be able to get an empty array if only hidden videos", (done: Done) => { - fetch(`${endpoint}/f3a1?categories=["sponsor"]`) - .then(async res => { + it("Should be able to get an empty array if only hidden videos", (done) => { + client.get(`${endpoint}/f3a1`, { params: { categories:`["sponsor"]` }}) + .then(res => { if (res.status !== 404) done(`non 404 status code, was ${res.status}`); else { - const body = await res.text(); - if (JSON.parse(body).length === 0 && body === "[]") done(); // pass + const body = res.data; + if (body.length === 0) done(); // pass else done("non empty array returned"); } }) .catch(err => done(err)); }); - it("Should return 400 prefix too short", (done: Done) => { - fetch(`${endpoint}/11?categories=["shilling"]`) + it("Should return 400 prefix too short", (done) => { + client.get(`${endpoint}/11`, { params: { categories: `["shilling"]` }}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -90,10 +84,10 @@ describe("getSkipSegmentsByHash", () => { .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); assert.ok(prefix.length > 33, "failed to generate long enough string"); - fetch(`${endpoint}/${prefix}?categories=["shilling"]`) + client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` }}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -101,9 +95,9 @@ describe("getSkipSegmentsByHash", () => { .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); - fetch(`${endpoint}/${prefix}?categories=["shilling"]`) + client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` }}) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -111,8 +105,8 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should return 400 for no hash", (done: Done) => { - fetch(`${endpoint}/?categories=["shilling"]`) + it("Should return 400 for no hash", (done) => { + client.get(`${endpoint}`, { params: { categories: `["shilling"]` }}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -120,8 +114,8 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should return 400 for bad format categories", (done: Done) => { - fetch(`${endpoint}/fdaf?categories=shilling`) + it("Should return 400 for bad format categories", (done) => { + client.get(`${endpoint}/fdaf`, { params: { categories: "shilling" }}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -129,11 +123,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get multiple videos", (done: Done) => { - fetch(`${endpoint}/fdaf?categories=["sponsor","intro"]`) - .then(async res => { + it("Should be able to get multiple videos", (done) => { + client.get(`${endpoint}/fdaf`, { params: { categories: `["sponsor","intro"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 2); assert.strictEqual(data[0].segments.length, 2); assert.strictEqual(data[1].segments.length, 1); @@ -142,12 +136,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get 200 for no categories (default sponsor)", (done: Done) => { - fetch(`${endpoint}/fdaf`) - .then(async res => { + it("Should be able to get 200 for no categories (default sponsor)", (done) => { + client.get(`${endpoint}/fdaf`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - assert.strictEqual(data.length, 2); + const data = res.data; const expected = [{ segments: [{ category: "sponsor", @@ -158,6 +151,7 @@ describe("getSkipSegmentsByHash", () => { category: "sponsor", }] }]; + assert.strictEqual(data.length, 2); assert.ok(partialDeepEquals(data, expected)); assert.strictEqual(data[0].segments.length, 1); assert.strictEqual(data[1].segments.length, 1); @@ -166,11 +160,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get 200 for no categories (default sponsor) with action type", (done: Done) => { - fetch(`${endpoint}/fdaf?actionType=skip`) - .then(async res => { + it("Should be able to get 200 for no categories (default sponsor) with action type", (done) => { + client.get(`${endpoint}/fdaf`, { params: { actionType: "skip" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 2); assert.strictEqual(data[0].segments.length, 1); assert.strictEqual(data[1].segments.length, 1); @@ -190,11 +184,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get 200 for no categories (default sponsor) with multiple action types", (done: Done) => { - fetch(`${endpoint}/fdaf?actionType=skip&actionType=mute`) - .then(async res => { + it("Should be able to get 200 for no categories (default sponsor) with multiple action types", (done) => { + client.get(`${endpoint}/fdaf?actionType=skip&actionType=mute`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 2); assert.strictEqual(data[0].segments.length, 2); assert.strictEqual(data[1].segments.length, 1); @@ -216,11 +210,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get 200 for no categories (default sponsor) with multiple action types (JSON array)", (done: Done) => { - fetch(`${endpoint}/fdaf?actionTypes=["skip","mute"]`) - .then(async res => { + it("Should be able to get 200 for no categories (default sponsor) with multiple action types (JSON array)", (done) => { + client.get(`${endpoint}/fdaf?actionTypes=["skip","mute"]`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 2); const expected = [{ segments: [{ @@ -240,11 +234,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done: Done) => { - fetch(`${endpoint}/fdaf?service=PeerTube`) - .then(async res => { + it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done) => { + client.get(`${endpoint}/fdaf`, { params: { service: "PeerTube" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segments: [{ @@ -258,11 +252,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should only return one segment when fetching highlight segments", (done: Done) => { - fetch(`${endpoint}/c962?category=poi_highlight`) - .then(async res => { + it("Should only return one segment when fetching highlight segments", (done) => { + client.get(`${endpoint}/c962`, { params: { category: "poi_highlight" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); assert.strictEqual(data[0].segments.length, 1); done(); @@ -270,24 +264,21 @@ describe("getSkipSegmentsByHash", () => { .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"; - fetch(`${getbaseURL()}/api/postVideoSponsorTimes`, { - ...postJSON, - body: JSON.stringify({ - userID: "test-qwertyuiopasdfghjklzxcvbnm", - videoID: testID, - segments: [{ - segment: [13, 17], - category: "sponsor", - }], - }), + client.post("/api/skipSegments", { + userID: "test-qwertyuiopasdfghjklzxcvbnm", + videoID: testID, + segments: [{ + segment: [13, 17], + category: "sponsor", + }], }) - .then(async () => { - fetch(`${endpoint}/${getHash(testID, 1).substring(0, 3)}`) - .then(async res => { + .then(() => { + client.get(`${endpoint}/${getHash(testID, 1).substring(0, 3)}`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segments: [{ @@ -303,11 +294,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(`(post) ${err}`)); }); - it("Should be able to get multiple categories with repeating parameters", (done: Done) => { - fetch(`${endpoint}/fdaff4?&category=sponsor&category=intro`) - .then(async res => { + it("Should be able to get multiple categories with repeating parameters", (done) => { + client.get(`${endpoint}/fdaff4?&category=sponsor&category=intro`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segments: [{ @@ -326,11 +317,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get specific segments with requiredSegments", (done: Done) => { - fetch(`${endpoint}/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]`) - .then(async res => { + it("Should be able to get specific segments with requiredSegments", (done) => { + client.get(`${endpoint}/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); const expected = [{ segments: [{ @@ -346,11 +337,11 @@ describe("getSkipSegmentsByHash", () => { .catch(err => done(err)); }); - it("Should be able to get specific segments with repeating requiredSegment", (done: Done) => { - fetch(`${endpoint}/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3`) - .then(async res => { + it("Should be able to get specific segments with repeating requiredSegment", (done) => { + client.get(`${endpoint}/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.strictEqual(data.length, 1); assert.strictEqual(data[0].segments.length, 2); const expected = [{ diff --git a/test/cases/getStatus.ts b/test/cases/getStatus.ts index a58c0b2..3f98e80 100644 --- a/test/cases/getStatus.ts +++ b/test/cases/getStatus.ts @@ -1,21 +1,19 @@ import assert from "assert"; -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; +import { client } from "../utils/httpClient"; let dbVersion: number; describe("getStatus", () => { - const endpoint = `${getbaseURL()}/api/status`; + const endpoint = "/api/status"; before(async () => { dbVersion = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value; }); - it("Should be able to get status", (done: Done) => { - fetch(endpoint) - .then(async res => { + it("Should be able to get status", (done) => { + client.get(endpoint) + .then(res => { 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.strictEqual(data.commit, "test"); assert.strictEqual(data.db, Number(dbVersion)); @@ -26,57 +24,52 @@ describe("getStatus", () => { .catch(err => done(err)); }); - it("Should be able to get uptime only", (done: Done) => { - fetch(`${endpoint}/uptime`) - .then(async res => { + it("Should be able to get uptime only", (done) => { + client.get(`${endpoint}/uptime`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.text(); - assert.ok(Number(data) >= 1); // uptime should be greater than 1s + assert.ok(Number(res.data) >= 1); // uptime should be greater than 1s done(); }) .catch(err => done(err)); }); - it("Should be able to get commit only", (done: Done) => { - fetch(`${endpoint}/commit`) - .then(async res => { + it("Should be able to get commit only", (done) => { + client.get(`${endpoint}/commit`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.text(); - assert.strictEqual(data, "test"); // commit should be test + assert.strictEqual(res.data, "test"); // commit should be test done(); }) .catch(err => done(err)); }); - it("Should be able to get db only", (done: Done) => { - fetch(`${endpoint}/db`) - .then(async res => { + it("Should be able to get db only", (done) => { + client.get(`${endpoint}/db`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.text(); - assert.strictEqual(Number(data), Number(dbVersion)); // commit should be test + assert.strictEqual(Number(res.data), Number(dbVersion)); // commit should be test done(); }) .catch(err => done(err)); }); - it("Should be able to get startTime only", (done: Done) => { - fetch(`${endpoint}/startTime`) - .then(async res => { + it("Should be able to get startTime only", (done) => { + client.get(`${endpoint}/startTime`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.text(); 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(); }) .catch(err => done(err)); }); - it("Should be able to get processTime only", (done: Done) => { - fetch(`${endpoint}/processTime`) - .then(async res => { + it("Should be able to get processTime only", (done) => { + client.get(`${endpoint}/processTime`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.text(); - assert.ok(Number(data) >= 0); + assert.ok(Number(res.data) >= 0); done(); }) .catch(err => done(err)); diff --git a/test/cases/getUserID.ts b/test/cases/getUserID.ts index 2e031c4..226da22 100644 --- a/test/cases/getUserID.ts +++ b/test/cases/getUserID.ts @@ -1,12 +1,13 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; +import { client } from "../utils/httpClient"; +import { AxiosResponse } from "axios"; + +const endpoint = "/api/userID"; +const getUserName = (username: string): Promise => client.get(endpoint, { params: { username }}); describe("getUserID", () => { - const endpoint = `${getbaseURL()}/api/userID`; before(async () => { const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; await db.prepare("run", insertUserNameQuery, [getHash("getuserid_user_01"), "fuzzy user 01"]); @@ -23,17 +24,17 @@ describe("getUserID", () => { await db.prepare("run", insertUserNameQuery, [getHash("getuserid_user_12"), "a"]); }); - it("Should be able to get a 200", (done: Done) => { - fetch(`${endpoint}?username=fuzzy+user+01`) - .then(async res => { + it("Should be able to get a 200", (done) => { + getUserName("fuzzy user 01") + .then(res => { assert.strictEqual(res.status, 200); done(); }) .catch(err => done(err)); }); - it("Should be able to get a 400 (No username parameter)", (done: Done) => { - fetch(endpoint) + it("Should be able to get a 400 (No username parameter)", (done) => { + client.get(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -41,17 +42,17 @@ describe("getUserID", () => { .catch(err => done(err)); }); - it("Should be able to get a 200 (username is public id)", (done: Done) => { - fetch(`${endpoint}?username=${getHash("getuserid_user_06")}`) - .then(async res => { + it("Should be able to get a 200 (username is public id)", (done) => { + client.get(endpoint, { params: { username: getHash("getuserid_user_06") }}) + .then(res => { assert.strictEqual(res.status, 200); done(); }) .catch(err => done(err)); }); - it("Should be able to get a 400 (username longer than 64 chars)", (done: Done) => { - fetch(`${endpoint}?username=${getHash("getuserid_user_06")}0`) + it("Should be able to get a 400 (username longer than 64 chars)", (done) => { + client.get(endpoint, { params: { username: `${getHash("getuserid_user_06")}0` }}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -59,24 +60,23 @@ describe("getUserID", () => { .catch(err => done(err)); }); - it("Should be able to get single username", (done: Done) => { - fetch(`${endpoint}?username=fuzzy+user+01`) - .then(async res => { + it("Should be able to get single username", (done) => { + client.get(endpoint, { params: { username: "fuzzy user 01" }}) + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "fuzzy user 01", userID: getHash("getuserid_user_01") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get multiple fuzzy user info from start", (done: Done) => { - fetch(`${endpoint}?username=fuzzy+user`) - .then(async res => { + it("Should be able to get multiple fuzzy user info from start", (done) => { + getUserName("fuzzy user") + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "fuzzy user 01", @@ -85,16 +85,15 @@ describe("getUserID", () => { userName: "fuzzy user 02", userID: getHash("getuserid_user_02") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get multiple fuzzy user info from middle", (done: Done) => { - fetch(`${endpoint}?username=user`) - .then(async res => { + it("Should be able to get multiple fuzzy user info from middle", (done) => { + getUserName("user") + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "fuzzy user 01", @@ -106,48 +105,45 @@ describe("getUserID", () => { userName: "specific user 03", userID: getHash("getuserid_user_03") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .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"); - fetch(`${endpoint}?username=${userID}`) - .then(async res => { + getUserName(userID) + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: userID, userID }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .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"); - fetch(`${endpoint}?username=${userID.substr(10,60)}`) - .then(async res => { + getUserName(userID.substr(10,60)) + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: userID, userID }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get repeating username", (done: Done) => { - fetch(`${endpoint}?username=repeating`) - .then(async res => { + it("Should be able to get repeating username", (done) => { + getUserName("repeating") + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "repeating", @@ -156,16 +152,15 @@ describe("getUserID", () => { userName: "repeating", userID: getHash("getuserid_user_05") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get repeating fuzzy username", (done: Done) => { - fetch(`${endpoint}?username=peat`) - .then(async res => { + it("Should be able to get repeating fuzzy username", (done) => { + getUserName("peat") + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "repeating", @@ -174,45 +169,42 @@ describe("getUserID", () => { userName: "repeating", userID: getHash("getuserid_user_05") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should avoid ReDOS with _", (done: Done) => { - fetch(`${endpoint}?username=_redos_`) - .then(async res => { + it("should avoid ReDOS with _", (done) => { + getUserName("_redos_") + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "_redos_", userID: getHash("getuserid_user_09") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should avoid ReDOS with %", (done: Done) => { - fetch(`${endpoint}?username=%redos%`) - .then(async res => { + it("should avoid ReDOS with %", (done) => { + getUserName("%redos%") + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "%redos%", userID: getHash("getuserid_user_08") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should return 404 if escaped backslashes present", (done: Done) => { - fetch(`${endpoint}?username=%redos\\\\_`) + it("should return 404 if escaped backslashes present", (done) => { + getUserName("%redos\\\\_") .then(res => { assert.strictEqual(res.status, 404); done(); @@ -220,8 +212,8 @@ describe("getUserID", () => { .catch(err => done(err)); }); - it("should return 404 if backslashes present", (done: Done) => { - fetch(`${endpoint}?username=\\%redos\\_`) + it("should return 404 if backslashes present", (done) => { + getUserName(`\\%redos\\_`) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -229,23 +221,22 @@ describe("getUserID", () => { .catch(err => done(err)); }); - it("should return user if just backslashes", (done: Done) => { - fetch(`${endpoint}?username=\\\\\\`) - .then(async res => { + it("should return user if just backslashes", (done) => { + getUserName(`\\\\\\`) + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "\\\\\\", userID: getHash("getuserid_user_11") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should not allow usernames more than 64 characters", (done: Done) => { - fetch(`${endpoint}?username=${"0".repeat(65)}`) + it("should not allow usernames more than 64 characters", (done) => { + getUserName("0".repeat(65)) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -253,8 +244,8 @@ describe("getUserID", () => { .catch(err => done(err)); }); - it("should not allow usernames less than 3 characters", (done: Done) => { - fetch(`${endpoint}?username=aa`) + it("should not allow usernames less than 3 characters", (done) => { + getUserName("aa") .then(res => { assert.strictEqual(res.status, 400); done(); @@ -262,24 +253,23 @@ describe("getUserID", () => { .catch(err => done(err)); }); - it("should allow exact match", (done: Done) => { - fetch(`${endpoint}?username=a&exact=true`) - .then(async res => { + it("should allow exact match", (done) => { + client.get(endpoint, { params: { username: "a", exact: true }}) + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "a", userID: getHash("getuserid_user_12") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get repeating username with exact username", (done: Done) => { - fetch(`${endpoint}?username=repeating&exact=true`) - .then(async res => { + it("Should be able to get repeating username with exact username", (done) => { + client.get(endpoint, { params: { username: "repeating", exact: true }}) + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "repeating", @@ -288,16 +278,15 @@ describe("getUserID", () => { userName: "repeating", userID: getHash("getuserid_user_05") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should not get exact unless explicitly set to true", (done: Done) => { - fetch(`${endpoint}?username=user&exact=1`) - .then(async res => { + it("Should not get exact unless explicitly set to true", (done) => { + client.get(endpoint, { params: { username: "user", exact: 1 }}) + .then(res => { assert.strictEqual(res.status, 200); const expected = [{ userName: "fuzzy user 01", @@ -309,15 +298,14 @@ describe("getUserID", () => { userName: "specific user 03", userID: getHash("getuserid_user_03") }]; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should return 400 if no username parameter specified", (done: Done) => { - fetch(endpoint) + it("should return 400 if no username parameter specified", (done) => { + client.get(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/getUserInfo.ts b/test/cases/getUserInfo.ts index d73f880..d4f56d3 100644 --- a/test/cases/getUserInfo.ts +++ b/test/cases/getUserInfo.ts @@ -1,13 +1,11 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import {db} from "../../src/databases/databases"; import {getHash} from "../../src/utils/getHash"; import assert from "assert"; +import { client } from "../utils/httpClient"; describe("getUserInfo", () => { - const endpoint = `${getbaseURL()}/api/userInfo`; + const endpoint = "/api/userInfo"; before(async () => { const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; await db.prepare("run", insertUserNameQuery, [getHash("getuserinfo_user_01"), "Username user 01"]); @@ -36,8 +34,8 @@ describe("getUserInfo", () => { await db.prepare("run", insertBanQuery, [getHash("getuserinfo_ban_01")]); }); - it("Should be able to get a 200", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_user_01`) + it("Should be able to get a 200", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_user_01" }}) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -45,8 +43,8 @@ describe("getUserInfo", () => { .catch(err => done(err)); }); - it("Should be able to get a 400 (No userID parameter)", (done: Done) => { - fetch(endpoint) + it("Should be able to get a 400 (No userID parameter)", (done) => { + client.get(endpoint, { params: { userID: "" }}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -54,9 +52,9 @@ describe("getUserInfo", () => { .catch(err => done(err)); }); - it("Should be able to get user info", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_user_01`) - .then(async res => { + it("Should be able to get user info", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_user_01" }}) + .then(res => { assert.strictEqual(res.status, 200); const expected = { userName: "Username user 01", @@ -72,98 +70,91 @@ describe("getUserInfo", () => { warnings: 0, warningReason: "" }; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should get warning data", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_0&value=warnings`) - .then(async res => { + it("Should get warning data", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_warning_0", value: "warnings" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warnings: 1 }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should get warning data with public ID", (done: Done) => { - fetch(`${endpoint}?publicUserID=${getHash("getuserinfo_warning_0")}&values=["warnings"]`) - .then(async res => { + it("Should get warning data with public ID", (done) => { + client.get(endpoint, { params: { publicUserID: getHash("getuserinfo_warning_0"), values: `["warnings"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warnings: 1 }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should get multiple warnings", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_1&value=warnings`) - .then(async res => { + it("Should get multiple warnings", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warnings" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warnings: 2 }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should not get warnings if none", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_2&value=warnings`) - .then(async res => { + it("Should not get warnings if none", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_warning_2", value: "warnings" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warnings: 0, }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should done(userID for userName (No userName set)", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_user_02&value=userName`) - .then(async res => { + it("Should done(userID for userName (No userName set)", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_user_02", value: "userName" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { userName: "c2a28fd225e88f74945794ae85aef96001d4a1aaa1022c656f0dd48ac0a3ea0f" }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should return null segment if none", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_null&value=lastSegmentID`) - .then(async res => { + it("Should return null segment if none", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - assert.strictEqual(data.lastSegmentID, null); + assert.strictEqual(res.data.lastSegmentID, null); done(); }) .catch(err => done(err)); }); - it("Should return zeroes if userid does not exist", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_null&value=lastSegmentID`) - .then(async res => { - const data = await res.json(); + it("Should return zeroes if userid does not exist", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" }}) + .then(res => { + const data = res.data; for (const value in data) { if (data[value] === null && value !== "lastSegmentID") { done(`returned null for ${value}`); @@ -174,115 +165,108 @@ describe("getUserInfo", () => { .catch(err => done(err)); }); - it("Should get warning reason from from single enabled warning", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_0&values=["warningReason"]`) - .then(async res => { + it("Should get warning reason from from single enabled warning", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_warning_0", values: `["warningReason"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warningReason: "warning0-0", }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); // pass }) .catch(err => done(err)); }); - it("Should get most recent warning from two enabled warnings", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_1&value=warningReason`) - .then(async res => { + it("Should get most recent warning from two enabled warnings", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warningReason" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warningReason: "warning1-1" }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); // pass }) .catch(err => done(err)); }); - it("Should not get disabled warning", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_2&values=["warnings","warningReason"]`) - .then(async res => { + it("Should not get disabled warning", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_warning_2", values: `["warnings","warningReason"]` }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warnings: 0, warningReason: "" }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); // pass }) .catch(err => done(err)); }); - it("Should not get newer disabled warning", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_3&value=warnings&value=warningReason`) - .then(async res => { + it("Should not get newer disabled warning", (done) => { + client.get(`${endpoint}?userID=getuserinfo_warning_3&value=warnings&value=warningReason`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { warnings: 1, warningReason: "warning3-0" }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); // pass }) .catch(err => done(err)); }); - it("Should get 400 if bad values specified", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_warning_3&value=invalid-value`) - .then(async res => { + it("Should get 400 if bad values specified", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_warning_3", value: "invalid-value" }}) + .then(res => { assert.strictEqual(res.status, 400); done(); // pass }) .catch(err => done(err)); }); - it("Should get ban data for banned user (only appears when specifically requested)", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_ban_01&value=banned`) - .then(async res => { + it("Should get ban data for banned user (only appears when specifically requested)", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_ban_01", value: "banned" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { banned: true }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); // pass }) .catch(err => done(err)); }); - it("Should get ban data for unbanned user (only appears when specifically requested)", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_notban_01&value=banned`) - .then(async res => { + it("Should get ban data for unbanned user (only appears when specifically requested)", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_notban_01", value: "banned" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { banned: false }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); // pass }) .catch(err => done(err)); }); - it("Should throw 400 on bad json in values", (done: Done) => { - fetch(`${endpoint}?userID=x&values=[userID]`) - .then(async res => { + it("Should throw 400 on bad json in values", (done) => { + client.get(endpoint, { params: { userID: "x", values: `[userID]` }}) + .then(res => { assert.strictEqual(res.status, 400); done(); // pass }) .catch(err => done(err)); }); - it("Should return 200 on userID not found", (done: Done) => { - fetch(`${endpoint}?userID=notused-userid`) - .then(async res => { + it("Should return 200 on userID not found", (done) => { + client.get(endpoint, { params: { userID: "notused-userid" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { minutesSaved: 0, segmentCount: 0, @@ -294,15 +278,15 @@ describe("getUserInfo", () => { reputation: 0, vip: false, }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); // pass }) .catch(err => done(err)); }); - it("Should only count long segments as 10 minutes", (done: Done) => { - fetch(`${endpoint}?userID=getuserinfo_user_03`) - .then(async res => { + it("Should only count long segments as 10 minutes", (done) => { + client.get(endpoint, { params: { userID: "getuserinfo_user_03" }}) + .then(res => { assert.strictEqual(res.status, 200); const expected = { userName: "807e0a5d0a62c9c4365fae3d403e4618a3226f231314a898fa1555a0e55eab9e", @@ -318,8 +302,7 @@ describe("getUserInfo", () => { warnings: 0, warningReason: "" }; - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); diff --git a/test/cases/getUserStats.ts b/test/cases/getUserStats.ts index 64336d1..1bbc756 100644 --- a/test/cases/getUserStats.ts +++ b/test/cases/getUserStats.ts @@ -1,12 +1,11 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import { db } from "../../src/databases/databases"; import { getHash } from "../../src/utils/getHash"; import assert from "assert"; +import { client } from "../utils/httpClient"; describe("getUserStats", () => { + const endpoint = "/api/userStats"; before(async () => { const insertUserNameQuery = 'INSERT INTO "userNames" ("userID", "userName") VALUES(?, ?)'; await db.prepare("run", insertUserNameQuery, [getHash("getuserstats_user_01"), "Username user 01"]); @@ -24,8 +23,8 @@ describe("getUserStats", () => { }); - it("Should be able to get a 400 (No userID parameter)", (done: Done) => { - fetch(`${getbaseURL()}/api/userStats`) + it("Should be able to get a 400 (No userID parameter)", (done) => { + client.get(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -33,9 +32,9 @@ describe("getUserStats", () => { .catch(err => done(err)); }); - it("Should be able to get all user info", (done: Done) => { - fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01&fetchCategoryStats=true&fetchActionTypeStats=true`) - .then(async res => { + it("Should be able to get all user info", (done) => { + client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchCategoryStats: true, fetchActionTypeStats: true }}) + .then(res => { assert.strictEqual(res.status, 200); const expected = { userName: "Username user 01", @@ -59,18 +58,17 @@ describe("getUserStats", () => { segmentCount: 8 } }; - const data = await res.json(); - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to get all zeroes for invalid userid", (done: Done) => { - fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_invalid`) - .then(async res => { + it("Should be able to get all zeroes for invalid userid", (done) => { + client.get(endpoint, { params: { userID: "getuserstats_user_invalid" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; for (const value in data.overallStats) { if (data[value]) { done(`returned non-zero for ${value}`); @@ -81,11 +79,11 @@ describe("getUserStats", () => { .catch(err => done(err)); }); - it("Should be able to get all zeroes for only ignored segments", (done: Done) => { - fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_02`) - .then(async res => { + it("Should be able to get all zeroes for only ignored segments", (done) => { + client.get(endpoint, { params: { userID: "getuserstats_user_02" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; for (const value in data.overallStats) { if (data[value]) { done(`returned non-zero for ${value}`); @@ -96,11 +94,11 @@ describe("getUserStats", () => { .catch(err => done(err)); }); - it("Should not get extra stats if not requested", (done: Done) => { - fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01`) - .then(async res => { + it("Should not get extra stats if not requested", (done) => { + client.get(endpoint, { params: { userID: "getuserstats_user_01" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; // check for categoryCount if (data.categoryCount || data.actionTypeCount) { done("returned extra stats"); @@ -110,11 +108,11 @@ describe("getUserStats", () => { .catch(err => done(err)); }); - it("Should get parts of extra stats if not requested", (done: Done) => { - fetch(`${getbaseURL()}/api/userStats?userID=getuserstats_user_01&fetchActionTypeStats=true`) - .then(async res => { + it("Should get parts of extra stats if not requested", (done) => { + client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchActionTypeStats: true }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; // check for categoryCount if (data.categoryCount && !data.actionTypeCount) { done("returned extra stats"); diff --git a/test/cases/lockCategoriesRecords.ts b/test/cases/lockCategoriesRecords.ts index e1949f5..8f844fa 100644 --- a/test/cases/lockCategoriesRecords.ts +++ b/test/cases/lockCategoriesRecords.ts @@ -1,10 +1,8 @@ -import fetch from "node-fetch"; -import { Done, postJSON } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; import {LockCategory } from "../../src/types/segments.model"; +import { client } from "../utils/httpClient"; const stringDeepEquals = (a: string[] ,b: string[]): boolean => { let result = true; @@ -14,8 +12,8 @@ const stringDeepEquals = (a: string[] ,b: string[]): boolean => { return result; }; -const endpoint = `${getbaseURL()}/api/lockCategories`; -const submitEndpoint = `${getbaseURL()}/api/skipSegments`; +const endpoint = "/api/lockCategories"; +const submitEndpoint = "/api/skipSegments"; const checkLockCategories = (videoID: string): Promise => db.prepare("all", 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', [videoID]); const lockVIPUser = "lockCategoriesRecordsVIPUser"; const lockVIPUserHash = getHash(lockVIPUser); @@ -44,7 +42,7 @@ describe("lockCategoriesRecords", () => { 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 = { videoID: "no-segments-video-id", userID: "lockCategoriesRecordsVIPUser", @@ -63,20 +61,16 @@ describe("lockCategoriesRecords", () => { "shilling", ], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json) - }) - .then(async res => { + client.post(endpoint, json) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .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 = { videoID, @@ -90,10 +84,7 @@ describe("lockCategoriesRecords", () => { "intro", ], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json) - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const result = await checkLockCategories(videoID); @@ -111,7 +102,7 @@ describe("lockCategoriesRecords", () => { .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 = { videoID, @@ -126,7 +117,6 @@ describe("lockCategoriesRecords", () => { ], reason: "new reason" }; - const expected = { submitted: [ "outro", @@ -135,20 +125,16 @@ describe("lockCategoriesRecords", () => { ], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json) - }) - .then(async res => { + client.post(endpoint, json) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - assert.deepStrictEqual(data.submitted, expected.submitted); + assert.deepStrictEqual(res.data.submitted, expected.submitted); done(); }) .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 = { videoID, @@ -170,10 +156,7 @@ describe("lockCategoriesRecords", () => { "intro" ]; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json) - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const result = await checkLockCategories(videoID); @@ -192,7 +175,7 @@ describe("lockCategoriesRecords", () => { .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 = { videoID: "underscore", userID: lockVIPUser, @@ -200,10 +183,7 @@ describe("lockCategoriesRecords", () => { "word_word", ], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const result = await checkLockCategories("underscore"); @@ -213,7 +193,7 @@ describe("lockCategoriesRecords", () => { .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 = { videoID: "bothCases", userID: lockVIPUser, @@ -221,10 +201,7 @@ describe("lockCategoriesRecords", () => { "wordWord", ], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const result = await checkLockCategories("bothCases"); @@ -234,7 +211,7 @@ describe("lockCategoriesRecords", () => { .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 = { videoID, @@ -244,10 +221,7 @@ describe("lockCategoriesRecords", () => { ], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const result = await checkLockCategories(videoID); @@ -257,11 +231,8 @@ describe("lockCategoriesRecords", () => { .catch(err => done(err)); }); - it("Should return 400 for missing params", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({}), - }) + it("Should return 400 for missing params", (done) => { + client.post(endpoint, {}) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -269,16 +240,13 @@ describe("lockCategoriesRecords", () => { .catch(err => done(err)); }); - it("Should return 400 for no categories", (done: Done) => { + it("Should return 400 for no categories", (done) => { const json: any = { videoID: "test", userID: "test", categories: [], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -286,17 +254,14 @@ describe("lockCategoriesRecords", () => { .catch(err => done(err)); }); - it("Should return 400 for no userID", (done: Done) => { - const json: any = { + it("Should return 400 for no userID", (done) => { + const json = { videoID: "test", userID: null, categories: ["sponsor"], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -304,17 +269,14 @@ describe("lockCategoriesRecords", () => { .catch(err => done(err)); }); - it("Should return 400 for no videoID", (done: Done) => { - const json: any = { + it("Should return 400 for no videoID", (done) => { + const json = { videoID: null, userID: "test", categories: ["sponsor"], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -322,17 +284,14 @@ describe("lockCategoriesRecords", () => { .catch(err => done(err)); }); - it("Should return 400 object categories", (done: Done) => { + it("Should return 400 object categories", (done) => { const json = { videoID: "test", userID: "test", categories: {}, }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -340,17 +299,14 @@ describe("lockCategoriesRecords", () => { .catch(err => done(err)); }); - it("Should return 400 bad format categories", (done: Done) => { + it("Should return 400 bad format categories", (done) => { const json = { videoID: "test", userID: "test", categories: "sponsor", }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -358,7 +314,7 @@ describe("lockCategoriesRecords", () => { .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 = { videoID: "test", userID: "test", @@ -367,10 +323,7 @@ describe("lockCategoriesRecords", () => { ], }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(res => { assert.strictEqual(res.status, 403); done(); @@ -378,7 +331,7 @@ describe("lockCategoriesRecords", () => { .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 = { videoID, @@ -388,13 +341,7 @@ describe("lockCategoriesRecords", () => { ], }; - fetch(endpoint, { - method: "DELETE", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(json), - }) + client.delete(endpoint, { data: json }) .then(async res => { assert.strictEqual(res.status, 200); const result = await checkLockCategories(videoID); @@ -404,7 +351,7 @@ describe("lockCategoriesRecords", () => { .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 = { videoID, @@ -414,13 +361,7 @@ describe("lockCategoriesRecords", () => { ], }; - fetch(endpoint, { - method: "DELETE", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(json), - }) + client.delete(endpoint, { data: json }) .then(async res => { assert.strictEqual(res.status, 200); const result = await checkLockCategories(videoID); @@ -437,41 +378,35 @@ describe("lockCategoriesRecords", () => { */ const lockedVideoID = "lockCategoryVideo"; const testSubmitUser = "testman42-qwertyuiopasdfghjklzxcvbnm"; - it("Should not be able to submit a segment to a video with a lock-category record (single submission)", (done: Done) => { - fetch(submitEndpoint, { - ...postJSON, - body: JSON.stringify({ - userID: testSubmitUser, - videoID: lockedVideoID, - segments: [{ - segment: [20, 40], - category: "sponsor", - }], - }), + it("Should not be able to submit a segment to a video with a lock-category record (single submission)", (done) => { + client.post(submitEndpoint, { + userID: testSubmitUser, + videoID: lockedVideoID, + segments: [{ + segment: [20, 40], + category: "sponsor", + }], }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); done(); }) .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) => { - fetch(submitEndpoint, { - ...postJSON, - body: JSON.stringify({ - userID: testSubmitUser, - videoID: lockedVideoID, - segments: [{ - segment: [20, 40], - category: "sponsor", - }, { - segment: [50, 60], - category: "intro", - }], - },), + it("Should not be able to submit segments to a video where any of the submissions with a no-segment record", (done) => { + client.post(submitEndpoint, { + userID: testSubmitUser, + videoID: lockedVideoID, + segments: [{ + segment: [20, 40], + category: "sponsor", + }, { + segment: [50, 60], + category: "intro", + }] }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); done(); }) @@ -479,45 +414,39 @@ describe("lockCategoriesRecords", () => { }); - it("Should be able to submit a segment to a video with a different no-segment record", (done: Done) => { - fetch(submitEndpoint, { - ...postJSON, - body: JSON.stringify({ - userID: testSubmitUser, - videoID: lockedVideoID, - segments: [{ - segment: [20, 40], - category: "intro", - }], - }), + it("Should be able to submit a segment to a video with a different no-segment record", (done) => { + client.post(submitEndpoint, { + userID: testSubmitUser, + videoID: lockedVideoID, + segments: [{ + segment: [20, 40], + category: "intro", + }], }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 200); done(); }) .catch(err => done(err)); }); - it("Should be able to submit a segment to a video with no no-segment records", (done: Done) => { - fetch(submitEndpoint, { - ...postJSON, - body: JSON.stringify({ - userID: testSubmitUser, - videoID: "normalVideo", - segments: [{ - segment: [20, 40], - category: "intro", - }], - }), + it("Should be able to submit a segment to a video with no no-segment records", (done) => { + client.post(submitEndpoint, { + userID: testSubmitUser, + videoID: "normalVideo", + segments: [{ + segment: [20, 40], + category: "intro", + }], }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 200); done(); }) .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 = { categories: [ "sponsor", @@ -526,10 +455,10 @@ describe("lockCategoriesRecords", () => { "shilling" ], }; - fetch(`${endpoint}?videoID=no-segments-video-id`) - .then(async res => { + client.get(endpoint, { params: {videoID: "no-segments-video-id" }}) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); + const data = res.data; assert.ok(stringDeepEquals(data.categories, expected.categories)); done(); }) diff --git a/test/cases/oldGetSponsorTime.ts b/test/cases/oldGetSponsorTime.ts index 756ec0b..5e35760 100644 --- a/test/cases/oldGetSponsorTime.ts +++ b/test/cases/oldGetSponsorTime.ts @@ -1,11 +1,10 @@ -import fetch from "node-fetch"; import {db} from "../../src/databases/databases"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; +import { client } from "../utils/httpClient"; -const endpoint = `${getbaseURL()}/api/getVideoSponsorTimes`; +const endpoint = "/api/getVideoSponsorTimes"; +const getOldSponsorTime = (videoID: string) => client.get(endpoint, { params: { videoID } }); describe("getVideoSponsorTime (Old get method)", () => { before(async () => { @@ -14,8 +13,8 @@ describe("getVideoSponsorTime (Old get method)", () => { 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) => { - fetch(`${endpoint}?videoID=oldGetSponsorTime0`) + it("Should be able to get a time", (done) => { + getOldSponsorTime("oldGetSponsorTime0") .then(res => { assert.strictEqual(res.status, 200); done(); @@ -23,8 +22,8 @@ describe("getVideoSponsorTime (Old get method)", () => { .catch(err => done(err)); }); - it("Should return 404 if no segment found", (done: Done) => { - fetch(`${endpoint}?videoID=notarealvideo`) + it("Should return 404 if no segment found", (done) => { + getOldSponsorTime("notarealvideo") .then(res => { assert.strictEqual(res.status, 404); done(); @@ -33,8 +32,8 @@ describe("getVideoSponsorTime (Old get method)", () => { }); - it("Should be possible to send unexpected query parameters", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime0&fakeparam=hello`) + it("Should be possible to send unexpected query parameters", (done) => { + client.get(endpoint, { params: { videoID: "oldGetSponsorTime0", fakeparam: "hello" }}) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -42,30 +41,28 @@ describe("getVideoSponsorTime (Old get method)", () => { .catch(() => done("couldn't callendpoint")); }); - it("Should be able send a comma in a query param", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime1,test`) - .then(async res => { + it("Should be able send a comma in a query param", (done) => { + getOldSponsorTime("oldGetSponsorTime1,test") + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { UUIDs: ["oldGetSponsorTime01"], }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); }); - it("Should be able to get the correct time", (done: Done) => { - fetch(`${getbaseURL()}/api/getVideoSponsorTimes?videoID=oldGetSponsorTime0`) - .then(async res => { + it("Should be able to get the correct time", (done) => { + getOldSponsorTime("oldGetSponsorTime0") + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = { sponsorTimes: [[1, 11]], UUIDs: ["oldGetSponsorTime00"] }; - assert.ok(partialDeepEquals(data, expected)); + assert.ok(partialDeepEquals(res.data, expected)); done(); }) .catch(err => done(err)); diff --git a/test/cases/oldSubmitSponsorTimes.ts b/test/cases/oldSubmitSponsorTimes.ts index 2c0ea9e..f3f4501 100644 --- a/test/cases/oldSubmitSponsorTimes.ts +++ b/test/cases/oldSubmitSponsorTimes.ts @@ -1,17 +1,15 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals";import {db} from "../../src/databases/databases"; 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)", () => { - it("Should be able to submit a time (GET)", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=${videoID1}&startTime=1&endTime=10&userID=${userID}`) + it("Should be able to submit a time (GET)", (done) => { + client.get(endpoint, { params: { videoID: videoID1, startTime: 1, endTime: 10, userID }}) .then(async res => { assert.strictEqual(res.status, 200); const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID1]); @@ -26,13 +24,11 @@ describe("postVideoSponsorTime (Old submission method)", () => { .catch(err => done(err)); }); - it("Should be able to submit a time (POST)", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?videoID=${videoID2}&startTime=1&endTime=11&userID=${userID}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, + it("Should be able to submit a time (POST)", (done) => { + client({ + url: endpoint, + params: { videoID: videoID2, startTime: 1, endTime: 11, userID }, + method: "post", }) .then(async res => { assert.strictEqual(res.status, 200); @@ -48,10 +44,9 @@ describe("postVideoSponsorTime (Old submission method)", () => { .catch(err => done(err)); }); - it("Should return 400 for missing params", (done: Done) => { - fetch(`${getbaseURL() - }/api/postVideoSponsorTimes?startTime=1&endTime=10&userID=${userID}`) - .then(async res => { + it("Should return 400 for missing params", (done) => { + client.post(endpoint, { params: { startTime: 1, endTime: 10, userID }}) + .then(res => { assert.strictEqual(res.status, 400); done(); }) diff --git a/test/utils/httpClient.ts b/test/utils/httpClient.ts new file mode 100644 index 0000000..6385e02 --- /dev/null +++ b/test/utils/httpClient.ts @@ -0,0 +1,13 @@ +import { config } from "../../src/config"; +import axios, { AxiosRequestConfig } from "axios"; + +export function getbaseURL(): string { + return `http://localhost:${config.port}`; +} + +export const defaultConfig: AxiosRequestConfig = { + baseURL: getbaseURL(), + validateStatus: (status) => status < 500 +}; + +export const client = axios.create(defaultConfig); From 9b6808273bbf2a70048d7f5c548c18fbe19f09d8 Mon Sep 17 00:00:00 2001 From: Michael C Date: Wed, 22 Sep 2021 17:57:12 -0400 Subject: [PATCH 10/14] json as any --- test/cases/lockCategoriesRecords.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/cases/lockCategoriesRecords.ts b/test/cases/lockCategoriesRecords.ts index 8f844fa..b7f13f5 100644 --- a/test/cases/lockCategoriesRecords.ts +++ b/test/cases/lockCategoriesRecords.ts @@ -255,7 +255,7 @@ describe("lockCategoriesRecords", () => { }); it("Should return 400 for no userID", (done) => { - const json = { + const json: any = { videoID: "test", userID: null, categories: ["sponsor"], @@ -270,7 +270,7 @@ describe("lockCategoriesRecords", () => { }); it("Should return 400 for no videoID", (done) => { - const json = { + const json: any = { videoID: null, userID: "test", categories: ["sponsor"], From 5dcc90b31a24787d09946b8e1a55ce928beed8aa Mon Sep 17 00:00:00 2001 From: Michael C Date: Wed, 22 Sep 2021 18:46:13 -0400 Subject: [PATCH 11/14] fix CI errors --- test/cases/getLockReason.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/cases/getLockReason.ts b/test/cases/getLockReason.ts index 156a50d..742f041 100644 --- a/test/cases/getLockReason.ts +++ b/test/cases/getLockReason.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; -import {Done, getbaseURL} from "../utils"; +import {Done} from "../utils/utils"; +import { getbaseURL } from "../utils/getBaseURL"; import {getHash} from "../../src/utils/getHash"; import {db} from "../../src/databases/databases"; import assert from "assert"; From a028eaa41ab4292a6fa77e9423cbcb3820441f53 Mon Sep 17 00:00:00 2001 From: Michael C Date: Wed, 22 Sep 2021 18:52:35 -0400 Subject: [PATCH 12/14] object-curly-spacing --- .eslintrc.js | 1 + src/app.ts | 80 ++++++++++++------------- src/config.ts | 2 +- src/databases/Mysql.ts | 4 +- src/databases/Postgres.ts | 2 +- src/databases/Sqlite.ts | 10 ++-- src/databases/databases.ts | 10 ++-- src/index.ts | 10 ++-- src/middleware/apiCsp.ts | 2 +- src/middleware/cors.ts | 2 +- src/middleware/logger.ts | 4 +- src/middleware/requestRateLimit.ts | 8 +-- src/middleware/userCounter.ts | 10 ++-- src/routes/addUnlistedVideo.ts | 2 +- src/routes/addUserAsVIP.ts | 8 +-- src/routes/deleteLockCategories.ts | 10 ++-- src/routes/dumpDatabase.ts | 6 +- src/routes/getDaysSavedFormatted.ts | 4 +- src/routes/getIsUserVIP.ts | 8 +-- src/routes/getLockCategories.ts | 6 +- src/routes/getLockCategoriesByHash.ts | 8 +-- src/routes/getLockReason.ts | 8 +-- src/routes/getSavedTimeForUser.ts | 8 +-- src/routes/getSkipSegments.ts | 10 ++-- src/routes/getSkipSegmentsByHash.ts | 6 +- src/routes/getStatus.ts | 6 +- src/routes/getTopUsers.ts | 8 +-- src/routes/getTotalStats.ts | 8 +-- src/routes/getUserID.ts | 6 +- src/routes/getUserInfo.ts | 12 ++-- src/routes/getUserStats.ts | 10 ++-- src/routes/getUsername.ts | 8 +-- src/routes/getViewsForUser.ts | 8 +-- src/routes/oldGetVideoSponsorTimes.ts | 4 +- src/routes/oldSubmitSponsorTimes.ts | 4 +- src/routes/postClearCache.ts | 2 +- src/routes/postLockCategories.ts | 10 ++-- src/routes/postPurgeAllSegments.ts | 14 ++--- src/routes/postSegmentShift.ts | 28 ++++----- src/routes/postSkipSegments.ts | 46 +++++++------- src/routes/postWarning.ts | 14 ++--- src/routes/setUsername.ts | 10 ++-- src/routes/shadowBanUser.ts | 6 +- src/routes/viewedVideoSponsorTime.ts | 4 +- src/routes/voteOnSponsorTime.ts | 22 +++---- src/utils/getIP.ts | 4 +- src/utils/getSubmissionUUID.ts | 2 +- src/utils/hashPrefixTester.ts | 2 +- src/utils/isUserTrustworthy.ts | 2 +- src/utils/isUserVIP.ts | 2 +- src/utils/logger.ts | 2 +- src/utils/queryCacher.ts | 2 +- src/utils/redis.ts | 14 ++--- src/utils/webhookUtils.ts | 4 +- src/utils/youtubeApi.ts | 8 +-- test/cases/dbUpgrade.ts | 2 +- test/cases/downvoteSegmentArchiveJob.ts | 2 +- test/cases/getHash.ts | 4 +- test/cases/getIsUserVIP.ts | 6 +- test/cases/getLockCategories.ts | 4 +- test/cases/getLockCategoriesByHash.ts | 4 +- test/cases/getLockReason.ts | 8 +-- test/cases/getSavedTimeForUser.ts | 8 +-- test/cases/getSearchSegments.ts | 30 +++++----- test/cases/getSegmentInfo.ts | 12 ++-- test/cases/getSkipSegments.ts | 38 ++++++------ test/cases/getSkipSegmentsByHash.ts | 34 +++++------ test/cases/getStatus.ts | 2 +- test/cases/getSubmissionUUID.ts | 2 +- test/cases/getUserID.ts | 18 +++--- test/cases/getUserInfo.ts | 42 ++++++------- test/cases/getUserStats.ts | 10 ++-- test/cases/lockCategoriesRecords.ts | 8 +-- test/cases/oldGetSponsorTime.ts | 4 +- test/cases/oldSubmitSponsorTimes.ts | 6 +- test/cases/postClearCache.ts | 4 +- test/cases/postPurgeAllSegments.ts | 8 +-- test/cases/postSkipSegments.ts | 10 ++-- test/cases/postWarning.ts | 4 +- test/cases/segmentShift.ts | 8 +-- test/cases/shadowBanUser.ts | 4 +- test/cases/testUtils.ts | 4 +- test/cases/voteOnSponsorTime.ts | 10 ++-- test/mocks.ts | 2 +- test/test.ts | 12 ++-- 85 files changed, 406 insertions(+), 405 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 2362e88..8837f26 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -25,5 +25,6 @@ module.exports = { "quotes": ["warn", "double", { "avoidEscape": true, "allowTemplateLiterals": true }], "no-multiple-empty-lines": ["error", { max: 2, maxEOF: 0 }], "indent": ["warn", 4, { "SwitchCase": 1 }], + "object-curly-spacing": ["warn", "always"], }, }; diff --git a/src/app.ts b/src/app.ts index 93a281d..d40c558 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,44 +1,44 @@ -import express, {Request, RequestHandler, Response, Router} from "express"; -import {config} from "./config"; -import {oldSubmitSponsorTimes} from "./routes/oldSubmitSponsorTimes"; -import {oldGetVideoSponsorTimes} from "./routes/oldGetVideoSponsorTimes"; -import {postSegmentShift} from "./routes/postSegmentShift"; -import {postWarning} from "./routes/postWarning"; -import {getIsUserVIP} from "./routes/getIsUserVIP"; -import {deleteLockCategoriesEndpoint} from "./routes/deleteLockCategories"; -import {postLockCategories} from "./routes/postLockCategories"; -import {endpoint as getUserInfo} from "./routes/getUserInfo"; -import {getDaysSavedFormatted} from "./routes/getDaysSavedFormatted"; -import {getTotalStats} from "./routes/getTotalStats"; -import {getTopUsers} from "./routes/getTopUsers"; -import {getViewsForUser} from "./routes/getViewsForUser"; -import {getSavedTimeForUser} from "./routes/getSavedTimeForUser"; -import {addUserAsVIP} from "./routes/addUserAsVIP"; -import {shadowBanUser} from "./routes/shadowBanUser"; -import {getUsername} from "./routes/getUsername"; -import {setUsername} from "./routes/setUsername"; -import {viewedVideoSponsorTime} from "./routes/viewedVideoSponsorTime"; -import {voteOnSponsorTime, getUserID as voteGetUserID} from "./routes/voteOnSponsorTime"; -import {getSkipSegmentsByHash} from "./routes/getSkipSegmentsByHash"; -import {postSkipSegments} from "./routes/postSkipSegments"; -import {endpoint as getSkipSegments} from "./routes/getSkipSegments"; -import {userCounter} from "./middleware/userCounter"; -import {loggerMiddleware} from "./middleware/logger"; -import {corsMiddleware} from "./middleware/cors"; -import {apiCspMiddleware} from "./middleware/apiCsp"; -import {rateLimitMiddleware} from "./middleware/requestRateLimit"; -import dumpDatabase, {redirectLink} from "./routes/dumpDatabase"; -import {endpoint as getSegmentInfo} from "./routes/getSegmentInfo"; -import {postClearCache} from "./routes/postClearCache"; +import express, { Request, RequestHandler, Response, Router } from "express"; +import { config } from "./config"; +import { oldSubmitSponsorTimes } from "./routes/oldSubmitSponsorTimes"; +import { oldGetVideoSponsorTimes } from "./routes/oldGetVideoSponsorTimes"; +import { postSegmentShift } from "./routes/postSegmentShift"; +import { postWarning } from "./routes/postWarning"; +import { getIsUserVIP } from "./routes/getIsUserVIP"; +import { deleteLockCategoriesEndpoint } from "./routes/deleteLockCategories"; +import { postLockCategories } from "./routes/postLockCategories"; +import { endpoint as getUserInfo } from "./routes/getUserInfo"; +import { getDaysSavedFormatted } from "./routes/getDaysSavedFormatted"; +import { getTotalStats } from "./routes/getTotalStats"; +import { getTopUsers } from "./routes/getTopUsers"; +import { getViewsForUser } from "./routes/getViewsForUser"; +import { getSavedTimeForUser } from "./routes/getSavedTimeForUser"; +import { addUserAsVIP } from "./routes/addUserAsVIP"; +import { shadowBanUser } from "./routes/shadowBanUser"; +import { getUsername } from "./routes/getUsername"; +import { setUsername } from "./routes/setUsername"; +import { viewedVideoSponsorTime } from "./routes/viewedVideoSponsorTime"; +import { voteOnSponsorTime, getUserID as voteGetUserID } from "./routes/voteOnSponsorTime"; +import { getSkipSegmentsByHash } from "./routes/getSkipSegmentsByHash"; +import { postSkipSegments } from "./routes/postSkipSegments"; +import { endpoint as getSkipSegments } from "./routes/getSkipSegments"; +import { userCounter } from "./middleware/userCounter"; +import { loggerMiddleware } from "./middleware/logger"; +import { corsMiddleware } from "./middleware/cors"; +import { apiCspMiddleware } from "./middleware/apiCsp"; +import { rateLimitMiddleware } from "./middleware/requestRateLimit"; +import dumpDatabase, { redirectLink } from "./routes/dumpDatabase"; +import { endpoint as getSegmentInfo } from "./routes/getSegmentInfo"; +import { postClearCache } from "./routes/postClearCache"; import { addUnlistedVideo } from "./routes/addUnlistedVideo"; -import {postPurgeAllSegments} from "./routes/postPurgeAllSegments"; -import {getUserID} from "./routes/getUserID"; -import {getLockCategories} from "./routes/getLockCategories"; -import {getLockCategoriesByHash} from "./routes/getLockCategoriesByHash"; -import {endpoint as getSearchSegments } from "./routes/getSearchSegments"; -import {getStatus } from "./routes/getStatus"; +import { postPurgeAllSegments } from "./routes/postPurgeAllSegments"; +import { getUserID } from "./routes/getUserID"; +import { getLockCategories } from "./routes/getLockCategories"; +import { getLockCategoriesByHash } from "./routes/getLockCategoriesByHash"; +import { endpoint as getSearchSegments } from "./routes/getSearchSegments"; +import { getStatus } from "./routes/getStatus"; import { getLockReason } from "./routes/getLockReason"; -import {getUserStats} from "./routes/getUserStats"; +import { getUserStats } from "./routes/getUserStats"; import ExpressPromiseRouter from "express-promise-router"; import { Server } from "http"; import { youtubeApiProxy } from "./routes/youtubeApiProxy"; @@ -188,7 +188,7 @@ function setupRoutes(router: Router) { router.get("/database/*", redirectLink); } else { router.get("/database.db", function (req: Request, res: Response) { - res.sendFile("./databases/sponsorTimes.db", {root: "./"}); + res.sendFile("./databases/sponsorTimes.db", { root: "./" }); }); } } diff --git a/src/config.ts b/src/config.ts index 7c3ef4d..d28d2aa 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,5 +1,5 @@ import fs from "fs"; -import {SBSConfig} from "./types/config.model"; +import { SBSConfig } from "./types/config.model"; import packageJson from "../package.json"; const isTestMode = process.env.npm_lifecycle_script === packageJson.scripts.test; diff --git a/src/databases/Mysql.ts b/src/databases/Mysql.ts index d9f8a1c..c93aa9f 100644 --- a/src/databases/Mysql.ts +++ b/src/databases/Mysql.ts @@ -1,5 +1,5 @@ -import {Logger} from "../utils/logger"; -import {IDatabase, QueryType} from "./IDatabase"; +import { Logger } from "../utils/logger"; +import { IDatabase, QueryType } from "./IDatabase"; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import MysqlInterface from "sync-mysql"; diff --git a/src/databases/Postgres.ts b/src/databases/Postgres.ts index 5e42aae..7c82bb3 100644 --- a/src/databases/Postgres.ts +++ b/src/databases/Postgres.ts @@ -56,7 +56,7 @@ export class Postgres implements IDatabase { Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`); try { - const queryResult = await this.pool.query({text: query, values: params}); + const queryResult = await this.pool.query({ text: query, values: params }); switch (type) { case "get": { diff --git a/src/databases/Sqlite.ts b/src/databases/Sqlite.ts index cc498dd..dc3bd47 100644 --- a/src/databases/Sqlite.ts +++ b/src/databases/Sqlite.ts @@ -1,9 +1,9 @@ -import {IDatabase, QueryType} from "./IDatabase"; -import Sqlite3, {Database, Database as SQLiteDatabase} from "better-sqlite3"; +import { IDatabase, QueryType } from "./IDatabase"; +import Sqlite3, { Database, Database as SQLiteDatabase } from "better-sqlite3"; import fs from "fs"; import path from "path"; -import {getHash} from "../utils/getHash"; -import {Logger} from "../utils/logger"; +import { getHash } from "../utils/getHash"; +import { Logger } from "../utils/logger"; export class Sqlite implements IDatabase { private db: SQLiteDatabase; @@ -36,7 +36,7 @@ export class Sqlite implements IDatabase { fs.mkdirSync(path.join(this.config.dbPath, "../")); } - this.db = new Sqlite3(this.config.dbPath, {readonly: this.config.readOnly, fileMustExist: !this.config.createDbIfNotExists}); + this.db = new Sqlite3(this.config.dbPath, { readonly: this.config.readOnly, fileMustExist: !this.config.createDbIfNotExists }); if (this.config.createDbIfNotExists && !this.config.readOnly && fs.existsSync(this.config.dbSchemaFileName)) { this.db.exec(Sqlite.processUpgradeQuery(fs.readFileSync(this.config.dbSchemaFileName).toString())); diff --git a/src/databases/databases.ts b/src/databases/databases.ts index d65b7ec..96a5b5f 100644 --- a/src/databases/databases.ts +++ b/src/databases/databases.ts @@ -1,8 +1,8 @@ -import {config} from "../config"; -import {Sqlite} from "./Sqlite"; -import {Mysql} from "./Mysql"; -import {Postgres} from "./Postgres"; -import {IDatabase} from "./IDatabase"; +import { config } from "../config"; +import { Sqlite } from "./Sqlite"; +import { Mysql } from "./Mysql"; +import { Postgres } from "./Postgres"; +import { IDatabase } from "./IDatabase"; let db: IDatabase; diff --git a/src/index.ts b/src/index.ts index 5cc7817..8ffaafb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,8 @@ -import {config} from "./config"; -import {initDb} from "./databases/databases"; -import {createServer} from "./app"; -import {Logger} from "./utils/logger"; -import {startAllCrons} from "./cronjob"; +import { config } from "./config"; +import { initDb } from "./databases/databases"; +import { createServer } from "./app"; +import { Logger } from "./utils/logger"; +import { startAllCrons } from "./cronjob"; import { getCommit } from "./utils/getCommit"; async function init() { diff --git a/src/middleware/apiCsp.ts b/src/middleware/apiCsp.ts index 1b99c9f..70b8d94 100644 --- a/src/middleware/apiCsp.ts +++ b/src/middleware/apiCsp.ts @@ -1,4 +1,4 @@ -import {NextFunction, Request, Response} from "express"; +import { NextFunction, Request, Response } from "express"; export function apiCspMiddleware(req: Request, res: Response, next: NextFunction): void { res.header("Content-Security-Policy", "script-src 'none'; object-src 'none'"); diff --git a/src/middleware/cors.ts b/src/middleware/cors.ts index b661ab1..84b30e4 100644 --- a/src/middleware/cors.ts +++ b/src/middleware/cors.ts @@ -1,4 +1,4 @@ -import {NextFunction, Request, Response} from "express"; +import { NextFunction, Request, Response } from "express"; export function corsMiddleware(req: Request, res: Response, next: NextFunction): void { res.header("Access-Control-Allow-Origin", "*"); diff --git a/src/middleware/logger.ts b/src/middleware/logger.ts index fa0bb6a..9b06efc 100644 --- a/src/middleware/logger.ts +++ b/src/middleware/logger.ts @@ -1,5 +1,5 @@ -import {Logger} from "../utils/logger"; -import {NextFunction, Request, Response} from "express"; +import { Logger } from "../utils/logger"; +import { NextFunction, Request, Response } from "express"; export function loggerMiddleware(req: Request, res: Response, next: NextFunction): void { Logger.info(`Request received: ${req.method} ${req.url}`); diff --git a/src/middleware/requestRateLimit.ts b/src/middleware/requestRateLimit.ts index 0b06a01..e5cb8b9 100644 --- a/src/middleware/requestRateLimit.ts +++ b/src/middleware/requestRateLimit.ts @@ -1,8 +1,8 @@ -import {getIP} from "../utils/getIP"; -import {getHash} from "../utils/getHash"; +import { getIP } from "../utils/getIP"; +import { getHash } from "../utils/getHash"; import rateLimit from "express-rate-limit"; -import {RateLimitConfig} from "../types/config.model"; -import {Request} from "express"; +import { RateLimitConfig } from "../types/config.model"; +import { Request } from "express"; import { isUserVIP } from "../utils/isUserVIP"; import { UserID } from "../types/user.model"; diff --git a/src/middleware/userCounter.ts b/src/middleware/userCounter.ts index a941cf5..a03ad96 100644 --- a/src/middleware/userCounter.ts +++ b/src/middleware/userCounter.ts @@ -1,9 +1,9 @@ import axios from "axios"; -import {Logger} from "../utils/logger"; -import {config} from "../config"; -import {getIP} from "../utils/getIP"; -import {getHash} from "../utils/getHash"; -import {NextFunction, Request, Response} from "express"; +import { Logger } from "../utils/logger"; +import { config } from "../config"; +import { getIP } from "../utils/getIP"; +import { getHash } from "../utils/getHash"; +import { NextFunction, Request, Response } from "express"; export function userCounter(req: Request, res: Response, next: NextFunction): void { axios.post(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`) diff --git a/src/routes/addUnlistedVideo.ts b/src/routes/addUnlistedVideo.ts index 01a1749..db5fef4 100644 --- a/src/routes/addUnlistedVideo.ts +++ b/src/routes/addUnlistedVideo.ts @@ -1,4 +1,4 @@ -import {Request, Response} from "express"; +import { Request, Response } from "express"; import { db } from "../databases/databases"; import { Logger } from "../utils/logger"; diff --git a/src/routes/addUserAsVIP.ts b/src/routes/addUserAsVIP.ts index bd976f0..dd2c244 100644 --- a/src/routes/addUserAsVIP.ts +++ b/src/routes/addUserAsVIP.ts @@ -1,7 +1,7 @@ -import {getHash} from "../utils/getHash"; -import {db} from "../databases/databases"; -import {config} from "../config"; -import {Request, Response} from "express"; +import { getHash } from "../utils/getHash"; +import { db } from "../databases/databases"; +import { config } from "../config"; +import { Request, Response } from "express"; import { isUserVIP } from "../utils/isUserVIP"; import { HashedUserID } from "../types/user.model"; diff --git a/src/routes/deleteLockCategories.ts b/src/routes/deleteLockCategories.ts index 6ed7a84..f50df50 100644 --- a/src/routes/deleteLockCategories.ts +++ b/src/routes/deleteLockCategories.ts @@ -1,7 +1,7 @@ -import {Request, Response} from "express"; -import {isUserVIP} from "../utils/isUserVIP"; -import {getHash} from "../utils/getHash"; -import {db} from "../databases/databases"; +import { Request, Response } from "express"; +import { isUserVIP } from "../utils/isUserVIP"; +import { getHash } from "../utils/getHash"; +import { db } from "../databases/databases"; import { Category, VideoID } from "../types/segments.model"; import { UserID } from "../types/user.model"; @@ -35,7 +35,7 @@ export async function deleteLockCategoriesEndpoint(req: Request, res: Response): await deleteLockCategories(videoID, categories); - return res.status(200).json({message: `Removed lock categories entrys for video ${videoID}`}); + return res.status(200).json({ message: `Removed lock categories entrys for video ${videoID}` }); } /** diff --git a/src/routes/dumpDatabase.ts b/src/routes/dumpDatabase.ts index 8ebd82c..e876449 100644 --- a/src/routes/dumpDatabase.ts +++ b/src/routes/dumpDatabase.ts @@ -1,6 +1,6 @@ -import {db} from "../databases/databases"; -import {Logger} from "../utils/logger"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { Logger } from "../utils/logger"; +import { Request, Response } from "express"; import { config } from "../config"; import util from "util"; import fs from "fs"; diff --git a/src/routes/getDaysSavedFormatted.ts b/src/routes/getDaysSavedFormatted.ts index 03a0ad0..61046e3 100644 --- a/src/routes/getDaysSavedFormatted.ts +++ b/src/routes/getDaysSavedFormatted.ts @@ -1,5 +1,5 @@ -import {db} from "../databases/databases"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { Request, Response } from "express"; export async function getDaysSavedFormatted(req: Request, res: Response): Promise { const row = await db.prepare("get", 'SELECT SUM(("endTime" - "startTime") / 60 / 60 / 24 * "views") as "daysSaved" from "sponsorTimes" where "shadowHidden" != 1', []); diff --git a/src/routes/getIsUserVIP.ts b/src/routes/getIsUserVIP.ts index 1363c2b..7b2d523 100644 --- a/src/routes/getIsUserVIP.ts +++ b/src/routes/getIsUserVIP.ts @@ -1,7 +1,7 @@ -import {Logger} from "../utils/logger"; -import {getHash} from "../utils/getHash"; -import {isUserVIP} from "../utils/isUserVIP"; -import {Request, Response} from "express"; +import { Logger } from "../utils/logger"; +import { getHash } from "../utils/getHash"; +import { isUserVIP } from "../utils/isUserVIP"; +import { Request, Response } from "express"; import { HashedUserID, UserID } from "../types/user.model"; export async function getIsUserVIP(req: Request, res: Response): Promise { diff --git a/src/routes/getLockCategories.ts b/src/routes/getLockCategories.ts index 047c757..735df8e 100644 --- a/src/routes/getLockCategories.ts +++ b/src/routes/getLockCategories.ts @@ -1,6 +1,6 @@ -import {db} from "../databases/databases"; -import {Logger} from "../utils/logger"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { Logger } from "../utils/logger"; +import { Request, Response } from "express"; import { Category, VideoID } from "../types/segments.model"; export async function getLockCategories(req: Request, res: Response): Promise { diff --git a/src/routes/getLockCategoriesByHash.ts b/src/routes/getLockCategoriesByHash.ts index 4bedc73..6ff6252 100644 --- a/src/routes/getLockCategoriesByHash.ts +++ b/src/routes/getLockCategoriesByHash.ts @@ -1,7 +1,7 @@ -import {db} from "../databases/databases"; -import {Logger} from "../utils/logger"; -import {Request, Response} from "express"; -import {hashPrefixTester} from "../utils/hashPrefixTester"; +import { db } from "../databases/databases"; +import { Logger } from "../utils/logger"; +import { Request, Response } from "express"; +import { hashPrefixTester } from "../utils/hashPrefixTester"; import { Category, VideoID, VideoIDHash } from "../types/segments.model"; interface LockResultByHash { diff --git a/src/routes/getLockReason.ts b/src/routes/getLockReason.ts index 27a311b..cf57828 100644 --- a/src/routes/getLockReason.ts +++ b/src/routes/getLockReason.ts @@ -1,8 +1,8 @@ -import {db} from "../databases/databases"; -import {Logger} from "../utils/logger"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { Logger } from "../utils/logger"; +import { Request, Response } from "express"; import { Category, VideoID } from "../types/segments.model"; -import {config} from "../config"; +import { config } from "../config"; const possibleCategoryList = config.categoryList; interface lockArray { diff --git a/src/routes/getSavedTimeForUser.ts b/src/routes/getSavedTimeForUser.ts index d2ab256..2b0f9e6 100644 --- a/src/routes/getSavedTimeForUser.ts +++ b/src/routes/getSavedTimeForUser.ts @@ -1,7 +1,7 @@ -import {db} from "../databases/databases"; -import {Request, Response} from "express"; -import {getHash} from "../utils/getHash"; -import {config} from "../config"; +import { db } from "../databases/databases"; +import { Request, Response } from "express"; +import { getHash } from "../utils/getHash"; +import { config } from "../config"; import { Logger } from "../utils/logger"; const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400; diff --git a/src/routes/getSkipSegments.ts b/src/routes/getSkipSegments.ts index 895ea64..16c87c6 100644 --- a/src/routes/getSkipSegments.ts +++ b/src/routes/getSkipSegments.ts @@ -13,7 +13,7 @@ import { getReputation } from "../utils/reputation"; import { getService } from "../utils/getService"; -async function prepareCategorySegments(req: Request, videoID: VideoID, category: Category, segments: DBSegment[], cache: SegmentCache = {shadowHiddenSegmentIPs: {}}): Promise { +async function prepareCategorySegments(req: Request, videoID: VideoID, category: Category, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }): Promise { const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => { if (segment.votes < -1 && !segment.required) { return false; //too untrustworthy, just ignore it @@ -56,7 +56,7 @@ async function prepareCategorySegments(req: Request, videoID: VideoID, category: async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories: Category[], actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise { - const cache: SegmentCache = {shadowHiddenSegmentIPs: {}}; + const cache: SegmentCache = { shadowHiddenSegmentIPs: {} }; const segments: Segment[] = []; try { @@ -89,7 +89,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories: async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[], actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise> { - const cache: SegmentCache = {shadowHiddenSegmentIPs: {}}; + const cache: SegmentCache = { shadowHiddenSegmentIPs: {} }; const segments: SBRecord = {}; try { @@ -182,7 +182,7 @@ function getWeightedRandomChoice(choices: T[], amountOf const weight = Math.exp(choice.votes * Math.max(1, choice.reputation + 1) + 3 + boost); totalWeight += Math.max(weight, 0); - return {...choice, weight}; + return { ...choice, weight }; }); //iterate and find amountOfChoices choices @@ -220,7 +220,7 @@ async function chooseSegments(segments: DBSegment[], max: number): Promise= cursor) { - currentGroup = {segments: [], votes: 0, reputation: 0, locked: false, required: false}; + currentGroup = { segments: [], votes: 0, reputation: 0, locked: false, required: false }; overlappingSegmentsGroups.push(currentGroup); } diff --git a/src/routes/getSkipSegmentsByHash.ts b/src/routes/getSkipSegmentsByHash.ts index 39ef9e6..a5ed122 100644 --- a/src/routes/getSkipSegmentsByHash.ts +++ b/src/routes/getSkipSegmentsByHash.ts @@ -1,6 +1,6 @@ -import {hashPrefixTester} from "../utils/hashPrefixTester"; -import {getSegmentsByHash} from "./getSkipSegments"; -import {Request, Response} from "express"; +import { hashPrefixTester } from "../utils/hashPrefixTester"; +import { getSegmentsByHash } from "./getSkipSegments"; +import { Request, Response } from "express"; import { ActionType, Category, SegmentUUID, Service, VideoIDHash } from "../types/segments.model"; import { getService } from "../utils/getService"; diff --git a/src/routes/getStatus.ts b/src/routes/getStatus.ts index b4f3dfc..704ffaf 100644 --- a/src/routes/getStatus.ts +++ b/src/routes/getStatus.ts @@ -1,6 +1,6 @@ -import {db} from "../databases/databases"; -import {Logger} from "../utils/logger"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { Logger } from "../utils/logger"; +import { Request, Response } from "express"; export async function getStatus(req: Request, res: Response): Promise { const startTime = Date.now(); diff --git a/src/routes/getTopUsers.ts b/src/routes/getTopUsers.ts index d1f7092..f063c6f 100644 --- a/src/routes/getTopUsers.ts +++ b/src/routes/getTopUsers.ts @@ -1,7 +1,7 @@ -import {db} from "../databases/databases"; -import {createMemoryCache} from "../utils/createMemoryCache"; -import {config} from "../config"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { createMemoryCache } from "../utils/createMemoryCache"; +import { config } from "../config"; +import { Request, Response } from "express"; const MILLISECONDS_IN_MINUTE = 60000; const getTopUsersWithCache = createMemoryCache(generateTopUsersStats, config.getTopUsersCacheTimeMinutes * MILLISECONDS_IN_MINUTE); diff --git a/src/routes/getTotalStats.ts b/src/routes/getTotalStats.ts index 2fe7af7..a757f7f 100644 --- a/src/routes/getTotalStats.ts +++ b/src/routes/getTotalStats.ts @@ -1,9 +1,9 @@ -import {db} from "../databases/databases"; -import {config} from "../config"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { config } from "../config"; +import { Request, Response } from "express"; 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 let chromeUsersCache = 0; diff --git a/src/routes/getUserID.ts b/src/routes/getUserID.ts index 08bd1d8..c93fa62 100644 --- a/src/routes/getUserID.ts +++ b/src/routes/getUserID.ts @@ -1,6 +1,6 @@ -import {db} from "../databases/databases"; -import {Request, Response} from "express"; -import {UserID} from "../types/user.model"; +import { db } from "../databases/databases"; +import { Request, Response } from "express"; +import { UserID } from "../types/user.model"; function getFuzzyUserID(userName: string): Promise<{userName: string, userID: UserID }[]> { // escape [_ % \] to avoid ReDOS diff --git a/src/routes/getUserInfo.ts b/src/routes/getUserInfo.ts index dc62f84..9311ee8 100644 --- a/src/routes/getUserInfo.ts +++ b/src/routes/getUserInfo.ts @@ -1,12 +1,12 @@ -import {db} from "../databases/databases"; -import {getHash} from "../utils/getHash"; -import {isUserVIP} from "../utils/isUserVIP"; -import {Request, Response} from "express"; -import {Logger} from "../utils/logger"; +import { db } from "../databases/databases"; +import { getHash } from "../utils/getHash"; +import { isUserVIP } from "../utils/isUserVIP"; +import { Request, Response } from "express"; +import { Logger } from "../utils/logger"; import { HashedUserID, UserID } from "../types/user.model"; import { getReputation } from "../utils/reputation"; import { SegmentUUID } from "../types/segments.model"; -import {config} from "../config"; +import { config } from "../config"; const maxRewardTime = config.maxRewardTimePerSegmentInSeconds; async function dbGetSubmittedSegmentSummary(userID: HashedUserID): Promise<{ minutesSaved: number, segmentCount: number }> { diff --git a/src/routes/getUserStats.ts b/src/routes/getUserStats.ts index c6b6420..7708255 100644 --- a/src/routes/getUserStats.ts +++ b/src/routes/getUserStats.ts @@ -1,8 +1,8 @@ -import {db} from "../databases/databases"; -import {getHash} from "../utils/getHash"; -import {Request, Response} from "express"; -import {HashedUserID, UserID} from "../types/user.model"; -import {config} from "../config"; +import { db } from "../databases/databases"; +import { getHash } from "../utils/getHash"; +import { Request, Response } from "express"; +import { HashedUserID, UserID } from "../types/user.model"; +import { config } from "../config"; import { Logger } from "../utils/logger"; type nestedObj = Record>; const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400; diff --git a/src/routes/getUsername.ts b/src/routes/getUsername.ts index 8867e8f..9fbafdf 100644 --- a/src/routes/getUsername.ts +++ b/src/routes/getUsername.ts @@ -1,7 +1,7 @@ -import {db} from "../databases/databases"; -import {getHash} from "../utils/getHash"; -import {Logger} from "../utils/logger"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { getHash } from "../utils/getHash"; +import { Logger } from "../utils/logger"; +import { Request, Response } from "express"; export async function getUsername(req: Request, res: Response): Promise { let userID = req.query.userID as string; diff --git a/src/routes/getViewsForUser.ts b/src/routes/getViewsForUser.ts index a7932ec..84f2b2c 100644 --- a/src/routes/getViewsForUser.ts +++ b/src/routes/getViewsForUser.ts @@ -1,7 +1,7 @@ -import {db} from "../databases/databases"; -import {Request, Response} from "express"; -import {getHash} from "../utils/getHash"; -import {Logger} from "../utils/logger"; +import { db } from "../databases/databases"; +import { Request, Response } from "express"; +import { getHash } from "../utils/getHash"; +import { Logger } from "../utils/logger"; export async function getViewsForUser(req: Request, res: Response): Promise { let userID = req.query.userID as string; diff --git a/src/routes/oldGetVideoSponsorTimes.ts b/src/routes/oldGetVideoSponsorTimes.ts index 6482f58..90a58ae 100644 --- a/src/routes/oldGetVideoSponsorTimes.ts +++ b/src/routes/oldGetVideoSponsorTimes.ts @@ -1,5 +1,5 @@ -import {handleGetSegments} from "./getSkipSegments"; -import {Request, Response} from "express"; +import { handleGetSegments } from "./getSkipSegments"; +import { Request, Response } from "express"; export async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise { const segments = await handleGetSegments(req, res); diff --git a/src/routes/oldSubmitSponsorTimes.ts b/src/routes/oldSubmitSponsorTimes.ts index 0ddc31a..592fb49 100644 --- a/src/routes/oldSubmitSponsorTimes.ts +++ b/src/routes/oldSubmitSponsorTimes.ts @@ -1,5 +1,5 @@ -import {postSkipSegments} from "./postSkipSegments"; -import {Request, Response} from "express"; +import { postSkipSegments } from "./postSkipSegments"; +import { Request, Response } from "express"; export async function oldSubmitSponsorTimes(req: Request, res: Response): Promise { req.query.category = "sponsor"; diff --git a/src/routes/postClearCache.ts b/src/routes/postClearCache.ts index 8835ddd..91d4184 100644 --- a/src/routes/postClearCache.ts +++ b/src/routes/postClearCache.ts @@ -35,7 +35,7 @@ export async function postClearCache(req: Request, res: Response): Promise { diff --git a/src/routes/postPurgeAllSegments.ts b/src/routes/postPurgeAllSegments.ts index 3785b6e..dbb870d 100644 --- a/src/routes/postPurgeAllSegments.ts +++ b/src/routes/postPurgeAllSegments.ts @@ -1,10 +1,10 @@ -import {Logger} from "../utils/logger"; -import {getHash} from "../utils/getHash"; -import {isUserVIP} from "../utils/isUserVIP"; -import {Request, Response} from "express"; -import {HashedUserID, UserID} from "../types/user.model"; -import {VideoID} from "../types/segments.model"; -import {db} from "../databases/databases"; +import { Logger } from "../utils/logger"; +import { getHash } from "../utils/getHash"; +import { isUserVIP } from "../utils/isUserVIP"; +import { Request, Response } from "express"; +import { HashedUserID, UserID } from "../types/user.model"; +import { VideoID } from "../types/segments.model"; +import { db } from "../databases/databases"; export async function postPurgeAllSegments(req: Request, res: Response): Promise { const userID = req.body.userID as UserID; diff --git a/src/routes/postSegmentShift.ts b/src/routes/postSegmentShift.ts index 84eb268..fe8758e 100644 --- a/src/routes/postSegmentShift.ts +++ b/src/routes/postSegmentShift.ts @@ -1,48 +1,48 @@ -import {Request, Response} from "express"; -import {Logger} from "../utils/logger"; -import {isUserVIP} from "../utils/isUserVIP"; -import {getHash} from "../utils/getHash"; -import {db} from "../databases/databases"; +import { Request, Response } from "express"; +import { Logger } from "../utils/logger"; +import { isUserVIP } from "../utils/isUserVIP"; +import { getHash } from "../utils/getHash"; +import { db } from "../databases/databases"; const ACTION_NONE = Symbol("none"); const ACTION_UPDATE = Symbol("update"); const ACTION_REMOVE = Symbol("remove"); function shiftSegment(segment: any, shift: { startTime: any; endTime: any }) { - if (segment.startTime >= segment.endTime) return {action: ACTION_NONE, segment}; - if (shift.startTime >= shift.endTime) return {action: ACTION_NONE, segment}; + if (segment.startTime >= segment.endTime) return { action: ACTION_NONE, segment }; + if (shift.startTime >= shift.endTime) return { action: ACTION_NONE, segment }; const duration = shift.endTime - shift.startTime; if (shift.endTime < segment.startTime) { // Scenario #1 cut before segment segment.startTime -= duration; segment.endTime -= duration; - return {action: ACTION_UPDATE, segment}; + return { action: ACTION_UPDATE, segment }; } if (shift.startTime > segment.endTime) { // Scenario #2 cut after segment - return {action: ACTION_NONE, segment}; + return { action: ACTION_NONE, segment }; } if (segment.startTime < shift.startTime && segment.endTime > shift.endTime) { // Scenario #3 cut inside segment segment.endTime -= duration; - return {action: ACTION_UPDATE, segment}; + return { action: ACTION_UPDATE, segment }; } if (segment.startTime >= shift.startTime && segment.endTime > shift.endTime) { // Scenario #4 cut overlap startTime segment.startTime = shift.startTime; segment.endTime -= duration; - return {action: ACTION_UPDATE, segment}; + return { action: ACTION_UPDATE, segment }; } if (segment.startTime < shift.startTime && segment.endTime <= shift.endTime) { // Scenario #5 cut overlap endTime segment.endTime = shift.startTime; - return {action: ACTION_UPDATE, segment}; + return { action: ACTION_UPDATE, segment }; } if (segment.startTime >= shift.startTime && segment.endTime <= shift.endTime) { // Scenario #6 cut overlap startTime and endTime - return {action: ACTION_REMOVE, segment}; + return { action: ACTION_REMOVE, segment }; } - return {action: ACTION_NONE, segment}; + return { action: ACTION_NONE, segment }; } export async function postSegmentShift(req: Request, res: Response): Promise { diff --git a/src/routes/postSkipSegments.ts b/src/routes/postSkipSegments.ts index 5420271..3dc4410 100644 --- a/src/routes/postSkipSegments.ts +++ b/src/routes/postSkipSegments.ts @@ -1,15 +1,15 @@ -import {config} from "../config"; -import {Logger} from "../utils/logger"; -import {db, privateDB} from "../databases/databases"; -import {getMaxResThumbnail, YouTubeAPI} from "../utils/youtubeApi"; -import {getSubmissionUUID} from "../utils/getSubmissionUUID"; +import { config } from "../config"; +import { Logger } from "../utils/logger"; +import { db, privateDB } from "../databases/databases"; +import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi"; +import { getSubmissionUUID } from "../utils/getSubmissionUUID"; import fetch from "node-fetch"; -import {getHash} from "../utils/getHash"; -import {getIP} from "../utils/getIP"; -import {getFormattedTime} from "../utils/getFormattedTime"; -import {isUserTrustworthy} from "../utils/isUserTrustworthy"; -import {dispatchEvent} from "../utils/webhookUtils"; -import {Request, Response} from "express"; +import { getHash } from "../utils/getHash"; +import { getIP } from "../utils/getIP"; +import { getFormattedTime } from "../utils/getFormattedTime"; +import { isUserTrustworthy } from "../utils/isUserTrustworthy"; +import { dispatchEvent } from "../utils/webhookUtils"; +import { Request, Response } from "express"; import { ActionType, Category, CategoryActionType, IncomingSegment, SegmentUUID, Service, VideoDuration, VideoID } from "../types/segments.model"; import { deleteLockCategories } from "./deleteLockCategories"; import { getCategoryActionType } from "../utils/categoryInfo"; @@ -33,7 +33,7 @@ const CHECK_PASS: CheckResult = { errorCode: 0 }; -async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: APIVideoData, {submissionStart, submissionEnd}: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) { +async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: APIVideoData, { submissionStart, submissionEnd }: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) { const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]); const userName = row !== undefined ? row.userName : null; @@ -66,7 +66,7 @@ async function sendWebhooks(apiVideoInfo: APIVideoInfo, userID: string, videoID: if (apiVideoInfo && service == Service.YouTube) { const userSubmissionCountRow = await db.prepare("get", `SELECT count(*) as "submissionCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]); - const {data, err} = apiVideoInfo; + const { data, err } = apiVideoInfo; if (err) return; const startTime = parseFloat(segmentInfo.segment[0]); @@ -182,7 +182,7 @@ async function sendWebhooksNB(userID: string, videoID: string, UUID: string, sta async function autoModerateSubmission(apiVideoInfo: APIVideoInfo, submission: { videoID: VideoID; userID: UserID; segments: IncomingSegment[] }) { if (apiVideoInfo) { - const {err, data} = apiVideoInfo; + const { err, data } = apiVideoInfo; if (err) return false; const duration = apiVideoInfo?.data?.lengthSeconds; @@ -355,11 +355,11 @@ async function checkEachSegmentValid(userID: string, videoID: VideoID, for (let i = 0; i < segments.length; i++) { if (segments[i] === undefined || segments[i].segment === undefined || segments[i].category === undefined) { //invalid request - return { pass: false, errorMessage: "One of your segments are invalid", errorCode: 400}; + return { pass: false, errorMessage: "One of your segments are invalid", errorCode: 400 }; } if (!config.categoryList.includes(segments[i].category)) { - return { pass: false, errorMessage: "Category doesn't exist.", errorCode: 400}; + return { pass: false, errorMessage: "Category doesn't exist.", errorCode: 400 }; } // Reject segment if it's in the locked categories list @@ -392,24 +392,24 @@ async function checkEachSegmentValid(userID: string, videoID: VideoID, || (getCategoryActionType(segments[i].category) === CategoryActionType.Skippable && startTime === endTime) || (getCategoryActionType(segments[i].category) === CategoryActionType.POI && startTime !== endTime)) { //invalid request - return { pass: false, errorMessage: "One of your segments times are invalid (too short, startTime before endTime, etc.)", errorCode: 400}; + return { pass: false, errorMessage: "One of your segments times are invalid (too short, startTime before endTime, etc.)", errorCode: 400 }; } // Check for POI segments before some seconds if (!isVIP && getCategoryActionType(segments[i].category) === CategoryActionType.POI && startTime < config.poiMinimumStartTime) { - return { pass: false, errorMessage: `POI cannot be that early`, errorCode: 400}; + return { pass: false, errorMessage: `POI cannot be that early`, errorCode: 400 }; } if (!isVIP && segments[i].category === "sponsor" && Math.abs(startTime - endTime) < 1) { // Too short - return { pass: false, errorMessage: "Sponsors must be longer than 1 second long", errorCode: 400}; + return { pass: false, errorMessage: "Sponsors must be longer than 1 second long", errorCode: 400 }; } //check if this info has already been submitted before const duplicateCheck2Row = await db.prepare("get", `SELECT COUNT(*) as count FROM "sponsorTimes" WHERE "startTime" = ? and "endTime" = ? and "category" = ? and "actionType" = ? and "videoID" = ? and "service" = ?`, [startTime, endTime, segments[i].category, segments[i].actionType, videoID, service]); if (duplicateCheck2Row.count > 0) { - return { pass: false, errorMessage: "Sponsors has already been submitted before.", errorCode: 409}; + return { pass: false, errorMessage: "Sponsors has already been submitted before.", errorCode: 409 }; } } @@ -419,7 +419,7 @@ async function checkEachSegmentValid(userID: string, videoID: VideoID, async function checkByAutoModerator(videoID: any, userID: any, segments: Array, isVIP: boolean, service:string, apiVideoInfo: APIVideoInfo, decreaseVotes: number): Promise { // Auto moderator check if (!isVIP && service == Service.YouTube) { - const autoModerateResult = await autoModerateSubmission(apiVideoInfo, {userID, videoID, segments});//startTime, endTime, category: segments[i].category}); + const autoModerateResult = await autoModerateSubmission(apiVideoInfo, { userID, videoID, segments });//startTime, endTime, category: segments[i].category}); if (autoModerateResult == "Rejected based on NeuralBlock predictions.") { // If NB automod rejects, the submission will start with -2 votes. // Note, if one submission is bad all submissions will be affected. @@ -570,7 +570,7 @@ function preprocessInput(req: Request) { const userAgent = req.query.userAgent ?? req.body.userAgent ?? parseUserAgent(req.get("user-agent")) ?? ""; - return {videoID, userID, service, videoDuration, videoDurationParam, segments, userAgent}; + return { videoID, userID, service, videoDuration, videoDurationParam, segments, userAgent }; } export async function postSkipSegments(req: Request, res: Response): Promise { @@ -579,7 +579,7 @@ export async function postSkipSegments(req: Request, res: Response): Promise { // exit early if no body passed in - if (!req.body.userID && !req.body.issuerUserID) return res.status(400).json({"message": "Missing parameters"}); + if (!req.body.userID && !req.body.issuerUserID) return res.status(400).json({ "message": "Missing parameters" }); // Collect user input data const issuerUserID: HashedUserID = getHash( req.body.issuerUserID); const userID: UserID = req.body.userID; @@ -34,7 +34,7 @@ export async function postWarning(req: Request, res: Response): Promise { return privateDB.prepare("run", diff --git a/src/routes/shadowBanUser.ts b/src/routes/shadowBanUser.ts index babe909..a01fe4a 100644 --- a/src/routes/shadowBanUser.ts +++ b/src/routes/shadowBanUser.ts @@ -1,6 +1,6 @@ -import {db} from "../databases/databases"; -import {getHash} from "../utils/getHash"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { getHash } from "../utils/getHash"; +import { Request, Response } from "express"; import { config } from "../config"; import { Category, Service, VideoID, VideoIDHash } from "../types/segments.model"; import { UserID } from "../types/user.model"; diff --git a/src/routes/viewedVideoSponsorTime.ts b/src/routes/viewedVideoSponsorTime.ts index 85ce060..f111cab 100644 --- a/src/routes/viewedVideoSponsorTime.ts +++ b/src/routes/viewedVideoSponsorTime.ts @@ -1,5 +1,5 @@ -import {db} from "../databases/databases"; -import {Request, Response} from "express"; +import { db } from "../databases/databases"; +import { Request, Response } from "express"; export async function viewedVideoSponsorTime(req: Request, res: Response): Promise { const UUID = req.query.UUID; diff --git a/src/routes/voteOnSponsorTime.ts b/src/routes/voteOnSponsorTime.ts index 82cc446..fae4425 100644 --- a/src/routes/voteOnSponsorTime.ts +++ b/src/routes/voteOnSponsorTime.ts @@ -1,14 +1,14 @@ -import {Request, Response} from "express"; -import {Logger} from "../utils/logger"; -import {isUserVIP} from "../utils/isUserVIP"; +import { Request, Response } from "express"; +import { Logger } from "../utils/logger"; +import { isUserVIP } from "../utils/isUserVIP"; import fetch from "node-fetch"; -import {getMaxResThumbnail, YouTubeAPI} from "../utils/youtubeApi"; -import {db, privateDB} from "../databases/databases"; -import {dispatchEvent, getVoteAuthor, getVoteAuthorRaw} from "../utils/webhookUtils"; -import {getFormattedTime} from "../utils/getFormattedTime"; -import {getIP} from "../utils/getIP"; -import {getHash} from "../utils/getHash"; -import {config} from "../config"; +import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi"; +import { db, privateDB } from "../databases/databases"; +import { dispatchEvent, getVoteAuthor, getVoteAuthorRaw } from "../utils/webhookUtils"; +import { getFormattedTime } from "../utils/getFormattedTime"; +import { getIP } from "../utils/getIP"; +import { getHash } from "../utils/getHash"; +import { config } from "../config"; import { UserID } from "../types/user.model"; import { Category, CategoryActionType, HashedIP, IPAddress, SegmentUUID, Service, VideoID, VideoIDHash, Visibility } from "../types/segments.model"; import { getCategoryActionType } from "../utils/categoryInfo"; @@ -459,6 +459,6 @@ export async function voteOnSponsorTime(req: Request, res: Response): Promise { diff --git a/src/utils/logger.ts b/src/utils/logger.ts index 159ec97..56a7e95 100644 --- a/src/utils/logger.ts +++ b/src/utils/logger.ts @@ -1,4 +1,4 @@ -import {config} from "../config"; +import { config } from "../config"; const enum LogLevel { ERROR = "ERROR", diff --git a/src/utils/queryCacher.ts b/src/utils/queryCacher.ts index d80fb53..c35e9b1 100644 --- a/src/utils/queryCacher.ts +++ b/src/utils/queryCacher.ts @@ -5,7 +5,7 @@ import { Service, VideoID, VideoIDHash } from "../types/segments.model"; import { UserID } from "../types/user.model"; async function get(fetchFromDB: () => Promise, key: string): Promise { - const {err, reply} = await redis.getAsync(key); + const { err, reply } = await redis.getAsync(key); if (!err && reply) { try { diff --git a/src/utils/redis.ts b/src/utils/redis.ts index 5fcbbe1..ef2a640 100644 --- a/src/utils/redis.ts +++ b/src/utils/redis.ts @@ -1,6 +1,6 @@ -import {config} from "../config"; -import {Logger} from "./logger"; -import redis, {Callback} from "redis"; +import { config } from "../config"; +import { Logger } from "./logger"; +import redis, { Callback } from "redis"; interface RedisSB { get(key: string, callback?: Callback): void; @@ -13,10 +13,10 @@ interface RedisSB { let exportObject: RedisSB = { get: (key, callback?) => callback(null, undefined), getAsync: () => - new Promise((resolve) => resolve({err: null, reply: undefined})), + new Promise((resolve) => resolve({ err: null, reply: undefined })), set: (key, value, callback) => callback(null, undefined), setAsync: () => - new Promise((resolve) => resolve({err: null, reply: undefined})), + new Promise((resolve) => resolve({ err: null, reply: undefined })), delAsync: () => new Promise((resolve) => resolve(null)), }; @@ -26,8 +26,8 @@ if (config.redis) { const client = redis.createClient(config.redis); exportObject = client; - exportObject.getAsync = (key) => new Promise((resolve) => client.get(key, (err, reply) => resolve({err, reply}))); - exportObject.setAsync = (key, value) => new Promise((resolve) => client.set(key, value, (err, reply) => resolve({err, reply}))); + exportObject.getAsync = (key) => new Promise((resolve) => client.get(key, (err, reply) => resolve({ err, reply }))); + exportObject.setAsync = (key, value) => new Promise((resolve) => client.set(key, value, (err, reply) => resolve({ err, reply }))); exportObject.delAsync = (...keys) => new Promise((resolve) => client.del(keys, (err) => resolve(err))); client.on("error", function(error) { diff --git a/src/utils/webhookUtils.ts b/src/utils/webhookUtils.ts index 2b5153a..76a40e0 100644 --- a/src/utils/webhookUtils.ts +++ b/src/utils/webhookUtils.ts @@ -1,5 +1,5 @@ -import {config} from "../config"; -import {Logger} from "../utils/logger"; +import { config } from "../config"; +import { Logger } from "../utils/logger"; import fetch from "node-fetch"; function getVoteAuthorRaw(submissionCount: number, isVIP: boolean, isOwnSubmission: boolean): string { diff --git a/src/utils/youtubeApi.ts b/src/utils/youtubeApi.ts index 96dd669..5d730b5 100644 --- a/src/utils/youtubeApi.ts +++ b/src/utils/youtubeApi.ts @@ -1,6 +1,6 @@ import fetch from "node-fetch"; -import {config} from "../config"; -import {Logger} from "./logger"; +import { config } from "../config"; +import { Logger } from "./logger"; import { APIVideoData, APIVideoInfo } from "../types/youtubeApi.model"; import DiskCache from "./diskCache"; @@ -24,7 +24,7 @@ export class YouTubeAPI { } } - if (!config.newLeafURLs || config.newLeafURLs.length <= 0) return {err: "NewLeaf URL not found", data: null}; + if (!config.newLeafURLs || config.newLeafURLs.length <= 0) return { err: "NewLeaf URL not found", data: null }; try { const result = await fetch(`${config.newLeafURLs[Math.floor(Math.random() * config.newLeafURLs.length)]}/api/v1/videos/${videoID}`, { method: "GET" }); @@ -45,7 +45,7 @@ export class YouTubeAPI { return { err: result.statusText, data: null }; } } catch (err) { - return {err: err as string | boolean, data: null}; + return { err: err as string | boolean, data: null }; } } } diff --git a/test/cases/dbUpgrade.ts b/test/cases/dbUpgrade.ts index c8de4a6..67a22f1 100644 --- a/test/cases/dbUpgrade.ts +++ b/test/cases/dbUpgrade.ts @@ -1,6 +1,6 @@ import assert from "assert"; -import {db, privateDB} from "../../src/databases/databases"; +import { db, privateDB } from "../../src/databases/databases"; describe("dbUpgrade", () => { it("Should update the database version when starting the application", async () => { diff --git a/test/cases/downvoteSegmentArchiveJob.ts b/test/cases/downvoteSegmentArchiveJob.ts index 07e6342..4a3ad8e 100644 --- a/test/cases/downvoteSegmentArchiveJob.ts +++ b/test/cases/downvoteSegmentArchiveJob.ts @@ -1,4 +1,4 @@ -import {strictEqual, ok} from "assert"; +import { strictEqual, ok } from "assert"; import { db } from "../../src/databases/databases"; import { archiveDownvoteSegment } from "../../src/cronjob/downvoteSegmentArchiveJob"; import { DBSegment } from "../../src/types/segments.model"; diff --git a/test/cases/getHash.ts b/test/cases/getHash.ts index 9643351..60686a0 100644 --- a/test/cases/getHash.ts +++ b/test/cases/getHash.ts @@ -1,5 +1,5 @@ -import {getHash} from "../../src/utils/getHash"; -import {notStrictEqual, strictEqual} from "assert"; +import { getHash } from "../../src/utils/getHash"; +import { notStrictEqual, strictEqual } from "assert"; describe("getHash", () => { it("Should not output the input string", () => { diff --git a/test/cases/getIsUserVIP.ts b/test/cases/getIsUserVIP.ts index be03fac..8f4c7f0 100644 --- a/test/cases/getIsUserVIP.ts +++ b/test/cases/getIsUserVIP.ts @@ -1,12 +1,12 @@ -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; import { client } from "../utils/httpClient"; import assert from "assert"; const VIPUser = "isUserVIPVIP"; const normalUser = "isUserVIPNormal"; const endpoint = "/api/isUserVIP"; -const vipUserRequest = (userID: string) => client.get(endpoint, { params: { userID }}); +const vipUserRequest = (userID: string) => client.get(endpoint, { params: { userID } }); describe("getIsUserVIP", () => { before(() => { diff --git a/test/cases/getLockCategories.ts b/test/cases/getLockCategories.ts index 128efdd..2b2ff9c 100644 --- a/test/cases/getLockCategories.ts +++ b/test/cases/getLockCategories.ts @@ -1,5 +1,5 @@ -import {getHash} from "../../src/utils/getHash"; -import {db} from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; import assert from "assert"; import { client } from "../utils/httpClient"; const endpoint = "/api/lockCategories"; diff --git a/test/cases/getLockCategoriesByHash.ts b/test/cases/getLockCategoriesByHash.ts index 63ab2a3..8e35b78 100644 --- a/test/cases/getLockCategoriesByHash.ts +++ b/test/cases/getLockCategoriesByHash.ts @@ -1,5 +1,5 @@ -import {getHash} from "../../src/utils/getHash"; -import {db} from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; import assert from "assert"; import { client } from "../utils/httpClient"; diff --git a/test/cases/getLockReason.ts b/test/cases/getLockReason.ts index 742f041..5b40182 100644 --- a/test/cases/getLockReason.ts +++ b/test/cases/getLockReason.ts @@ -1,8 +1,8 @@ import fetch from "node-fetch"; -import {Done} from "../utils/utils"; +import { Done } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; -import {getHash} from "../../src/utils/getHash"; -import {db} from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; import assert from "assert"; const endpoint = `${getbaseURL()}/api/lockReason`; @@ -63,7 +63,7 @@ describe("getLockReason", () => { const data = await res.json(); const expected = [ { category: "sponsor", locked: 1, reason: "sponsor-reason" }, - { category: "intro", locked: 0, reason: ""} + { category: "intro", locked: 0, reason: "" } ]; assert.deepStrictEqual(data, expected); done(); diff --git a/test/cases/getSavedTimeForUser.ts b/test/cases/getSavedTimeForUser.ts index 7fd27cd..7ed809f 100644 --- a/test/cases/getSavedTimeForUser.ts +++ b/test/cases/getSavedTimeForUser.ts @@ -1,6 +1,6 @@ -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; -import {deepStrictEqual} from "assert"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import { deepStrictEqual } from "assert"; import { client } from "../utils/httpClient"; const endpoint = "/api/getSavedTimeForUser"; @@ -14,7 +14,7 @@ describe("getSavedTimeForUser", () => { }); it("Should be able to get a 200", (done) => { - client.get(endpoint, { params: { userID: user1 }}) + client.get(endpoint, { params: { userID: user1 } }) .then(res => { // (end-start)*minute * views const savedMinutes = ((11-1)/60) * 50; diff --git a/test/cases/getSearchSegments.ts b/test/cases/getSearchSegments.ts index 9a9be1e..005f6d4 100644 --- a/test/cases/getSearchSegments.ts +++ b/test/cases/getSearchSegments.ts @@ -1,4 +1,4 @@ -import {db} from "../../src/databases/databases"; +import { db } from "../../src/databases/databases"; import { client } from "../utils/httpClient"; import assert from "assert"; @@ -33,7 +33,7 @@ describe("getSearchSegments", () => { }); it("Should be able to show all segments under searchTest0", (done) => { - client.get(endpoint, { params: { videoID: "searchTest0" }}) + client.get(endpoint, { params: { videoID: "searchTest0" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -51,7 +51,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by category", (done) => { - client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" }}) + client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -65,7 +65,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by category", (done) => { - client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" }}) + client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -79,7 +79,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by lock status", (done) => { - client.get(endpoint, { params: { videoID: "searchTest0", locked: false }}) + client.get(endpoint, { params: { videoID: "searchTest0", locked: false } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -96,7 +96,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by hide status", (done) => { - client.get(endpoint, { params: { videoID: "searchTest0", hidden: false }}) + client.get(endpoint, { params: { videoID: "searchTest0", hidden: false } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -113,7 +113,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter by ignored status", (done) => { - client.get(endpoint, { params: { videoID: "searchTest0", ignored: false }}) + client.get(endpoint, { params: { videoID: "searchTest0", ignored: false } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -129,7 +129,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by min views", (done) => { - client.get(endpoint, { params: { videoID: "searchTest1", minViews: 6 }}) + client.get(endpoint, { params: { videoID: "searchTest1", minViews: 6 } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -143,7 +143,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by max views", (done) => { - client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10 }}) + client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10 } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -157,7 +157,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by min and max views", (done) => { - client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10, minViews: 1 }}) + client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10, minViews: 1 } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -171,7 +171,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by min votes", (done) => { - client.get(endpoint, { params: { videoID: "searchTest2", minVotes: 0 }}) + client.get(endpoint, { params: { videoID: "searchTest2", minVotes: 0 } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -186,7 +186,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by max votes", (done) => { - client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10 }}) + client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10 } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -201,7 +201,7 @@ describe("getSearchSegments", () => { }); it("Should be able to filter segments by both min and max votes", (done) => { - client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10, minVotes: 0 }}) + client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10, minVotes: 0 } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -215,7 +215,7 @@ describe("getSearchSegments", () => { }); it("Should be able to get first page of results", (done) => { - client.get(endpoint, { params: { videoID: "searchTest4" }}) + client.get(endpoint, { params: { videoID: "searchTest4" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -238,7 +238,7 @@ describe("getSearchSegments", () => { }); it("Should be able to get second page of results", (done) => { - client.get(endpoint, { params: { videoID: "searchTest4", page: 1 }}) + client.get(endpoint, { params: { videoID: "searchTest4", page: 1 } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; diff --git a/test/cases/getSegmentInfo.ts b/test/cases/getSegmentInfo.ts index 6153ab0..87245cc 100644 --- a/test/cases/getSegmentInfo.ts +++ b/test/cases/getSegmentInfo.ts @@ -1,4 +1,4 @@ -import {db} from "../../src/databases/databases"; +import { db } from "../../src/databases/databases"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; import { client } from "../utils/httpClient"; @@ -169,7 +169,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive single segment in array", (done) => { - client.get(endpoint, { params: { UUIDs: `["${upvotedID}"]` }}) + client.get(endpoint, { params: { UUIDs: `["${upvotedID}"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -185,7 +185,7 @@ describe("getSegmentInfo", () => { }); it("Should be able to retreive multiple segments in array", (done) => { - client.get(endpoint, { params: { UUIDs: `["${upvotedID}", "${downvotedID}"]` }}) + client.get(endpoint, { params: { UUIDs: `["${upvotedID}", "${downvotedID}"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -204,7 +204,7 @@ describe("getSegmentInfo", () => { }); it("Should be possible to send unexpected query parameters", (done) => { - client.get(endpoint, { params: { UUID: upvotedID, fakeparam: "hello", category: "sponsor" }}) + client.get(endpoint, { params: { UUID: upvotedID, fakeparam: "hello", category: "sponsor" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -273,7 +273,7 @@ describe("getSegmentInfo", () => { it("Should cut off array at 10", function(done) { this.timeout(10000); const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`; - client.get(endpoint, { params: { UUIDs: filledIDArray }}) + client.get(endpoint, { params: { UUIDs: filledIDArray } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -298,7 +298,7 @@ describe("getSegmentInfo", () => { }); it("Should return 400 if UUID not found", (done) => { - client.get(endpoint, { params: { UUID: ENOENTID }}) + client.get(endpoint, { params: { UUID: ENOENTID } }) .then(res => { if (res.status !== 400) done(`non 400 response code: ${res.status}`); else done(); // pass diff --git a/test/cases/getSkipSegments.ts b/test/cases/getSkipSegments.ts index f13ae1b..63002f7 100644 --- a/test/cases/getSkipSegments.ts +++ b/test/cases/getSkipSegments.ts @@ -1,4 +1,4 @@ -import {db} from "../../src/databases/databases"; +import { db } from "../../src/databases/databases"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; import { client } from "../utils/httpClient"; @@ -27,7 +27,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category 1", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -43,7 +43,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category and action type", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionType: "mute" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionType: "mute" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -81,7 +81,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionTypes: `["mute","skip"]` }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionTypes: `["mute","skip"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -100,7 +100,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category for a different service 1", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID1", category: "sponsor", service: "PeerTube" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID1", category: "sponsor", service: "PeerTube" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -118,7 +118,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by category 2", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "intro" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "intro" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -135,7 +135,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by categories array", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor"]` }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -153,7 +153,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get a time by categories array 2", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["intro"]` }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["intro"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -171,7 +171,7 @@ describe("getSkipSegments", () => { }); it("Should return 404 if all submissions are hidden", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID6" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID6" } }) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -180,7 +180,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get getSkipSegmentMultiple times by category", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentMultiple", categories: `["intro"]` }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentMultiple", categories: `["intro"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -201,7 +201,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor", "intro"]` }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor", "intro"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -222,7 +222,7 @@ describe("getSkipSegments", () => { }); it("Should be possible to send unexpected query parameters", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", fakeparam: "hello", category: "sponsor" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", fakeparam: "hello", category: "sponsor" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -239,7 +239,7 @@ describe("getSkipSegments", () => { }); it("Low voted submissions should be hidden", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID3", category: "sponsor" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID3", category: "sponsor" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -256,7 +256,7 @@ describe("getSkipSegments", () => { }); it("Should return 404 if no segment found", (done) => { - client.get(endpoint, { params: { videoID: "notarealvideo" }}) + client.get(endpoint, { params: { videoID: "notarealvideo" } }) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -265,7 +265,7 @@ describe("getSkipSegments", () => { }); it("Should return 400 if bad categories argument", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `[not-quoted,not-quoted]` }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `[not-quoted,not-quoted]` } }) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -274,7 +274,7 @@ describe("getSkipSegments", () => { }); it("Should be able send a comma in a query param", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentID2", category: "sponsor" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentID2", category: "sponsor" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -291,7 +291,7 @@ describe("getSkipSegments", () => { }); it("Should always get getSkipSegmentLocked segment", (done) => { - client.get(endpoint, { params: { videoID: "getSkipSegmentLocked", category: "intro" }}) + client.get(endpoint, { params: { videoID: "getSkipSegmentLocked", category: "intro" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -308,7 +308,7 @@ describe("getSkipSegments", () => { }); it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done) => { - client.get(`${endpoint}?category=sponsor&category=intro`, { params: { videoID: "getSkipSegmentID0" }}) + client.get(`${endpoint}?category=sponsor&category=intro`, { params: { videoID: "getSkipSegmentID0" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -348,7 +348,7 @@ describe("getSkipSegments", () => { it("Should be able to get specific segments with requiredSegments", (done) => { const required2 = "requiredSegmentVid2"; const required3 = "requiredSegmentVid3"; - client.get(endpoint, { params: { videoID: "requiredSegmentVid", requiredSegments: `["${required2}","${required3}"]` }}) + client.get(endpoint, { params: { videoID: "requiredSegmentVid", requiredSegments: `["${required2}","${required3}"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; diff --git a/test/cases/getSkipSegmentsByHash.ts b/test/cases/getSkipSegmentsByHash.ts index bc9efff..fb83ec0 100644 --- a/test/cases/getSkipSegmentsByHash.ts +++ b/test/cases/getSkipSegmentsByHash.ts @@ -1,9 +1,9 @@ -import {db} from "../../src/databases/databases"; +import { db } from "../../src/databases/databases"; import { partialDeepEquals } from "../utils/partialDeepEquals"; -import {getHash} from "../../src/utils/getHash"; -import {ImportMock,} from "ts-mock-imports"; +import { getHash } from "../../src/utils/getHash"; +import { ImportMock, } from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; -import {YouTubeApiMock} from "../youtubeMock"; +import { YouTubeApiMock } from "../youtubeMock"; import assert from "assert"; import { client } from "../utils/httpClient"; @@ -33,7 +33,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get a 200", (done) => { - client.get(`${endpoint}/3272f`, { params: { categories: `["sponsor", "intro"]` }}) + client.get(`${endpoint}/3272f`, { params: { categories: `["sponsor", "intro"]` } }) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -42,7 +42,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 404 if no segments are found even if a video for the given hash is known", (done) => { - client.get(`${endpoint}/3272f`, { params: { categories: `["shilling"]` }}) + client.get(`${endpoint}/3272f`, { params: { categories: `["shilling"]` } }) .then(res => { assert.strictEqual(res.status, 404); assert.equal(res.data.length, 0); @@ -52,7 +52,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get an empty array if no videos", (done) => { - client.get(`${endpoint}/11111`, { params: { categories: `["shilling"]` }}) + client.get(`${endpoint}/11111`, { params: { categories: `["shilling"]` } }) .then(res => { assert.strictEqual(res.status, 404); const body = res.data; @@ -63,7 +63,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get an empty array if only hidden videos", (done) => { - client.get(`${endpoint}/f3a1`, { params: { categories:`["sponsor"]` }}) + client.get(`${endpoint}/f3a1`, { params: { categories:`["sponsor"]` } }) .then(res => { if (res.status !== 404) done(`non 404 status code, was ${res.status}`); else { @@ -76,7 +76,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 400 prefix too short", (done) => { - client.get(`${endpoint}/11`, { params: { categories: `["shilling"]` }}) + client.get(`${endpoint}/11`, { params: { categories: `["shilling"]` } }) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -87,7 +87,7 @@ describe("getSkipSegmentsByHash", () => { it("Should return 400 prefix too long", (done) => { const prefix = "1".repeat(50); assert.ok(prefix.length > 33, "failed to generate long enough string"); - client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` }}) + client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` } }) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -97,7 +97,7 @@ describe("getSkipSegmentsByHash", () => { it("Should return 404 prefix in range", (done) => { const prefix = "1".repeat(5); - client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` }}) + client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` } }) .then(res => { assert.strictEqual(res.status, 404); done(); @@ -106,7 +106,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 400 for no hash", (done) => { - client.get(`${endpoint}`, { params: { categories: `["shilling"]` }}) + client.get(`${endpoint}`, { params: { categories: `["shilling"]` } }) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -115,7 +115,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should return 400 for bad format categories", (done) => { - client.get(`${endpoint}/fdaf`, { params: { categories: "shilling" }}) + client.get(`${endpoint}/fdaf`, { params: { categories: "shilling" } }) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -124,7 +124,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get multiple videos", (done) => { - client.get(`${endpoint}/fdaf`, { params: { categories: `["sponsor","intro"]` }}) + client.get(`${endpoint}/fdaf`, { params: { categories: `["sponsor","intro"]` } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -161,7 +161,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get 200 for no categories (default sponsor) with action type", (done) => { - client.get(`${endpoint}/fdaf`, { params: { actionType: "skip" }}) + client.get(`${endpoint}/fdaf`, { params: { actionType: "skip" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -235,7 +235,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done) => { - client.get(`${endpoint}/fdaf`, { params: { service: "PeerTube" }}) + client.get(`${endpoint}/fdaf`, { params: { service: "PeerTube" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -253,7 +253,7 @@ describe("getSkipSegmentsByHash", () => { }); it("Should only return one segment when fetching highlight segments", (done) => { - client.get(`${endpoint}/c962`, { params: { category: "poi_highlight" }}) + client.get(`${endpoint}/c962`, { params: { category: "poi_highlight" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; diff --git a/test/cases/getStatus.ts b/test/cases/getStatus.ts index 3f98e80..5d175d7 100644 --- a/test/cases/getStatus.ts +++ b/test/cases/getStatus.ts @@ -1,5 +1,5 @@ import assert from "assert"; -import {db} from "../../src/databases/databases"; +import { db } from "../../src/databases/databases"; import { client } from "../utils/httpClient"; let dbVersion: number; diff --git a/test/cases/getSubmissionUUID.ts b/test/cases/getSubmissionUUID.ts index e71ef9b..ad6ae63 100644 --- a/test/cases/getSubmissionUUID.ts +++ b/test/cases/getSubmissionUUID.ts @@ -1,4 +1,4 @@ -import {getSubmissionUUID} from "../../src/utils/getSubmissionUUID"; +import { getSubmissionUUID } from "../../src/utils/getSubmissionUUID"; import assert from "assert"; import { ActionType, VideoID } from "../../src/types/segments.model"; import { UserID } from "../../src/types/user.model"; diff --git a/test/cases/getUserID.ts b/test/cases/getUserID.ts index 226da22..a255816 100644 --- a/test/cases/getUserID.ts +++ b/test/cases/getUserID.ts @@ -1,11 +1,11 @@ -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; import assert from "assert"; import { client } from "../utils/httpClient"; import { AxiosResponse } from "axios"; const endpoint = "/api/userID"; -const getUserName = (username: string): Promise => client.get(endpoint, { params: { username }}); +const getUserName = (username: string): Promise => client.get(endpoint, { params: { username } }); describe("getUserID", () => { before(async () => { @@ -43,7 +43,7 @@ describe("getUserID", () => { }); it("Should be able to get a 200 (username is public id)", (done) => { - client.get(endpoint, { params: { username: getHash("getuserid_user_06") }}) + client.get(endpoint, { params: { username: getHash("getuserid_user_06") } }) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -52,7 +52,7 @@ describe("getUserID", () => { }); it("Should be able to get a 400 (username longer than 64 chars)", (done) => { - client.get(endpoint, { params: { username: `${getHash("getuserid_user_06")}0` }}) + client.get(endpoint, { params: { username: `${getHash("getuserid_user_06")}0` } }) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -61,7 +61,7 @@ describe("getUserID", () => { }); it("Should be able to get single username", (done) => { - client.get(endpoint, { params: { username: "fuzzy user 01" }}) + client.get(endpoint, { params: { username: "fuzzy user 01" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -254,7 +254,7 @@ describe("getUserID", () => { }); it("should allow exact match", (done) => { - client.get(endpoint, { params: { username: "a", exact: true }}) + client.get(endpoint, { params: { username: "a", exact: true } }) .then(res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -268,7 +268,7 @@ describe("getUserID", () => { }); it("Should be able to get repeating username with exact username", (done) => { - client.get(endpoint, { params: { username: "repeating", exact: true }}) + client.get(endpoint, { params: { username: "repeating", exact: true } }) .then(res => { assert.strictEqual(res.status, 200); const expected = [{ @@ -285,7 +285,7 @@ describe("getUserID", () => { }); it("Should not get exact unless explicitly set to true", (done) => { - client.get(endpoint, { params: { username: "user", exact: 1 }}) + client.get(endpoint, { params: { username: "user", exact: 1 } }) .then(res => { assert.strictEqual(res.status, 200); const expected = [{ diff --git a/test/cases/getUserInfo.ts b/test/cases/getUserInfo.ts index d4f56d3..098d092 100644 --- a/test/cases/getUserInfo.ts +++ b/test/cases/getUserInfo.ts @@ -1,6 +1,6 @@ import { partialDeepEquals } from "../utils/partialDeepEquals"; -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; import assert from "assert"; import { client } from "../utils/httpClient"; @@ -35,7 +35,7 @@ describe("getUserInfo", () => { }); it("Should be able to get a 200", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_user_01" }}) + client.get(endpoint, { params: { userID: "getuserinfo_user_01" } }) .then(res => { assert.strictEqual(res.status, 200); done(); @@ -44,7 +44,7 @@ describe("getUserInfo", () => { }); it("Should be able to get a 400 (No userID parameter)", (done) => { - client.get(endpoint, { params: { userID: "" }}) + client.get(endpoint, { params: { userID: "" } }) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -53,7 +53,7 @@ describe("getUserInfo", () => { }); it("Should be able to get user info", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_user_01" }}) + client.get(endpoint, { params: { userID: "getuserinfo_user_01" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -77,7 +77,7 @@ describe("getUserInfo", () => { }); it("Should get warning data", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_warning_0", value: "warnings" }}) + client.get(endpoint, { params: { userID: "getuserinfo_warning_0", value: "warnings" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -90,7 +90,7 @@ describe("getUserInfo", () => { }); it("Should get warning data with public ID", (done) => { - client.get(endpoint, { params: { publicUserID: getHash("getuserinfo_warning_0"), values: `["warnings"]` }}) + client.get(endpoint, { params: { publicUserID: getHash("getuserinfo_warning_0"), values: `["warnings"]` } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -103,7 +103,7 @@ describe("getUserInfo", () => { }); it("Should get multiple warnings", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warnings" }}) + client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warnings" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -116,7 +116,7 @@ describe("getUserInfo", () => { }); it("Should not get warnings if none", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_warning_2", value: "warnings" }}) + client.get(endpoint, { params: { userID: "getuserinfo_warning_2", value: "warnings" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -129,7 +129,7 @@ describe("getUserInfo", () => { }); it("Should done(userID for userName (No userName set)", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_user_02", value: "userName" }}) + client.get(endpoint, { params: { userID: "getuserinfo_user_02", value: "userName" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -142,7 +142,7 @@ describe("getUserInfo", () => { }); it("Should return null segment if none", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" }}) + client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" } }) .then(res => { assert.strictEqual(res.status, 200); assert.strictEqual(res.data.lastSegmentID, null); @@ -152,7 +152,7 @@ describe("getUserInfo", () => { }); it("Should return zeroes if userid does not exist", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" }}) + client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" } }) .then(res => { const data = res.data; for (const value in data) { @@ -166,7 +166,7 @@ describe("getUserInfo", () => { }); it("Should get warning reason from from single enabled warning", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_warning_0", values: `["warningReason"]` }}) + client.get(endpoint, { params: { userID: "getuserinfo_warning_0", values: `["warningReason"]` } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -179,7 +179,7 @@ describe("getUserInfo", () => { }); it("Should get most recent warning from two enabled warnings", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warningReason" }}) + client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warningReason" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -192,7 +192,7 @@ describe("getUserInfo", () => { }); it("Should not get disabled warning", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_warning_2", values: `["warnings","warningReason"]` }}) + client.get(endpoint, { params: { userID: "getuserinfo_warning_2", values: `["warnings","warningReason"]` } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -220,7 +220,7 @@ describe("getUserInfo", () => { }); it("Should get 400 if bad values specified", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_warning_3", value: "invalid-value" }}) + client.get(endpoint, { params: { userID: "getuserinfo_warning_3", value: "invalid-value" } }) .then(res => { assert.strictEqual(res.status, 400); done(); // pass @@ -229,7 +229,7 @@ describe("getUserInfo", () => { }); it("Should get ban data for banned user (only appears when specifically requested)", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_ban_01", value: "banned" }}) + client.get(endpoint, { params: { userID: "getuserinfo_ban_01", value: "banned" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -242,7 +242,7 @@ describe("getUserInfo", () => { }); it("Should get ban data for unbanned user (only appears when specifically requested)", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_notban_01", value: "banned" }}) + client.get(endpoint, { params: { userID: "getuserinfo_notban_01", value: "banned" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -255,7 +255,7 @@ describe("getUserInfo", () => { }); it("Should throw 400 on bad json in values", (done) => { - client.get(endpoint, { params: { userID: "x", values: `[userID]` }}) + client.get(endpoint, { params: { userID: "x", values: `[userID]` } }) .then(res => { assert.strictEqual(res.status, 400); done(); // pass @@ -264,7 +264,7 @@ describe("getUserInfo", () => { }); it("Should return 200 on userID not found", (done) => { - client.get(endpoint, { params: { userID: "notused-userid" }}) + client.get(endpoint, { params: { userID: "notused-userid" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -285,7 +285,7 @@ describe("getUserInfo", () => { }); it("Should only count long segments as 10 minutes", (done) => { - client.get(endpoint, { params: { userID: "getuserinfo_user_03" }}) + client.get(endpoint, { params: { userID: "getuserinfo_user_03" } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { diff --git a/test/cases/getUserStats.ts b/test/cases/getUserStats.ts index 1bbc756..900a595 100644 --- a/test/cases/getUserStats.ts +++ b/test/cases/getUserStats.ts @@ -33,7 +33,7 @@ describe("getUserStats", () => { }); it("Should be able to get all user info", (done) => { - client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchCategoryStats: true, fetchActionTypeStats: true }}) + client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchCategoryStats: true, fetchActionTypeStats: true } }) .then(res => { assert.strictEqual(res.status, 200); const expected = { @@ -65,7 +65,7 @@ describe("getUserStats", () => { }); it("Should be able to get all zeroes for invalid userid", (done) => { - client.get(endpoint, { params: { userID: "getuserstats_user_invalid" }}) + client.get(endpoint, { params: { userID: "getuserstats_user_invalid" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -80,7 +80,7 @@ describe("getUserStats", () => { }); it("Should be able to get all zeroes for only ignored segments", (done) => { - client.get(endpoint, { params: { userID: "getuserstats_user_02" }}) + client.get(endpoint, { params: { userID: "getuserstats_user_02" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -95,7 +95,7 @@ describe("getUserStats", () => { }); it("Should not get extra stats if not requested", (done) => { - client.get(endpoint, { params: { userID: "getuserstats_user_01" }}) + client.get(endpoint, { params: { userID: "getuserstats_user_01" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; @@ -109,7 +109,7 @@ describe("getUserStats", () => { }); it("Should get parts of extra stats if not requested", (done) => { - client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchActionTypeStats: true }}) + client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchActionTypeStats: true } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; diff --git a/test/cases/lockCategoriesRecords.ts b/test/cases/lockCategoriesRecords.ts index b7f13f5..15a23f8 100644 --- a/test/cases/lockCategoriesRecords.ts +++ b/test/cases/lockCategoriesRecords.ts @@ -1,7 +1,7 @@ -import {getHash} from "../../src/utils/getHash"; -import {db} from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; 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 => { @@ -455,7 +455,7 @@ describe("lockCategoriesRecords", () => { "shilling" ], }; - client.get(endpoint, { params: {videoID: "no-segments-video-id" }}) + client.get(endpoint, { params: { videoID: "no-segments-video-id" } }) .then(res => { assert.strictEqual(res.status, 200); const data = res.data; diff --git a/test/cases/oldGetSponsorTime.ts b/test/cases/oldGetSponsorTime.ts index 5e35760..734c8ff 100644 --- a/test/cases/oldGetSponsorTime.ts +++ b/test/cases/oldGetSponsorTime.ts @@ -1,4 +1,4 @@ -import {db} from "../../src/databases/databases"; +import { db } from "../../src/databases/databases"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import assert from "assert"; import { client } from "../utils/httpClient"; @@ -33,7 +33,7 @@ describe("getVideoSponsorTime (Old get method)", () => { it("Should be possible to send unexpected query parameters", (done) => { - client.get(endpoint, { params: { videoID: "oldGetSponsorTime0", fakeparam: "hello" }}) + client.get(endpoint, { params: { videoID: "oldGetSponsorTime0", fakeparam: "hello" } }) .then(res => { assert.strictEqual(res.status, 200); done(); diff --git a/test/cases/oldSubmitSponsorTimes.ts b/test/cases/oldSubmitSponsorTimes.ts index f3f4501..ca5edf6 100644 --- a/test/cases/oldSubmitSponsorTimes.ts +++ b/test/cases/oldSubmitSponsorTimes.ts @@ -1,4 +1,4 @@ -import { partialDeepEquals } from "../utils/partialDeepEquals";import {db} from "../../src/databases/databases"; +import { partialDeepEquals } from "../utils/partialDeepEquals";import { db } from "../../src/databases/databases"; import assert from "assert"; import { client } from "../utils/httpClient"; @@ -9,7 +9,7 @@ const endpoint = "/api/postVideoSponsorTimes"; describe("postVideoSponsorTime (Old submission method)", () => { it("Should be able to submit a time (GET)", (done) => { - client.get(endpoint, { params: { videoID: videoID1, startTime: 1, endTime: 10, userID }}) + client.get(endpoint, { params: { videoID: videoID1, startTime: 1, endTime: 10, userID } }) .then(async res => { assert.strictEqual(res.status, 200); const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID1]); @@ -45,7 +45,7 @@ describe("postVideoSponsorTime (Old submission method)", () => { }); it("Should return 400 for missing params", (done) => { - client.post(endpoint, { params: { startTime: 1, endTime: 10, userID }}) + client.post(endpoint, { params: { startTime: 1, endTime: 10, userID } }) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/postClearCache.ts b/test/cases/postClearCache.ts index d1d71d6..bcaf141 100644 --- a/test/cases/postClearCache.ts +++ b/test/cases/postClearCache.ts @@ -1,8 +1,8 @@ import fetch from "node-fetch"; import { Done } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; import assert from "assert"; const VIPUser = "clearCacheVIP"; diff --git a/test/cases/postPurgeAllSegments.ts b/test/cases/postPurgeAllSegments.ts index dc34ce3..4fc0874 100644 --- a/test/cases/postPurgeAllSegments.ts +++ b/test/cases/postPurgeAllSegments.ts @@ -1,9 +1,9 @@ import fetch from "node-fetch"; -import {Done, postJSON} from "../utils/utils"; +import { Done, postJSON } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; -import {IDatabase} from "../../src/databases/IDatabase"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import { IDatabase } from "../../src/databases/IDatabase"; import assert from "assert"; async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) { diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index ea77d23..829eed6 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -1,13 +1,13 @@ import fetch from "node-fetch"; -import {config} from "../../src/config"; -import {getHash} from "../../src/utils/getHash"; +import { config } from "../../src/config"; +import { getHash } from "../../src/utils/getHash"; import { Done, postJSON } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; -import {db} from "../../src/databases/databases"; -import {ImportMock} from "ts-mock-imports"; +import { db } from "../../src/databases/databases"; +import { ImportMock } from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; -import {YouTubeApiMock} from "../youtubeMock"; +import { YouTubeApiMock } from "../youtubeMock"; import assert from "assert"; const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); diff --git a/test/cases/postWarning.ts b/test/cases/postWarning.ts index 2dedef5..81ea56e 100644 --- a/test/cases/postWarning.ts +++ b/test/cases/postWarning.ts @@ -2,8 +2,8 @@ import fetch from "node-fetch"; import { Done, postJSON } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; import assert from "assert"; describe("postWarning", () => { diff --git a/test/cases/segmentShift.ts b/test/cases/segmentShift.ts index 430710b..5c1c80c 100644 --- a/test/cases/segmentShift.ts +++ b/test/cases/segmentShift.ts @@ -1,9 +1,9 @@ import fetch from "node-fetch"; -import {Done, postJSON} from "../utils/utils"; +import { Done, postJSON } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; -import {db} from "../../src/databases/databases"; -import {getHash} from "../../src/utils/getHash"; -import {IDatabase} from "../../src/databases/IDatabase"; +import { db } from "../../src/databases/databases"; +import { getHash } from "../../src/utils/getHash"; +import { IDatabase } from "../../src/databases/IDatabase"; import assert from "assert"; describe("segmentShift", function () { diff --git a/test/cases/shadowBanUser.ts b/test/cases/shadowBanUser.ts index d167fd8..d78ed78 100644 --- a/test/cases/shadowBanUser.ts +++ b/test/cases/shadowBanUser.ts @@ -1,8 +1,8 @@ import fetch from "node-fetch"; -import {db} from "../../src/databases/databases"; +import { db } from "../../src/databases/databases"; import { Done } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; -import {getHash} from "../../src/utils/getHash"; +import { getHash } from "../../src/utils/getHash"; import assert from "assert"; import { Category } from "../../src/types/segments.model"; diff --git a/test/cases/testUtils.ts b/test/cases/testUtils.ts index f60156a..fb252b6 100644 --- a/test/cases/testUtils.ts +++ b/test/cases/testUtils.ts @@ -15,8 +15,8 @@ describe("Test utils ", () => { false ), "Did not match empty expect"); assert(partialDeepEquals( - [{a: [1,2,3]}, {a: [1,2]}], - [{a: [1,2,3]}, {a: [1,2]}] + [{ a: [1,2,3] }, { a: [1,2] }], + [{ a: [1,2,3] }, { a: [1,2] }] ), "Did not match same arrays"); assert(partialDeepEquals( { diff --git a/test/cases/voteOnSponsorTime.ts b/test/cases/voteOnSponsorTime.ts index 5929f94..28a740b 100644 --- a/test/cases/voteOnSponsorTime.ts +++ b/test/cases/voteOnSponsorTime.ts @@ -1,12 +1,12 @@ import fetch from "node-fetch"; -import {config} from "../../src/config"; -import {db} from "../../src/databases/databases"; +import { config } from "../../src/config"; +import { db } from "../../src/databases/databases"; import { Done } from "../utils/utils"; import { getbaseURL } from "../utils/getBaseURL"; -import {getHash} from "../../src/utils/getHash"; -import {ImportMock} from "ts-mock-imports"; +import { getHash } from "../../src/utils/getHash"; +import { ImportMock } from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; -import {YouTubeApiMock} from "../youtubeMock"; +import { YouTubeApiMock } from "../youtubeMock"; import assert from "assert"; const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); diff --git a/test/mocks.ts b/test/mocks.ts index ece1b65..a5c578e 100644 --- a/test/mocks.ts +++ b/test/mocks.ts @@ -1,5 +1,5 @@ import express from "express"; -import {config} from "../src/config"; +import { config } from "../src/config"; import { Server } from "http"; const app = express(); diff --git a/test/test.ts b/test/test.ts index 992fb01..904ec1d 100644 --- a/test/test.ts +++ b/test/test.ts @@ -1,12 +1,12 @@ import Mocha from "mocha"; import fs from "fs"; import path from "path"; -import {config} from "../src/config"; -import {createServer} from "../src/app"; -import {createMockServer} from "./mocks"; -import {Logger} from "../src/utils/logger"; -import {initDb} from "../src/databases/databases"; -import {ImportMock} from "ts-mock-imports"; +import { config } from "../src/config"; +import { createServer } from "../src/app"; +import { createMockServer } from "./mocks"; +import { Logger } from "../src/utils/logger"; +import { initDb } from "../src/databases/databases"; +import { ImportMock } from "ts-mock-imports"; import * as rateLimitMiddlewareModule from "../src/middleware/requestRateLimit"; import rateLimit from "express-rate-limit"; From 4e50f0ab4b63817f1e5c92ed4b8e85382bd0fc96 Mon Sep 17 00:00:00 2001 From: Michael C Date: Wed, 22 Sep 2021 23:18:31 -0400 Subject: [PATCH 13/14] remaining tests --- test/cases/postClearCache.ts | 37 +- test/cases/postPurgeAllSegments.ts | 35 +- test/cases/postSkipSegments.ts | 826 ++++++++++++++--------------- test/cases/postWarning.ts | 45 +- test/cases/segmentShift.ts | 101 ++-- test/cases/setUsername.ts | 133 ++--- test/cases/shadowBanUser.ts | 95 +++- test/cases/unBan.ts | 27 +- test/cases/voteOnSponsorTime.ts | 206 +++---- 9 files changed, 743 insertions(+), 762 deletions(-) diff --git a/test/cases/postClearCache.ts b/test/cases/postClearCache.ts index bcaf141..7269e3e 100644 --- a/test/cases/postClearCache.ts +++ b/test/cases/postClearCache.ts @@ -1,13 +1,12 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { db } from "../../src/databases/databases"; import { getHash } from "../../src/utils/getHash"; import assert from "assert"; +import { client } from "../utils/httpClient"; const VIPUser = "clearCacheVIP"; const regularUser = "regular-user"; -const endpoint = `${getbaseURL()}/api/clearCache`; +const endpoint = "/api/clearCache"; +const postClearCache = (userID: string, videoID: string) => client({ method: "post", url: endpoint, params: { userID, videoID } }); describe("postClearCache", () => { before(async () => { @@ -16,10 +15,8 @@ describe("postClearCache", () => { 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) => { - fetch(`${endpoint}?userID=${VIPUser}&videoID=clear-test`, { - method: "POST" - }) + it("Should be able to clear cache for existing video", (done) => { + postClearCache(VIPUser, "clear-test") .then(res => { assert.strictEqual(res.status, 200); done(); @@ -27,10 +24,8 @@ describe("postClearCache", () => { .catch(err => done(err)); }); - it("Should be able to clear cache for nonexistent video", (done: Done) => { - fetch(`${endpoint}?userID=${VIPUser}&videoID=dne-video`, { - method: "POST" - }) + it("Should be able to clear cache for nonexistent video", (done) => { + postClearCache(VIPUser, "dne-video") .then(res => { assert.strictEqual(res.status, 200); done(); @@ -38,10 +33,8 @@ describe("postClearCache", () => { .catch(err => done(err)); }); - it("Should get 403 as non-vip", (done: Done) => { - fetch(`${endpoint}?userID=${regularUser}&videoID=clear-tes`, { - method: "POST" - }) + it("Should get 403 as non-vip", (done) => { + postClearCache(regularUser, "clear-test") .then(async res => { assert.strictEqual(res.status, 403); done(); @@ -49,10 +42,8 @@ describe("postClearCache", () => { .catch(err => done(err)); }); - it("Should give 400 with missing videoID", (done: Done) => { - fetch(`${endpoint}?userID=${VIPUser}`, { - method: "POST" - }) + it("Should give 400 with missing videoID", (done) => { + client.post(endpoint, { params: { userID: VIPUser } }) .then(async res => { assert.strictEqual(res.status, 400); done(); @@ -60,10 +51,8 @@ describe("postClearCache", () => { .catch(err => done(err)); }); - it("Should give 400 with missing userID", (done: Done) => { - fetch(`${endpoint}?userID=${VIPUser}`, { - method: "POST" - }) + it("Should give 400 with missing userID", (done) => { + client.post(endpoint, { params: { videoID: "clear-test" } }) .then(async res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/postPurgeAllSegments.ts b/test/cases/postPurgeAllSegments.ts index 4fc0874..9d9c675 100644 --- a/test/cases/postPurgeAllSegments.ts +++ b/test/cases/postPurgeAllSegments.ts @@ -1,10 +1,8 @@ -import fetch from "node-fetch"; -import { Done, postJSON } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { db } from "../../src/databases/databases"; import { getHash } from "../../src/utils/getHash"; import { IDatabase } from "../../src/databases/IDatabase"; import assert from "assert"; +import { client } from "../utils/httpClient"; async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) { const votes = 0, @@ -34,7 +32,8 @@ async function dbSponsorTimesCompareExpect(db: IDatabase, videoId: string, expec describe("postPurgeAllSegments", function () { const privateVipUserID = "VIPUser-purgeAll"; const vipUserID = getHash(privateVipUserID); - const endpoint = `${getbaseURL()}/api/purgeAllSegments`; + const endpoint = "/api/purgeAllSegments"; + const postSegmentShift = (videoID: string, userID: string) => client.post(endpoint, { videoID, userID }); before(async function () { // startTime and endTime get set in beforeEach for consistency @@ -46,29 +45,17 @@ describe("postPurgeAllSegments", function () { await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES (?)`, [vipUserID]); }); - it("Reject non-VIP user", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegpurge01", - userID: "segshift_randomuser001", - }), - }) - .then(async res => { + it("Reject non-VIP user", function (done) { + postSegmentShift("vsegpurge01", "segshift_randomuser001") + .then(res => { assert.strictEqual(res.status, 403); done(); }) .catch(err => done(err)); }); - it("Purge all segments success", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegpurge01", - userID: privateVipUserID, - }), - }) + it("Purge all segments success", function (done) { + postSegmentShift("vsegpurge01", privateVipUserID) .then(async res => { assert.strictEqual(res.status, 200); done(await dbSponsorTimesCompareExpect(db, "vsegpurge01", 1) || await dbSponsorTimesCompareExpect(db, "vseg-not-purged01", 0)); @@ -76,9 +63,9 @@ describe("postPurgeAllSegments", function () { .catch(err => done(err)); }); - it("Should return 400 if missing body", function (done: Done) { - fetch(endpoint, { ...postJSON }) - .then(async res => { + it("Should return 400 if missing body", function (done) { + client.post(endpoint, {}) + .then(res => { assert.strictEqual(res.status, 400); done(); }) diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index 829eed6..3e0e89a 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -1,14 +1,12 @@ -import fetch from "node-fetch"; import { config } from "../../src/config"; import { getHash } from "../../src/utils/getHash"; -import { Done, postJSON } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import { db } from "../../src/databases/databases"; import { ImportMock } from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; import { YouTubeApiMock } from "../youtubeMock"; import assert from "assert"; +import { client } from "../utils/httpClient"; const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const sinonStub = mockManager.mock("listVideos"); @@ -38,7 +36,17 @@ describe("postSkipSegments", () => { const queryDatabaseActionType = (videoID: string) => db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); const queryDatabaseDuration = (videoID: string) => db.prepare("get", `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID]); - const endpoint = `${getbaseURL()}/api/skipSegments`; + const endpoint = "/api/skipSegments"; + const postSkipSegmentJSON = (data: Record) => client({ + method: "POST", + url: endpoint, + data + }); + const postSkipSegmentParam = (params: Record) => client({ + method: "POST", + url: endpoint, + params + }); before(() => { const insertSponsorTimeQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "UUID", "userID", "timeSubmitted", views, category, "shadowHidden", "hashedVideoID") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; @@ -81,10 +89,14 @@ describe("postSkipSegments", () => { db.prepare("run", insertVipUserQuery, [getHash(submitVIPuser)]); }); - it("Should be able to submit a single time (Params method)", (done: Done) => { + it("Should be able to submit a single time (Params method)", (done) => { const videoID = "dQw4w9WgXcR"; - fetch(`${endpoint}?videoID=${videoID}&startTime=2&endTime=10&userID=${submitUserOne}&category=sponsor`, { - method: "POST" + postSkipSegmentParam({ + videoID, + startTime: 2, + endTime: 10, + userID: submitUserOne, + category: "sponsor" }) .then(async res => { assert.strictEqual(res.status, 200); @@ -100,18 +112,15 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit a single time (JSON method)", (done: Done) => { + it("Should be able to submit a single time (JSON method)", (done) => { const videoID = "dQw4w9WgXcF"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [0, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -128,19 +137,16 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit a single time with an action type (JSON method)", (done: Done) => { + it("Should be able to submit a single time with an action type (JSON method)", (done) => { const videoID = "dQw4w9WgXcV"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [0, 10], - category: "sponsor", - actionType: "mute" - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [0, 10], + category: "sponsor", + actionType: "mute" + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -157,19 +163,16 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should not be able to submit an intro with mute action type (JSON method)", (done: Done) => { + it("Should not be able to submit an intro with mute action type (JSON method)", (done) => { const videoID = "dQw4w9WgXpQ"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [0, 10], - category: "intro", - actionType: "mute" - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [0, 10], + category: "intro", + actionType: "mute" + }], }) .then(async res => { assert.strictEqual(res.status, 400); @@ -180,19 +183,16 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit a single time with a duration from the YouTube API (JSON method)", (done: Done) => { + it("Should be able to submit a single time with a duration from the YouTube API (JSON method)", (done) => { const videoID = "dQw4w9WgXZX"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - videoDuration: 100, - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + videoDuration: 100, + segments: [{ + segment: [0, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -209,19 +209,16 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit a single time with a precise duration close to the one from the YouTube API (JSON method)", (done: Done) => { + it("Should be able to submit a single time with a precise duration close to the one from the YouTube API (JSON method)", (done) => { const videoID = "dQw4w9WgXZH"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - videoDuration: 4980.20, - segments: [{ - segment: [1, 10], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + videoDuration: 4980.20, + segments: [{ + segment: [1, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -239,19 +236,16 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit a single time with a duration in the body (JSON method)", (done: Done) => { + it("Should be able to submit a single time with a duration in the body (JSON method)", (done) => { const videoID = "noDuration"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - videoDuration: 100, - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + videoDuration: 100, + segments: [{ + segment: [0, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -275,17 +269,14 @@ describe("postSkipSegments", () => { VALUES(?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "sponsor"]); try { - const res = await fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - videoDuration: 100, - segments: [{ - segment: [1, 10], - category: "sponsor", - }], - }), + const res = await postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + videoDuration: 100, + segments: [{ + segment: [1, 10], + category: "sponsor", + }], }); assert.strictEqual(res.status, 200); const lockCategoriesRow = await db.prepare("get", `SELECT * from "lockCategories" WHERE videoID = ?`, [videoID]); @@ -309,10 +300,16 @@ describe("postSkipSegments", () => { } }); - it("Should still not be allowed if youtube thinks duration is 0", (done: Done) => { + it("Should still not be allowed if youtube thinks duration is 0", (done) => { const videoID= "noDuration"; - fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=10000&userID=${submitUserThree}&category=sponsor`, { - method: "POST", + postSkipSegmentJSON({ + userID: submitUserThree, + videoID, + videoDuration: 100, + segments: [{ + segment: [30, 10000], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 403); @@ -321,19 +318,16 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit a single time under a different service (JSON method)", (done: Done) => { + it("Should be able to submit a single time under a different service (JSON method)", (done) => { const videoID = "dQw4w9WgXcG"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - service: "PeerTube", - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + service: "PeerTube", + segments: [{ + segment: [0, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -351,18 +345,15 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("VIP submission should start locked", (done: Done) => { + it("VIP submission should start locked", (done) => { const videoID = "vipuserIDSubmission"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitVIPuser, - videoID, - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitVIPuser, + videoID, + segments: [{ + segment: [0, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -379,21 +370,18 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit multiple times (JSON method)", (done: Done) => { + it("Should be able to submit multiple times (JSON method)", (done) => { const videoID = "dQw4w9WgXcT"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [3, 10], - category: "sponsor", - }, { - segment: [30, 60], - category: "intro", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [3, 10], + category: "sponsor", + }, { + segment: [30, 60], + category: "intro", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -413,27 +401,24 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }).timeout(5000); - it("Should allow multiple times if total is under 80% of video(JSON method)", (done: Done) => { + it("Should allow multiple times if total is under 80% of video(JSON method)", (done) => { const videoID = "L_jWHffIx5E"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [3, 3000], - category: "sponsor", - }, { - segment: [3002, 3050], - category: "intro", - }, { - segment: [45, 100], - category: "interaction", - }, { - segment: [99, 170], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [3, 3000], + category: "sponsor", + }, { + segment: [3002, 3050], + category: "intro", + }, { + segment: [45, 100], + category: "interaction", + }, { + segment: [99, 170], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 200); @@ -461,27 +446,24 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }).timeout(5000); - it("Should reject multiple times if total is over 80% of video (JSON method)", (done: Done) => { + it("Should reject multiple times if total is over 80% of video (JSON method)", (done) => { const videoID = "n9rIGdXnSJc"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [0, 2000], - category: "interaction", - }, { - segment: [3000, 4000], - category: "sponsor", - }, { - segment: [1500, 2750], - category: "sponsor", - }, { - segment: [4050, 4750], - category: "intro", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [0, 2000], + category: "interaction", + }, { + segment: [3000, 4000], + category: "sponsor", + }, { + segment: [1500, 2750], + category: "sponsor", + }, { + segment: [4050, 4750], + category: "intro", + }], }) .then(async res => { assert.strictEqual(res.status, 403); @@ -492,24 +474,21 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }).timeout(5000); - it("Should reject multiple times if total is over 80% of video including previosuly submitted times(JSON method)", (done: Done) => { + it("Should reject multiple times if total is over 80% of video including previosuly submitted times(JSON method)", (done) => { const videoID = "80percent_video"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [2000, 4000], - category: "sponsor", - }, { - segment: [1500, 2750], - category: "sponsor", - }, { - segment: [4050, 4750], - category: "sponsor", - }], - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [2000, 4000], + category: "sponsor", + }, { + segment: [1500, 2750], + category: "sponsor", + }, { + segment: [4050, 4750], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 403); @@ -533,10 +512,14 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }).timeout(5000); - it("Should be accepted if a non-sponsor is less than 1 second", (done: Done) => { + it("Should be accepted if a non-sponsor is less than 1 second", (done) => { const videoID = "qqwerty"; - fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30.5&userID=${submitUserTwo}&category=intro`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 30, + endTime: 30.5, + userID: submitUserTwo, + category: "intro" }) .then(res => { assert.strictEqual(res.status, 200); @@ -545,10 +528,14 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be rejected if segment starts and ends at the same time", (done: Done) => { + it("Should be rejected if segment starts and ends at the same time", (done) => { const videoID = "qqwerty"; - fetch(`${endpoint}?videoID=${videoID}&startTime=90&endTime=90&userID=${submitUserTwo}&category=intro`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 90, + endTime: 90, + userID: submitUserTwo, + category: "intro" }) .then(res => { assert.strictEqual(res.status, 400); @@ -557,10 +544,14 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be accepted if highlight segment starts and ends at the same time", (done: Done) => { + it("Should be accepted if highlight segment starts and ends at the same time", (done) => { const videoID = "qqwerty"; - fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30&userID=${submitUserTwo}&category=poi_highlight`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 30, + endTime: 30, + userID: submitUserTwo, + category: "poi_highlight" }) .then(res => { assert.strictEqual(res.status, 200); @@ -569,10 +560,14 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be rejected if highlight segment doesn't start and end at the same time", (done: Done) => { + it("Should be rejected if highlight segment doesn't start and end at the same time", (done) => { const videoID = "qqwerty"; - fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30.5&userID=${submitUserTwo}&category=poi_highlight`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 30, + endTime: 30.5, + userID: submitUserTwo, + category: "poi_highlight" }) .then(res => { assert.strictEqual(res.status, 400); @@ -581,10 +576,13 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be rejected if a sponsor is less than 1 second", (done: Done) => { + it("Should be rejected if a sponsor is less than 1 second", (done) => { const videoID = "qqwerty"; - fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=30.5&userID=${submitUserTwo}`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 30, + endTime: 30.5, + userID: submitUserTwo }) .then(res => { assert.strictEqual(res.status, 400); @@ -593,45 +591,50 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be rejected if over 80% of the video", (done: Done) => { + it("Should be rejected if over 80% of the video", (done) => { const videoID = "qqwerty"; - fetch(`${endpoint}?videoID=${videoID}&startTime=30&endTime=1000000&userID=${submitUserTwo}&category=sponsor`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 30, + endTime: 1000000, + userID: submitUserTwo, + category: "sponsor" }) - .then( async res => { + .then(res => { assert.strictEqual(res.status, 403); done(); }) .catch(err => done(err)); }); - it("Should be rejected if NB's predicted probability is <70%.", (done: Done) => { + it("Should be rejected if NB's predicted probability is <70%.", (done) => { const videoID = "LevkAjUE6d4"; - fetch(`${endpoint}?videoID=${videoID}&startTime=40&endTime=60&userID=${submitUserTwo}&category=sponsor`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 40, + endTime: 60, + userID: submitUserTwo, + category: "sponsor" }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 200); done(); }) .catch(err => done(err)); }); - it("Should be rejected with custom message if user has to many active warnings", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: warnUser01, - videoID: warnVideoID, - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - }), + it("Should be rejected with custom message if user has to many active warnings", (done) => { + postSkipSegmentJSON({ + userID: warnUser01, + videoID: warnVideoID, + segments: [{ + segment: [0, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 403); - const errorMessage = await res.text(); + const errorMessage = res.data; const reason = "Reason01"; const expected = "Submission rejected due to a warning from a moderator. This means that we noticed you were making some common mistakes" + " that are not malicious, and we just want to clarify the rules. " @@ -644,97 +647,85 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be accepted if user has some active warnings", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: warnUser02, - videoID: warnVideoID, - segments: [{ - segment: [50, 60], - category: "sponsor", - }], - }), + it("Should be accepted if user has some active warnings", (done) => { + postSkipSegmentJSON({ + userID: warnUser02, + videoID: warnVideoID, + segments: [{ + segment: [50, 60], + category: "sponsor", + }], }) - .then(async res => { + .then(res => { if (res.status === 200) { done(); // success } else { - const body = await res.text(); - done(`Status code was ${res.status} ${body}`); + done(`Status code was ${res.status} ${res.data}`); } }) .catch(err => done(err)); }); - it("Should be accepted if user has some warnings removed", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: warnUser03, - videoID: warnVideoID, - segments: [{ - segment: [53, 60], - category: "sponsor", - }], - }), + it("Should be accepted if user has some warnings removed", (done) => { + postSkipSegmentJSON({ + userID: warnUser03, + videoID: warnVideoID, + segments: [{ + segment: [53, 60], + category: "sponsor", + }], }) - .then(async res => { + .then(res => { if (res.status === 200) { done(); // success } else { - const body = await res.text(); - done(`Status code was ${res.status} ${body}`); + done(`Status code was ${res.status} ${res.data}`); } }) .catch(err => done(err)); }); - it("Should return 400 for missing params (Params method)", (done: Done) => { - fetch(`${endpoint}?startTime=9&endTime=10&userID=${submitUserOne}`, { - method: "POST", + it("Should return 400 for missing params (Params method)", (done) => { + postSkipSegmentParam({ + startTime: 9, + endTime: 10, + userID: submitUserOne }) - .then(async res => { + .then(res => { if (res.status === 400) done(); else done(true); }) .catch(err => done(err)); }); - it("Should be rejected with default message if user has to many active warnings", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: warnUser01, - videoID: warnVideoID, - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - }), + it("Should be rejected with default message if user has to many active warnings", (done) => { + postSkipSegmentJSON({ + userID: warnUser01, + videoID: warnVideoID, + segments: [{ + segment: [0, 10], + category: "sponsor", + }], }) .then(async res => { assert.strictEqual(res.status, 403); - const errorMessage = await res.text(); + const errorMessage = res.data; assert.notStrictEqual(errorMessage, ""); done(); }) .catch(err => done(err)); }); - it("Should return 400 for missing params (JSON method) 1", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - segments: [{ - segment: [9, 10], - category: "sponsor", - }, { - segment: [31, 60], - category: "intro", - }], - }), + it("Should return 400 for missing params (JSON method) 1", (done) => { + postSkipSegmentJSON({ + userID: submitUserOne, + segments: [{ + segment: [9, 10], + category: "sponsor", + }, { + segment: [31, 60], + category: "intro", + }], }) .then(res => { assert.strictEqual(res.status, 400); @@ -742,13 +733,10 @@ describe("postSkipSegments", () => { }) .catch(err => done(err)); }); - it("Should return 400 for missing params (JSON method) 2", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID: badInputVideoID, - }), + it("Should return 400 for missing params (JSON method) 2", (done) => { + postSkipSegmentJSON({ + userID: submitUserOne, + videoID: badInputVideoID, }) .then(res => { assert.strictEqual(res.status, 400); @@ -756,54 +744,17 @@ describe("postSkipSegments", () => { }) .catch(err => done(err)); }); - it("Should return 400 for missing params (JSON method) 3", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID: badInputVideoID, - segments: [{ - segment: [0], - category: "sponsor", - }, { - segment: [31, 60], - category: "intro", - }], - }), - }) - .then(res => { - assert.strictEqual(res.status, 400); - done(); - }) - .catch(err => done(err)); - }); - it("Should return 400 for missing params (JSON method) 4", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID: badInputVideoID, - segments: [{ - segment: [9, 10], - }, { - segment: [31, 60], - category: "intro", - }], - }), - }) - .then(res => { - assert.strictEqual(res.status, 400); - done(); - }) - .catch(err => done(err)); - }); - it("Should return 400 for missing params (JSON method) 5", (done: Done) => { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID: badInputVideoID, - }), + it("Should return 400 for missing params (JSON method) 3", (done) => { + postSkipSegmentJSON({ + userID: submitUserOne, + videoID: badInputVideoID, + segments: [{ + segment: [0], + category: "sponsor", + }, { + segment: [31, 60], + category: "intro", + }], }) .then(res => { assert.strictEqual(res.status, 400); @@ -812,73 +763,94 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should return 403 and custom reason for submiting in lockedCategory", async () => { + it("Should return 400 for missing params (JSON method) 4", (done) => { + postSkipSegmentJSON({ + userID: submitUserOne, + videoID: badInputVideoID, + segments: [{ + segment: [9, 10], + }, { + segment: [31, 60], + category: "intro", + }], + }) + .then(res => { + assert.strictEqual(res.status, 400); + done(); + }) + .catch(err => done(err)); + }); + + it("Should return 400 for missing params (JSON method) 5", (done) => { + postSkipSegmentJSON({ + userID: submitUserOne, + videoID: badInputVideoID, + }) + .then(res => { + assert.strictEqual(res.status, 400); + done(); + }) + .catch(err => done(err)); + }); + + it("Should return 403 and custom reason for submiting in lockedCategory", (done) => { const videoID = "lockedVideo"; - await db.prepare("run", `INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") - VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "sponsor", "Custom Reason"]); - - try { - const res = await fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [1, 10], - category: "sponsor", - }], - }), - }); - - assert.strictEqual(res.status, 403); - assert.match(await res.text(), /Lock reason: /); - assert.match(await res.text(), /Custom Reason/); - } catch (e) { - return e; - } + db.prepare("run", `INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") + VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "sponsor", "Custom Reason"]) + .then(() => postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [1, 10], + category: "sponsor", + }], + })) + .then(res => { + assert.strictEqual(res.status, 403); + assert.match(res.data, /Lock reason: /); + assert.match(res.data, /Custom Reason/); + done(); + }) + .catch(err => done(err)); }); - it("Should return 403 for submiting in lockedCategory", async () => { + it("Should return 403 for submiting in lockedCategory", (done) => { const videoID = "lockedVideo1"; - await db.prepare("run", `INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") - VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "intro", ""]); + db.prepare("run", `INSERT INTO "lockCategories" ("userID", "videoID", "category", "reason") + VALUES(?, ?, ?, ?)`, [getHash("VIPUser-lockCategories"), videoID, "intro", ""]) + .then(() => postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: [1, 10], + category: "intro", + }], + })) + .then(res => { + assert.strictEqual(res.status, 403); + assert.doesNotMatch(res.data, /Lock reason: /); + assert.doesNotMatch(res.data, /Custom Reason/); + done(); + }) + .catch(err => done(err)); + }); - try { - const res = await fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: [1, 10], - category: "intro", - }], - }), - }); - - assert.strictEqual(res.status, 403); - assert.doesNotMatch(await res.text(), /Lock reason: /); - assert.doesNotMatch(await res.text(), /Custom Reason/); - } catch (e) { - return e; - } - }).timeout(5000); - - it("Should be able to submit with custom user-agent 1", (done: Done) => { - fetch(endpoint, { + it("Should be able to submit with custom user-agent 1", (done) => { + client({ + url: endpoint, method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "com.google.android.youtube/5.0" }, - body: JSON.stringify({ + data: { userID: submitUserOne, videoID: "userAgent-1", segments: [{ segment: [0, 10], category: "sponsor", }], - }), + } }) .then(async res => { assert.strictEqual(res.status, 200); @@ -894,21 +866,19 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit with empty user-agent", (done: Done) => { - fetch(endpoint, { + it("Should be able to submit with empty user-agent", (done) => { + client({ + url: endpoint, method: "POST", - headers: { - "Content-Type": "application/json", - "User-Agent": "" - }, - body: JSON.stringify({ + data: { userID: submitUserOne, videoID: "userAgent-3", segments: [{ segment: [0, 10], category: "sponsor", }], - }), + userAgent: "", + } }) .then(async res => { assert.strictEqual(res.status, 200); @@ -924,21 +894,15 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit with custom userAgent in body", (done: Done) => { - fetch(endpoint, { - method: "POST", - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify({ - userID: submitUserOne, - videoID: "userAgent-4", - segments: [{ - segment: [0, 10], - category: "sponsor", - }], - userAgent: "MeaBot/5.0" - }), + it("Should be able to submit with custom userAgent in body", (done) => { + postSkipSegmentJSON({ + userID: submitUserOne, + videoID: "userAgent-4", + segments: [{ + segment: [0, 10], + category: "sponsor", + }], + userAgent: "MeaBot/5.0" }) .then(async res => { assert.strictEqual(res.status, 200); @@ -954,18 +918,15 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be able to submit with commas in timestamps", (done: Done) => { + it("Should be able to submit with commas in timestamps", (done) => { const videoID = "commas-1"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: ["0,2", "10,392"], - category: "sponsor", - }] - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: ["0,2", "10,392"], + category: "sponsor", + }] }) .then(async res => { assert.strictEqual(res.status, 200); @@ -980,10 +941,14 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should be rejected if a POI is at less than 1 second", (done: Done) => { + it("Should be rejected if a POI is at less than 1 second", (done) => { const videoID = "qqwerty"; - fetch(`${endpoint}?videoID=${videoID}&startTime=0.5&endTime=0.5&category=poi_highlight&userID=${submitUserTwo}`, { - method: "POST", + postSkipSegmentParam({ + videoID, + startTime: 0.5, + endTime: 0.5, + category: "poi_highlight", + userID: submitUserTwo }) .then(res => { assert.strictEqual(res.status, 400); @@ -992,18 +957,15 @@ describe("postSkipSegments", () => { .catch(err => done(err)); }); - it("Should not be able to submit with colons in timestamps", (done: Done) => { + it("Should not be able to submit with colons in timestamps", (done) => { const videoID = "colon-1"; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - userID: submitUserOne, - videoID, - segments: [{ - segment: ["0:2.000", "3:10.392"], - category: "sponsor", - }] - }), + postSkipSegmentJSON({ + userID: submitUserOne, + videoID, + segments: [{ + segment: ["0:2.000", "3:10.392"], + category: "sponsor", + }] }) .then(res => { assert.strictEqual(res.status, 400); diff --git a/test/cases/postWarning.ts b/test/cases/postWarning.ts index 81ea56e..d4bb0c2 100644 --- a/test/cases/postWarning.ts +++ b/test/cases/postWarning.ts @@ -1,30 +1,25 @@ -import fetch from "node-fetch"; -import { Done, postJSON } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { partialDeepEquals } from "../utils/partialDeepEquals"; import { db } from "../../src/databases/databases"; import { getHash } from "../../src/utils/getHash"; import assert from "assert"; +import { client } from "../utils/httpClient"; describe("postWarning", () => { // constants - const endpoint = `${getbaseURL()}/api/warnUser`; + const endpoint = "/api/warnUser"; const getWarning = (userID: string) => db.prepare("get", `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [userID]); before(async () => { 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 = { issuerUserID: "warning-vip", userID: "warning-0", reason: "warning-reason-0" }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const row = await getWarning(json.userID); @@ -39,16 +34,13 @@ describe("postWarning", () => { .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 = { issuerUserID: "warning-vip", userID: "warning-0", }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 409); const row = await getWarning(json.userID); @@ -62,17 +54,14 @@ describe("postWarning", () => { .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 = { issuerUserID: "warning-vip", userID: "warning-0", enabled: false }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const row = await getWarning(json.userID); @@ -85,16 +74,13 @@ describe("postWarning", () => { .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 = { issuerUserID: "warning-not-vip", userID: "warning-1", }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(res => { assert.strictEqual(res.status, 403); done(); @@ -102,8 +88,8 @@ describe("postWarning", () => { .catch(err => done(err)); }); - it("Should return 400 if missing body", (done: Done) => { - fetch(endpoint, postJSON) + it("Should return 400 if missing body", (done) => { + client.post(endpoint, {}) .then(async res => { assert.strictEqual(res.status, 400); done(); @@ -111,17 +97,14 @@ describe("postWarning", () => { .catch(err => done(err)); }); - it("Should re-enable disabled warning", (done: Done) => { + it("Should re-enable disabled warning", (done) => { const json = { issuerUserID: "warning-vip", userID: "warning-0", enabled: true }; - fetch(endpoint, { - ...postJSON, - body: JSON.stringify(json), - }) + client.post(endpoint, json) .then(async res => { assert.strictEqual(res.status, 200); const data = await getWarning(json.userID); diff --git a/test/cases/segmentShift.ts b/test/cases/segmentShift.ts index 5c1c80c..33fca34 100644 --- a/test/cases/segmentShift.ts +++ b/test/cases/segmentShift.ts @@ -1,10 +1,8 @@ -import fetch from "node-fetch"; -import { Done, postJSON } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { db } from "../../src/databases/databases"; import { getHash } from "../../src/utils/getHash"; import { IDatabase } from "../../src/databases/IDatabase"; import assert from "assert"; +import { client } from "../utils/httpClient"; describe("segmentShift", function () { // functions @@ -42,7 +40,12 @@ describe("segmentShift", function () { // constants const privateVipUserID = "VIPUser-segmentShift"; const vipUserID = getHash(privateVipUserID); - const endpoint = `${getbaseURL()}/api/segmentShift`; + const endpoint = "/api/segmentShift"; + const postSegmentShift = async (data: Record) => client({ + method: "POST", + url: endpoint, + data, + }); before(async function () { // startTime and endTime get set in beforeEach for consistency @@ -61,15 +64,12 @@ describe("segmentShift", function () { await dbSponsorTimesSetByUUID(db, "vsegshifttest01uuid04", 120, 140); }); - it("Reject none VIP user", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegshift01", - userID: "segshift_randomuser001", - startTime: 20, - endTime: 30, - }), + it("Reject non VIP user", (done) => { + postSegmentShift({ + videoID: "vsegshift01", + userID: "segshift_randomuser001", + startTime: 20, + endTime: 30, }) .then(async res => { assert.strictEqual(res.status, 403); @@ -78,15 +78,12 @@ describe("segmentShift", function () { .catch(err => done(err)); }); - it("Shift is outside segments", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegshift01", - userID: privateVipUserID, - startTime: 20, - endTime: 30, - }), + it("Shift is outside segments", (done) => { + postSegmentShift({ + videoID: "vsegshift01", + userID: privateVipUserID, + startTime: 20, + endTime: 30, }) .then(async res => { assert.strictEqual(res.status, 200); @@ -112,15 +109,12 @@ describe("segmentShift", function () { .catch(err => done(err)); }); - it("Shift is inside segment", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegshift01", - userID: privateVipUserID, - startTime: 65, - endTime: 75, - }), + it("Shift is inside segment", (done) => { + postSegmentShift({ + videoID: "vsegshift01", + userID: privateVipUserID, + startTime: 65, + endTime: 75, }) .then(async res => { assert.strictEqual(res.status, 200); @@ -146,15 +140,12 @@ describe("segmentShift", function () { .catch(err => done(err)); }); - it("Shift is overlaping startTime of segment", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegshift01", - userID: privateVipUserID, - startTime: 32, - endTime: 42, - }), + it("Shift is overlaping startTime of segment", (done) => { + postSegmentShift({ + videoID: "vsegshift01", + userID: privateVipUserID, + startTime: 32, + endTime: 42, }) .then(async res => { assert.strictEqual(res.status, 200); @@ -180,15 +171,12 @@ describe("segmentShift", function () { .catch(err => done(err)); }); - it("Shift is overlaping endTime of segment", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegshift01", - userID: privateVipUserID, - startTime: 85, - endTime: 95, - }), + it("Shift is overlaping endTime of segment", (done) => { + postSegmentShift({ + videoID: "vsegshift01", + userID: privateVipUserID, + startTime: 85, + endTime: 95, }) .then(async res => { assert.strictEqual(res.status, 200); @@ -214,15 +202,12 @@ describe("segmentShift", function () { .catch(err => done(err)); }); - it("Shift is overlaping segment", function (done: Done) { - fetch(endpoint, { - ...postJSON, - body: JSON.stringify({ - videoID: "vsegshift01", - userID: privateVipUserID, - startTime: 35, - endTime: 55, - }), + it("Shift is overlaping segment", (done) => { + postSegmentShift({ + videoID: "vsegshift01", + userID: privateVipUserID, + startTime: 35, + endTime: 55, }) .then(async res => { assert.strictEqual(res.status, 200); diff --git a/test/cases/setUsername.ts b/test/cases/setUsername.ts index 75f87dd..482311b 100644 --- a/test/cases/setUsername.ts +++ b/test/cases/setUsername.ts @@ -1,9 +1,7 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { db, privateDB } from "../../src/databases/databases"; import { getHash } from "../../src/utils/getHash"; import assert from "assert"; +import { client } from "../utils/httpClient"; const adminPrivateUserID = "testUserId"; const user00PrivateUserID = "setUsername_00"; @@ -52,7 +50,7 @@ function wellFormatUserName(userName: string) { 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); assert.strictEqual(newUserName, log.newUserName); assert.strictEqual(oldUserName, log.oldUserName); @@ -60,8 +58,27 @@ async function testUserNameChangelog(userID: string, newUserName: string, oldUse 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", () => { - const endpoint = `${getbaseURL()}/api/setUsername`; before(async () => { await addUsername(getHash(user01PrivateUserID), username01, 0); await addUsername(getHash(user02PrivateUserID), username02, 0); @@ -72,157 +89,147 @@ describe("setUsername", () => { await addUsername(getHash(user07PrivateUserID), username07, 1); }); - it("Should be able to set username that has never been set", (done: Done) => { - fetch(`${endpoint}?userID=${user00PrivateUserID}&username=${username00}`, { - method: "POST", - }) + it("Should be able to set username that has never been set", (done) => { + postSetUserName(user00PrivateUserID, username00) .then(async res => { + console.log(res.data); const usernameInfo = await getUsernameInfo(getHash(user00PrivateUserID)); assert.strictEqual(res.status, 200); assert.strictEqual(usernameInfo.userName, username00); assert.notStrictEqual(usernameInfo.locked, 1, "username should not be locked"); done(); }) - .catch(() => done(`couldn't call endpoint`)); + .catch((err) => done(err)); }); - it("Should return 200", (done: Done) => { - fetch(`${endpoint}?userID=${user01PrivateUserID}&username=Changed%20Username`, { - method: "POST", - }) + it("Should return 200", (done) => { + const username = "Changed%20Username"; + postSetUserName(user01PrivateUserID, username) .then(async res => { 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) => { - fetch(`${endpoint}?username=MyUsername`, { + it('Should return 400 for missing param "userID"', (done) => { + client({ method: "POST", + url: endpoint, + data: { + userName: "MyUsername" + } }) .then(res => { assert.strictEqual(res.status, 400); done(); }) - .catch(() => done(`couldn't call endpoint`)); + .catch((err) => done(err)); }); - it('Should return 400 for missing param "username"', (done: Done) => { - fetch(`${endpoint}?userID=test`, { + it('Should return 400 for missing param "username"', (done) => { + client({ method: "POST", + url: endpoint, + data: { + userID: "test" + } }) .then(res => { assert.strictEqual(res.status, 400); 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"; - fetch(`${endpoint}?userID=test&username=${encodeURIComponent(username65)}`, { - method: "POST", - }) + postSetUserName("test", username65) .then(res => { assert.strictEqual(res.status, 400); 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"; - fetch(`${endpoint}?userID=${user02PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { - method: "POST", - }) + postSetUserName(user02PrivateUserID, newUsername) .then(async res => { assert.strictEqual(res.status, 200); const userNameInfo = await getUsernameInfo(getHash(user02PrivateUserID)); assert.notStrictEqual(userNameInfo.userName, newUsername); 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"; - fetch(`${endpoint}?userID=${user03PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { - method: "POST", - }) + postSetUserName(user03PrivateUserID, newUsername) .then(async () => { const usernameInfo = await getUsernameInfo(getHash(user03PrivateUserID)); assert.strictEqual(usernameInfo.userName, newUsername, "Username should change"); assert.notStrictEqual(usernameInfo.locked, 1, "Username should not be locked"); 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"; - fetch(`${endpoint}?userID=${user04PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { - method: "POST", - }) + postSetUserName(user04PrivateUserID, newUsername) .then(async () => { const usernameInfo = await getUsernameInfo(getHash(user04PrivateUserID)); assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not be changed"); assert.strictEqual(usernameInfo.locked, 1, "username should be locked"); 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"; - fetch(`${endpoint}?userID=${user05PrivateUserID}&username=${encodeURIComponent(newUsername)}`, { - method: "POST", - }) + postSetUserName(user05PrivateUserID, newUsername) .then(async () => { const usernameInfo = await getUsernameInfo(getHash(user05PrivateUserID)); assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not contain control characters"); 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"; - fetch(`${endpoint}?adminUserID=invalidAdminID&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { - method: "POST", - }) - .then(async res => { + postSetUserNameAdmin(getHash(user06PrivateUserID), newUsername,"invalidAdminID") + .then(res => { assert.strictEqual(res.status, 403); 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"; - fetch(`${endpoint}?adminUserID=${adminPrivateUserID}&userID=${getHash(user06PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { - method: "POST", - }) + postSetUserNameAdmin(getHash(user06PrivateUserID), newUsername, adminPrivateUserID) .then(async () => { const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID)); assert.strictEqual(usernameInfo.userName, newUsername, "username should be changed"); assert.strictEqual(usernameInfo.locked, 1, "Username should be locked"); 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"; - fetch(`${endpoint}?adminUserID=${adminPrivateUserID}&userID=${getHash(user07PrivateUserID)}&username=${encodeURIComponent(newUsername)}`, { - method: "POST", - }) + postSetUserNameAdmin(getHash(user07PrivateUserID), newUsername, adminPrivateUserID) .then(async () => { const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID)); assert.strictEqual(usernameInfo.userName, newUsername, "Username should be changed"); assert.strictEqual(usernameInfo.locked, 1, "Username should be locked"); testUserNameChangelog(user07PrivateUserID, newUsername, username07, true, done); }) - .catch(() => done(`couldn't call endpoint`)); + .catch((err) => done(err)); }); }); diff --git a/test/cases/shadowBanUser.ts b/test/cases/shadowBanUser.ts index d78ed78..834382c 100644 --- a/test/cases/shadowBanUser.ts +++ b/test/cases/shadowBanUser.ts @@ -1,17 +1,15 @@ -import fetch from "node-fetch"; import { db } from "../../src/databases/databases"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { getHash } from "../../src/utils/getHash"; import assert from "assert"; import { Category } from "../../src/types/segments.model"; +import { client } from "../utils/httpClient"; describe("shadowBanUser", () => { - const endpoint = `${getbaseURL()}/api/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 () => { @@ -36,10 +34,15 @@ describe("shadowBanUser", () => { await db.prepare("run", `INSERT INTO "vipUsers" ("userID") VALUES(?)`, [getHash(VIPuserID)]); }); - it("Should be able to ban user and hide submissions", (done: Done) => { + it("Should be able to ban user and hide submissions", (done) => { const userID = "shadowBanned"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}`, { - method: "POST" + client({ + method: "POST", + url: endpoint, + params: { + userID, + adminUserID: VIPuserID, + } }) .then(async res => { assert.strictEqual(res.status, 200); @@ -52,10 +55,17 @@ describe("shadowBanUser", () => { .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) => { const userID = "shadowBanned"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=false&unHideOldSubmissions=false`, { - method: "POST" + client({ + method: "POST", + url: endpoint, + params: { + userID, + adminUserID: VIPuserID, + enabled: false, + unHideOldSubmissions: false, + } }) .then(async res => { assert.strictEqual(res.status, 200); @@ -68,10 +78,16 @@ describe("shadowBanUser", () => { .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) => { const userID = "shadowBanned2"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&categories=["sponsor"]`, { - method: "POST" + client({ + method: "POST", + url: endpoint, + params: { + userID, + adminUserID: VIPuserID, + categories: `["sponsor"]` + } }) .then(async res => { assert.strictEqual(res.status, 200); @@ -85,10 +101,16 @@ describe("shadowBanUser", () => { .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) => { const userID = "shadowBanned2"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=false`, { - method: "POST" + client({ + method: "POST", + url: endpoint, + params: { + userID, + adminUserID: VIPuserID, + enabled: false, + } }) .then(async res => { assert.strictEqual(res.status, 200); @@ -101,10 +123,17 @@ describe("shadowBanUser", () => { .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) => { const userID = "shadowBanned3"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=false&categories=["sponsor"]`, { - method: "POST" + client({ + method: "POST", + url: endpoint, + params: { + userID, + adminUserID: VIPuserID, + enabled: false, + categories: `["sponsor"]` + } }) .then(async res => { assert.strictEqual(res.status, 200); @@ -118,10 +147,18 @@ describe("shadowBanUser", () => { .catch(err => done(err)); }); - it("Should get 409 when re-shadowbanning user", (done: Done) => { + it("Should get 409 when re-shadowbanning user", (done) => { const userID = "shadowBanned4"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=true&categories=["sponsor"]&unHideOldSubmissions=false`, { - method: "POST" + client({ + method: "POST", + url: endpoint, + params: { + userID, + adminUserID: VIPuserID, + enabled: true, + categories: `["sponsor"]`, + unHideOldSubmissions: false + } }) .then(async res => { assert.strictEqual(res.status, 409); @@ -135,10 +172,18 @@ describe("shadowBanUser", () => { .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) => { const userID = "shadowBanned4"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuserID}&enabled=true&categories=["sponsor"]&unHideOldSubmissions=true`, { - method: "POST" + client({ + method: "POST", + url: endpoint, + params: { + userID, + adminUserID: VIPuserID, + enabled: true, + categories: `["sponsor"]`, + unHideOldSubmissions: true + } }) .then(async res => { assert.strictEqual(res.status, 200); diff --git a/test/cases/unBan.ts b/test/cases/unBan.ts index cb34d0b..2f3fec8 100644 --- a/test/cases/unBan.ts +++ b/test/cases/unBan.ts @@ -1,13 +1,20 @@ -import fetch from "node-fetch"; -import { postJSON } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { getHash } from "../../src/utils/getHash"; import { db } from "../../src/databases/databases"; +import { client } from "../utils/httpClient"; import assert from "assert"; describe("unBan", () => { - const endpoint = `${getbaseURL()}/api/shadowBanUser`; + 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 () => { const insertShadowBannedUserQuery = 'INSERT INTO "shadowBannedUsers" VALUES(?)'; @@ -30,9 +37,7 @@ describe("unBan", () => { it("Should be able to unban a user and re-enable shadow banned segments", (done) => { const userID = "testMan-unBan"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuser}&enabled=false`, { - ...postJSON - }) + postUnBan(userID, VIPuser, false) .then(async res => { assert.strictEqual(res.status, 200); const result = await videoIDUnBanCheck("unBan-videoID-0", userID, 1); @@ -44,9 +49,7 @@ describe("unBan", () => { it("Should be able to unban a user and re-enable shadow banned segments without lockCategories entrys", (done) => { const userID = "testWoman-unBan"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuser}&enabled=false`, { - ...postJSON - }) + postUnBan(userID, VIPuser, false) .then(async res => { assert.strictEqual(res.status, 200); const result = await videoIDUnBanCheck("unBan-videoID-1", userID, 1); @@ -58,9 +61,7 @@ describe("unBan", () => { it("Should be able to unban a user and re-enable shadow banned segments with a mix of lockCategories entrys", (done) => { const userID = "testEntity-unBan"; - fetch(`${endpoint}?userID=${userID}&adminUserID=${VIPuser}&enabled=false`, { - ...postJSON - }) + postUnBan(userID, VIPuser, false) .then(async res => { assert.strictEqual(res.status, 200); const result = await db.prepare("all", 'SELECT * FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?', [userID, 1]); diff --git a/test/cases/voteOnSponsorTime.ts b/test/cases/voteOnSponsorTime.ts index 28a740b..d987b89 100644 --- a/test/cases/voteOnSponsorTime.ts +++ b/test/cases/voteOnSponsorTime.ts @@ -1,17 +1,17 @@ -import fetch from "node-fetch"; import { config } from "../../src/config"; import { db } from "../../src/databases/databases"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { getHash } from "../../src/utils/getHash"; import { ImportMock } from "ts-mock-imports"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; import { YouTubeApiMock } from "../youtubeMock"; import assert from "assert"; +import { client } from "../utils/httpClient"; const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const sinonStub = mockManager.mock("listVideos"); sinonStub.callsFake(YouTubeApiMock.listVideos); +const vipUser = "VIPUser"; +const randomID2 = "randomID2"; describe("voteOnSponsorTime", () => { before(async () => { @@ -35,7 +35,7 @@ describe("voteOnSponsorTime", () => { 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]); 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]); + 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]); 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]); @@ -59,19 +59,38 @@ describe("voteOnSponsorTime", () => { 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 "lockCategories" ("videoID", "userID", "category") VALUES (?, ?, ?)', ["no-sponsor-segments-video", "someUser", "sponsor"]); }); // constants - const endpoint = `${getbaseURL()}/api/voteOnSponsorTime`; + 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 + } + }); + const getSegmentVotes = (UUID: string) => db.prepare("get", `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]); const getSegmentCategory = (UUID: string) => db.prepare("get", `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]); - it("Should be able to upvote a segment", (done: Done) => { + it("Should be able to upvote a segment", (done) => { const UUID = "vote-uuid-0"; - fetch(`${endpoint}?userID=randomID&UUID=${UUID}&type=1`) + postVote("randomID", UUID, 1) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -81,9 +100,9 @@ describe("voteOnSponsorTime", () => { .catch(err => done(err)); }); - it("Should be able to downvote a segment", (done: Done) => { + it("Should be able to downvote a segment", (done) => { const UUID = "vote-uuid-2"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=0`) + postVote(randomID2, UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -93,9 +112,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "vote-uuid-2"; - fetch(`${endpoint}?userID=randomID3&UUID=${UUID}&type=0`) + postVote("randomID3", UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -105,75 +124,81 @@ describe("voteOnSponsorTime", () => { .catch(err => done(err)); }); - it("Should not be able to downvote a segment if the user is shadow banned", (done: Done) => { - fetch(`${endpoint}?userID=randomID4&UUID=vote-uuid-1.6&type=0`) + it("Should not be able to downvote a segment if the user is shadow banned", (done) => { + const UUID = "vote-uuid-1.6"; + postVote("randomID4", UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); - const row = await getSegmentVotes("vote-uuid-1.6"); + const row = await getSegmentVotes(UUID); assert.strictEqual(row.votes, 10); done(); }) .catch(err => done(err)); }); - it("Should not be able to upvote a segment if the user hasn't submitted yet", (done: Done) => { - fetch(`${endpoint}?userID=hasNotSubmittedID&UUID=vote-uuid-1&type=1`) + it("Should not be able to upvote a segment if the user hasn't submitted yet", (done) => { + const UUID = "vote-uuid-1"; + postVote("hasNotSubmittedID", UUID, 1) .then(async res => { assert.strictEqual(res.status, 200); - const row = await getSegmentVotes("vote-uuid-1"); + const row = await getSegmentVotes(UUID); assert.strictEqual(row.votes, 2); done(); }) .catch(err => done(err)); }); - it("Should not be able to downvote a segment if the user hasn't submitted yet", (done: Done) => { - fetch(`${endpoint}?userID=hasNotSubmittedID&UUID=vote-uuid-1.5&type=0`) + it("Should not be able to downvote a segment if the user hasn't submitted yet", (done) => { + const UUID = "vote-uuid-1.5"; + postVote("hasNotSubmittedID", UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); - const row = await getSegmentVotes("vote-uuid-1.5"); + const row = await getSegmentVotes(UUID); assert.strictEqual(row.votes, 10); done(); }) .catch(err => done(err)); }); - it("VIP should be able to completely downvote a segment", (done: Done) => { - fetch(`${endpoint}?userID=VIPUser&UUID=vote-uuid-3&type=0`) + it("VIP should be able to completely downvote a segment", (done) => { + const UUID = "vote-uuid-3"; + postVote(vipUser, UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); - const row = await getSegmentVotes("vote-uuid-3"); + const row = await getSegmentVotes(UUID); assert.ok(row.votes <= -2); done(); }) .catch(err => done(err)); }); - it("should be able to completely downvote your own segment", (done: Done) => { - fetch(`${endpoint}?userID=own-submission-id&UUID=own-submission-uuid&type=0`) + it("should be able to completely downvote your own segment", (done) => { + const UUID = "own-submission-uuid"; + postVote("own-submission-id", UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); - const row = await getSegmentVotes("own-submission-uuid"); + const row = await getSegmentVotes(UUID); assert.ok(row.votes <= -2); done(); }) .catch(err => done(err)); }); - it("should not be able to completely downvote somebody elses segment", (done: Done) => { - fetch(`${endpoint}?userID=randomID2&UUID=not-own-submission-uuid&type=0`) + it("should not be able to completely downvote somebody elses segment", (done) => { + const UUID = "not-own-submission-uuid"; + postVote(randomID2, UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); - const row = await getSegmentVotes("not-own-submission-uuid"); + const row = await getSegmentVotes(UUID); assert.strictEqual(row.votes, 499); done(); }) .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) => { const UUID = "vote-uuid-4"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=intro`) + postVoteCategory(randomID2, UUID, "intro") .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentCategory(UUID); @@ -189,9 +214,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "incorrect-category"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=fakecategory`) + postVoteCategory(randomID2, UUID, "fakecategory") .then(async res => { assert.strictEqual(res.status, 400); const row = await getSegmentCategory(UUID); @@ -201,9 +226,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "incorrect-category"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=highlight`) + postVoteCategory(randomID2, UUID, "highlight") .then(async res => { assert.strictEqual(res.status, 400); const row = await getSegmentCategory(UUID); @@ -213,39 +238,36 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "vote-uuid-4"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=outro`) + postVoteCategory(randomID2, UUID, "outro") .then(async res => { - if (res.status === 200) { - const submissionRow = await getSegmentCategory(UUID); - const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, [UUID]); - let introVotes = 0; - let outroVotes = 0; - let sponsorVotes = 0; - for (const row of categoryRows) { - if (row?.category === "intro") introVotes += row?.votes; - if (row?.category === "outro") outroVotes += row?.votes; - if (row?.category === "sponsor") sponsorVotes += row?.votes; - } - assert.strictEqual(submissionRow.category, "sponsor"); - assert.strictEqual(categoryRows.length, 3); - assert.strictEqual(introVotes, 0); - assert.strictEqual(outroVotes, 1); - assert.strictEqual(sponsorVotes, 1); - done(); - } else { - done(`Status code was ${res.status}`); + assert.strictEqual(res.status, 200, "Status code should be 200"); + const submissionRow = await getSegmentCategory(UUID); + const categoryRows = await db.prepare("all", `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, [UUID]); + let introVotes = 0; + let outroVotes = 0; + let sponsorVotes = 0; + for (const row of categoryRows) { + if (row?.category === "intro") introVotes += row?.votes; + if (row?.category === "outro") outroVotes += row?.votes; + if (row?.category === "sponsor") sponsorVotes += row?.votes; } + assert.strictEqual(submissionRow.category, "sponsor"); + assert.strictEqual(categoryRows.length, 3); + assert.strictEqual(introVotes, 0); + assert.strictEqual(outroVotes, 1); + assert.strictEqual(sponsorVotes, 1); + done(); }) .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 UUID = "incorrect-category-change"; - const vote = (inputCat: string, assertCat: string, callback: Done) => { - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&category=${inputCat}`) + const vote = (inputCat: string, assertCat: string, callback: Mocha.Done) => { + postVoteCategory(randomID2, UUID, inputCat) .then(async () => { const row = await getSegmentCategory(UUID); assert.strictEqual(row.category, assertCat); @@ -259,9 +281,9 @@ 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) => { const UUID = "vote-uuid-5"; - fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&category=outro`) + postVoteCategory(vipUser, UUID, "outro") .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentCategory(UUID); @@ -273,9 +295,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "vote-uuid-5_1"; - fetch(`${endpoint}?userID=testman&UUID=${UUID}&category=outro`) + postVoteCategory("testman", UUID, "outro") .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentCategory("vote-uuid-5"); @@ -285,9 +307,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "invalid-uuid"; - fetch(`${endpoint}?userID=randomID3&UUID=${UUID}&category=intro`) + postVoteCategory("randomID3", UUID, "intro") .then(async res => { assert.strictEqual(res.status, 400); done(); @@ -295,9 +317,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "vote-uuid-5"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=1`) + postVote(randomID2, UUID, 1) .then(async res => { assert.strictEqual(res.status, 403); const row = await getSegmentVotes(UUID); @@ -307,9 +329,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "vote-uuid-5"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=0`) + postVote(randomID2, UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -319,9 +341,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "vote-uuid-5"; - fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=1`) + postVote(vipUser, UUID, 1) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -331,9 +353,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "warnvote-uuid-0"; - fetch(`${endpoint}?userID=warn-voteuser01&UUID=${UUID}&type=1`) + postVote("warn-voteuser01", UUID, 1) .then(async res => { assert.strictEqual(res.status, 403); done(); @@ -341,9 +363,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "no-sponsor-segments-uuid-0"; - fetch(`${endpoint}?userID=randomID&UUID=${UUID}&type=0`) + postVote("randomID", UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -353,9 +375,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "no-sponsor-segments-uuid-0"; - fetch(`${endpoint}?userID=randomID&UUID=${UUID}&type=1`) + postVote("randomID", UUID, 1) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -365,9 +387,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "no-sponsor-segments-uuid-0"; - fetch(`${endpoint}?userID=randomID&UUID=${UUID}&category=outro`) + postVoteCategory("randomID", UUID, "outro") .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentCategory(UUID); @@ -377,9 +399,9 @@ describe("voteOnSponsorTime", () => { .catch(err => done(err)); }); - it("VIP upvote should lock segment", (done: Done) => { + it("VIP upvote should lock segment", (done) => { const UUID = "segment-locking-uuid-1"; - fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=1`) + postVote(vipUser, UUID, 1) .then(async res => { assert.strictEqual(res.status, 200); const row = await db.prepare("get", `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]); @@ -389,9 +411,9 @@ describe("voteOnSponsorTime", () => { .catch(err => done(err)); }); - it("VIP downvote should unlock segment", (done: Done) => { + it("VIP downvote should unlock segment", (done) => { const UUID = "segment-locking-uuid-1"; - fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=0`) + postVote(vipUser, UUID, 0) .then(async res => { assert.strictEqual(res.status, 200); const row = await db.prepare("get", `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]); @@ -401,9 +423,9 @@ describe("voteOnSponsorTime", () => { .catch(err => done(err)); }); - it("VIP upvote should unhide segment", (done: Done) => { + it("VIP upvote should unhide segment", (done) => { const UUID = "segment-hidden-uuid-1"; - fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=1`) + postVote(vipUser, UUID, 1) .then(async res => { assert.strictEqual(res.status, 200); const row = await db.prepare("get", `SELECT "hidden" FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]); @@ -413,9 +435,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "vote-uuid-2"; - fetch(`${endpoint}?userID=randomID2&UUID=${UUID}&type=20`) + postVote(randomID2, UUID, 20) .then(async res => { assert.strictEqual(res.status, 200); const row = await getSegmentVotes(UUID); @@ -425,9 +447,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "segment-locking-uuid-1"; - fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=10`) + postVote(vipUser, UUID, 10) .then(res => { assert.strictEqual(res.status, 400); done(); @@ -435,9 +457,9 @@ describe("voteOnSponsorTime", () => { .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) => { const UUID = "segment-locking-uuid-1"; - fetch(`${endpoint}?userID=VIPUser&UUID=${UUID}&type=11`) + postVote(vipUser, UUID, 11) .then(res => { assert.strictEqual(res.status, 400); done(); From 28d637f620fa1c4d5e90cc041a3d3cb3363496ec Mon Sep 17 00:00:00 2001 From: Michael C Date: Wed, 22 Sep 2021 23:34:46 -0400 Subject: [PATCH 14/14] remove extra async and extra utils --- .eslintrc.js | 1 + src/databases/Mysql.ts | 1 + src/databases/Sqlite.ts | 2 ++ src/routes/getSearchSegments.ts | 2 +- src/routes/getSkipSegmentsByHash.ts | 2 +- src/routes/getUserInfo.ts | 2 +- src/routes/oldSubmitSponsorTimes.ts | 2 +- src/routes/postSkipSegments.ts | 2 +- src/routes/setUsername.ts | 2 +- test/cases/getLockReason.ts | 56 +++++++++++++---------------- test/cases/postClearCache.ts | 6 ++-- test/cases/postSkipSegments.ts | 6 ++-- test/cases/postWarning.ts | 2 +- test/cases/segmentShift.ts | 4 +-- test/cases/setUsername.ts | 6 ++-- test/cases/testUtils.ts | 2 +- test/cases/voteOnSponsorTime.ts | 4 +-- test/utils/getBaseURL.ts | 5 --- test/utils/httpClient.ts | 8 ++--- test/utils/utils.ts | 11 ------ test/youtubeMock.ts | 1 + 21 files changed, 52 insertions(+), 75 deletions(-) delete mode 100644 test/utils/getBaseURL.ts delete mode 100644 test/utils/utils.ts diff --git a/.eslintrc.js b/.eslintrc.js index 8837f26..14b67b2 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -26,5 +26,6 @@ module.exports = { "no-multiple-empty-lines": ["error", { max: 2, maxEOF: 0 }], "indent": ["warn", 4, { "SwitchCase": 1 }], "object-curly-spacing": ["warn", "always"], + "require-await": "warn", }, }; diff --git a/src/databases/Mysql.ts b/src/databases/Mysql.ts index c93aa9f..d15b692 100644 --- a/src/databases/Mysql.ts +++ b/src/databases/Mysql.ts @@ -10,6 +10,7 @@ export class Mysql implements IDatabase { constructor(private config: unknown) { } + // eslint-disable-next-line require-await async init(): Promise { this.connection = new MysqlInterface(this.config); } diff --git a/src/databases/Sqlite.ts b/src/databases/Sqlite.ts index dc3bd47..fc45bbe 100644 --- a/src/databases/Sqlite.ts +++ b/src/databases/Sqlite.ts @@ -12,6 +12,7 @@ export class Sqlite implements IDatabase { { } + // eslint-disable-next-line require-await async prepare(type: QueryType, query: string, params: any[] = []): Promise { // Logger.debug(`prepare (sqlite): type: ${type}, query: ${query}, params: ${params}`); const preparedQuery = this.db.prepare(query); @@ -30,6 +31,7 @@ export class Sqlite implements IDatabase { } } + // eslint-disable-next-line require-await async init(): Promise { // Make dirs if required if (!fs.existsSync(path.join(this.config.dbPath, "../"))) { diff --git a/src/routes/getSearchSegments.ts b/src/routes/getSearchSegments.ts index 684386b..6720df4 100644 --- a/src/routes/getSearchSegments.ts +++ b/src/routes/getSearchSegments.ts @@ -10,7 +10,7 @@ type searchSegmentResponse = { segments: DBSegment[] }; -async function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): Promise { +function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): Promise { return db.prepare( "all", `SELECT "UUID", "timeSubmitted", "startTime", "endTime", "category", "actionType", "votes", "views", "locked", "hidden", "shadowHidden" FROM "sponsorTimes" diff --git a/src/routes/getSkipSegmentsByHash.ts b/src/routes/getSkipSegmentsByHash.ts index a5ed122..48f916d 100644 --- a/src/routes/getSkipSegmentsByHash.ts +++ b/src/routes/getSkipSegmentsByHash.ts @@ -1,7 +1,7 @@ import { hashPrefixTester } from "../utils/hashPrefixTester"; import { getSegmentsByHash } from "./getSkipSegments"; import { Request, Response } from "express"; -import { ActionType, Category, SegmentUUID, Service, VideoIDHash } from "../types/segments.model"; +import { ActionType, Category, SegmentUUID, VideoIDHash } from "../types/segments.model"; import { getService } from "../utils/getService"; export async function getSkipSegmentsByHash(req: Request, res: Response): Promise { diff --git a/src/routes/getUserInfo.ts b/src/routes/getUserInfo.ts index 9311ee8..ebca98c 100644 --- a/src/routes/getUserInfo.ts +++ b/src/routes/getUserInfo.ts @@ -116,7 +116,7 @@ const objSwitch = (cases: cases) => (defaultCase: string) => (key: string) => const functionSwitch = (cases: cases) => (defaultCase: string) => (key: string) => executeIfFunction(objSwitch(cases)(defaultCase)(key)); -const dbGetValue = async (userID: HashedUserID, property: string): Promise => { +const dbGetValue = (userID: HashedUserID, property: string): Promise => { return functionSwitch({ userID, userName: dbGetUsername(userID), diff --git a/src/routes/oldSubmitSponsorTimes.ts b/src/routes/oldSubmitSponsorTimes.ts index 592fb49..22cde5b 100644 --- a/src/routes/oldSubmitSponsorTimes.ts +++ b/src/routes/oldSubmitSponsorTimes.ts @@ -1,7 +1,7 @@ import { postSkipSegments } from "./postSkipSegments"; import { Request, Response } from "express"; -export async function oldSubmitSponsorTimes(req: Request, res: Response): Promise { +export function oldSubmitSponsorTimes(req: Request, res: Response): Promise { req.query.category = "sponsor"; return postSkipSegments(req, res); } diff --git a/src/routes/postSkipSegments.ts b/src/routes/postSkipSegments.ts index 3dc4410..5e4ca67 100644 --- a/src/routes/postSkipSegments.ts +++ b/src/routes/postSkipSegments.ts @@ -274,7 +274,7 @@ async function autoModerateSubmission(apiVideoInfo: APIVideoInfo, } } -async function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise { +function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise { if (config.newLeafURLs !== null) { return YouTubeAPI.listVideos(videoID, ignoreCache); } else { diff --git a/src/routes/setUsername.ts b/src/routes/setUsername.ts index 90ffeee..dee0e99 100644 --- a/src/routes/setUsername.ts +++ b/src/routes/setUsername.ts @@ -4,7 +4,7 @@ import { db, privateDB } from "../databases/databases"; import { getHash } from "../utils/getHash"; import { Request, Response } from "express"; -async function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise { +function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise { return privateDB.prepare("run", `INSERT INTO "userNameLogs"("userID", "newUserName", "oldUserName", "updatedByAdmin", "updatedAt") VALUES(?, ?, ?, ?, ?)`, [userID, newUserName, oldUserName, + updatedByAdmin, new Date().getTime()] diff --git a/test/cases/getLockReason.ts b/test/cases/getLockReason.ts index 5b40182..2941077 100644 --- a/test/cases/getLockReason.ts +++ b/test/cases/getLockReason.ts @@ -1,11 +1,9 @@ -import fetch from "node-fetch"; -import { Done } from "../utils/utils"; -import { getbaseURL } from "../utils/getBaseURL"; import { getHash } from "../../src/utils/getHash"; import { db } from "../../src/databases/databases"; import assert from "assert"; +import { client } from "../utils/httpClient"; -const endpoint = `${getbaseURL()}/api/lockReason`; +const endpoint = "/api/lockReason"; describe("getLockReason", () => { before(async () => { @@ -28,71 +26,65 @@ describe("getLockReason", () => { else return `Version isn't greater than 20. Version is ${version}`; }); - it("Should be able to get single reason", (done: Done) => { - fetch(`${endpoint}?videoID=getLockReason&category=sponsor`) - .then(async res => { + it("Should be able to get single reason", (done) => { + client.get(endpoint, { params: { videoID: "getLockReason", category: "sponsor" } }) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [ { category: "sponsor", locked: 1, reason: "sponsor-reason" } ]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("Should be able to get empty locks", (done: Done) => { - fetch(`${endpoint}?videoID=getLockReason&category=intro`) - .then(async res => { + it("Should be able to get empty locks", (done) => { + client.get(endpoint, { params: { videoID: "getLockReason", category: "intro" } }) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [ { category: "intro", locked: 0, reason: "" } ]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should get multiple locks with array", (done: Done) => { - fetch(`${endpoint}?videoID=getLockReason&categories=["intro","sponsor"]`) - .then(async res => { + it("should get multiple locks with array", (done) => { + client.get(endpoint, { params: { videoID: "getLockReason", categories: `["intro","sponsor"]` } }) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [ { category: "sponsor", locked: 1, reason: "sponsor-reason" }, { category: "intro", locked: 0, reason: "" } ]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should get multiple locks with repeated category", (done: Done) => { - fetch(`${endpoint}?videoID=getLockReason&category=interaction&category=music_offtopic&category=intro`) - .then(async res => { + it("should get multiple locks with repeated category", (done) => { + client.get(`${endpoint}?videoID=getLockReason&category=interaction&category=music_offtopic&category=intro`) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); const expected = [ { category: "interaction", locked: 1, reason: "interaction-reason" }, { category: "music_offtopic", locked: 1, reason: "nonmusic-reason" }, { category: "intro", locked: 0, reason: "" } ]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should return all categories if none specified", (done: Done) => { - fetch(`${endpoint}?videoID=getLockReason`) - .then(async res => { + it("should return all categories if none specified", (done) => { + client.get(endpoint, { params: { videoID: "getLockReason" } }) + .then(res => { assert.strictEqual(res.status, 200); - const data = await res.json(); - console.log(data); const expected = [ { category: "sponsor", locked: 1, reason: "sponsor-reason" }, { category: "interaction", locked: 1, reason: "interaction-reason" }, @@ -103,14 +95,14 @@ describe("getLockReason", () => { { category: "outro", locked: 0, reason: "" }, { category: "poi_highlight", locked: 0, reason: "" } ]; - assert.deepStrictEqual(data, expected); + assert.deepStrictEqual(res.data, expected); done(); }) .catch(err => done(err)); }); - it("should return 400 if no videoID specified", (done: Done) => { - fetch(endpoint) + it("should return 400 if no videoID specified", (done) => { + client.get(endpoint) .then(res => { assert.strictEqual(res.status, 400); done(); diff --git a/test/cases/postClearCache.ts b/test/cases/postClearCache.ts index 7269e3e..671a9e4 100644 --- a/test/cases/postClearCache.ts +++ b/test/cases/postClearCache.ts @@ -35,7 +35,7 @@ describe("postClearCache", () => { it("Should get 403 as non-vip", (done) => { postClearCache(regularUser, "clear-test") - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); done(); }) @@ -44,7 +44,7 @@ describe("postClearCache", () => { it("Should give 400 with missing videoID", (done) => { client.post(endpoint, { params: { userID: VIPUser } }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 400); done(); }) @@ -53,7 +53,7 @@ describe("postClearCache", () => { it("Should give 400 with missing userID", (done) => { client.post(endpoint, { params: { videoID: "clear-test" } }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 400); done(); }) diff --git a/test/cases/postSkipSegments.ts b/test/cases/postSkipSegments.ts index 3e0e89a..67c7de6 100644 --- a/test/cases/postSkipSegments.ts +++ b/test/cases/postSkipSegments.ts @@ -311,7 +311,7 @@ describe("postSkipSegments", () => { category: "sponsor", }], }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); done(); }) @@ -632,7 +632,7 @@ describe("postSkipSegments", () => { category: "sponsor", }], }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); const errorMessage = res.data; const reason = "Reason01"; @@ -707,7 +707,7 @@ describe("postSkipSegments", () => { category: "sponsor", }], }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); const errorMessage = res.data; assert.notStrictEqual(errorMessage, ""); diff --git a/test/cases/postWarning.ts b/test/cases/postWarning.ts index d4bb0c2..93730b3 100644 --- a/test/cases/postWarning.ts +++ b/test/cases/postWarning.ts @@ -90,7 +90,7 @@ describe("postWarning", () => { it("Should return 400 if missing body", (done) => { client.post(endpoint, {}) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 400); done(); }) diff --git a/test/cases/segmentShift.ts b/test/cases/segmentShift.ts index 33fca34..98629b1 100644 --- a/test/cases/segmentShift.ts +++ b/test/cases/segmentShift.ts @@ -41,7 +41,7 @@ describe("segmentShift", function () { const privateVipUserID = "VIPUser-segmentShift"; const vipUserID = getHash(privateVipUserID); const endpoint = "/api/segmentShift"; - const postSegmentShift = async (data: Record) => client({ + const postSegmentShift = (data: Record) => client({ method: "POST", url: endpoint, data, @@ -71,7 +71,7 @@ describe("segmentShift", function () { startTime: 20, endTime: 30, }) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); done(); }) diff --git a/test/cases/setUsername.ts b/test/cases/setUsername.ts index 482311b..f1f3f15 100644 --- a/test/cases/setUsername.ts +++ b/test/cases/setUsername.ts @@ -34,14 +34,14 @@ async function getUsernameInfo(userID: string): Promise<{ userName: string, lock return row; } -async function addLogUserNameChange(userID: string, newUserName: string, oldUserName = "") { +function addLogUserNameChange(userID: string, newUserName: string, oldUserName = "") { privateDB.prepare("run", `INSERT INTO "userNameLogs"("userID", "newUserName", "oldUserName", "updatedAt", "updatedByAdmin") VALUES(?, ?, ?, ?, ?)`, [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)]); } @@ -105,7 +105,7 @@ describe("setUsername", () => { it("Should return 200", (done) => { const username = "Changed%20Username"; postSetUserName(user01PrivateUserID, username) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 200); testUserNameChangelog(user01PrivateUserID, username, username01, false, done); }) diff --git a/test/cases/testUtils.ts b/test/cases/testUtils.ts index fb252b6..78818c8 100644 --- a/test/cases/testUtils.ts +++ b/test/cases/testUtils.ts @@ -2,7 +2,7 @@ import assert from "assert"; import { partialDeepEquals } from "../utils/partialDeepEquals"; describe("Test utils ", () => { - it("objectContain", async () => { + it("objectContain", () => { assert(partialDeepEquals( { name: "John Wick", diff --git a/test/cases/voteOnSponsorTime.ts b/test/cases/voteOnSponsorTime.ts index d987b89..32f937b 100644 --- a/test/cases/voteOnSponsorTime.ts +++ b/test/cases/voteOnSponsorTime.ts @@ -310,7 +310,7 @@ describe("voteOnSponsorTime", () => { it("Should not be able to category-vote on an invalid UUID submission", (done) => { const UUID = "invalid-uuid"; postVoteCategory("randomID3", UUID, "intro") - .then(async res => { + .then(res => { assert.strictEqual(res.status, 400); done(); }) @@ -356,7 +356,7 @@ describe("voteOnSponsorTime", () => { it("Should not be able to upvote a segment (Too many warning)", (done) => { const UUID = "warnvote-uuid-0"; postVote("warn-voteuser01", UUID, 1) - .then(async res => { + .then(res => { assert.strictEqual(res.status, 403); done(); }) diff --git a/test/utils/getBaseURL.ts b/test/utils/getBaseURL.ts deleted file mode 100644 index 3632cb4..0000000 --- a/test/utils/getBaseURL.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { config } from "../../src/config"; - -export function getbaseURL(): string { - return `http://localhost:${config.port}`; -} \ No newline at end of file diff --git a/test/utils/httpClient.ts b/test/utils/httpClient.ts index 6385e02..b100f13 100644 --- a/test/utils/httpClient.ts +++ b/test/utils/httpClient.ts @@ -1,12 +1,8 @@ import { config } from "../../src/config"; import axios, { AxiosRequestConfig } from "axios"; -export function getbaseURL(): string { - return `http://localhost:${config.port}`; -} - -export const defaultConfig: AxiosRequestConfig = { - baseURL: getbaseURL(), +const defaultConfig: AxiosRequestConfig = { + baseURL: `http://localhost:${config.port}`, validateStatus: (status) => status < 500 }; diff --git a/test/utils/utils.ts b/test/utils/utils.ts deleted file mode 100644 index 4bbb8f4..0000000 --- a/test/utils/utils.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Duplicated from Mocha types. TypeScript doesn't infer that type by itself for some reason. - */ -export type Done = (err?: any) => void; - -export const postJSON = { - method: "POST", - headers: { - "Content-Type": "application/json", - }, -}; \ No newline at end of file diff --git a/test/youtubeMock.ts b/test/youtubeMock.ts index f0a91f1..39d8c8f 100644 --- a/test/youtubeMock.ts +++ b/test/youtubeMock.ts @@ -1,6 +1,7 @@ import { APIVideoData, APIVideoInfo } from "../src/types/youtubeApi.model"; export class YouTubeApiMock { + // eslint-disable-next-line require-await static async listVideos(videoID: string): Promise { const obj = { id: videoID