Merge branch 'master' into 400-on-noparam

This commit is contained in:
Michael M. Chang
2021-07-11 14:27:32 -04:00
committed by GitHub
27 changed files with 1915 additions and 2633 deletions

1029
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,37 +16,33 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@ajayyy/lru-diskcache": "^1.1.9", "@ajayyy/lru-diskcache": "^1.1.9",
"abort-controller": "^3.0.0", "@types/request": "^2.48.6",
"better-sqlite3": "^7.1.5", "better-sqlite3": "^7.4.1",
"dotenv": "^8.2.0",
"express": "^4.17.1", "express": "^4.17.1",
"express-promise-router": "^4.1.0", "express-promise-router": "^4.1.0",
"express-rate-limit": "^5.1.3", "express-rate-limit": "^5.3.0",
"http": "0.0.0", "node-fetch": "^2.6.1",
"node-fetch": "^2.6.0", "pg": "^8.6.0",
"pg": "^8.5.1", "redis": "^3.1.2",
"redis": "^3.1.1", "sync-mysql": "^3.0.1"
"sync-mysql": "^3.0.1",
"uuid": "^3.3.2"
}, },
"devDependencies": { "devDependencies": {
"@types/better-sqlite3": "^5.4.0", "@types/better-sqlite3": "^5.4.3",
"@types/express": "^4.17.8", "@types/express": "^4.17.13",
"@types/express-rate-limit": "^5.1.0", "@types/express-rate-limit": "^5.1.3",
"@types/mocha": "^8.2.2", "@types/mocha": "^8.2.3",
"@types/node": "^14.11.9", "@types/node": "^16.3.0",
"@types/node-fetch": "^2.5.7", "@types/node-fetch": "^2.5.11",
"@types/pg": "^7.14.10", "@types/pg": "^8.6.1",
"@types/redis": "^2.8.28", "@types/redis": "^2.8.31",
"@types/request": "^2.48.5", "@typescript-eslint/eslint-plugin": "^4.28.2",
"@typescript-eslint/eslint-plugin": "^4.28.1", "@typescript-eslint/parser": "^4.28.2",
"@typescript-eslint/parser": "^4.28.1",
"eslint": "^7.30.0", "eslint": "^7.30.0",
"mocha": "^8.4.0", "mocha": "^9.0.2",
"nodemon": "^2.0.2", "nodemon": "^2.0.2",
"sinon": "^9.2.0", "sinon": "^11.1.1",
"ts-mock-imports": "^1.3.0", "ts-mock-imports": "^1.3.7",
"ts-node": "^9.0.0", "ts-node": "^10.0.0",
"typescript": "^4.0.3" "typescript": "^4.3.5"
} }
} }

View File

@@ -16,6 +16,7 @@ import { getCategoryActionType } from '../utils/categoryInfo';
import { QueryCacher } from '../utils/queryCacher'; import { QueryCacher } from '../utils/queryCacher';
import { getReputation } from '../utils/reputation'; import { getReputation } from '../utils/reputation';
import { APIVideoData, APIVideoInfo } from '../types/youtubeApi.model'; import { APIVideoData, APIVideoInfo } from '../types/youtubeApi.model';
import { UserID } from '../types/user.model';
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 row = await db.prepare('get', `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
@@ -164,7 +165,7 @@ async function sendWebhooksNB(userID: string, videoID: string, UUID: string, sta
// false for a pass - it was confusing and lead to this bug - any use of this function in // false for a pass - it was confusing and lead to this bug - any use of this function in
// the future could have the same problem. // the future could have the same problem.
async function autoModerateSubmission(apiVideoInfo: APIVideoInfo, async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
submission: { videoID: any; userID: any; segments: any }) { submission: { videoID: VideoID; userID: UserID; segments: IncomingSegment[] }) {
if (apiVideoInfo) { if (apiVideoInfo) {
const {err, data} = apiVideoInfo; const {err, data} = apiVideoInfo;
if (err) return false; if (err) return false;
@@ -234,7 +235,7 @@ async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
const startTime = parseFloat(segments[i].segment[0]); const startTime = parseFloat(segments[i].segment[0]);
const endTime = parseFloat(segments[i].segment[1]); const endTime = parseFloat(segments[i].segment[1]);
const UUID = getSubmissionUUID(submission.videoID, segments[i].category, submission.userID, startTime, endTime); const UUID = getSubmissionUUID(submission.videoID, segments[i].actionType, submission.userID, startTime, endTime);
// Send to Discord // Send to Discord
// Note, if this is too spammy. Consider sending all the segments as one Webhook // Note, if this is too spammy. Consider sending all the segments as one Webhook
sendWebhooksNB(submission.userID, submission.videoID, UUID, startTime, endTime, segments[i].category, nbPredictions.probabilities[predictionIdx], data); sendWebhooksNB(submission.userID, submission.videoID, UUID, startTime, endTime, segments[i].category, nbPredictions.probabilities[predictionIdx], data);
@@ -519,7 +520,7 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
//this can just be a hash of the data //this can just be a hash of the data
//it's better than generating an actual UUID like what was used before //it's better than generating an actual UUID like what was used before
//also better for duplication checking //also better for duplication checking
const UUID = getSubmissionUUID(videoID, segmentInfo.category, userID, parseFloat(segmentInfo.segment[0]), parseFloat(segmentInfo.segment[1])); const UUID = getSubmissionUUID(videoID, segmentInfo.actionType, userID, parseFloat(segmentInfo.segment[0]), parseFloat(segmentInfo.segment[1]));
const hashedVideoID = getHash(videoID, 1); const hashedVideoID = getHash(videoID, 1);
const startingLocked = isVIP ? 1 : 0; const startingLocked = isVIP ? 1 : 0;

View File

@@ -1,6 +1,8 @@
import {getHash} from './getHash'; import {getHash} from './getHash';
import { HashedValue } from '../types/hash.model'; import { HashedValue } from '../types/hash.model';
import { ActionType, Category, VideoID } from '../types/segments.model';
import { UserID } from '../types/user.model';
export function getSubmissionUUID(videoID: string, category: string, userID: string, startTime: number, endTime: number): HashedValue{ export function getSubmissionUUID(videoID: VideoID, actionType: ActionType, userID: UserID, startTime: number, endTime: number): HashedValue{
return getHash('v2-categories' + videoID + startTime + endTime + category + userID, 1); return `3${getHash('v3' + videoID + startTime + endTime + userID, 1)}` as HashedValue;
} }

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {getbaseURL, Done} from '../utils'; import {getbaseURL, Done} from '../utils';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import assert from 'assert';
describe('getIsUserVIP', () => { describe('getIsUserVIP', () => {
before((done: Done) => { before((done: Done) => {
@@ -11,20 +12,20 @@ describe('getIsUserVIP', () => {
it('Should be able to get a 200', (done: Done) => { it('Should be able to get a 200', (done: Done) => {
fetch(getbaseURL() + "/api/isUserVIP?userID=supertestman") fetch(getbaseURL() + "/api/isUserVIP?userID=supertestman")
.then(res => { .then(res => {
if (res.status !== 200) done("non 200: " + res.status); assert.strictEqual(res.status, 200, "response should be 200");
else done(); // pass done();
}) })
.catch(() => done("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should get a 400 if no userID', (done: Done) => { it('Should get a 400 if no userID', (done: Done) => {
fetch(getbaseURL() + "/api/isUserVIP") fetch(getbaseURL() + "/api/isUserVIP")
.then(res => { .then(res => {
if (res.status !== 400) done("non 400: " + res.status); assert.strictEqual(res.status, 400, "response should be 400");
else done(); // pass done();
}) })
.catch(() => done("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should say a VIP is a VIP', (done: Done) => { it('Should say a VIP is a VIP', (done: Done) => {
@@ -33,11 +34,11 @@ describe('getIsUserVIP', () => {
if (res.status !== 200) done("non 200: " + res.status); if (res.status !== 200) done("non 200: " + res.status);
else { else {
const data = await res.json(); const data = await res.json();
if (data.vip === true) done(); // pass assert.strictEqual(data.vip, true);
else done("Result was non-vip when should have been vip"); done();
} }
}) })
.catch(() => done("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should say a normal user is not a VIP', (done: Done) => { it('Should say a normal user is not a VIP', (done: Done) => {
@@ -46,10 +47,10 @@ describe('getIsUserVIP', () => {
if (res.status !== 200) done("non 200: " + res.status); if (res.status !== 200) done("non 200: " + res.status);
else { else {
const data = await res.json(); const data = await res.json();
if (data.vip === false) done(); // pass assert.strictEqual(data.vip, false);
else done("Result was vip when should have been non-vip"); done();
} }
}) })
.catch(() => done("couldn't call endpoint")); .catch(err => done(err));
}); });
}); });

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import assert from 'assert';
describe('getLockCategories', () => { describe('getLockCategories', () => {
@@ -27,58 +28,51 @@ describe('getLockCategories', () => {
it('Should be able to get multiple locks', (done: Done) => { it('Should be able to get multiple locks', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories?videoID=getLock-1') fetch(getbaseURL() + '/api/lockCategories?videoID=getLock-1')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200");
} else {
const data = await res.json(); const data = await res.json();
if (data.categories.length !== 2) { const expected = {
done(`Returned incorrect number of locks "${data.categories.length}"`); categories: [
} else if (data.categories[0] !== "sponsor") { "sponsor",
done(`Returned incorrect category "${data.categories[0]}"`); "interaction"
} else if (data.categories[1] !== "interaction") { ]
done(`Returned incorrect category "${data.categories[1]}"`); };
} else { assert.deepStrictEqual(data, expected);
done(); // pass done();
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get single locks', (done: Done) => { it('Should be able to get single locks', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories?videoID=getLock-2') fetch(getbaseURL() + '/api/lockCategories?videoID=getLock-2')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200");
} else {
const data = await res.json(); const data = await res.json();
if (data.categories.length !== 1) { const expected = {
done('Returned incorrect number of locks "' + data.categories.length + '"'); categories: [
} else if (data.categories[0] !== "preview") { "preview"
done(`Returned incorrect category "${data.categories[0].category}"`); ]
} else { };
done(); // pass assert.deepStrictEqual(data, expected);
} done();
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 404 if no lock exists', (done: Done) => { it('should return 404 if no lock exists', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories?videoID=getLock-0') fetch(getbaseURL() + '/api/lockCategories?videoID=getLock-0')
.then(res => { .then(res => {
if (res.status !== 404) done('non 404 (' + res.status + ')'); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 400 if no videoID specified', (done: Done) => { it('should return 400 if no videoID specified', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories') fetch(getbaseURL() + '/api/lockCategories')
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
}); });

View File

@@ -31,147 +31,117 @@ describe('getLockCategoriesByHash', () => {
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: Done) => {
fetch(getbaseURL() + '/api/lockCategories/67a65') fetch(getbaseURL() + '/api/lockCategories/67a65')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200");
} else {
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { const expected = [{
done(`Returned incorrect number of videos "${data.length}"`); videoID: "getLockHash-1",
} else if (data[0].videoID !== "getLockHash-1") { hash: getHash("getLockHash-1", 1),
done(`Returned incorrect videoID "${data[0].videoID}"`); categories: [
} else if (data[0].hash !== getHash("getLockHash-1", 1)) { "sponsor",
done(`Returned incorrect hash "${data[0].hash}"`); "interaction"
} else if (data[0].categories[0] !== "sponsor") { ]
done(`Returned incorrect category "${data[0].categories[0]}"`); }];
} else if (data[0].categories[1] !== "interaction") { assert.deepStrictEqual(data, expected);
done(`Returned incorrect category "${data[0].categories[1]}"`); done();
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get single lock', (done: Done) => { it('Should be able to get single lock', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories/dff09') fetch(getbaseURL() + '/api/lockCategories/dff09')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200");
} else {
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { const expected = [{
done('Returned incorrect number of videos "' + data.length + '"'); videoID: "getLockHash-2",
} else if (data[0].videoID !== "getLockHash-2") { hash: getHash("getLockHash-2", 1),
done(`Returned incorrect videoID "${data[0].videoID}"`); categories: [
} else if (data[0].hash !== getHash("getLockHash-2", 1)) { "preview"
done(`Returned incorrect hashedVideoID hash "${data[0].hash}"`); ]
} else if (data[0].categories.length !== 1) { }];
done(`Returned incorrect number of categories "${data[0].categories.length}"`); assert.deepStrictEqual(data, expected);
} else if (data[0].categories[0] !== "preview") { done();
done(`Returned incorrect category "${data[0].categories[0]}"`);
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .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: Done) => {
fetch(getbaseURL() + '/api/lockCategories/bf1b122fd5630e0df8626d00c4a95c58') fetch(getbaseURL() + '/api/lockCategories/bf1b122fd5630e0df8626d00c4a95c58')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200");
} else {
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { const expected = [{
done('Returned incorrect number of videos "' + data.length + '"'); videoID: "getLockHash-3",
} else if (data[0].videoID !== "getLockHash-3") { hash: getHash("getLockHash-3", 1),
done(`Returned incorrect videoID "${data[0].videoID}"`); categories: [
} else if (data[0].hash !== getHash("getLockHash-3", 1)) { "nonmusic"
done(`Returned incorrect hashedVideoID hash "${data[0].hash}"`); ]
} else if (data[0].categories.length !== 1) { }];
done(`Returned incorrect number of categories "${data[0].categories.length}"`); assert.deepStrictEqual(data, expected);
} else if (data[0].categories[0] !== "nonmusic") { done();
done(`Returned incorrect category "${data[0].categories[0]}"`);
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get multiple by similar hash with multiple categories', (done: Done) => { it('Should be able to get multiple by similar hash with multiple categories', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories/b05a') fetch(getbaseURL() + '/api/lockCategories/b05a')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200");
} else {
const data = await res.json(); const data = await res.json();
if (data.length !== 2) { const expected = [{
done(`Returned incorrect number of locks "${data.length}"`); videoID: "fakehash-1",
} else if (data[0].videoID !== "fakehash-1") { hash: "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35",
done(`Returned incorrect videoID "${data[0].videoID}"`); categories: [
} else if (data[1].videoID !== "fakehash-2") { "outro"
done(`Returned incorrect videoID "${data[1].videoID}"`); ]
} else if (data[0].hash !== "b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35") { }, {
done(`Returned incorrect hashedVideoID hash "${data[0].hash}"`); videoID: "fakehash-2",
} else if (data[1].hash !== "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450") { hash: "b05acd1cd6ec7dffe5ffea64ada91ae7469d6db2ce21c7e30ad7fa62075d450",
done(`Returned incorrect hashedVideoID hash "${data[1].hash}"`); categories: [
} else if (data[0].categories.length !== 1) { "intro",
done(`Returned incorrect number of categories "${data[0].categories.length}"`); "preview"
} else if (data[1].categories.length !== 2) { ]
done(`Returned incorrect number of categories "${data[1].categories.length}"`); }];
} else if (data[0].categories[0] !== "outro") { assert.deepStrictEqual(data, expected);
done(`Returned incorrect category "${data[0].category}"`); done();
} else if (data[1].categories[0] !== "intro") {
done(`Returned incorrect category "${data[1].category}"`);
} else if (data[1].categories[1] !== "preview") {
done(`Returned incorrect category "${data[1].category}"`);
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 404 once hash prefix varies', (done: Done) => { it('should return 404 once hash prefix varies', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories/aaaaaa') fetch(getbaseURL() + '/api/lockCategories/b05aa')
.then(res => { .then(res => {
if (res.status !== 404) done('non 404 (' + res.status + ')'); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 404 if no lock exists', (done: Done) => { it('should return 404 if no lock exists', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories/aaaaaa') fetch(getbaseURL() + '/api/lockCategories/aaaaaa')
.then(res => { .then(res => {
if (res.status !== 404) done('non 404 (' + res.status + ')'); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 400 if no videoID specified', (done: Done) => { it('should return 400 if no videoID specified', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories/') fetch(getbaseURL() + '/api/lockCategories/')
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 400 if full hash sent', (done: Done) => { it('should return 400 if full hash sent', (done: Done) => {
fetch(getbaseURL() + '/api/lockCategories/b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35') fetch(getbaseURL() + '/api/lockCategories/b05a20424f24a53dac1b059fb78d861ba9723645026be2174c93a94f9106bb35')
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 400 if hash too short', (done: Done) => { it('should return 400 if hash too short', (done: Done) => {

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import assert from 'assert';
describe('getSavedTimeForUser', () => { describe('getSavedTimeForUser', () => {
before(async () => { before(async () => {
@@ -13,10 +14,16 @@ describe('getSavedTimeForUser', () => {
it('Should be able to get a 200', (done: Done) => { it('Should be able to get a 200', (done: Done) => {
fetch(getbaseURL() + "/api/getSavedTimeForUser?userID=testman") fetch(getbaseURL() + "/api/getSavedTimeForUser?userID=testman")
.then(res => { .then(async res => {
if (res.status !== 200) done("non 200"); const data = await res.json();
else done(); // pass // (end-start)*minute * views
const savedMinutes = ((11-1)/60) * 50;
const expected = {
timeSaved: savedMinutes
};
assert.deepStrictEqual(data, expected);
done();
}) })
.catch(() => done("couldn't call endpoint")); .catch((err) => done(err));
}); });
}); });

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import assert from 'assert';
const ENOENTID = "0".repeat(64); const ENOENTID = "0".repeat(64);
const upvotedID = "a"+"0".repeat(63); const upvotedID = "a"+"0".repeat(63);
@@ -43,231 +44,188 @@ describe('getSegmentInfo', () => {
it('Should be able to retreive upvoted segment', (done: Done) => { it('Should be able to retreive upvoted segment', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${upvotedID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${upvotedID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "upvoted" && data[0].votes === 2) { assert.strictEqual(data[0].videoID, "upvoted");
assert.strictEqual(data[0].votes, 2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive downvoted segment', (done: Done) => { it('Should be able to retreive downvoted segment', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${downvotedID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${downvotedID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "downvoted" && data[0].votes === -2) { assert.strictEqual(data[0].videoID, "downvoted");
assert.strictEqual(data[0].votes, -2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive locked up segment', (done: Done) => { it('Should be able to retreive locked up segment', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${lockedupID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${lockedupID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "locked-up" && data[0].locked === 1 && data[0].votes === 2) { assert.strictEqual(data[0].videoID, "locked-up");
assert.strictEqual(data[0].locked, 1);
assert.strictEqual(data[0].votes, 2);
done(); done();
} else {
done ("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive infinite vote segment', (done: Done) => { it('Should be able to retreive infinite vote segment', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${infvotesID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${infvotesID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "infvotes" && data[0].votes === 100000) { assert.strictEqual(data[0].videoID, "infvotes");
assert.strictEqual(data[0].votes, 100000);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive shadowhidden segment', (done: Done) => { it('Should be able to retreive shadowhidden segment', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${shadowhiddenID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${shadowhiddenID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "shadowhidden" && data[0].shadowHidden === 1) { assert.strictEqual(data[0].videoID, "shadowhidden");
assert.strictEqual(data[0].shadowHidden, 1);
done(); done();
} else {
done ("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive locked down segment', (done: Done) => { it('Should be able to retreive locked down segment', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${lockeddownID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${lockeddownID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "locked-down" && data[0].votes === -2 && data[0].locked === 1) { assert.strictEqual(data[0].videoID, "locked-down");
assert.strictEqual(data[0].votes, -2);
assert.strictEqual(data[0].locked, 1);
done(); done();
} else {
done ("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive hidden segment', (done: Done) => { it('Should be able to retreive hidden segment', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${hiddenID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${hiddenID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "hidden" && data[0].hidden === 1) { assert.strictEqual(data[0].videoID, "hidden");
assert.strictEqual(data[0].hidden, 1);
done(); done();
} else {
done ("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive segment with old ID', (done: Done) => { it('Should be able to retreive segment with old ID', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${oldID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${oldID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "oldID" && data[0].votes === 1) { assert.strictEqual(data[0].videoID, "oldID");
assert.strictEqual(data[0].votes, 1);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive single segment in array', (done: Done) => { it('Should be able to retreive single segment in array', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}"]`) fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}"]`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].videoID === "upvoted" && data[0].votes === 2) { assert.strictEqual(data.length, 1);
assert.strictEqual(data[0].videoID, "upvoted");
assert.strictEqual(data[0].votes, 2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to retreive multiple segments in array', (done: Done) => { it('Should be able to retreive multiple segments in array', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}", "${downvotedID}"]`) fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}", "${downvotedID}"]`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 2 && assert.strictEqual(data.length, 2);
(data[0].videoID === "upvoted" && data[0].votes === 2) && assert.strictEqual(data[0].videoID, "upvoted");
(data[1].videoID === "downvoted" && data[1].votes === -2)) { assert.strictEqual(data[0].votes, 2);
assert.strictEqual(data[1].videoID, "downvoted");
assert.strictEqual(data[1].votes, -2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be possible to send unexpected query parameters', (done: Done) => { it('Should be possible to send unexpected query parameters', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${upvotedID}&fakeparam=hello&category=sponsor`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${upvotedID}&fakeparam=hello&category=sponsor`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data[0].videoID === "upvoted" && data[0].votes === 2) { assert.strictEqual(data[0].videoID, "upvoted");
assert.strictEqual(data[0].votes, 2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should return 400 if array passed to UUID', (done: Done) => { it('Should return 400 if array passed to UUID', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=["${upvotedID}", "${downvotedID}"]`) fetch(getbaseURL() + `/api/segmentInfo?UUID=["${upvotedID}", "${downvotedID}"]`)
.then(res => { .then(res => {
if (res.status !== 400) done("non 400 respone code: " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 if bad array passed to UUIDs', (done: Done) => { it('Should return 400 if bad array passed to UUIDs', (done: Done) => {
fetch(getbaseURL() + "/api/segmentInfo?UUIDs=[not-quoted,not-quoted]") fetch(getbaseURL() + "/api/segmentInfo?UUIDs=[not-quoted,not-quoted]")
.then(res => { .then(res => {
if (res.status !== 400) done("non 404 respone code: " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 if bad UUID passed', (done: Done) => { it('Should return 400 if bad UUID passed', (done: Done) => {
fetch(getbaseURL() + "/api/segmentInfo?UUID=notarealuuid") fetch(getbaseURL() + "/api/segmentInfo?UUID=notarealuuid")
.then(res => { .then(res => {
if (res.status !== 400) done("non 400 respone code: " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 if bad UUIDs passed in array', (done: Done) => { it('Should return 400 if bad UUIDs passed in array', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["notarealuuid", "anotherfakeuuid"]`) fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["notarealuuid", "anotherfakeuuid"]`)
.then(res => { .then(res => {
if (res.status !== 400) done("non 400 respone code: " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return good UUID when mixed with bad UUIDs', (done: Done) => { it('Should return good UUID when mixed with bad UUIDs', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}", "anotherfakeuuid"]`) fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}", "anotherfakeuuid"]`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].videoID === "upvoted" && data[0].votes === 2) { assert.strictEqual(data.length, 1);
assert.strictEqual(data[0].videoID, "upvoted");
assert.strictEqual(data[0].votes, 2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should cut off array at 10', function(done: Done) { it('Should cut off array at 10', function(done: Done) {
@@ -275,34 +233,31 @@ describe('getSegmentInfo', () => {
const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`; const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`;
fetch(getbaseURL() + `/api/segmentInfo?UUIDs=${filledIDArray}`) fetch(getbaseURL() + `/api/segmentInfo?UUIDs=${filledIDArray}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
// last segment should be fillerID4 assert.strictEqual(data.length, 10);
if (data.length === 10 && data[0].videoID === "upvoted" && data[0].votes === 2 && data[9].videoID === "filler" && data[9].UUID === fillerID4) { assert.strictEqual(data[0].videoID, "upvoted");
assert.strictEqual(data[0].votes, 2);
assert.strictEqual(data[9].videoID, "filler");
assert.strictEqual(data[9].UUID, fillerID4);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should not duplicate reponses', (done: Done) => { it('Should not duplicate reponses', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`) fetch(getbaseURL() + `/api/segmentInfo?UUIDs=["${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${upvotedID}", "${downvotedID}"]`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 2 && data[0].videoID === "upvoted" && data[0].votes === 2 && data[1].videoID === "downvoted" && data[1].votes === -2) { assert.strictEqual(data.length, 2);
assert.strictEqual(data[0].videoID, "upvoted");
assert.strictEqual(data[0].votes, 2);
assert.strictEqual(data[1].videoID, "downvoted");
assert.strictEqual(data[1].votes, -2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 if UUID not found', (done: Done) => { it('Should return 400 if UUID not found', (done: Done) => {
@@ -311,41 +266,33 @@ describe('getSegmentInfo', () => {
if (res.status !== 400) done("non 400 respone code: " + res.status); if (res.status !== 400) done("non 400 respone code: " + res.status);
else done(); // pass else done(); // pass
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to retreive multiple segments with multiple parameters', (done: Done) => { it('Should be able to retreive multiple segments with multiple parameters', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${upvotedID}&UUID=${downvotedID}`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${upvotedID}&UUID=${downvotedID}`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 2 && assert.strictEqual(data.length, 2);
(data[0].videoID === "upvoted" && data[0].votes === 2) && assert.strictEqual(data[0].videoID, "upvoted");
(data[1].videoID === "downvoted" && data[1].votes === -2)) { assert.strictEqual(data[1].videoID, "downvoted");
assert.strictEqual(data[0].votes, 2);
assert.strictEqual(data[1].votes, -2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should not parse repeated UUID if UUIDs present', (done: Done) => { it('Should not parse repeated UUID if UUIDs present', (done: Done) => {
fetch(getbaseURL() + `/api/segmentInfo?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`) fetch(getbaseURL() + `/api/segmentInfo?UUID=${downvotedID}&UUID=${lockedupID}&UUIDs=["${upvotedID}"]`)
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && assert.strictEqual(data[0].videoID, "upvoted");
(data[0].videoID === "upvoted" && data[0].votes === 2)) { assert.strictEqual(data[0].votes, 2);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
}); });

View File

@@ -30,373 +30,315 @@ describe('getSkipSegments', () => {
it('Should be able to get a time by category 1', (done: Done) => { 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=testtesttest&category=sponsor")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data.length, 1);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0" && data[0].videoDuration === 100) { 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].videoDuration, 100);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to get a time by category and action type', (done: Done) => { it('Should be able to get a time by category and action type', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 12 && data[0].segment[1] === 14 assert.strictEqual(data.length, 1);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0-2" && data[0].videoDuration === 100) { assert.strictEqual(data[0].segment[0], 12);
assert.strictEqual(data[0].segment[1], 14);
assert.strictEqual(data[0].category, "sponsor");
assert.strictEqual(data[0].UUID, "1-uuid-0-2");
assert.strictEqual(data[0].videoDuration, 100);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to get a time by category and multiple action types', (done: Done) => { it('Should be able to get a time by category and multiple action types', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute&actionType=skip") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=sponsor&actionType=mute&actionType=skip")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 2 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data.length, 2);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0" assert.strictEqual(data[0].segment[0], 1);
&& data[1].UUID === "1-uuid-0-2" && data[0].videoDuration === 100) { assert.strictEqual(data[0].segment[1], 11);
assert.strictEqual(data[0].category, "sponsor");
assert.strictEqual(data[0].UUID, "1-uuid-0");
assert.strictEqual(data[1].UUID, "1-uuid-0-2");
assert.strictEqual(data[0].videoDuration, 100);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to get a time by category and multiple action types (JSON array)', (done: Done) => { it('Should be able to get a time by category and multiple action types (JSON array)', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments?videoID=testtesttest&category=sponsor&actionTypes=["mute","skip"]') fetch(getbaseURL() + '/api/skipSegments?videoID=testtesttest&category=sponsor&actionTypes=["mute","skip"]')
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 2 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data.length, 2);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0" assert.strictEqual(data[0].segment[0], 1);
&& data[1].UUID === "1-uuid-0-2" && data[0].videoDuration === 100) { assert.strictEqual(data[0].segment[1], 11);
assert.strictEqual(data[0].category, "sponsor");
assert.strictEqual(data[0].UUID, "1-uuid-0");
assert.strictEqual(data[1].UUID, "1-uuid-0-2");
assert.strictEqual(data[0].videoDuration, 100);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to get a time by category for a different service 1', (done: Done) => { it('Should be able to get a time by category for a different service 1', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest2&category=sponsor&service=PeerTube") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest2&category=sponsor&service=PeerTube")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data.length, 1);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0-1" && data[0].videoDuration === 120) { 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-1");
assert.strictEqual(data[0].videoDuration, 120);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => "Couldn't call endpoint"); .catch(err => done(err));
}); });
it('Should be able to get a time by category 2', (done: Done) => { it('Should be able to get a time by category 2', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=intro") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=intro")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 20 && data[0].segment[1] === 33 assert.strictEqual(data.length, 1);
&& data[0].category === "intro" && data[0].UUID === "1-uuid-2") { assert.strictEqual(data[0].segment[0], 20);
assert.strictEqual(data[0].segment[1], 33);
assert.strictEqual(data[0].category, "intro");
assert.strictEqual(data[0].UUID, "1-uuid-2");
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get a time by categories array', (done: Done) => { it('Should be able to get a time by categories array', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"sponsor\"]") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"sponsor\"]")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data.length, 1);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0" && data[0].videoDuration === 100) { 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].videoDuration, 100);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get a time by categories array 2', (done: Done) => { it('Should be able to get a time by categories array 2', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"intro\"]") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"intro\"]")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 20 && data[0].segment[1] === 33 assert.strictEqual(data.length, 1);
&& data[0].category === "intro" && data[0].UUID === "1-uuid-2" && data[0].videoDuration === 101) { assert.strictEqual(data[0].segment[0], 20);
assert.strictEqual(data[0].segment[1], 33);
assert.strictEqual(data[0].category, "intro");
assert.strictEqual(data[0].UUID, "1-uuid-2");
assert.strictEqual(data[0].videoDuration, 101);
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 404 if all submissions are hidden', (done: Done) => { it('Should return 404 if all submissions are hidden', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=onlyHiddenSegments") fetch(getbaseURL() + "/api/skipSegments?videoID=onlyHiddenSegments")
.then(res => { .then(res => {
if (res.status !== 404) done("non 404 respone code: " + res.status); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get multiple times by category', (done: Done) => { it('Should be able to get multiple times by category', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=multiple&categories=[\"intro\"]") fetch(getbaseURL() + "/api/skipSegments?videoID=multiple&categories=[\"intro\"]")
.then(async res => { .then(async res => {
if (res.status !== 200)done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.text(); assert.strictEqual(data.length, 2);
const data = JSON.parse(body); assert.strictEqual(data[0].segment[0], 1);
if (data.length === 2) { assert.strictEqual(data[0].segment[1], 11);
let success = true; assert.strictEqual(data[0].category, "intro");
for (const segment of data) { assert.strictEqual(data[0].UUID, "1-uuid-6");
if ((segment.segment[0] !== 20 || segment.segment[1] !== 33 assert.strictEqual(data[1].segment[0], 20);
|| segment.category !== "intro" || segment.UUID !== "1-uuid-7") && assert.strictEqual(data[1].segment[1], 33);
(segment.segment[0] !== 1 || segment.segment[1] !== 11 assert.strictEqual(data[1].category, "intro");
|| segment.category !== "intro" || segment.UUID !== "1-uuid-6")) { assert.strictEqual(data[1].UUID, "1-uuid-7");
success = false; done();
break;
}
}
if (success) done();
else done("Received incorrect body: " + body);
} else {
done("Received incorrect body: " + body);
}
}
}) })
.catch(err => ("Couldn't call endpoint\n\n" + err)); .catch(err => done(err));
}); });
it('Should be able to get multiple times by multiple categories', (done: Done) => { it('Should be able to get multiple times by multiple categories', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"sponsor\", \"intro\"]") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"sponsor\", \"intro\"]")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.text(); assert.strictEqual(data.length, 2);
const data = JSON.parse(body); assert.strictEqual(data[0].segment[0], 1);
if (data.length === 2) { assert.strictEqual(data[0].segment[1], 11);
assert.strictEqual(data[0].category, "sponsor");
let success = true; assert.strictEqual(data[0].UUID, "1-uuid-0");
for (const segment of data) { assert.strictEqual(data[1].segment[0], 20);
if ((segment.segment[0] !== 20 || segment.segment[1] !== 33 assert.strictEqual(data[1].segment[1], 33);
|| segment.category !== "intro" || segment.UUID !== "1-uuid-2") && assert.strictEqual(data[1].category, "intro");
(segment.segment[0] !== 1 || segment.segment[1] !== 11 assert.strictEqual(data[1].UUID, "1-uuid-2");
|| segment.category !== "sponsor" || segment.UUID !== "1-uuid-0")) { done();
success = false;
break;
}
}
if (success) done();
else done("Received incorrect body: " + body);
} else {
done("Received incorrect body: " + body);
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be possible to send unexpected query parameters', (done: Done) => { it('Should be possible to send unexpected query parameters', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&fakeparam=hello&category=sponsor") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&fakeparam=hello&category=sponsor")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.text(); assert.strictEqual(data.length, 1);
const data = JSON.parse(body); assert.strictEqual(data[0].segment[0], 1);
if (data.length === 1 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data[0].segment[1], 11);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0") { assert.strictEqual(data[0].category, "sponsor");
assert.strictEqual(data[0].UUID, "1-uuid-0");
done(); done();
} else {
done("Received incorrect body: " + body);
}
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Low voted submissions should be hidden', (done: Done) => { it('Low voted submissions should be hidden', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=test3&category=sponsor") fetch(getbaseURL() + "/api/skipSegments?videoID=test3&category=sponsor")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.text(); assert.strictEqual(data.length, 1);
const data = JSON.parse(body); assert.strictEqual(data[0].segment[0], 1);
if (data.length === 1 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data[0].segment[1], 11);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-4") { assert.strictEqual(data[0].category, "sponsor");
assert.strictEqual(data[0].UUID, "1-uuid-4");
done(); done();
} else {
done("Received incorrect body: " + body);
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 404 if no segment found', (done: Done) => { it('Should return 404 if no segment found', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=notarealvideo") fetch(getbaseURL() + "/api/skipSegments?videoID=notarealvideo")
.then(res => { .then(res => {
if (res.status !== 404) done("non 404 respone code: " + res.status); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 if bad categories argument', (done: Done) => { 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=testtesttest&categories=[not-quoted,not-quoted]")
.then(res => { .then(res => {
if (res.status !== 400) done("non 400 respone code: " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able send a comma in a query param', (done: Done) => { it('Should be able send a comma in a query param', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest,test&category=sponsor") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest,test&category=sponsor")
.then(async res => { .then(async res => {
if (res.status !== 200) done ("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.text(); assert.strictEqual(data.length, 1);
const data = JSON.parse(body); assert.strictEqual(data[0].segment[0], 1);
if (data.length === 1 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data[0].segment[1], 11);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-1") { assert.strictEqual(data[0].category, "sponsor");
assert.strictEqual(data[0].UUID, "1-uuid-1");
done(); done();
} else {
done("Received incorrect body: " + body);
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should always get locked segment', (done: Done) => { it('Should always get locked segment', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=locked&category=intro") fetch(getbaseURL() + "/api/skipSegments?videoID=locked&category=intro")
.then(async res => { .then(async res => {
if (res.status !== 200) done ("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 20 && data[0].segment[1] === 33 assert.strictEqual(data.length, 1);
&& data[0].category === "intro" && data[0].UUID === "1-uuid-locked-8") { assert.strictEqual(data[0].segment[0], 20);
assert.strictEqual(data[0].segment[1], 33);
assert.strictEqual(data[0].category, "intro");
assert.strictEqual(data[0].UUID, "1-uuid-locked-8");
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get multiple categories with repeating parameters', (done: Done) => { it('Should be able to get multiple categories with repeating parameters', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=sponsor&category=intro") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&category=sponsor&category=intro")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.text(); assert.strictEqual(data.length, 2);
const data = JSON.parse(body); assert.strictEqual(data[0].segment[0], 1);
if (data.length === 2) { assert.strictEqual(data[0].segment[1], 11);
assert.strictEqual(data[0].category, "sponsor");
let success = true; assert.strictEqual(data[0].UUID, "1-uuid-0");
for (const segment of data) { assert.strictEqual(data[1].segment[0], 20);
if ((segment.segment[0] !== 20 || segment.segment[1] !== 33 assert.strictEqual(data[1].segment[1], 33);
|| segment.category !== "intro" || segment.UUID !== "1-uuid-2") && assert.strictEqual(data[1].category, "intro");
(segment.segment[0] !== 1 || segment.segment[1] !== 11 assert.strictEqual(data[1].UUID, "1-uuid-2");
|| segment.category !== "sponsor" || segment.UUID !== "1-uuid-0")) { done();
success = false;
break;
}
}
if (success) done();
else done("Received incorrect body: " + body);
} else {
done("Received incorrect body: " + body);
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get, categories param overriding repeating category', (done: Done) => { it('Should be able to get, categories param overriding repeating category', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"sponsor\"]&category=intro") fetch(getbaseURL() + "/api/skipSegments?videoID=testtesttest&categories=[\"sponsor\"]&category=intro")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const data = await res.json(); const data = await res.json();
if (data.length === 1 && data[0].segment[0] === 1 && data[0].segment[1] === 11 assert.strictEqual(data.length, 1);
&& data[0].category === "sponsor" && data[0].UUID === "1-uuid-0") { 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");
done(); done();
} else {
done("Received incorrect body: " + (await res.text()));
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .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: Done) => {
fetch(getbaseURL() + '/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegments=["requiredSegmentVid-raw-2","requiredSegmentVid-raw-3"]') fetch(getbaseURL() + '/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegments=["requiredSegmentVid-raw-2","requiredSegmentVid-raw-3"]')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 2);
if (body.length !== 2) done("expected 2 segments, got " + body.length); assert.strictEqual(data[0].UUID, "requiredSegmentVid-raw-2");
else if (body[0].UUID !== 'requiredSegmentVid-raw-2' assert.strictEqual(data[1].UUID, "requiredSegmentVid-raw-3");
|| body[1].UUID !== 'requiredSegmentVid-raw-3') done("Did not recieve the correct segments\n" + JSON.stringify(body, null, 2)); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
fetch(getbaseURL() + '/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegment=requiredSegmentVid-raw-2&requiredSegment=requiredSegmentVid-raw-3') fetch(getbaseURL() + '/api/skipSegments?videoID=requiredSegmentVid-raw&requiredSegment=requiredSegmentVid-raw-2&requiredSegment=requiredSegmentVid-raw-3')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 2);
if (body.length !== 2) done("expected 2 segments, got " + body.length); assert.strictEqual(data[0].UUID, 'requiredSegmentVid-raw-2');
else if (body[0].UUID !== 'requiredSegmentVid-raw-2' assert.strictEqual(data[1].UUID, 'requiredSegmentVid-raw-3');
|| body[1].UUID !== 'requiredSegmentVid-raw-3') done("Did not recieve the correct segments\n" + JSON.stringify(body, null, 2)); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should get 400 if no videoID passed in', (done: Done) => { it('Should get 400 if no videoID passed in', (done: Done) => {

View File

@@ -5,6 +5,7 @@ import {getHash} from '../../src/utils/getHash';
import {ImportMock,} from 'ts-mock-imports'; import {ImportMock,} from 'ts-mock-imports';
import * as YouTubeAPIModule from '../../src/utils/youtubeApi'; import * as YouTubeAPIModule from '../../src/utils/youtubeApi';
import {YouTubeApiMock} from '../youtubeMock'; import {YouTubeApiMock} from '../youtubeMock';
import assert from 'assert';
const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, 'YouTubeAPI'); const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, 'YouTubeAPI');
const sinonStub = mockManager.mock('listVideos'); const sinonStub = mockManager.mock('listVideos');
@@ -31,36 +32,35 @@ describe('getSegmentsByHash', () => {
it('Should be able to get a 200', (done: Done) => { it('Should be able to get a 200', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/3272f?categories=["sponsor", "intro"]') fetch(getbaseURL() + '/api/skipSegments/3272f?categories=["sponsor", "intro"]')
.then(res => { .then(res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else done(); // pass done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 404 if no segments are found even if a video for the given hash is known', (done: Done) => { it('Should return 404 if no segments are found even if a video for the given hash is known', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/3272f?categories=["shilling"]') fetch(getbaseURL() + '/api/skipSegments/3272f?categories=["shilling"]')
.then(async res => { .then(async res => {
if (res.status !== 404) done("non 404 status code, was " + res.status); assert.strictEqual(res.status, 404);
else { const expected = '[]';
const body = await res.text(); const body = await res.text();
if (body === '[]') done(); // pass assert.strictEqual(body, expected);
else done("Response had videos"); done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get an empty array if no videos', (done: Done) => { it('Should be able to get an empty array if no videos', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/11111?categories=["shilling"]') fetch(getbaseURL() + '/api/skipSegments/11111?categories=["shilling"]')
.then(async res => { .then(async res => {
if (res.status !== 404) done("non 404 status code, was " + res.status); assert.strictEqual(res.status, 404);
else {
const body = await res.text(); const body = await res.text();
if (JSON.parse(body).length === 0 && body === '[]') done(); // pass const expected = '[]';
else done("non empty array returned"); assert.strictEqual(JSON.parse(body).length, 0);
} assert.strictEqual(body, expected);
done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get an empty array if only hidden videos', (done: Done) => { it('Should be able to get an empty array if only hidden videos', (done: Done) => {
@@ -73,175 +73,159 @@ describe('getSegmentsByHash', () => {
else done("non empty array returned"); else done("non empty array returned");
} }
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 prefix too short', (done: Done) => { it('Should return 400 prefix too short', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/11?categories=["shilling"]') fetch(getbaseURL() + '/api/skipSegments/11?categories=["shilling"]')
.then(res => { .then(res => {
if (res.status !== 400) done("non 400 status code, was " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 prefix too long', (done: Done) => { it('Should return 400 prefix too long', (done: Done) => {
const prefix = new Array(50).join('1'); const prefix = '1'.repeat(50);
if (prefix.length <= 32) { // default value, config can change this assert.ok(prefix.length > 33, "failed to generate long enough string");
done('failed to generate a long enough string for the test ' + prefix.length);
return;
}
fetch(getbaseURL() + '/api/skipSegments/' + prefix + '?categories=["shilling"]') fetch(getbaseURL() + '/api/skipSegments/' + prefix + '?categories=["shilling"]')
.then(res => { .then(res => {
if (res.status !== 400) done("non 400 status code, was " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should not return 400 prefix in range', (done: Done) => { it('Should return 404 prefix in range', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/11111?categories=["shilling"]') const prefix = '1'.repeat(5);
fetch(getbaseURL() + '/api/skipSegments/'+prefix+'?categories=["shilling"]')
.then(res => { .then(res => {
if (res.status === 400) done("prefix length 5 gave 400 " + res.status); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 for no hash', (done: Done) => { it('Should return 400 for no hash', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/?categories=["shilling"]') fetch(getbaseURL() + '/api/skipSegments/?categories=["shilling"]')
.then(res => { .then(res => {
if (res.status !== 400) done("expected 400, got " + res.status); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 400 for bad format categories', (done: Done) => { it('Should return 400 for bad format categories', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/fdaf?categories=shilling') fetch(getbaseURL() + '/api/skipSegments/fdaf?categories=shilling')
.then(res => { .then(res => {
if (res.status !== 400) done("expected 400 got " + res.status); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get multiple videos', (done: Done) => { it('Should be able to get multiple videos', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/fdaf?categories=["sponsor","intro"]') fetch(getbaseURL() + '/api/skipSegments/fdaf?categories=["sponsor","intro"]')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 2);
if (body.length !== 2) done("expected 2 videos, got " + body.length); assert.strictEqual(data[0].segments.length, 2);
else if (body[0].segments.length !== 2) done("expected 2 segments for first video, got " + body[0].segments.length); assert.strictEqual(data[1].segments.length, 1);
else if (body[1].segments.length !== 1) done("expected 1 segment for second video, got " + body[1].segments.length); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get 200 for no categories (default sponsor)', (done: Done) => { it('Should be able to get 200 for no categories (default sponsor)', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/fdaf') fetch(getbaseURL() + '/api/skipSegments/fdaf')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 2);
if (body.length !== 2) done("expected 2 videos, got " + body.length); assert.strictEqual(data[0].segments.length, 1);
else if (body[0].segments.length !== 1) done("expected 1 segments for first video, got " + body[0].segments.length); assert.strictEqual(data[1].segments.length, 1);
else if (body[1].segments.length !== 1) done("expected 1 segments for second video, got " + body[1].segments.length); assert.strictEqual(data[0].segments[0].category, 'sponsor');
else if (body[0].segments[0].category !== 'sponsor' assert.strictEqual(data[0].segments[0].UUID, 'getSegmentsByHash-0-0');
|| body[0].segments[0].UUID !== 'getSegmentsByHash-0-0' assert.strictEqual(data[1].segments[0].category, 'sponsor');
|| body[1].segments[0].category !== 'sponsor') done("both segments are not sponsor"); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get 200 for no categories (default sponsor) with action type', (done: Done) => { it('Should be able to get 200 for no categories (default sponsor) with action type', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/fdaf?actionType=skip') fetch(getbaseURL() + '/api/skipSegments/fdaf?actionType=skip')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 2);
if (body.length !== 2) done("expected 2 videos, got " + body.length); assert.strictEqual(data[0].segments.length, 1);
else if (body[0].segments.length !== 1) done("expected 1 segments for first video, got " + body[0].segments.length); assert.strictEqual(data[1].segments.length, 1);
else if (body[1].segments.length !== 1) done("expected 1 segments for second video, got " + body[1].segments.length); assert.strictEqual(data[0].segments[0].category, 'sponsor');
else if (body[0].segments[0].category !== 'sponsor' assert.strictEqual(data[0].segments[0].UUID, 'getSegmentsByHash-0-0');
|| body[0].segments[0].UUID !== 'getSegmentsByHash-0-0' assert.strictEqual(data[1].segments[0].category, 'sponsor');
|| body[1].segments[0].category !== 'sponsor') done("both segments are not sponsor"); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get 200 for no categories (default sponsor) with multiple action types', (done: Done) => { it('Should be able to get 200 for no categories (default sponsor) with multiple action types', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/fdaf?actionType=skip&actionType=mute') fetch(getbaseURL() + '/api/skipSegments/fdaf?actionType=skip&actionType=mute')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 2);
if (body.length !== 2) done("expected 2 videos, got " + body.length); assert.strictEqual(data[0].segments.length, 2);
else if (body[0].segments.length !== 2) done("expected 2 segments for first video, got " + body[0].segments.length); assert.strictEqual(data[1].segments.length, 1);
else if (body[1].segments.length !== 1) done("expected 1 segments for second video, got " + body[1].segments.length); assert.strictEqual(data[0].segments[0].category, 'sponsor');
else if (body[0].segments[0].category !== 'sponsor' assert.strictEqual(data[0].segments[0].UUID, 'getSegmentsByHash-0-0');
|| body[0].segments[0].UUID !== 'getSegmentsByHash-0-0' assert.strictEqual(data[0].segments[1].UUID, 'getSegmentsByHash-0-2');
|| body[0].segments[1].UUID !== 'getSegmentsByHash-0-2' assert.strictEqual(data[1].segments[0].category, 'sponsor');
|| body[1].segments[0].category !== 'sponsor') done("both segments are not sponsor"); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get 200 for no categories (default sponsor) with multiple action types (JSON array)', (done: Done) => { it('Should be able to get 200 for no categories (default sponsor) with multiple action types (JSON array)', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/fdaf?actionTypes=["skip","mute"]') fetch(getbaseURL() + '/api/skipSegments/fdaf?actionTypes=["skip","mute"]')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 2);
if (body.length !== 2) done("expected 2 videos, got " + body.length); assert.strictEqual(data[0].segments.length, 2);
else if (body[0].segments.length !== 2) done("expected 2 segments for first video, got " + body[0].segments.length); assert.strictEqual(data[1].segments.length, 1);
else if (body[1].segments.length !== 1) done("expected 1 segments for second video, got " + body[1].segments.length); assert.strictEqual(data[0].segments[0].category, 'sponsor');
else if (body[0].segments[0].category !== 'sponsor' assert.strictEqual(data[0].segments[0].UUID, 'getSegmentsByHash-0-0');
|| body[0].segments[0].UUID !== 'getSegmentsByHash-0-0' assert.strictEqual(data[0].segments[1].UUID, 'getSegmentsByHash-0-2');
|| body[0].segments[1].UUID !== 'getSegmentsByHash-0-2' assert.strictEqual(data[1].segments[0].category, 'sponsor');
|| body[1].segments[0].category !== 'sponsor') done("both segments are not sponsor"); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get 200 for no categories (default sponsor) for a non YouTube service', (done: Done) => { it('Should be able to get 200 for no categories (default sponsor) for a non YouTube service', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/fdaf?service=PeerTube') fetch(getbaseURL() + '/api/skipSegments/fdaf?service=PeerTube')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 1);
if (body.length !== 1) done("expected 1 video, got " + body.length); assert.strictEqual(data[0].segments.length, 1);
else if (body[0].segments.length !== 1) done("expected 1 segments for first video, got " + body[0].segments.length); assert.strictEqual(data[0].segments[0].UUID, 'getSegmentsByHash-0-0-1');
else if (body[0].segments[0].UUID !== 'getSegmentsByHash-0-0-1') done("both segments are not sponsor"); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should only return one segment when fetching highlight segments', (done: Done) => { it('Should only return one segment when fetching highlight segments', (done: Done) => {
fetch(getbaseURL() + '/api/skipSegments/c962?category=highlight') fetch(getbaseURL() + '/api/skipSegments/c962?category=highlight')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 1);
if (body.length !== 1) done("expected 1 video, got " + body.length); assert.strictEqual(data[0].segments.length, 1);
else if (body[0].segments.length !== 1) done("expected 1 segment, got " + body[0].segments.length); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -260,23 +244,17 @@ describe('getSegmentsByHash', () => {
}], }],
}), }),
}) })
.then(async res => { .then(async () => {
if (res.status === 200) {
fetch(getbaseURL() + '/api/skipSegments/' + getHash(testID, 1).substring(0, 3)) fetch(getbaseURL() + '/api/skipSegments/' + getHash(testID, 1).substring(0, 3))
.then(async res => { .then(async res => {
if (res.status !== 200) done("(get) non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 1);
if (body.length !== 1) done("(get) expected 1 video, got " + body.length); assert.strictEqual(data[0].segments.length, 1);
else if (body[0].segments.length !== 1) done("(get) expected 1 segments for first video, got " + body[0].segments.length); assert.strictEqual(data[0].segments[0].category, 'sponsor');
else if (body[0].segments[0].category !== 'sponsor') done("(get) segment should be sponsor, was " + body[0].segments[0].category); done();
else done();
}
}) })
.catch(() => done("(get) Couldn't call endpoint")); .catch(err => done('(get) ' + err));
} else {
done("(post) non 200 status code, was " + res.status);
}
}) })
.catch(err => done('(post) ' + err)); .catch(err => done('(post) ' + err));
}); });
@@ -284,64 +262,48 @@ describe('getSegmentsByHash', () => {
it('Should be able to get multiple categories with repeating parameters', (done: Done) => { it('Should be able to get multiple categories with repeating parameters', (done: Done) => {
fetch(getbaseURL() + "/api/skipSegments/fdaff4?&category=sponsor&category=intro") fetch(getbaseURL() + "/api/skipSegments/fdaff4?&category=sponsor&category=intro")
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 1);
if (body.length !== 1) done("expected 1 video, got " + body.length); assert.strictEqual(data[0].segments[0].segment[0], 1);
assert.strictEqual(data[0].segments[0].segment[1], 10);
const data = body[0].segments; assert.strictEqual(data[0].segments[0].category, "sponsor");
if (data.length === 2) { assert.strictEqual(data[0].segments[0].UUID, "getSegmentsByHash-0-0");
let success = true; assert.strictEqual(data[0].segments[1].segment[0], 20);
for (const segment of data) { assert.strictEqual(data[0].segments[1].segment[1], 30);
if ((segment.segment[0] !== 1 || segment.segment[1] !== 10 assert.strictEqual(data[0].segments[1].category, "intro");
|| segment.category !== "sponsor" || segment.UUID !== "getSegmentsByHash-0-0") && assert.strictEqual(data[0].segments[1].UUID, "getSegmentsByHash-0-1");
(segment.segment[0] !== 20 || segment.segment[1] !== 30 done();
|| segment.category !== "intro" || segment.UUID !== "getSegmentsByHash-0-1")) {
success = false;
break;
}
}
if (success) done();
else done("Received incorrect body: " + JSON.stringify(body));
} else {
done("Received incorrect body: " + JSON.stringify(body));
}
}
}) })
.catch(() => ("Couldn't call endpoint")); .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: Done) => {
fetch(getbaseURL() + '/api/skipSegments/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]') fetch(getbaseURL() + '/api/skipSegments/d518?requiredSegments=["requiredSegmentVid-2","requiredSegmentVid-3"]')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 1);
if (body.length !== 1) done("expected 1 video, got " + body.length); assert.strictEqual(data[0].segments.length, 2);
else if (body[0].segments.length !== 2) done("expected 2 segments for video, got " + body[0].segments.length); assert.strictEqual(data[0].segments[0].UUID, 'requiredSegmentVid-2');
else if (body[0].segments[0].UUID !== 'requiredSegmentVid-2' assert.strictEqual(data[0].segments[0].UUID, 'requiredSegmentVid-2');
|| body[0].segments[1].UUID !== 'requiredSegmentVid-3') done("Did not recieve the correct segments\n" + JSON.stringify(body, null, 2)); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
fetch(getbaseURL() + '/api/skipSegments/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3') fetch(getbaseURL() + '/api/skipSegments/d518?requiredSegment=requiredSegmentVid-2&requiredSegment=requiredSegmentVid-3')
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200 status code, was " + res.status); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const body = await res.json(); assert.strictEqual(data.length, 1);
if (body.length !== 1) done("expected 1 video, got " + body.length); assert.strictEqual(data[0].segments.length, 2);
else if (body[0].segments.length !== 2) done("expected 2 segments for video, got " + body[0].segments.length); assert.strictEqual(data[0].segments[0].UUID, 'requiredSegmentVid-2');
else if (body[0].segments[0].UUID !== 'requiredSegmentVid-2' assert.strictEqual(data[0].segments[1].UUID, 'requiredSegmentVid-3');
|| body[0].segments[1].UUID !== 'requiredSegmentVid-3') done("Did not recieve the correct segments\n" + JSON.stringify(body, null, 2)); done();
else done();
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
}); });

View File

@@ -1,8 +1,10 @@
import {getSubmissionUUID} from '../../src/utils/getSubmissionUUID'; import {getSubmissionUUID} from '../../src/utils/getSubmissionUUID';
import assert from 'assert'; import assert from 'assert';
import { ActionType, VideoID } from '../../src/types/segments.model';
import { UserID } from '../../src/types/user.model';
describe('getSubmissionUUID', () => { describe('getSubmissionUUID', () => {
it('Should return the hashed value', () => { it('Should return the hashed value', () => {
assert.strictEqual(getSubmissionUUID('video001', 'sponsor', 'testuser001', 13.33337, 42.000001), '1d33d7016aa6482849019bd906d75c08fe6b815e64e823146df35f66c35612dd'); assert.strictEqual(getSubmissionUUID('video001' as VideoID, 'skip' as ActionType, 'testuser001' as UserID, 13.33337, 42.000001), '3572aa64e0a2d6352c3de14ca45f8a83d193c32635669a7ae0b40c9eb36395872');
}); });
}); });

View File

@@ -24,380 +24,294 @@ describe('getUserID', () => {
it('Should be able to get a 200', (done: Done) => { it('Should be able to get a 200', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=fuzzy+user+01') fetch(getbaseURL() + '/api/userID?username=fuzzy+user+01')
.then(async res => { .then(async res => {
if (res.status !== 200) done('non 200 (' + res.status + ')'); assert.strictEqual(res.status, 200);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .catch(err => done(err));
}); });
it('Should be able to get a 400 (No username parameter)', (done: Done) => { it('Should be able to get a 400 (No username parameter)', (done: Done) => {
fetch(getbaseURL() + '/api/userID') fetch(getbaseURL() + '/api/userID')
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .catch(err => done(err));
}); });
it('Should be able to get a 200 (username is public id)', (done: Done) => { it('Should be able to get a 200 (username is public id)', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username='+getHash("getuserid_user_06")) fetch(getbaseURL() + '/api/userID?username='+getHash("getuserid_user_06"))
.then(async res => { .then(async res => {
if (res.status !== 200) done('non 200 (' + res.status + ')'); assert.strictEqual(res.status, 200);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .catch(err => done(err));
}); });
it('Should be able to get a 400 (username longer than 64 chars)', (done: Done) => { it('Should be able to get a 400 (username longer than 64 chars)', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username='+getHash("getuserid_user_06")+'0') fetch(getbaseURL() + '/api/userID?username='+getHash("getuserid_user_06")+'0')
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .catch(err => done(err));
}); });
it('Should be able to get single username', (done: Done) => { it('Should be able to get single username', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=fuzzy+user+01') fetch(getbaseURL() + '/api/userID?username=fuzzy+user+01')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "fuzzy user 01",
userID: getHash("getuserid_user_01")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "fuzzy user 01") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_01")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get multiple fuzzy user info from start', (done: Done) => { it('Should be able to get multiple fuzzy user info from start', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=fuzzy+user') fetch(getbaseURL() + '/api/userID?username=fuzzy+user')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "fuzzy user 01",
userID: getHash("getuserid_user_01")
}, {
userName: "fuzzy user 02",
userID: getHash("getuserid_user_02")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 2) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "fuzzy user 01") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_01")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[1].userName !== "fuzzy user 02") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[1].userID !== getHash("getuserid_user_02")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get multiple fuzzy user info from middle', (done: Done) => { it('Should be able to get multiple fuzzy user info from middle', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=user') fetch(getbaseURL() + '/api/userID?username=user')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "fuzzy user 01",
userID: getHash("getuserid_user_01")
}, {
userName: "fuzzy user 02",
userID: getHash("getuserid_user_02")
}, {
userName: "specific user 03",
userID: getHash("getuserid_user_03")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 3) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "fuzzy user 01") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_01")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[1].userName !== "fuzzy user 02") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[1].userID !== getHash("getuserid_user_02")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[2].userName !== "specific user 03") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[2].userID !== getHash("getuserid_user_03")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .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: Done) => {
const userID = getHash("getuserid_user_06"); const userID = getHash("getuserid_user_06");
fetch(getbaseURL() + '/api/userID?username='+userID) fetch(getbaseURL() + '/api/userID?username='+userID)
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: userID,
userID
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== userID) {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== userID) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .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: Done) => {
const userID = getHash("getuserid_user_06"); const userID = getHash("getuserid_user_06");
fetch(getbaseURL() + '/api/userID?username='+userID.substr(10,60)) fetch(getbaseURL() + '/api/userID?username='+userID.substr(10,60))
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: userID,
userID
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== userID) {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== userID) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get repeating username', (done: Done) => { it('Should be able to get repeating username', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=repeating') fetch(getbaseURL() + '/api/userID?username=repeating')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "repeating",
userID: getHash("getuserid_user_04")
}, {
userName: "repeating",
userID: getHash("getuserid_user_05")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 2) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "repeating") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_04")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[1].userName !== "repeating") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[1].userID !== getHash("getuserid_user_05")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get repeating fuzzy username', (done: Done) => { it('Should be able to get repeating fuzzy username', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=peat') fetch(getbaseURL() + '/api/userID?username=peat')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "repeating",
userID: getHash("getuserid_user_04")
}, {
userName: "repeating",
userID: getHash("getuserid_user_05")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 2) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "repeating") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_04")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[1].userName !== "repeating") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[1].userID !== getHash("getuserid_user_05")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should avoid ReDOS with _', (done: Done) => { it('should avoid ReDOS with _', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=_redos_') fetch(getbaseURL() + '/api/userID?username=_redos_')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "_redos_",
userID: getHash("getuserid_user_09")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "_redos_") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_09")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should avoid ReDOS with %', (done: Done) => { it('should avoid ReDOS with %', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=%redos%') fetch(getbaseURL() + '/api/userID?username=%redos%')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "%redos%",
userID: getHash("getuserid_user_08")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "%redos%") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_08")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 404 if escaped backslashes present', (done: Done) => { it('should return 404 if escaped backslashes present', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=%redos\\\\_') fetch(getbaseURL() + '/api/userID?username=%redos\\\\_')
.then(res => { .then(res => {
if (res.status !== 404) done('non 404 (' + res.status + ')'); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 404 if backslashes present', (done: Done) => { it('should return 404 if backslashes present', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=\\%redos\\_') fetch(getbaseURL() + '/api/userID?username=\\%redos\\_')
.then(res => { .then(res => {
if (res.status !== 404) done('non 404 (' + res.status + ')'); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return user if just backslashes', (done: Done) => { it('should return user if just backslashes', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=\\\\\\') fetch(getbaseURL() + '/api/userID?username=\\\\\\')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "\\\\\\",
userID: getHash("getuserid_user_11")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "\\\\\\") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_11")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should not allow usernames more than 64 characters', (done: Done) => { it('should not allow usernames more than 64 characters', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username='+'0'.repeat(65)) fetch(getbaseURL() + '/api/userID?username='+'0'.repeat(65))
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should not allow usernames less than 3 characters', (done: Done) => { it('should not allow usernames less than 3 characters', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=aa') fetch(getbaseURL() + '/api/userID?username=aa')
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should allow exact match', (done: Done) => { it('should allow exact match', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=a&exact=true') fetch(getbaseURL() + '/api/userID?username=a&exact=true')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "a",
userID: getHash("getuserid_user_12")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 1) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "a") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_12")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get repeating username with exact username', (done: Done) => { it('Should be able to get repeating username with exact username', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=repeating&exact=true') fetch(getbaseURL() + '/api/userID?username=repeating&exact=true')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "repeating",
userID: getHash("getuserid_user_04")
}, {
userName: "repeating",
userID: getHash("getuserid_user_05")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 2) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "repeating") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_04")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[1].userName !== "repeating") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[1].userID !== getHash("getuserid_user_05")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should not get exact unless explicitly set to true', (done: Done) => { it('Should not get exact unless explicitly set to true', (done: Done) => {
fetch(getbaseURL() + '/api/userID?username=user&exact=1') fetch(getbaseURL() + '/api/userID?username=user&exact=1')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = [{
} else { userName: "fuzzy user 01",
userID: getHash("getuserid_user_01")
}, {
userName: "fuzzy user 02",
userID: getHash("getuserid_user_02")
}, {
userName: "specific user 03",
userID: getHash("getuserid_user_03")
}];
const data = await res.json(); const data = await res.json();
if (data.length !== 3) { assert.deepStrictEqual(data, expected);
done('Returned incorrect number of users "' + data.length + '"'); done();
} else if (data[0].userName !== "fuzzy user 01") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[0].userID !== getHash("getuserid_user_01")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[1].userName !== "fuzzy user 02") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[1].userID !== getHash("getuserid_user_02")) {
done('Returned incorrect userID "' + data.userID + '"');
} else if (data[2].userName !== "specific user 03") {
done('Returned incorrect username "' + data.userName + '"');
} else if (data[2].userID !== getHash("getuserid_user_03")) {
done('Returned incorrect userID "' + data.userID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('should return 400 if no username parameter specified', (done: Done) => { it('should return 400 if no username parameter specified', (done: Done) => {

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import assert from 'assert';
describe('getUserInfo', () => { describe('getUserInfo', () => {
before(async () => { before(async () => {
@@ -27,136 +28,109 @@ describe('getUserInfo', () => {
it('Should be able to get a 200', (done: Done) => { it('Should be able to get a 200', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_user_01') fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_user_01')
.then(res => { .then(res => {
if (res.status !== 200) done('non 200 (' + res.status + ')'); assert.strictEqual(res.status, 200);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .catch(err => done(err));
}); });
it('Should be able to get a 400 (No userID parameter)', (done: Done) => { it('Should be able to get a 400 (No userID parameter)', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo') fetch(getbaseURL() + '/api/userInfo')
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .catch(err => done(err));
}); });
it('Should be able to get user info', (done: Done) => { it('Should be able to get user info', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_user_01') fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_user_01')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done("non 200"); const expected = {
} else { userName: 'Username user 01',
userID: "66e7c974039ffb870a500a33eca3a3989861018909b938c313cf1a8a366800b8",
minutesSaved: 5,
viewCount: 30,
ignoredViewCount: 20,
segmentCount: 3,
ignoredSegmentCount: 2,
reputation: -2,
lastSegmentID: "uuid000005",
vip: false,
warnings: 0
};
const data = await res.json(); const data = await res.json();
if (data.userName !== 'Username user 01') { assert.deepStrictEqual(data, expected);
done('Returned incorrect userName "' + data.userName + '"'); done();
} else if (data.minutesSaved !== 5) {
done('Returned incorrect minutesSaved "' + data.minutesSaved + '"');
} else if (data.viewCount !== 30) {
done('Returned incorrect viewCount "' + data.viewCount + '"');
} else if (data.ignoredViewCount !== 20) {
done('Returned incorrect ignoredViewCount "' + data.ignoredViewCount + '"');
} else if (data.segmentCount !== 3) {
done('Returned incorrect segmentCount "' + data.segmentCount + '"');
} else if (data.ignoredSegmentCount !== 2) {
done('Returned incorrect ignoredSegmentCount "' + data.ignoredSegmentCount + '"');
} else if (data.reputation !== -2) {
done('Returned incorrect reputation "' + data.reputation + '"');
} else if (data.lastSegmentID !== "uuid000005") {
done('Returned incorrect last segment "' + data.lastSegmentID + '"');
} else {
done(); // pass
}
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should get warning data', (done: Done) => { it('Should get warning data', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_warning_0') fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_warning_0')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done('non 200 (' + res.status + ')');
} else {
const data = await res.json(); const data = await res.json();
if (data.warnings !== 1) done('wrong number of warnings: ' + data.warnings + ', not ' + 1); assert.strictEqual(data.warnings, 1);
else done(); // pass done();
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should get warning data with public ID', (done: Done) => { it('Should get warning data with public ID', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?publicUserID=' + getHash("getuserinfo_warning_0")) fetch(getbaseURL() + '/api/userInfo?publicUserID=' + getHash("getuserinfo_warning_0"))
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done('non 200 (' + res.status + ')');
} else {
const data = await res.json(); const data = await res.json();
if (data.warnings !== 1) done('wrong number of warnings: ' + data.warnings + ', not ' + 1); assert.strictEqual(data.warnings, 1);
else done(); done();
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should get multiple warnings', (done: Done) => { it('Should get multiple warnings', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_warning_1') fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_warning_1')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done('non 200 (' + res.status + ')');
} else {
const data = await res.json(); const data = await res.json();
if (data.warnings !== 2) done('wrong number of warnings: ' + data.warnings + ', not ' + 2); assert.strictEqual(data.warnings, 2);
else done(); // pass done();
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should not get warnings if none', (done: Done) => { it('Should not get warnings if none', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_warning_2') fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_warning_2')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done('non 200 (' + res.status + ')');
} else {
const data = await res.json(); const data = await res.json();
if (data.warnings !== 0) done('wrong number of warnings: ' + data.warnings + ', not ' + 0); assert.strictEqual(data.warnings, 0);
else done(); // pass done();
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should done(userID for userName (No userName set)', (done: Done) => { it('Should done(userID for userName (No userName set)', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_user_02') fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_user_02')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done('non 200 (' + res.status + ')');
} else {
const data = await res.json(); const data = await res.json();
if (data.userName !== 'c2a28fd225e88f74945794ae85aef96001d4a1aaa1022c656f0dd48ac0a3ea0f') { assert.strictEqual(data.userName, 'c2a28fd225e88f74945794ae85aef96001d4a1aaa1022c656f0dd48ac0a3ea0f');
done('Did not done(userID for userName'); done();
}
done(); // pass
}
}) })
.catch(() => ('couldn\'t call endpoint')); .catch(err => done(err));
}); });
it('Should return null segment if none', (done: Done) => { it('Should return null segment if none', (done: Done) => {
fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_null') fetch(getbaseURL() + '/api/userInfo?userID=getuserinfo_null')
.then(async res => { .then(async res => {
if (res.status !== 200) { assert.strictEqual(res.status, 200);
done('non 200 (' + res.status + ')');
} else {
const data = await res.json(); const data = await res.json();
if (data.lastSegmentID !== null) done('returned segment ' + data.warnings + ', not ' + null); assert.strictEqual(data.lastSegmentID, null);
else done(); // pass done();
}
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return zeroes if userid does not exist', (done: Done) => { it('Should return zeroes if userid does not exist', (done: Done) => {
@@ -170,6 +144,6 @@ describe('getUserInfo', () => {
} }
done(); // pass done(); // pass
}) })
.catch(() => ("couldn't call endpoint")); .catch(err => done(err));
}); });
}); });

View File

@@ -2,9 +2,11 @@ import fetch from 'node-fetch';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import assert from 'assert';
import {LockCategory} from '../../src/types/segments.model'; import {LockCategory} from '../../src/types/segments.model';
const deepEquals = (a: string[],b: string[]) => { const deepStringEqual = (a: string[], b: string[]): boolean => {
if (a.length !== b.length) return false;
a.forEach((e) => { if (!b.includes(e)) return false; }); a.forEach((e) => { if (!b.includes(e)) return false; });
return true; return true;
}; };
@@ -30,8 +32,7 @@ describe('lockCategoriesRecords', () => {
it('Should update the database version when starting the application', async () => { it('Should update the database version when starting the application', async () => {
const version = (await db.prepare('get', 'SELECT key, value FROM config where key = ?', ['version'])).value; const version = (await db.prepare('get', 'SELECT key, value FROM config where key = ?', ['version'])).value;
if (version > 1) return; assert.ok(version > 1);
else return 'Version isn\'t greater than 1. Version is ' + version;
}); });
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: Done) => {
@@ -47,14 +48,12 @@ describe('lockCategoriesRecords', () => {
'intro', 'intro',
], ],
}; };
const expected = { const expected = {
submitted: [ submitted: [
'outro', 'outro',
'shilling', 'shilling',
], ],
}; };
fetch(getbaseURL() + "/api/lockCategories", { fetch(getbaseURL() + "/api/lockCategories", {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -63,16 +62,10 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json) body: JSON.stringify(json)
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const data = await res.json(); const data = await res.json();
if (deepEquals(data.submitted, expected.submitted)) { assert.deepStrictEqual(data, expected);
done(); done();
} else {
done("Incorrect response: expected " + JSON.stringify(expected) + " got " + JSON.stringify(data));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -90,7 +83,6 @@ describe('lockCategoriesRecords', () => {
'intro', 'intro',
], ],
}; };
fetch(getbaseURL() + "/api/lockCategories", { fetch(getbaseURL() + "/api/lockCategories", {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -99,28 +91,20 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json) body: JSON.stringify(json)
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['no-segments-video-id-1']) as LockCategory[]; const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['no-segments-video-id-1']) as LockCategory[];
if (result.length !== 4) { assert.strictEqual(result.length, 4);
done("Expected 4 entrys in db, got " + result.length); const oldRecordNotChangeReason = result.filter(item =>
} else { item.reason === 'reason-2' && ['sponsor', 'intro'].includes(item.category)
const oldRecordNotChangeReason = result.filter(item => { );
return item.reason === 'reason-2' && ['sponsor', 'intro'].includes(item.category);
});
const newRecordWithEmptyReason = result.filter(item => { const newRecordWithEmptyReason = result.filter(item =>
return item.reason === '' && ['outro', 'shilling'].includes(item.category); item.reason === '' && ['outro', 'shilling'].includes(item.category)
}); );
if (newRecordWithEmptyReason.length !== 2 || oldRecordNotChangeReason.length !== 2) { assert.strictEqual(newRecordWithEmptyReason.length, 2);
done(`Incorrect reason update with oldRecordNotChangeReason=${oldRecordNotChangeReason} instead of 2 or newRecordWithEmptyReason=${newRecordWithEmptyReason} instead of 2`); assert.strictEqual(oldRecordNotChangeReason.length, 2);
} else {
done(); done();
}
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -156,16 +140,10 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json) body: JSON.stringify(json)
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const data = await res.json(); const data = await res.json();
if (deepEquals(data.submitted, expected.submitted)) { assert.deepStrictEqual(data.submitted, expected.submitted);
done(); done();
} else {
done("Incorrect response: expected " + JSON.stringify(expected) + " got " + JSON.stringify(data));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -199,30 +177,19 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json) body: JSON.stringify(json)
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['no-segments-video-id-1']) as LockCategory[]; const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['no-segments-video-id-1']) as LockCategory[];
if (result.length !== 4) { assert.strictEqual(result.length, 4);
done("Expected 4 entrys in db, got " + result.length); const newRecordWithNewReason = result.filter(item =>
} else { expectedWithNewReason.includes(item.category) && item.reason === 'new reason'
const newRecordWithNewReason = result.filter(item => { );
return expectedWithNewReason.includes(item.category) && item.reason === 'new reason'; const oldRecordNotChangeReason = result.filter(item =>
}); item.reason === 'reason-2'
);
const oldRecordNotChangeReason = result.filter(item => { assert.strictEqual(newRecordWithNewReason.length, 3);
return item.reason === 'reason-2'; assert.strictEqual(oldRecordNotChangeReason.length, 1);
});
if (newRecordWithNewReason.length !== 3) {
done("Expected 3 entrys in db with new reason, got " + newRecordWithNewReason.length);
} else if (oldRecordNotChangeReason.length !== 1) {
done("Expected 1 entrys in db with old reason, got " + oldRecordNotChangeReason.length);
} else {
done(); done();
}
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -235,7 +202,6 @@ describe('lockCategoriesRecords', () => {
'word_word', 'word_word',
], ],
}; };
fetch(getbaseURL() + "/api/lockCategories", { fetch(getbaseURL() + "/api/lockCategories", {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -244,16 +210,10 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['underscore']); const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['underscore']);
if (result.length !== 1) { assert.strictEqual(result.length, 1);
done("Expected 1 entrys in db, got " + result.length);
} else {
done(); done();
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -266,7 +226,6 @@ describe('lockCategoriesRecords', () => {
'wordWord', 'wordWord',
], ],
}; };
fetch(getbaseURL() + "/api/lockCategories", { fetch(getbaseURL() + "/api/lockCategories", {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -275,16 +234,10 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['bothCases']); const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['bothCases']);
if (result.length !== 1) { assert.strictEqual(result.length, 1);
done("Expected 1 entrys in db, got " + result.length);
} else {
done(); done();
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -306,16 +259,10 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['specialChar']); const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['specialChar']);
if (result.length !== 0) { assert.strictEqual(result.length, 0);
done("Expected 0 entrys in db, got " + result.length);
} else {
done(); done();
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -328,12 +275,9 @@ describe('lockCategoriesRecords', () => {
}, },
body: JSON.stringify({}), body: JSON.stringify({}),
}) })
.then(async res => { .then(res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -344,7 +288,6 @@ describe('lockCategoriesRecords', () => {
userID: 'test', userID: 'test',
categories: [], categories: [],
}; };
fetch(getbaseURL() + "/api/lockCategories", { fetch(getbaseURL() + "/api/lockCategories", {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -352,12 +295,9 @@ describe('lockCategoriesRecords', () => {
}, },
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -376,12 +316,9 @@ describe('lockCategoriesRecords', () => {
}, },
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -400,12 +337,9 @@ describe('lockCategoriesRecords', () => {
}, },
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -424,12 +358,9 @@ describe('lockCategoriesRecords', () => {
}, },
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -448,12 +379,9 @@ describe('lockCategoriesRecords', () => {
}, },
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -474,12 +402,9 @@ describe('lockCategoriesRecords', () => {
}, },
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -501,16 +426,10 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['delete-record']); const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['delete-record']);
if (result.length === 0) { assert.strictEqual(result.length, 0);
done(); done();
} else {
done("Didn't delete record");
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -532,16 +451,10 @@ describe('lockCategoriesRecords', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['delete-record-1']); const result = await db.prepare('all', 'SELECT * FROM "lockCategories" WHERE "videoID" = ?', ['delete-record-1']);
if (result.length === 1) { assert.strictEqual(result.length, 1);
done(); done();
} else {
done("Didn't delete record");
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -568,11 +481,8 @@ describe('lockCategoriesRecords', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -596,11 +506,8 @@ describe('lockCategoriesRecords', () => {
},), },),
}) })
.then(async res => { .then(async res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -622,11 +529,8 @@ describe('lockCategoriesRecords', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -647,11 +551,8 @@ describe('lockCategoriesRecords', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
done(); done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -668,29 +569,11 @@ describe('lockCategoriesRecords', () => {
fetch(getbaseURL() + "/api/lockCategories?videoID=" + "no-segments-video-id") fetch(getbaseURL() + "/api/lockCategories?videoID=" + "no-segments-video-id")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const data = await res.json(); const data = await res.json();
if (deepEquals(data.categories, expected.categories)) { assert.ok(deepStringEqual(data.categories, expected.categories));
done(); done();
} else {
done("Incorrect response: expected " + JSON.stringify(expected) + " got " + JSON.stringify(data));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
it('Should be able to get hashedVideoID from lock', (done: Done) => {
const hashedVideoID = getHash('no-segments-video-id', 1);
db.prepare('get', 'SELECT "hashedVideoID" FROM "lockCategories" WHERE "videoID" = ?', ['no-segments-video-id'])
.then(result => {
if (result !== hashedVideoID) {
done();
} else {
done("Got unexpected video hash " + result);
}
});
});
}); });

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import assert from 'assert';
describe('getVideoSponsorTime (Old get method)', () => { describe('getVideoSponsorTime (Old get method)', () => {
before(async () => { before(async () => {
@@ -13,27 +14,27 @@ describe('getVideoSponsorTime (Old get method)', () => {
it('Should be able to get a time', (done: Done) => { it('Should be able to get a time', (done: Done) => {
fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest") fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest")
.then(res => { .then(res => {
if (res.status !== 200) done("non 200 (" + res.status + ")"); assert.strictEqual(res.status, 200);
else done(); // pass done();
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should return 404 if no segment found', (done: Done) => { it('Should return 404 if no segment found', (done: Done) => {
fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=notarealvideo") fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=notarealvideo")
.then(res => { .then(res => {
if (res.status !== 404) done("non 404 respone code: " + res.status); assert.strictEqual(res.status, 404);
else done(); // pass done();
}) })
.catch(() => done("couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be possible to send unexpected query parameters', (done: Done) => { it('Should be possible to send unexpected query parameters', (done: Done) => {
fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest&fakeparam=hello") fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest&fakeparam=hello")
.then(res => { .then(res => {
if (res.status !== 200) done("non 200"); assert.strictEqual(res.status, 200);
else done(); // pass done();
}) })
.catch(() => done("couldn't callendpoint")); .catch(() => done("couldn't callendpoint"));
}); });
@@ -41,30 +42,24 @@ describe('getVideoSponsorTime (Old get method)', () => {
it('Should be able send a comma in a query param', (done: Done) => { it('Should be able send a comma in a query param', (done: Done) => {
fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest,test") fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest,test")
.then(async res => { .then(async res => {
const body = await res.text(); assert.strictEqual(res.status, 200);
if (res.status !== 200) done("non 200 response: " + res.status); const data = await res.json();
else if (JSON.parse(body).UUIDs[0] === 'uuid-1') done(); // pass assert.strictEqual(data.UUIDs[0], "uuid-1");
else done("couldn't parse response"); done();
}) })
.catch(() => done("couln't call endpoint")); .catch(err => done(err));
}); });
it('Should be able to get the correct time', (done: Done) => { it('Should be able to get the correct time', (done: Done) => {
fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest") fetch(getbaseURL() + "/api/getVideoSponsorTimes?videoID=old-testtesttest")
.then(async res => { .then(async res => {
if (res.status !== 200) done("non 200"); assert.strictEqual(res.status, 200);
else { const data = await res.json();
const parsedBody = await res.json(); assert.strictEqual(data.sponsorTimes[0][0], 1);
if (parsedBody.sponsorTimes[0][0] === 1 assert.strictEqual(data.sponsorTimes[0][1], 11);
&& parsedBody.sponsorTimes[0][1] === 11 assert.strictEqual(data.UUIDs[0], 'uuid-0');
&& parsedBody.UUIDs[0] === 'uuid-0') { done();
done(); // pass
} else {
done("Wrong data was returned + " + JSON.stringify(parsedBody));
}
}
}) })
.catch(() => done("couldn't call endpoint")); .catch(err => done(err));
}); });
}); });

View File

@@ -1,23 +1,19 @@
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import assert from 'assert';
describe('postVideoSponsorTime (Old submission method)', () => { describe('postVideoSponsorTime (Old submission method)', () => {
it('Should be able to submit a time (GET)', (done: Done) => { it('Should be able to submit a time (GET)', (done: Done) => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/postVideoSponsorTimes?videoID=dQw4w9WgXcQ&startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest") + "/api/postVideoSponsorTimes?videoID=dQw4w9WgXcQ&startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcQ"]); const row = await db.prepare('get', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcQ"]);
if (row.startTime === 1 && row.endTime === 10 && row.category === "sponsor") { assert.strictEqual(row.startTime, 1);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -31,16 +27,12 @@ describe('postVideoSponsorTime (Old submission method)', () => {
}, },
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcE"]); const row = await db.prepare('get', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcE"]);
if (row.startTime === 1 && row.endTime === 11 && row.category === "sponsor") { assert.strictEqual(row.startTime, 1);
assert.strictEqual(row.endTime, 11);
assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -49,8 +41,8 @@ describe('postVideoSponsorTime (Old submission method)', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/postVideoSponsorTimes?startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest") + "/api/postVideoSponsorTimes?startTime=1&endTime=10&userID=testtesttesttesttesttesttesttesttest")
.then(async res => { .then(async res => {
if (res.status === 400) done(); assert.strictEqual(res.status, 400);
else done("Status code was: " + res.status); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import assert from 'assert';
describe('postClearCache', () => { describe('postClearCache', () => {
before(async () => { before(async () => {
@@ -16,8 +17,8 @@ describe('postClearCache', () => {
method: 'POST' method: 'POST'
}) })
.then(res => { .then(res => {
if (res.status === 200) done(); assert.strictEqual(res.status, 200);
else done("Status code was " + res.status); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -28,8 +29,8 @@ describe('postClearCache', () => {
method: 'POST' method: 'POST'
}) })
.then(res => { .then(res => {
if (res.status === 200) done(); assert.strictEqual(res.status, 200);
else done("Status code was " + res.status); done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -40,8 +41,8 @@ describe('postClearCache', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 403) done('non 403 (' + res.status + ')'); assert.strictEqual(res.status, 403);
else done(); // pass done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -52,8 +53,8 @@ describe('postClearCache', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -64,8 +65,8 @@ describe('postClearCache', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });

View File

@@ -58,7 +58,8 @@ describe('postPurgeAllSegments', function () {
}), }),
}) })
.then(async res => { .then(async res => {
done(res.status === 403 ? undefined : res.status); assert.strictEqual(res.status, 403);
done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -75,7 +76,7 @@ describe('postPurgeAllSegments', function () {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) return done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
done(await dbSponsorTimesCompareExpect(db, 'vsegpurge01', 1) || await dbSponsorTimesCompareExpect(db, 'vseg-not-purged01', 0)); done(await dbSponsorTimesCompareExpect(db, 'vsegpurge01', 1) || await dbSponsorTimesCompareExpect(db, 'vseg-not-purged01', 0));
}) })
.catch(err => done(err)); .catch(err => done(err));

View File

@@ -6,6 +6,7 @@ import {db} from '../../src/databases/databases';
import {ImportMock} from 'ts-mock-imports'; import {ImportMock} from 'ts-mock-imports';
import * as YouTubeAPIModule from '../../src/utils/youtubeApi'; import * as YouTubeAPIModule from '../../src/utils/youtubeApi';
import {YouTubeApiMock} from '../youtubeMock'; import {YouTubeApiMock} from '../youtubeMock';
import assert from 'assert';
const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, 'YouTubeAPI'); const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, 'YouTubeAPI');
const sinonStub = mockManager.mock('listVideos'); const sinonStub = mockManager.mock('listVideos');
@@ -62,16 +63,12 @@ describe('postSkipSegments', () => {
}, },
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcR"]); const row = await db.prepare('get', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcR"]);
if (row.startTime === 2 && row.endTime === 10 && row.category === "sponsor") { assert.strictEqual(row.startTime, 2);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -93,16 +90,13 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcF"]); const row = await db.prepare('get', `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcF"]);
if (row.startTime === 0 && row.endTime === 10 && row.locked === 0 && row.category === "sponsor") { assert.strictEqual(row.startTime, 0);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.locked, 0);
assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -125,16 +119,14 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { 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 db.prepare('get', `SELECT "startTime", "endTime", "locked", "category", "actionType" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcV"]);
if (row.startTime === 0 && row.endTime === 10 && row.locked === 0 && row.category === "sponsor" && row.actionType === "mute") { assert.strictEqual(row.startTime, 0);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.locked, 0);
assert.strictEqual(row.category, "sponsor");
assert.strictEqual(row.actionType, "mute");
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -157,16 +149,14 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { 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 db.prepare('get', `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXZX"]);
if (row.startTime === 0 && row.endTime === 10 && row.locked === 0 && row.category === "sponsor" && row.videoDuration === 4980) { assert.strictEqual(row.startTime, 0);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.locked, 0);
assert.strictEqual(row.category, "sponsor");
assert.strictEqual(row.videoDuration, 4980);
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -189,16 +179,14 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { 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 db.prepare('get', `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXZH"]);
if (row.startTime === 1 && row.endTime === 10 && row.locked === 0 && row.category === "sponsor" && row.videoDuration === 4980.20) { assert.strictEqual(row.startTime, 1);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.locked, 0);
assert.strictEqual(row.category, "sponsor");
assert.strictEqual(row.videoDuration, 4980.20);
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -221,16 +209,14 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { 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 db.prepare('get', `SELECT "startTime", "endTime", "locked", "category", "videoDuration" FROM "sponsorTimes" WHERE "videoID" = ?`, ["noDuration"]);
if (row.startTime === 0 && row.endTime === 10 && row.locked === 0 && row.category === "sponsor" && row.videoDuration === 100) { assert.strictEqual(row.startTime, 0);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.locked, 0);
assert.strictEqual(row.category, "sponsor");
assert.strictEqual(row.videoDuration, 100);
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -256,23 +242,21 @@ describe('postSkipSegments', () => {
}], }],
}), }),
}); });
assert.strictEqual(res.status, 200);
if (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 = ?`, ["noDuration"]);
const videoRows = await db.prepare('all', `SELECT "startTime", "endTime", "locked", "category", "videoDuration" 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`, ["noDuration"]);
const videoRow = videoRows[0]; const videoRow = videoRows[0];
const hiddenVideoRows = await db.prepare('all', `SELECT "startTime", "endTime", "locked", "category", "videoDuration" 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`, ["noDuration"]);
if (lockCategoriesRow === undefined && videoRows.length === 1 && hiddenVideoRows.length === 1 && videoRow.startTime === 1 && videoRow.endTime === 10 assert.ok(!lockCategoriesRow);
&& videoRow.locked === 0 && videoRow.category === "sponsor" && videoRow.videoDuration === 100) { assert.strictEqual(videoRows.length, 1);
return; assert.strictEqual(hiddenVideoRows.length, 1);
} else { assert.strictEqual(videoRow.startTime, 1);
return "Submitted times were not saved. Actual submission: " + JSON.stringify(videoRow); assert.strictEqual(videoRow.endTime, 10);
} assert.strictEqual(videoRow.locked, 0);
} else { assert.strictEqual(videoRow.category, "sponsor");
return "Status code was " + res.status; assert.strictEqual(videoRow.videoDuration, 100);
}
} catch (e) { } catch (e) {
return e; return e;
} }
@@ -284,13 +268,10 @@ describe('postSkipSegments', () => {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(async res => {
if (res.status === 403) done(); // pass assert.strictEqual(res.status, 403);
else { done();
const body = await res.text();
done("non 403 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -311,16 +292,14 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { 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" = ?`, ["dQw4w9WgXcG"]);
if (row.startTime === 0 && row.endTime === 10 && row.locked === 0 && row.category === "sponsor" && row.service === "PeerTube") { assert.strictEqual(row.startTime, 0);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.locked, 0);
assert.strictEqual(row.category, "sponsor");
assert.strictEqual(row.service, "PeerTube");
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -342,16 +321,13 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["vipuserIDSubmission"]); const row = await db.prepare('get', `SELECT "startTime", "endTime", "locked", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["vipuserIDSubmission"]);
if (row.startTime === 0 && row.endTime === 10 && row.locked === 1 && row.category === "sponsor") { assert.strictEqual(row.startTime, 0);
assert.strictEqual(row.endTime, 10);
assert.strictEqual(row.locked, 1);
assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Submitted times were not saved. Actual submission: " + JSON.stringify(row));
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -365,7 +341,7 @@ describe('postSkipSegments', () => {
}, },
body: JSON.stringify({ body: JSON.stringify({
userID: "testtesttesttesttesttesttesttesttest", userID: "testtesttesttesttesttesttesttesttest",
videoID: "dQw4w9WgXcQ", videoID: "dQw4w9WgXcT",
segments: [{ segments: [{
segment: [3, 10], segment: [3, 10],
category: "sponsor", category: "sponsor",
@@ -376,23 +352,19 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const rows = await db.prepare('all', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcR"]); const rows = await db.prepare('all', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, ["dQw4w9WgXcT"]);
let success = true; const expected = [{
if (rows.length === 2) { startTime: 3,
for (const row of rows) { endTime: 10,
if ((row.startTime !== 3 || row.endTime !== 10 || row.category !== "sponsor") && category: "sponsor"
(row.startTime !== 30 || row.endTime !== 60 || row.category !== "intro")) { }, {
success = false; startTime: 30,
break; endTime: 60,
} category: "intro"
} }];
} assert.deepStrictEqual(rows, expected);
if (success) done(); done();
else done("Submitted times were not saved. Actual submissions: " + JSON.stringify(rows));
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}).timeout(5000); }).timeout(5000);
@@ -423,25 +395,27 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { 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`, ["L_jWHffIx5E"]);
let success = true; const expected = [{
if (rows.length === 4) { startTime: 3,
for (const row of rows) { endTime: 3000,
if ((row.startTime !== 3 || row.endTime !== 3000 || row.category !== "sponsor") && category: "sponsor"
(row.startTime !== 3002 || row.endTime !== 3050 || row.category !== "intro") && }, {
(row.startTime !== 45 || row.endTime !== 100 || row.category !== "interaction") && startTime: 3002,
(row.startTime !== 99 || row.endTime !== 170 || row.category !== "sponsor")) { endTime: 3050,
success = false; category: "intro"
break; }, {
} startTime: 45,
} endTime: 100,
} category: "interaction"
if (success) done(); }, {
else done("Submitted times were not saved. Actual submissions: " + JSON.stringify(rows)); startTime: 99,
} else { endTime: 170,
done("Status code was " + res.status); category: "sponsor"
} }];
assert.deepStrictEqual(rows, expected);
done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}).timeout(5000); }).timeout(5000);
@@ -472,27 +446,10 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 403) { 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`, ["n9rIGdXnSJc"]);
let success = true; assert.deepStrictEqual(rows, []);
if (rows.length === 4) { done();
for (const row of rows) {
if ((row.startTime === 0 || row.endTime === 2000 || row.category === "interaction") ||
(row.startTime === 3000 || row.endTime === 4000 || row.category === "sponsor") ||
(row.startTime === 1500 || row.endTime === 2750 || row.category === "sponsor") ||
(row.startTime === 4050 || row.endTime === 4750 || row.category === "intro")) {
success = false;
break;
}
}
}
if (success) done();
else
done("Submitted times were not saved. Actual submissions: " + JSON.stringify(rows));
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}).timeout(5000); }).timeout(5000);
@@ -520,23 +477,23 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
const expected = [{
category: "sponsor",
startTime: 2000,
endTime: 4000
}, {
category: "sponsor",
startTime: 1500,
endTime: 2750
}, {
category: "sponsor",
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 db.prepare('all', `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ? and "votes" > -1`, ["80percent_video"]);
let success = rows.length == 2; assert.notDeepStrictEqual(rows, expected);
for (const row of rows) { done();
if ((row.startTime === 2000 || row.endTime === 4000 || row.category === "sponsor") ||
(row.startTime === 1500 || row.endTime === 2750 || row.category === "sponsor") ||
(row.startTime === 4050 || row.endTime === 4750 || row.category === "sponsor")) {
success = false;
break;
}
}
if (success) done();
else
done("Submitted times were not saved. Actual submissions: " + JSON.stringify(rows));
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}).timeout(5000); }).timeout(5000);
@@ -546,14 +503,11 @@ describe('postSkipSegments', () => {
+ "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting&category=intro", { + "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting&category=intro", {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(res => {
if (res.status === 200) done(); // pass assert.strictEqual(res.status, 200);
else { done();
const body = await res.text();
done("non 200 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -561,14 +515,11 @@ describe('postSkipSegments', () => {
+ "/api/skipSegments?videoID=qqwerty&startTime=90&endTime=90&userID=testtesttesttesttesttesttesttesttesting&category=intro", { + "/api/skipSegments?videoID=qqwerty&startTime=90&endTime=90&userID=testtesttesttesttesttesttesttesttesting&category=intro", {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); // pass assert.strictEqual(res.status, 400);
else { done();
const body = await res.text();
done("non 400 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -576,14 +527,11 @@ describe('postSkipSegments', () => {
+ "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30&userID=testtesttesttesttesttesttesttesttesting&category=highlight", { + "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30&userID=testtesttesttesttesttesttesttesttesting&category=highlight", {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(res => {
if (res.status === 200) done(); // pass assert.strictEqual(res.status, 200);
else { done();
const body = await res.text();
done("non 200 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -591,14 +539,11 @@ describe('postSkipSegments', () => {
+ "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting&category=highlight", { + "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting&category=highlight", {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); // pass assert.strictEqual(res.status, 400);
else { done();
const body = await res.text();
done("non 400 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -606,40 +551,31 @@ describe('postSkipSegments', () => {
+ "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting", { + "/api/skipSegments?videoID=qqwerty&startTime=30&endTime=30.5&userID=testtesttesttesttesttesttesttesttesting", {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); // pass assert.strictEqual(res.status, 400);
else { done();
const body = await res.text();
done("non 403 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/postVideoSponsorTimes?videoID=qqwerty&startTime=30&endTime=1000000&userID=testtesttesttesttesttesttesttesttesting") + "/api/postVideoSponsorTimes?videoID=qqwerty&startTime=30&endTime=1000000&userID=testtesttesttesttesttesttesttesttesting")
.then(async res => { .then(res => {
if (res.status === 403) done(); // pass assert.strictEqual(res.status, 403);
else { done();
const body = await res.text();
done("non 403 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/postVideoSponsorTimes?videoID=LevkAjUE6d4&startTime=40&endTime=60&userID=testtesttesttesttesttesttesttesttesting") + "/api/postVideoSponsorTimes?videoID=LevkAjUE6d4&startTime=40&endTime=60&userID=testtesttesttesttesttesttesttesttesting")
.then(async res => { .then(res => {
if (res.status === 200) done(); // pass assert.strictEqual(res.status, 200);
else { done();
const body = await res.text();
done("non 200 status code: " + res.status + " (" + body + ")");
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
it('Should be rejected with custom message if user has to many active warnings', (done: Done) => { it('Should be rejected with custom message if user has to many active warnings', (done: Done) => {
@@ -659,16 +595,10 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
const errorMessage = await res.text(); const errorMessage = await res.text();
if (errorMessage === 'Reason01') { assert.strictEqual(errorMessage, 'Reason01');
done(); // success done();
} else {
done("Status code was 403 but message was: " + errorMessage);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -736,7 +666,7 @@ describe('postSkipSegments', () => {
if (res.status === 400) done(); if (res.status === 400) done();
else done(true); else done(true);
}) })
.catch(() => done(true)); .catch(err => done(err));
}); });
it('Should be rejected with default message if user has to many active warnings', (done: Done) => { it('Should be rejected with default message if user has to many active warnings', (done: Done) => {
@@ -756,16 +686,10 @@ describe('postSkipSegments', () => {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
const errorMessage = await res.text(); const errorMessage = await res.text();
if (errorMessage !== '') { assert.notStrictEqual(errorMessage, '');
done(); // success done();
} else {
done("Status code was 403 but message was: " + errorMessage);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -788,11 +712,11 @@ describe('postSkipSegments', () => {
}], }],
}), }),
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); assert.strictEqual(res.status, 400);
else done(true); done();
}) })
.catch(() => done(true)); .catch(err => done(err));
}); });
it('Should return 400 for missing params (JSON method) 2', (done: Done) => { it('Should return 400 for missing params (JSON method) 2', (done: Done) => {
fetch(getbaseURL() fetch(getbaseURL()
@@ -806,11 +730,11 @@ describe('postSkipSegments', () => {
videoID: "dQw4w9WgXcQ", videoID: "dQw4w9WgXcQ",
}), }),
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); assert.strictEqual(res.status, 400);
else done(true); done();
}) })
.catch(() => done(true)); .catch(err => done(err));
}); });
it('Should return 400 for missing params (JSON method) 3', (done: Done) => { it('Should return 400 for missing params (JSON method) 3', (done: Done) => {
fetch(getbaseURL() fetch(getbaseURL()
@@ -831,11 +755,11 @@ describe('postSkipSegments', () => {
}], }],
}), }),
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); assert.strictEqual(res.status, 400);
else done(true); done();
}) })
.catch(() => done(true)); .catch(err => done(err));
}); });
it('Should return 400 for missing params (JSON method) 4', (done: Done) => { it('Should return 400 for missing params (JSON method) 4', (done: Done) => {
fetch(getbaseURL() fetch(getbaseURL()
@@ -855,11 +779,11 @@ describe('postSkipSegments', () => {
}], }],
}), }),
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); assert.strictEqual(res.status, 400);
else done(true); done();
}) })
.catch(() => done(true)); .catch(err => done(err));
}); });
it('Should return 400 for missing params (JSON method) 5', (done: Done) => { it('Should return 400 for missing params (JSON method) 5', (done: Done) => {
fetch(getbaseURL() fetch(getbaseURL()
@@ -873,10 +797,10 @@ describe('postSkipSegments', () => {
videoID: "dQw4w9WgXcQ", videoID: "dQw4w9WgXcQ",
}), }),
}) })
.then(async res => { .then(res => {
if (res.status === 400) done(); assert.strictEqual(res.status, 400);
else done(true); done();
}) })
.catch(() => done(true)); .catch(err => done(err));
}); });
}); });

View File

@@ -24,18 +24,12 @@ describe('postWarning', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [json.userID]); const row = await db.prepare('get', `SELECT "userID", "issueTime", "issuerUserID", enabled, "reason" FROM warnings WHERE "userID" = ?`, [json.userID]);
if (row?.enabled == 1 && row?.issuerUserID == getHash(json.issuerUserID) && row?.reason === json.reason) { assert.strictEqual(row.enabled, 1);
assert.strictEqual(row.issuerUserID, getHash(json.issuerUserID));
assert.strictEqual(row.reason, json.reason);
done(); done();
} else {
done("Warning missing from database");
}
} else {
const body = await res.text();
console.log(body);
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -55,18 +49,11 @@ describe('postWarning', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 409) { assert.strictEqual(res.status, 409);
const row = await db.prepare('get', `SELECT "userID", "issueTime", "issuerUserID", enabled FROM warnings WHERE "userID" = ?`, [json.userID]); const row = await db.prepare('get', `SELECT "userID", "issueTime", "issuerUserID", enabled FROM warnings WHERE "userID" = ?`, [json.userID]);
if (row?.enabled == 1 && row?.issuerUserID == getHash(json.issuerUserID)) { assert.strictEqual(row.enabled, 1);
assert.strictEqual(row.issuerUserID, getHash(json.issuerUserID));
done(); done();
} else {
done("Warning missing from database");
}
} else {
const body = await res.text();
console.log(body);
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -87,18 +74,10 @@ describe('postWarning', () => {
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "userID", "issueTime", "issuerUserID", enabled FROM warnings WHERE "userID" = ?`, [json.userID]); const row = await db.prepare('get', `SELECT "userID", "issueTime", "issuerUserID", enabled FROM warnings WHERE "userID" = ?`, [json.userID]);
if (row?.enabled == 0) { assert.strictEqual(row.enabled, 0);
done(); done();
} else {
done("Warning missing from database");
}
} else {
const body = await res.text();
console.log(body);
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -117,14 +96,9 @@ describe('postWarning', () => {
}, },
body: JSON.stringify(json), body: JSON.stringify(json),
}) })
.then(async res => { .then(res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
done(); done();
} else {
const body = await res.text();
console.log(body);
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });

View File

@@ -3,6 +3,7 @@ import {Done, getbaseURL} from '../utils';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import {IDatabase} from '../../src/databases/IDatabase'; import {IDatabase} from '../../src/databases/IDatabase';
import assert from 'assert';
async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) { async function dbSponsorTimesAdd(db: IDatabase, videoID: string, startTime: number, endTime: number, UUID: string, category: string) {
const votes = 0, const votes = 0,
@@ -22,25 +23,18 @@ async function dbSponsorTimesSetByUUID(db: IDatabase, UUID: string, startTime: n
await db.prepare('run', `UPDATE "sponsorTimes" SET "startTime" = ?, "endTime" = ? WHERE "UUID" = ?`, [startTime, endTime, UUID]); await db.prepare('run', `UPDATE "sponsorTimes" SET "startTime" = ?, "endTime" = ? WHERE "UUID" = ?`, [startTime, endTime, UUID]);
} }
async function dbSponsorTimesCompareExpect(db: IDatabase, expect: any) { async function dbSponsorTimesCompareExpect(db: IDatabase, expect: any): Promise<void> {
for (let i = 0, len = expect.length; i < len; i++) { for (let i = 0, len = expect.length; i < len; i++) {
const expectSeg = expect[i]; const expectSeg = expect[i];
const seg = await db.prepare('get', `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "UUID" = ?`, [expectSeg.UUID]); const seg = await db.prepare('get', `SELECT "startTime", "endTime" FROM "sponsorTimes" WHERE "UUID" = ?`, [expectSeg.UUID]);
if ('removed' in expect) { if ('removed' in expect) {
if (expect.removed === true && seg.votes === -2) { assert.ok(expect.removed);
return; assert.strictEqual(seg.votes, -2);
} else { assert.deepStrictEqual(seg, expectSeg);
return `${expectSeg.UUID} doesnt got removed`; assert.strictEqual(seg.startTime, expectSeg.startTime);
assert.strictEqual(seg.endTime, expectSeg.endTime);
} }
} }
if (seg.startTime !== expectSeg.startTime) {
return `${expectSeg.UUID} startTime is incorrect. seg.startTime is ${seg.startTime} expected ${expectSeg.startTime}`;
}
if (seg.endTime !== expectSeg.endTime) {
return `${expectSeg.UUID} endTime is incorrect. seg.endTime is ${seg.endTime} expected ${expectSeg.endTime}`;
}
}
return;
} }
describe('segmentShift', function () { describe('segmentShift', function () {
@@ -79,7 +73,8 @@ describe('segmentShift', function () {
}), }),
}) })
.then(async res => { .then(async res => {
done(res.status === 403 ? undefined : res.status); assert.strictEqual(res.status, 403);
done();
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -98,7 +93,7 @@ describe('segmentShift', function () {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) return done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
const expect = [ const expect = [
{ {
UUID: 'vsegshifttest01uuid01', UUID: 'vsegshifttest01uuid01',
@@ -140,7 +135,7 @@ describe('segmentShift', function () {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) return done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
const expect = [ const expect = [
{ {
UUID: 'vsegshifttest01uuid01', UUID: 'vsegshifttest01uuid01',
@@ -182,7 +177,7 @@ describe('segmentShift', function () {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) return done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
const expect = [ const expect = [
{ {
UUID: 'vsegshifttest01uuid01', UUID: 'vsegshifttest01uuid01',
@@ -224,7 +219,7 @@ describe('segmentShift', function () {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) return done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
const expect = [ const expect = [
{ {
UUID: 'vsegshifttest01uuid01', UUID: 'vsegshifttest01uuid01',
@@ -266,7 +261,7 @@ describe('segmentShift', function () {
}), }),
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) return done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
const expect = [ const expect = [
{ {
UUID: 'vsegshifttest01uuid01', UUID: 'vsegshifttest01uuid01',

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import { Done, getbaseURL } from '../utils'; import { Done, getbaseURL } from '../utils';
import { db, privateDB } from '../../src/databases/databases'; import { db, privateDB } from '../../src/databases/databases';
import { getHash } from '../../src/utils/getHash'; import { getHash } from '../../src/utils/getHash';
import assert from 'assert';
const adminPrivateUserID = 'testUserId'; const adminPrivateUserID = 'testUserId';
const user00PrivateUserID = 'setUsername_00'; const user00PrivateUserID = 'setUsername_00';
@@ -51,21 +52,10 @@ function wellFormatUserName(userName: string) {
} }
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: Done) {
const log = await getLastLogUserNameChange(userID); const log = await getLastLogUserNameChange(userID);
assert.strictEqual(newUserName, log.newUserName);
if (newUserName !== log.newUserName) { assert.strictEqual(oldUserName, log.oldUserName);
return done(`UserID '${userID}' incorrect log on newUserName: ${newUserName} !== ${log.newUserName}`); assert.strictEqual(byAdmin, Boolean(log.updatedByAdmin));
}
if (oldUserName !== log.oldUserName) {
return done(`UserID '${userID}' incorrect log on oldUserName: ${oldUserName} !== ${log.oldUserName}`);
}
if (byAdmin !== Boolean(log.updatedByAdmin)) {
return done(`UserID '${userID}' incorrect log on updatedByAdmin: ${byAdmin} !== ${log.updatedByAdmin}`);
}
return done(); return done();
} }
@@ -86,9 +76,9 @@ describe('setUsername', () => {
}) })
.then(async res => { .then(async res => {
const usernameInfo = await getUsernameInfo(getHash(user00PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user00PrivateUserID));
if (res.status !== 200) done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
if (usernameInfo.userName !== username00) done(`Username did not change. Currently is ${usernameInfo.userName}`); assert.strictEqual(usernameInfo.userName, username00);
if (usernameInfo.locked == "1") done(`Username was locked when it shouldn't have been`); assert.notStrictEqual(usernameInfo.locked, 1, "username should not be locked");
done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
@@ -99,10 +89,8 @@ describe('setUsername', () => {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
else {
testUserNameChangelog(user01PrivateUserID, decodeURIComponent('Changed%20Username'), username01, false, done); testUserNameChangelog(user01PrivateUserID, decodeURIComponent('Changed%20Username'), username01, false, done);
}
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -112,8 +100,8 @@ describe('setUsername', () => {
method: 'POST', method: 'POST',
}) })
.then(res => { .then(res => {
if (res.status !== 400) done(`Status code was ${res.status}`); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -123,8 +111,8 @@ describe('setUsername', () => {
method: 'POST', method: 'POST',
}) })
.then(res => { .then(res => {
if (res.status !== 400) done(`Status code was ${res.status}`); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -135,8 +123,8 @@ describe('setUsername', () => {
method: 'POST', method: 'POST',
}) })
.then(res => { .then(res => {
if (res.status !== 400) done(`Status code was ${res.status}`); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -147,14 +135,10 @@ describe('setUsername', () => {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) done(`Status code was ${res.status}`); assert.strictEqual(res.status, 200);
else {
const userNameInfo = await getUsernameInfo(getHash(user02PrivateUserID)); const userNameInfo = await getUsernameInfo(getHash(user02PrivateUserID));
if (userNameInfo.userName === newUsername) { assert.notStrictEqual(userNameInfo.userName, newUsername);
done(`Username '${username02}' got changed to '${newUsername}'`); done();
}
else done();
}
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -166,8 +150,8 @@ describe('setUsername', () => {
}) })
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user03PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user03PrivateUserID));
if (usernameInfo.userName !== newUsername) done(`Username did not change`); assert.strictEqual(usernameInfo.userName, newUsername, "Username should change");
if (usernameInfo.locked == "1") done(`Username was locked when it shouldn't have been`); assert.notStrictEqual(usernameInfo.locked, 1, "Username should not be locked");
testUserNameChangelog(user03PrivateUserID, newUsername, username03, false, done); testUserNameChangelog(user03PrivateUserID, newUsername, username03, false, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
@@ -180,9 +164,9 @@ describe('setUsername', () => {
}) })
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user04PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user04PrivateUserID));
if (usernameInfo.userName === newUsername) done(`Username '${username04}' got changed to '${usernameInfo}'`); assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not be changed");
if (usernameInfo.locked == "0") done(`Username was unlocked when it shouldn't have been`); assert.strictEqual(usernameInfo.locked, 1, "username should be locked");
else done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -194,7 +178,7 @@ describe('setUsername', () => {
}) })
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user05PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user05PrivateUserID));
if (usernameInfo.userName === newUsername) done(`Username contains unicode control characters`); assert.notStrictEqual(usernameInfo.userName, newUsername, "Username should not contain control characters");
testUserNameChangelog(user05PrivateUserID, wellFormatUserName(newUsername), username05, false, done); testUserNameChangelog(user05PrivateUserID, wellFormatUserName(newUsername), username05, false, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
@@ -206,8 +190,8 @@ describe('setUsername', () => {
method: 'POST', method: 'POST',
}) })
.then(async res => { .then(async res => {
if (res.status !== 403) done(`Status code was ${res.status}`); assert.strictEqual(res.status, 403);
else done(); done();
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -219,9 +203,9 @@ describe('setUsername', () => {
}) })
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID));
if (usernameInfo.userName !== newUsername) done(`Failed to change username from '${username06}' to '${newUsername}'`); assert.strictEqual(usernameInfo.userName, newUsername, "username should be changed");
if (usernameInfo.locked == "0") done(`Username was not locked`); assert.strictEqual(usernameInfo.locked, 1, "Username should be locked");
else testUserNameChangelog(user06PrivateUserID, newUsername, username06, true, done); testUserNameChangelog(user06PrivateUserID, newUsername, username06, true, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });
@@ -233,9 +217,9 @@ describe('setUsername', () => {
}) })
.then(async () => { .then(async () => {
const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID)); const usernameInfo = await getUsernameInfo(getHash(user06PrivateUserID));
if (usernameInfo.userName !== newUsername) done(`Failed to change username from '${username06}' to '${newUsername}'`); assert.strictEqual(usernameInfo.userName, newUsername, "Username should be changed");
if (usernameInfo.locked == "0") done(`Username was unlocked when it shouldn't have been`); assert.strictEqual(usernameInfo.locked, 1, "Username should be locked");
else testUserNameChangelog(user07PrivateUserID, newUsername, username07, true, done); testUserNameChangelog(user07PrivateUserID, newUsername, username07, true, done);
}) })
.catch(() => done(`couldn't call endpoint`)); .catch(() => done(`couldn't call endpoint`));
}); });

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import {db} from '../../src/databases/databases'; import {db} from '../../src/databases/databases';
import {Done, getbaseURL} from '../utils'; import {Done, getbaseURL} from '../utils';
import {getHash} from '../../src/utils/getHash'; import {getHash} from '../../src/utils/getHash';
import assert from 'assert';
describe('shadowBanUser', () => { describe('shadowBanUser', () => {
before(async () => { before(async () => {
@@ -28,19 +29,14 @@ describe('shadowBanUser', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const videoRow = await db.prepare('all', `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned", 1]); 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 shadowRow = await db.prepare('get', `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned"]);
assert.ok(shadowRow);
if (shadowRow && videoRow?.length === 3) { assert.strictEqual(videoRow.length, 3);
done(); done();
} else {
done("Ban failed " + JSON.stringify(videoRow) + " " + JSON.stringify(shadowRow));
}
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -48,19 +44,14 @@ describe('shadowBanUser', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const videoRow = await db.prepare('all', `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned", 1]); 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 shadowRow = await db.prepare('get', `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned"]);
assert.ok(!shadowRow);
if (!shadowRow && videoRow?.length === 3) { assert.strictEqual(videoRow.length, 3);
done(); done();
} else {
done("Unban failed " + JSON.stringify(videoRow) + " " + JSON.stringify(shadowRow));
}
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -68,19 +59,15 @@ describe('shadowBanUser', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const videoRow: {category: string, shadowHidden: number}[] = (await db.prepare('all', `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned2", 1])); 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 shadowRow = await db.prepare('get', `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned2"]);
assert.ok(shadowRow);
if (shadowRow && 2 == videoRow?.length && 2 === videoRow?.filter((elem) => elem?.category === "sponsor")?.length) { assert.strictEqual(videoRow.length, 2);
assert.strictEqual(videoRow.filter((elem) => elem.category === "sponsor").length, 2);
done(); done();
} else {
done("Ban failed " + JSON.stringify(videoRow) + " " + JSON.stringify(shadowRow));
}
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -88,19 +75,14 @@ describe('shadowBanUser', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const videoRow = await db.prepare('all', `SELECT "shadowHidden" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned2", 1]); 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 shadowRow = await db.prepare('get', `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned2"]);
assert.ok(!shadowRow);
if (!shadowRow && videoRow?.length === 0) { assert.strictEqual(videoRow?.length, 0);
done(); done();
} else {
done("Unban failed " + JSON.stringify(videoRow) + " " + JSON.stringify(shadowRow));
}
}
}) })
.catch(() => done("Couldn't call endpoint")); .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: Done) => {
@@ -108,19 +90,15 @@ describe('shadowBanUser', () => {
method: 'POST' method: 'POST'
}) })
.then(async res => { .then(async res => {
if (res.status !== 200) done("Status code was: " + res.status); assert.strictEqual(res.status, 200);
else {
const videoRow = await db.prepare('all', `SELECT "shadowHidden", "category" FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?`, ["shadowBanned3", 1]); 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 shadowRow = await db.prepare('get', `SELECT * FROM "shadowBannedUsers" WHERE "userID" = ?`, ["shadowBanned3"]);
assert.ok(!shadowRow);
if (!shadowRow && videoRow?.length === 1 && videoRow[0]?.category === "intro") { assert.strictEqual(videoRow.length, 1);
assert.strictEqual(videoRow[0].category, "intro");
done(); done();
} else {
done("Unban failed " + JSON.stringify(videoRow) + " " + JSON.stringify(shadowRow));
}
}
}) })
.catch(() => done("Couldn't call endpoint")); .catch(err => done(err));
}); });
}); });

View File

@@ -2,6 +2,7 @@ import fetch from 'node-fetch';
import * as utils from '../utils'; import * as utils from '../utils';
import { getHash } from '../../src/utils/getHash'; import { getHash } from '../../src/utils/getHash';
import { db } from '../../src/databases/databases'; import { db } from '../../src/databases/databases';
import assert from 'assert';
describe('unBan', () => { describe('unBan', () => {
before(async () => { before(async () => {
@@ -31,19 +32,10 @@ describe('unBan', () => {
}, },
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "sponsorTimes" WHERE "videoID" = ? AND "userID" = ? AND "shadowHidden" = ?', ['unBan-videoID-0', 'testMan-unBan', 1]); const result = await db.prepare('all', 'SELECT * FROM "sponsorTimes" WHERE "videoID" = ? AND "userID" = ? AND "shadowHidden" = ?', ['unBan-videoID-0', 'testMan-unBan', 1]);
if (result.length !== 0) { assert.strictEqual(result.length, 0);
console.log(result);
done("Expected 0 banned entrys in db, got " + result.length);
} else {
done(); done();
}
} else {
const body = await res.text();
console.log(body);
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -56,19 +48,10 @@ describe('unBan', () => {
}, },
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "sponsorTimes" WHERE "videoID" = ? AND "userID" = ? AND "shadowHidden" = ?', ['unBan-videoID-1', 'testWoman-unBan', 1]); const result = await db.prepare('all', 'SELECT * FROM "sponsorTimes" WHERE "videoID" = ? AND "userID" = ? AND "shadowHidden" = ?', ['unBan-videoID-1', 'testWoman-unBan', 1]);
if (result.length !== 1) { assert.strictEqual(result.length, 1);
console.log(result);
done("Expected 1 banned entry1 in db, got " + result.length);
} else {
done(); done();
}
} else {
const body = await res.text();
console.log(body);
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -81,19 +64,10 @@ describe('unBan', () => {
}, },
}) })
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const result = await db.prepare('all', 'SELECT * FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?', ['testEntity-unBan', 1]); const result = await db.prepare('all', 'SELECT * FROM "sponsorTimes" WHERE "userID" = ? AND "shadowHidden" = ?', ['testEntity-unBan', 1]);
if (result.length !== 1) { assert.strictEqual(result.length, 1);
console.log(result);
done("Expected 1 banned entry1 in db, got " + result.length);
} else {
done(); done();
}
} else {
const body = await res.text();
console.log(body);
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });

View File

@@ -6,6 +6,7 @@ import {getHash} from '../../src/utils/getHash';
import {ImportMock} from 'ts-mock-imports'; import {ImportMock} from 'ts-mock-imports';
import * as YouTubeAPIModule from '../../src/utils/youtubeApi'; import * as YouTubeAPIModule from '../../src/utils/youtubeApi';
import {YouTubeApiMock} from '../youtubeMock'; import {YouTubeApiMock} from '../youtubeMock';
import assert from 'assert';
const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, 'YouTubeAPI'); const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, 'YouTubeAPI');
const sinonStub = mockManager.mock('listVideos'); const sinonStub = mockManager.mock('listVideos');
@@ -66,16 +67,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID&UUID=vote-uuid-0&type=1") + "/api/voteOnSponsorTime?userID=randomID&UUID=vote-uuid-0&type=1")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-0"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-0"]);
if (row.votes === 3) { assert.strictEqual(row.votes, 3);
done(); done();
} else {
done("Vote did not succeed. Submission went from 2 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -84,16 +79,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=0") + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]);
if (row.votes < 10) { assert.ok(row.votes < 10);
done(); done();
} else {
done("Vote did not succeed. Submission went from 10 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -102,16 +91,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID3&UUID=vote-uuid-2&type=0") + "/api/voteOnSponsorTime?userID=randomID3&UUID=vote-uuid-2&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]);
if (row.votes === 9) { assert.strictEqual(row.votes, 9);
done(); done();
} else {
done("Vote did not fail. Submission went from 9 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -120,16 +103,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID4&UUID=vote-uuid-1.6&type=0") + "/api/voteOnSponsorTime?userID=randomID4&UUID=vote-uuid-1.6&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1.6"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1.6"]);
if (row.votes === 10) { assert.strictEqual(row.votes, 10);
done(); done();
} else {
done("Vote did not fail. Submission went from 10 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -138,16 +115,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1&type=1") + "/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1&type=1")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1"]);
if (row.votes === 2) { assert.strictEqual(row.votes, 2);
done(); done();
} else {
done("Vote did not fail. Submission went from 2 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -156,16 +127,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1.5&type=0") + "/api/voteOnSponsorTime?userID=hasNotSubmittedID&UUID=vote-uuid-1.5&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1.5"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-1.5"]);
if (row.votes === 10) { assert.strictEqual(row.votes, 10);
done(); done();
} else {
done("Vote did not fail. Submission went from 10 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -174,16 +139,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-3&type=0") + "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-3&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-3"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-3"]);
if (row.votes <= -2) { assert.ok(row.votes <= -2);
done(); done();
} else {
done("Vote did not succeed. Submission went from 100 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -192,16 +151,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=own-submission-id&UUID=own-submission-uuid&type=0") + "/api/voteOnSponsorTime?userID=own-submission-id&UUID=own-submission-uuid&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["own-submission-uuid"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["own-submission-uuid"]);
if (row.votes <= -2) { assert.ok(row.votes <= -2);
done(); done();
} else {
done("Vote did not succeed. Submission went from 500 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -210,16 +163,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=not-own-submission-uuid&type=0") + "/api/voteOnSponsorTime?userID=randomID2&UUID=not-own-submission-uuid&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["not-own-submission-uuid"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["not-own-submission-uuid"]);
if (row.votes === 499) { assert.strictEqual(row.votes, 499);
done(); done();
} else {
done("Vote did not succeed. Submission went from 500 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -228,19 +175,16 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=intro") + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-4&category=intro")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-4"]); const row = await 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 categoryRows = await db.prepare('all', `SELECT votes, category FROM "categoryVotes" WHERE "UUID" = ?`, ["vote-uuid-4"]);
if (row.category === "sponsor" && categoryRows.length === 2 assert.strictEqual(row.category, "sponsor");
&& categoryRows[0]?.votes === 1 && categoryRows[0]?.category === "intro" assert.strictEqual(categoryRows.length, 2);
&& categoryRows[1]?.votes === 1 && categoryRows[1]?.category === "sponsor") { assert.strictEqual(categoryRows[0].votes, 1);
assert.strictEqual(categoryRows[0].category, "intro");
assert.strictEqual(categoryRows[1].votes, 1);
assert.strictEqual(categoryRows[1].category, "sponsor");
done(); done();
} else {
done("Submission changed to " + row.category + " instead of staying as sponsor. Vote was applied as " + categoryRows[0]?.category + " with " + categoryRows[0]?.votes + " votes and there were " + categoryRows.length + " rows.");
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -249,16 +193,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=fakecategory") + "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=fakecategory")
.then(async res => { .then(async res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category"]); const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category"]);
if (row.category === "sponsor") { assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Vote did not succeed. Submission went from sponsor to " + row.category);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -267,16 +205,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=highlight") + "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category&category=highlight")
.then(async res => { .then(async res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category"]); const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category"]);
if (row.category === "sponsor") { assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Vote did not succeed. Submission went from sponsor to " + row.category);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -296,13 +228,12 @@ describe('voteOnSponsorTime', () => {
if (row?.category === "outro") outroVotes += row?.votes; if (row?.category === "outro") outroVotes += row?.votes;
if (row?.category === "sponsor") sponsorVotes += row?.votes; if (row?.category === "sponsor") sponsorVotes += row?.votes;
} }
if (submissionRow.category === "sponsor" && categoryRows.length === 3 assert.strictEqual(submissionRow.category, "sponsor");
&& introVotes === 0 && outroVotes === 1 && sponsorVotes === 1) { assert.strictEqual(categoryRows.length, 3);
assert.strictEqual(introVotes, 0);
assert.strictEqual(outroVotes, 1);
assert.strictEqual(sponsorVotes, 1);
done(); done();
} else {
done("Submission changed to " + submissionRow.category + " instead of staying as sponsor. There were "
+ introVotes + " intro votes, " + outroVotes + " outro votes and " + sponsorVotes + " sponsor votes.");
}
} else { } else {
done("Status code was " + res.status); done("Status code was " + res.status);
} }
@@ -317,11 +248,8 @@ describe('voteOnSponsorTime', () => {
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category-change&category=" + inputCat) + "/api/voteOnSponsorTime?userID=randomID2&UUID=incorrect-category-change&category=" + inputCat)
.then(async () => { .then(async () => {
const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category-change"]); const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["incorrect-category-change"]);
if (row.category === assertCat) { assert.strictEqual(row.category, assertCat);
callback(); callback();
} else {
done("Vote did not succeed. Submission went from sponsor to " + row.category);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}; };
@@ -335,17 +263,12 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&category=outro") + "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&category=outro")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await 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 row2 = await db.prepare('get', `SELECT votes FROM "categoryVotes" WHERE "UUID" = ? and category = ?`, ["vote-uuid-5", "outro"]);
if (row.category === "outro" && row2.votes === 500) { assert.strictEqual(row.category, "outro");
assert.strictEqual(row2.votes, 500);
done(); done();
} else {
done("Vote did not succeed. Submission went from intro to " + row.category + ". Category votes are " + row2.votes + " and should be 500.");
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -354,16 +277,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=testman&UUID=vote-uuid-5_1&category=outro") + "/api/voteOnSponsorTime?userID=testman&UUID=vote-uuid-5_1&category=outro")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]);
if (row.category === "outro") { assert.strictEqual(row.category, "outro");
done(); done();
} else {
done("Vote did not succeed. Submission went from intro to " + row.category + ".");
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -372,11 +289,8 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID3&UUID=invalid-uuid&category=intro") + "/api/voteOnSponsorTime?userID=randomID3&UUID=invalid-uuid&category=intro")
.then(async res => { .then(async res => {
if (res.status === 400) { assert.strictEqual(res.status, 400);
done(); done();
} else {
done("Status code was " + res.status + " instead of 400.");
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -385,12 +299,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=1") + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=1")
.then(async res => { .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 db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]);
if (res.status === 403 && row.votes === -3) { assert.strictEqual(row.votes, -3);
done(); done();
} else {
done("Status code was " + res.status + ", row is " + JSON.stringify(row));
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -399,12 +311,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=0") + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-5&type=0")
.then(async res => { .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 db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]);
if (res.status === 200 && row.votes === -3) { assert.strictEqual(row.votes, -3);
done(); done();
} else {
done("Status code was " + res.status + ", row is " + JSON.stringify(row));
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -413,16 +323,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&type=1") + "/api/voteOnSponsorTime?userID=VIPUser&UUID=vote-uuid-5&type=1")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-5"]);
if (row.votes > -3) { assert.ok(row.votes > -3);
done(); done();
} else {
done("Vote did not succeed. Votes raised from -3 to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -431,11 +335,8 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=warn-voteuser01&UUID=warnvote-uuid-0&type=1") + "/api/voteOnSponsorTime?userID=warn-voteuser01&UUID=warnvote-uuid-0&type=1")
.then(async res => { .then(async res => {
if (res.status === 403) { assert.strictEqual(res.status, 403);
done(); // success done();
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -444,12 +345,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=0") + "/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=0")
.then(async res => { .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 db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["no-sponsor-segments-uuid-0"]);
if (res.status === 200 && row.votes === 2) { assert.strictEqual(row.votes, 2);
done(); done();
} else {
done("Status code was " + res.status + " instead of 200, row was " + JSON.stringify(row));
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -458,12 +357,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=1") + "/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&type=1")
.then(async res => { .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 db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["no-sponsor-segments-uuid-0"]);
if (res.status === 200 && row.votes === 3) { assert.strictEqual(row.votes, 3);
done(); done();
} else {
done("Status code was " + res.status + " instead of 403, row was " + JSON.stringify(row));
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -472,12 +369,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&category=outro") + "/api/voteOnSponsorTime?userID=randomID&UUID=no-sponsor-segments-uuid-0&category=outro")
.then(async res => { .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 db.prepare('get', `SELECT "category" FROM "sponsorTimes" WHERE "UUID" = ?`, ["no-sponsor-segments-uuid-0"]);
if (res.status === 200 && row.category === "sponsor") { assert.strictEqual(row.category, "sponsor");
done(); done();
} else {
done("Status code was " + res.status + " instead of 200, row was " + JSON.stringify(row));
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -486,16 +381,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=1") + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=1")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-locking-uuid-1"]); const row = await db.prepare('get', `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-locking-uuid-1"]);
if (row?.locked) { assert.ok(row.locked);
done(); done();
} else {
done("Segment not locked");
}
} else {
done("Status code was " + res.status + " instead of 200");
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -504,16 +393,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=0") + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=0")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-locking-uuid-1"]); const row = await db.prepare('get', `SELECT "locked" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-locking-uuid-1"]);
if (!row?.locked) { assert.ok(!row.locked);
done(); done();
} else {
done("Segment not locked");
}
} else {
done("Status code was " + res.status + " instead of 200");
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -522,16 +405,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-hidden-uuid-1&type=1") + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-hidden-uuid-1&type=1")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "hidden" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-hidden-uuid-1"]); const row = await db.prepare('get', `SELECT "hidden" FROM "sponsorTimes" WHERE "UUID" = ?`, ["segment-hidden-uuid-1"]);
if (!row?.hidden) { assert.ok(!row?.hidden);
done(); done();
} else {
done("Segment not unhidden");
}
} else {
done("Status code was " + res.status + " instead of 200");
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -540,16 +417,10 @@ describe('voteOnSponsorTime', () => {
fetch(getbaseURL() fetch(getbaseURL()
+ "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=20") + "/api/voteOnSponsorTime?userID=randomID2&UUID=vote-uuid-2&type=20")
.then(async res => { .then(async res => {
if (res.status === 200) { assert.strictEqual(res.status, 200);
const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]); const row = await db.prepare('get', `SELECT "votes" FROM "sponsorTimes" WHERE "UUID" = ?`, ["vote-uuid-2"]);
if (row.votes === 10) { assert.strictEqual(row.votes, 10);
done(); done();
} else {
done("Vote did not succeed. Submission went from 10 votes to " + row.votes);
}
} else {
done("Status code was " + res.status);
}
}) })
.catch(err => done(err)); .catch(err => done(err));
}); });
@@ -557,19 +428,18 @@ describe('voteOnSponsorTime', () => {
it('Should not be able to vote with type 10', (done: Done) => { 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") fetch(getbaseURL() + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=10")
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .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: Done) => {
fetch(getbaseURL() + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=11") fetch(getbaseURL() + "/api/voteOnSponsorTime?userID=VIPUser&UUID=segment-locking-uuid-1&type=11")
.then(res => { .then(res => {
if (res.status !== 400) done('non 400 (' + res.status + ')'); assert.strictEqual(res.status, 400);
else done(); // pass done();
}) })
.catch(() => done('couldn\'t call endpoint')); .catch(err => done(err));
}); });
}); });

View File

@@ -12,9 +12,7 @@ import rateLimit from 'express-rate-limit';
async function init() { async function init() {
ImportMock.mockFunction(rateLimitMiddlewareModule, 'rateLimitMiddleware', rateLimit({ ImportMock.mockFunction(rateLimitMiddlewareModule, 'rateLimitMiddleware', rateLimit({
skip: () => { skip: () => true
return true;
}
})); }));
// delete old test database // delete old test database
@@ -35,10 +33,10 @@ async function init() {
// Add each .ts file to the mocha instance // Add each .ts file to the mocha instance
fs.readdirSync(testDir) fs.readdirSync(testDir)
.filter(function(file) { .filter((file) =>
// Only keep the .ts files // Only keep the .ts files
return file.substr(-3) === '.ts'; file.substr(-3) === '.ts'
}) )
.forEach(function(file) { .forEach(function(file) {
mocha.addFile( mocha.addFile(
path.join(testDir, file) path.join(testDir, file)