object-curly-spacing

This commit is contained in:
Michael C
2021-09-22 18:52:35 -04:00
parent 5dcc90b31a
commit a028eaa41a
85 changed files with 406 additions and 405 deletions

View File

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

View File

@@ -1,44 +1,44 @@
import express, {Request, RequestHandler, Response, Router} from "express"; import express, { Request, RequestHandler, Response, Router } from "express";
import {config} from "./config"; import { config } from "./config";
import {oldSubmitSponsorTimes} from "./routes/oldSubmitSponsorTimes"; import { oldSubmitSponsorTimes } from "./routes/oldSubmitSponsorTimes";
import {oldGetVideoSponsorTimes} from "./routes/oldGetVideoSponsorTimes"; import { oldGetVideoSponsorTimes } from "./routes/oldGetVideoSponsorTimes";
import {postSegmentShift} from "./routes/postSegmentShift"; import { postSegmentShift } from "./routes/postSegmentShift";
import {postWarning} from "./routes/postWarning"; import { postWarning } from "./routes/postWarning";
import {getIsUserVIP} from "./routes/getIsUserVIP"; import { getIsUserVIP } from "./routes/getIsUserVIP";
import {deleteLockCategoriesEndpoint} from "./routes/deleteLockCategories"; import { deleteLockCategoriesEndpoint } from "./routes/deleteLockCategories";
import {postLockCategories} from "./routes/postLockCategories"; import { postLockCategories } from "./routes/postLockCategories";
import {endpoint as getUserInfo} from "./routes/getUserInfo"; import { endpoint as getUserInfo } from "./routes/getUserInfo";
import {getDaysSavedFormatted} from "./routes/getDaysSavedFormatted"; import { getDaysSavedFormatted } from "./routes/getDaysSavedFormatted";
import {getTotalStats} from "./routes/getTotalStats"; import { getTotalStats } from "./routes/getTotalStats";
import {getTopUsers} from "./routes/getTopUsers"; import { getTopUsers } from "./routes/getTopUsers";
import {getViewsForUser} from "./routes/getViewsForUser"; import { getViewsForUser } from "./routes/getViewsForUser";
import {getSavedTimeForUser} from "./routes/getSavedTimeForUser"; import { getSavedTimeForUser } from "./routes/getSavedTimeForUser";
import {addUserAsVIP} from "./routes/addUserAsVIP"; import { addUserAsVIP } from "./routes/addUserAsVIP";
import {shadowBanUser} from "./routes/shadowBanUser"; import { shadowBanUser } from "./routes/shadowBanUser";
import {getUsername} from "./routes/getUsername"; import { getUsername } from "./routes/getUsername";
import {setUsername} from "./routes/setUsername"; import { setUsername } from "./routes/setUsername";
import {viewedVideoSponsorTime} from "./routes/viewedVideoSponsorTime"; import { viewedVideoSponsorTime } from "./routes/viewedVideoSponsorTime";
import {voteOnSponsorTime, getUserID as voteGetUserID} from "./routes/voteOnSponsorTime"; import { voteOnSponsorTime, getUserID as voteGetUserID } from "./routes/voteOnSponsorTime";
import {getSkipSegmentsByHash} from "./routes/getSkipSegmentsByHash"; import { getSkipSegmentsByHash } from "./routes/getSkipSegmentsByHash";
import {postSkipSegments} from "./routes/postSkipSegments"; import { postSkipSegments } from "./routes/postSkipSegments";
import {endpoint as getSkipSegments} from "./routes/getSkipSegments"; import { endpoint as getSkipSegments } from "./routes/getSkipSegments";
import {userCounter} from "./middleware/userCounter"; import { userCounter } from "./middleware/userCounter";
import {loggerMiddleware} from "./middleware/logger"; import { loggerMiddleware } from "./middleware/logger";
import {corsMiddleware} from "./middleware/cors"; import { corsMiddleware } from "./middleware/cors";
import {apiCspMiddleware} from "./middleware/apiCsp"; import { apiCspMiddleware } from "./middleware/apiCsp";
import {rateLimitMiddleware} from "./middleware/requestRateLimit"; import { rateLimitMiddleware } from "./middleware/requestRateLimit";
import dumpDatabase, {redirectLink} from "./routes/dumpDatabase"; import dumpDatabase, { redirectLink } from "./routes/dumpDatabase";
import {endpoint as getSegmentInfo} from "./routes/getSegmentInfo"; import { endpoint as getSegmentInfo } from "./routes/getSegmentInfo";
import {postClearCache} from "./routes/postClearCache"; import { postClearCache } from "./routes/postClearCache";
import { addUnlistedVideo } from "./routes/addUnlistedVideo"; import { addUnlistedVideo } from "./routes/addUnlistedVideo";
import {postPurgeAllSegments} from "./routes/postPurgeAllSegments"; import { postPurgeAllSegments } from "./routes/postPurgeAllSegments";
import {getUserID} from "./routes/getUserID"; import { getUserID } from "./routes/getUserID";
import {getLockCategories} from "./routes/getLockCategories"; import { getLockCategories } from "./routes/getLockCategories";
import {getLockCategoriesByHash} from "./routes/getLockCategoriesByHash"; import { getLockCategoriesByHash } from "./routes/getLockCategoriesByHash";
import {endpoint as getSearchSegments } from "./routes/getSearchSegments"; import { endpoint as getSearchSegments } from "./routes/getSearchSegments";
import {getStatus } from "./routes/getStatus"; import { getStatus } from "./routes/getStatus";
import { getLockReason } from "./routes/getLockReason"; import { getLockReason } from "./routes/getLockReason";
import {getUserStats} from "./routes/getUserStats"; import { getUserStats } from "./routes/getUserStats";
import ExpressPromiseRouter from "express-promise-router"; import ExpressPromiseRouter from "express-promise-router";
import { Server } from "http"; import { Server } from "http";
import { youtubeApiProxy } from "./routes/youtubeApiProxy"; import { youtubeApiProxy } from "./routes/youtubeApiProxy";
@@ -188,7 +188,7 @@ function setupRoutes(router: Router) {
router.get("/database/*", redirectLink); router.get("/database/*", redirectLink);
} else { } else {
router.get("/database.db", function (req: Request, res: Response) { router.get("/database.db", function (req: Request, res: Response) {
res.sendFile("./databases/sponsorTimes.db", {root: "./"}); res.sendFile("./databases/sponsorTimes.db", { root: "./" });
}); });
} }
} }

View File

@@ -1,5 +1,5 @@
import fs from "fs"; import fs from "fs";
import {SBSConfig} from "./types/config.model"; import { SBSConfig } from "./types/config.model";
import packageJson from "../package.json"; import packageJson from "../package.json";
const isTestMode = process.env.npm_lifecycle_script === packageJson.scripts.test; const isTestMode = process.env.npm_lifecycle_script === packageJson.scripts.test;

View File

@@ -1,5 +1,5 @@
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {IDatabase, QueryType} from "./IDatabase"; import { IDatabase, QueryType } from "./IDatabase";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // @ts-ignore
import MysqlInterface from "sync-mysql"; import MysqlInterface from "sync-mysql";

View File

@@ -56,7 +56,7 @@ export class Postgres implements IDatabase {
Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`); Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`);
try { try {
const queryResult = await this.pool.query({text: query, values: params}); const queryResult = await this.pool.query({ text: query, values: params });
switch (type) { switch (type) {
case "get": { case "get": {

View File

@@ -1,9 +1,9 @@
import {IDatabase, QueryType} from "./IDatabase"; import { IDatabase, QueryType } from "./IDatabase";
import Sqlite3, {Database, Database as SQLiteDatabase} from "better-sqlite3"; import Sqlite3, { Database, Database as SQLiteDatabase } from "better-sqlite3";
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
export class Sqlite implements IDatabase { export class Sqlite implements IDatabase {
private db: SQLiteDatabase; private db: SQLiteDatabase;
@@ -36,7 +36,7 @@ export class Sqlite implements IDatabase {
fs.mkdirSync(path.join(this.config.dbPath, "../")); fs.mkdirSync(path.join(this.config.dbPath, "../"));
} }
this.db = new Sqlite3(this.config.dbPath, {readonly: this.config.readOnly, fileMustExist: !this.config.createDbIfNotExists}); this.db = new Sqlite3(this.config.dbPath, { readonly: this.config.readOnly, fileMustExist: !this.config.createDbIfNotExists });
if (this.config.createDbIfNotExists && !this.config.readOnly && fs.existsSync(this.config.dbSchemaFileName)) { if (this.config.createDbIfNotExists && !this.config.readOnly && fs.existsSync(this.config.dbSchemaFileName)) {
this.db.exec(Sqlite.processUpgradeQuery(fs.readFileSync(this.config.dbSchemaFileName).toString())); this.db.exec(Sqlite.processUpgradeQuery(fs.readFileSync(this.config.dbSchemaFileName).toString()));

View File

@@ -1,8 +1,8 @@
import {config} from "../config"; import { config } from "../config";
import {Sqlite} from "./Sqlite"; import { Sqlite } from "./Sqlite";
import {Mysql} from "./Mysql"; import { Mysql } from "./Mysql";
import {Postgres} from "./Postgres"; import { Postgres } from "./Postgres";
import {IDatabase} from "./IDatabase"; import { IDatabase } from "./IDatabase";
let db: IDatabase; let db: IDatabase;

View File

@@ -1,8 +1,8 @@
import {config} from "./config"; import { config } from "./config";
import {initDb} from "./databases/databases"; import { initDb } from "./databases/databases";
import {createServer} from "./app"; import { createServer } from "./app";
import {Logger} from "./utils/logger"; import { Logger } from "./utils/logger";
import {startAllCrons} from "./cronjob"; import { startAllCrons } from "./cronjob";
import { getCommit } from "./utils/getCommit"; import { getCommit } from "./utils/getCommit";
async function init() { async function init() {

View File

@@ -1,4 +1,4 @@
import {NextFunction, Request, Response} from "express"; import { NextFunction, Request, Response } from "express";
export function apiCspMiddleware(req: Request, res: Response, next: NextFunction): void { export function apiCspMiddleware(req: Request, res: Response, next: NextFunction): void {
res.header("Content-Security-Policy", "script-src 'none'; object-src 'none'"); res.header("Content-Security-Policy", "script-src 'none'; object-src 'none'");

View File

@@ -1,4 +1,4 @@
import {NextFunction, Request, Response} from "express"; import { NextFunction, Request, Response } from "express";
export function corsMiddleware(req: Request, res: Response, next: NextFunction): void { export function corsMiddleware(req: Request, res: Response, next: NextFunction): void {
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");

View File

@@ -1,5 +1,5 @@
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {NextFunction, Request, Response} from "express"; import { NextFunction, Request, Response } from "express";
export function loggerMiddleware(req: Request, res: Response, next: NextFunction): void { export function loggerMiddleware(req: Request, res: Response, next: NextFunction): void {
Logger.info(`Request received: ${req.method} ${req.url}`); Logger.info(`Request received: ${req.method} ${req.url}`);

View File

@@ -1,8 +1,8 @@
import {getIP} from "../utils/getIP"; import { getIP } from "../utils/getIP";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import rateLimit from "express-rate-limit"; import rateLimit from "express-rate-limit";
import {RateLimitConfig} from "../types/config.model"; import { RateLimitConfig } from "../types/config.model";
import {Request} from "express"; import { Request } from "express";
import { isUserVIP } from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import { UserID } from "../types/user.model"; import { UserID } from "../types/user.model";

View File

@@ -1,9 +1,9 @@
import axios from "axios"; import axios from "axios";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {config} from "../config"; import { config } from "../config";
import {getIP} from "../utils/getIP"; import { getIP } from "../utils/getIP";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {NextFunction, Request, Response} from "express"; import { NextFunction, Request, Response } from "express";
export function userCounter(req: Request, res: Response, next: NextFunction): void { export function userCounter(req: Request, res: Response, next: NextFunction): void {
axios.post(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`) axios.post(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`)

View File

@@ -1,4 +1,4 @@
import {Request, Response} from "express"; import { Request, Response } from "express";
import { db } from "../databases/databases"; import { db } from "../databases/databases";
import { Logger } from "../utils/logger"; import { Logger } from "../utils/logger";

View File

@@ -1,7 +1,7 @@
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {config} from "../config"; import { config } from "../config";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { isUserVIP } from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import { HashedUserID } from "../types/user.model"; import { HashedUserID } from "../types/user.model";

View File

@@ -1,7 +1,7 @@
import {Request, Response} from "express"; import { Request, Response } from "express";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import { Category, VideoID } from "../types/segments.model"; import { Category, VideoID } from "../types/segments.model";
import { UserID } from "../types/user.model"; import { UserID } from "../types/user.model";
@@ -35,7 +35,7 @@ export async function deleteLockCategoriesEndpoint(req: Request, res: Response):
await deleteLockCategories(videoID, categories); await deleteLockCategories(videoID, categories);
return res.status(200).json({message: `Removed lock categories entrys for video ${videoID}`}); return res.status(200).json({ message: `Removed lock categories entrys for video ${videoID}` });
} }
/** /**

View File

@@ -1,6 +1,6 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { config } from "../config"; import { config } from "../config";
import util from "util"; import util from "util";
import fs from "fs"; import fs from "fs";

View File

@@ -1,5 +1,5 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Request, Response} from "express"; import { Request, Response } from "express";
export async function getDaysSavedFormatted(req: Request, res: Response): Promise<Response> { export async function getDaysSavedFormatted(req: Request, res: Response): Promise<Response> {
const row = await db.prepare("get", 'SELECT SUM(("endTime" - "startTime") / 60 / 60 / 24 * "views") as "daysSaved" from "sponsorTimes" where "shadowHidden" != 1', []); const row = await db.prepare("get", 'SELECT SUM(("endTime" - "startTime") / 60 / 60 / 24 * "views") as "daysSaved" from "sponsorTimes" where "shadowHidden" != 1', []);

View File

@@ -1,7 +1,7 @@
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { HashedUserID, UserID } from "../types/user.model"; import { HashedUserID, UserID } from "../types/user.model";
export async function getIsUserVIP(req: Request, res: Response): Promise<Response> { export async function getIsUserVIP(req: Request, res: Response): Promise<Response> {

View File

@@ -1,6 +1,6 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { Category, VideoID } from "../types/segments.model"; import { Category, VideoID } from "../types/segments.model";
export async function getLockCategories(req: Request, res: Response): Promise<Response> { export async function getLockCategories(req: Request, res: Response): Promise<Response> {

View File

@@ -1,7 +1,7 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {Request, Response} from "express"; import { Request, Response } from "express";
import {hashPrefixTester} from "../utils/hashPrefixTester"; import { hashPrefixTester } from "../utils/hashPrefixTester";
import { Category, VideoID, VideoIDHash } from "../types/segments.model"; import { Category, VideoID, VideoIDHash } from "../types/segments.model";
interface LockResultByHash { interface LockResultByHash {

View File

@@ -1,8 +1,8 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { Category, VideoID } from "../types/segments.model"; import { Category, VideoID } from "../types/segments.model";
import {config} from "../config"; import { config } from "../config";
const possibleCategoryList = config.categoryList; const possibleCategoryList = config.categoryList;
interface lockArray { interface lockArray {

View File

@@ -1,7 +1,7 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Request, Response} from "express"; import { Request, Response } from "express";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {config} from "../config"; import { config } from "../config";
import { Logger } from "../utils/logger"; import { Logger } from "../utils/logger";
const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400; const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400;

View File

@@ -13,7 +13,7 @@ import { getReputation } from "../utils/reputation";
import { getService } from "../utils/getService"; import { getService } from "../utils/getService";
async function prepareCategorySegments(req: Request, videoID: VideoID, category: Category, segments: DBSegment[], cache: SegmentCache = {shadowHiddenSegmentIPs: {}}): Promise<Segment[]> { async function prepareCategorySegments(req: Request, videoID: VideoID, category: Category, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }): Promise<Segment[]> {
const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => { const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => {
if (segment.votes < -1 && !segment.required) { if (segment.votes < -1 && !segment.required) {
return false; //too untrustworthy, just ignore it return false; //too untrustworthy, just ignore it
@@ -56,7 +56,7 @@ async function prepareCategorySegments(req: Request, videoID: VideoID, category:
async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories: Category[], async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories: Category[],
actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise<Segment[]> { actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise<Segment[]> {
const cache: SegmentCache = {shadowHiddenSegmentIPs: {}}; const cache: SegmentCache = { shadowHiddenSegmentIPs: {} };
const segments: Segment[] = []; const segments: Segment[] = [];
try { try {
@@ -89,7 +89,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[], async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[],
actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> { actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> {
const cache: SegmentCache = {shadowHiddenSegmentIPs: {}}; const cache: SegmentCache = { shadowHiddenSegmentIPs: {} };
const segments: SBRecord<VideoID, VideoData> = {}; const segments: SBRecord<VideoID, VideoData> = {};
try { try {
@@ -182,7 +182,7 @@ function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOf
const weight = Math.exp(choice.votes * Math.max(1, choice.reputation + 1) + 3 + boost); const weight = Math.exp(choice.votes * Math.max(1, choice.reputation + 1) + 3 + boost);
totalWeight += Math.max(weight, 0); totalWeight += Math.max(weight, 0);
return {...choice, weight}; return { ...choice, weight };
}); });
//iterate and find amountOfChoices choices //iterate and find amountOfChoices choices
@@ -220,7 +220,7 @@ async function chooseSegments(segments: DBSegment[], max: number): Promise<DBSeg
let cursor = -1; //-1 to make sure that, even if the 1st segment starts at 0, a new group is created let cursor = -1; //-1 to make sure that, even if the 1st segment starts at 0, a new group is created
for (const segment of segments) { for (const segment of segments) {
if (segment.startTime >= cursor) { if (segment.startTime >= cursor) {
currentGroup = {segments: [], votes: 0, reputation: 0, locked: false, required: false}; currentGroup = { segments: [], votes: 0, reputation: 0, locked: false, required: false };
overlappingSegmentsGroups.push(currentGroup); overlappingSegmentsGroups.push(currentGroup);
} }

View File

@@ -1,6 +1,6 @@
import {hashPrefixTester} from "../utils/hashPrefixTester"; import { hashPrefixTester } from "../utils/hashPrefixTester";
import {getSegmentsByHash} from "./getSkipSegments"; import { getSegmentsByHash } from "./getSkipSegments";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { ActionType, Category, SegmentUUID, Service, VideoIDHash } from "../types/segments.model"; import { ActionType, Category, SegmentUUID, Service, VideoIDHash } from "../types/segments.model";
import { getService } from "../utils/getService"; import { getService } from "../utils/getService";

View File

@@ -1,6 +1,6 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {Request, Response} from "express"; import { Request, Response } from "express";
export async function getStatus(req: Request, res: Response): Promise<Response> { export async function getStatus(req: Request, res: Response): Promise<Response> {
const startTime = Date.now(); const startTime = Date.now();

View File

@@ -1,7 +1,7 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {createMemoryCache} from "../utils/createMemoryCache"; import { createMemoryCache } from "../utils/createMemoryCache";
import {config} from "../config"; import { config } from "../config";
import {Request, Response} from "express"; import { Request, Response } from "express";
const MILLISECONDS_IN_MINUTE = 60000; const MILLISECONDS_IN_MINUTE = 60000;
const getTopUsersWithCache = createMemoryCache(generateTopUsersStats, config.getTopUsersCacheTimeMinutes * MILLISECONDS_IN_MINUTE); const getTopUsersWithCache = createMemoryCache(generateTopUsersStats, config.getTopUsersCacheTimeMinutes * MILLISECONDS_IN_MINUTE);

View File

@@ -1,9 +1,9 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {config} from "../config"; import { config } from "../config";
import {Request, Response} from "express"; import { Request, Response } from "express";
import fetch from "node-fetch"; import fetch from "node-fetch";
import axios from "axios"; import axios from "axios";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
// A cache of the number of chrome web store users // A cache of the number of chrome web store users
let chromeUsersCache = 0; let chromeUsersCache = 0;

View File

@@ -1,6 +1,6 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Request, Response} from "express"; import { Request, Response } from "express";
import {UserID} from "../types/user.model"; import { UserID } from "../types/user.model";
function getFuzzyUserID(userName: string): Promise<{userName: string, userID: UserID }[]> { function getFuzzyUserID(userName: string): Promise<{userName: string, userID: UserID }[]> {
// escape [_ % \] to avoid ReDOS // escape [_ % \] to avoid ReDOS

View File

@@ -1,12 +1,12 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import {Request, Response} from "express"; import { Request, Response } from "express";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import { HashedUserID, UserID } from "../types/user.model"; import { HashedUserID, UserID } from "../types/user.model";
import { getReputation } from "../utils/reputation"; import { getReputation } from "../utils/reputation";
import { SegmentUUID } from "../types/segments.model"; import { SegmentUUID } from "../types/segments.model";
import {config} from "../config"; import { config } from "../config";
const maxRewardTime = config.maxRewardTimePerSegmentInSeconds; const maxRewardTime = config.maxRewardTimePerSegmentInSeconds;
async function dbGetSubmittedSegmentSummary(userID: HashedUserID): Promise<{ minutesSaved: number, segmentCount: number }> { async function dbGetSubmittedSegmentSummary(userID: HashedUserID): Promise<{ minutesSaved: number, segmentCount: number }> {

View File

@@ -1,8 +1,8 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {Request, Response} from "express"; import { Request, Response } from "express";
import {HashedUserID, UserID} from "../types/user.model"; import { HashedUserID, UserID } from "../types/user.model";
import {config} from "../config"; import { config } from "../config";
import { Logger } from "../utils/logger"; import { Logger } from "../utils/logger";
type nestedObj = Record<string, Record<string, number>>; type nestedObj = Record<string, Record<string, number>>;
const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400; const maxRewardTimePerSegmentInSeconds = config.maxRewardTimePerSegmentInSeconds ?? 86400;

View File

@@ -1,7 +1,7 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {Request, Response} from "express"; import { Request, Response } from "express";
export async function getUsername(req: Request, res: Response): Promise<Response> { export async function getUsername(req: Request, res: Response): Promise<Response> {
let userID = req.query.userID as string; let userID = req.query.userID as string;

View File

@@ -1,7 +1,7 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Request, Response} from "express"; import { Request, Response } from "express";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
export async function getViewsForUser(req: Request, res: Response): Promise<Response> { export async function getViewsForUser(req: Request, res: Response): Promise<Response> {
let userID = req.query.userID as string; let userID = req.query.userID as string;

View File

@@ -1,5 +1,5 @@
import {handleGetSegments} from "./getSkipSegments"; import { handleGetSegments } from "./getSkipSegments";
import {Request, Response} from "express"; import { Request, Response } from "express";
export async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> { export async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> {
const segments = await handleGetSegments(req, res); const segments = await handleGetSegments(req, res);

View File

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

View File

@@ -35,7 +35,7 @@ export async function postClearCache(req: Request, res: Response): Promise<Respo
// Ensure user is a VIP // Ensure user is a VIP
if (!(await isUserVIP(hashedUserID))){ if (!(await isUserVIP(hashedUserID))){
Logger.warn(`Permission violation: User ${hashedUserID} attempted to clear cache for video ${videoID}.`); Logger.warn(`Permission violation: User ${hashedUserID} attempted to clear cache for video ${videoID}.`);
return res.status(403).json({"message": "Not a VIP"}); return res.status(403).json({ "message": "Not a VIP" });
} }
try { try {

View File

@@ -1,8 +1,8 @@
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { VideoIDHash } from "../types/segments.model"; import { VideoIDHash } from "../types/segments.model";
export async function postLockCategories(req: Request, res: Response): Promise<string[]> { export async function postLockCategories(req: Request, res: Response): Promise<string[]> {

View File

@@ -1,10 +1,10 @@
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import {Request, Response} from "express"; import { Request, Response } from "express";
import {HashedUserID, UserID} from "../types/user.model"; import { HashedUserID, UserID } from "../types/user.model";
import {VideoID} from "../types/segments.model"; import { VideoID } from "../types/segments.model";
import {db} from "../databases/databases"; import { db } from "../databases/databases";
export async function postPurgeAllSegments(req: Request, res: Response): Promise<Response> { export async function postPurgeAllSegments(req: Request, res: Response): Promise<Response> {
const userID = req.body.userID as UserID; const userID = req.body.userID as UserID;

View File

@@ -1,48 +1,48 @@
import {Request, Response} from "express"; import { Request, Response } from "express";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {db} from "../databases/databases"; import { db } from "../databases/databases";
const ACTION_NONE = Symbol("none"); const ACTION_NONE = Symbol("none");
const ACTION_UPDATE = Symbol("update"); const ACTION_UPDATE = Symbol("update");
const ACTION_REMOVE = Symbol("remove"); const ACTION_REMOVE = Symbol("remove");
function shiftSegment(segment: any, shift: { startTime: any; endTime: any }) { function shiftSegment(segment: any, shift: { startTime: any; endTime: any }) {
if (segment.startTime >= segment.endTime) return {action: ACTION_NONE, segment}; if (segment.startTime >= segment.endTime) return { action: ACTION_NONE, segment };
if (shift.startTime >= shift.endTime) return {action: ACTION_NONE, segment}; if (shift.startTime >= shift.endTime) return { action: ACTION_NONE, segment };
const duration = shift.endTime - shift.startTime; const duration = shift.endTime - shift.startTime;
if (shift.endTime < segment.startTime) { if (shift.endTime < segment.startTime) {
// Scenario #1 cut before segment // Scenario #1 cut before segment
segment.startTime -= duration; segment.startTime -= duration;
segment.endTime -= duration; segment.endTime -= duration;
return {action: ACTION_UPDATE, segment}; return { action: ACTION_UPDATE, segment };
} }
if (shift.startTime > segment.endTime) { if (shift.startTime > segment.endTime) {
// Scenario #2 cut after segment // Scenario #2 cut after segment
return {action: ACTION_NONE, segment}; return { action: ACTION_NONE, segment };
} }
if (segment.startTime < shift.startTime && segment.endTime > shift.endTime) { if (segment.startTime < shift.startTime && segment.endTime > shift.endTime) {
// Scenario #3 cut inside segment // Scenario #3 cut inside segment
segment.endTime -= duration; segment.endTime -= duration;
return {action: ACTION_UPDATE, segment}; return { action: ACTION_UPDATE, segment };
} }
if (segment.startTime >= shift.startTime && segment.endTime > shift.endTime) { if (segment.startTime >= shift.startTime && segment.endTime > shift.endTime) {
// Scenario #4 cut overlap startTime // Scenario #4 cut overlap startTime
segment.startTime = shift.startTime; segment.startTime = shift.startTime;
segment.endTime -= duration; segment.endTime -= duration;
return {action: ACTION_UPDATE, segment}; return { action: ACTION_UPDATE, segment };
} }
if (segment.startTime < shift.startTime && segment.endTime <= shift.endTime) { if (segment.startTime < shift.startTime && segment.endTime <= shift.endTime) {
// Scenario #5 cut overlap endTime // Scenario #5 cut overlap endTime
segment.endTime = shift.startTime; segment.endTime = shift.startTime;
return {action: ACTION_UPDATE, segment}; return { action: ACTION_UPDATE, segment };
} }
if (segment.startTime >= shift.startTime && segment.endTime <= shift.endTime) { if (segment.startTime >= shift.startTime && segment.endTime <= shift.endTime) {
// Scenario #6 cut overlap startTime and endTime // Scenario #6 cut overlap startTime and endTime
return {action: ACTION_REMOVE, segment}; return { action: ACTION_REMOVE, segment };
} }
return {action: ACTION_NONE, segment}; return { action: ACTION_NONE, segment };
} }
export async function postSegmentShift(req: Request, res: Response): Promise<Response> { export async function postSegmentShift(req: Request, res: Response): Promise<Response> {

View File

@@ -1,15 +1,15 @@
import {config} from "../config"; import { config } from "../config";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {db, privateDB} from "../databases/databases"; import { db, privateDB } from "../databases/databases";
import {getMaxResThumbnail, YouTubeAPI} from "../utils/youtubeApi"; import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi";
import {getSubmissionUUID} from "../utils/getSubmissionUUID"; import { getSubmissionUUID } from "../utils/getSubmissionUUID";
import fetch from "node-fetch"; import fetch from "node-fetch";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {getIP} from "../utils/getIP"; import { getIP } from "../utils/getIP";
import {getFormattedTime} from "../utils/getFormattedTime"; import { getFormattedTime } from "../utils/getFormattedTime";
import {isUserTrustworthy} from "../utils/isUserTrustworthy"; import { isUserTrustworthy } from "../utils/isUserTrustworthy";
import {dispatchEvent} from "../utils/webhookUtils"; import { dispatchEvent } from "../utils/webhookUtils";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { ActionType, Category, CategoryActionType, IncomingSegment, SegmentUUID, Service, VideoDuration, VideoID } from "../types/segments.model"; import { ActionType, Category, CategoryActionType, IncomingSegment, SegmentUUID, Service, VideoDuration, VideoID } from "../types/segments.model";
import { deleteLockCategories } from "./deleteLockCategories"; import { deleteLockCategories } from "./deleteLockCategories";
import { getCategoryActionType } from "../utils/categoryInfo"; import { getCategoryActionType } from "../utils/categoryInfo";
@@ -33,7 +33,7 @@ const CHECK_PASS: CheckResult = {
errorCode: 0 errorCode: 0
}; };
async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: APIVideoData, {submissionStart, submissionEnd}: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) { async function sendWebhookNotification(userID: string, videoID: string, UUID: string, submissionCount: number, youtubeData: APIVideoData, { submissionStart, submissionEnd }: { submissionStart: number; submissionEnd: number; }, segmentInfo: any) {
const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]); const row = await db.prepare("get", `SELECT "userName" FROM "userNames" WHERE "userID" = ?`, [userID]);
const userName = row !== undefined ? row.userName : null; const userName = row !== undefined ? row.userName : null;
@@ -66,7 +66,7 @@ async function sendWebhooks(apiVideoInfo: APIVideoInfo, userID: string, videoID:
if (apiVideoInfo && service == Service.YouTube) { if (apiVideoInfo && service == Service.YouTube) {
const userSubmissionCountRow = await db.prepare("get", `SELECT count(*) as "submissionCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]); const userSubmissionCountRow = await db.prepare("get", `SELECT count(*) as "submissionCount" FROM "sponsorTimes" WHERE "userID" = ?`, [userID]);
const {data, err} = apiVideoInfo; const { data, err } = apiVideoInfo;
if (err) return; if (err) return;
const startTime = parseFloat(segmentInfo.segment[0]); const startTime = parseFloat(segmentInfo.segment[0]);
@@ -182,7 +182,7 @@ async function sendWebhooksNB(userID: string, videoID: string, UUID: string, sta
async function autoModerateSubmission(apiVideoInfo: APIVideoInfo, async function autoModerateSubmission(apiVideoInfo: APIVideoInfo,
submission: { videoID: VideoID; userID: UserID; segments: IncomingSegment[] }) { 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;
const duration = apiVideoInfo?.data?.lengthSeconds; const duration = apiVideoInfo?.data?.lengthSeconds;
@@ -355,11 +355,11 @@ async function checkEachSegmentValid(userID: string, videoID: VideoID,
for (let i = 0; i < segments.length; i++) { for (let i = 0; i < segments.length; i++) {
if (segments[i] === undefined || segments[i].segment === undefined || segments[i].category === undefined) { if (segments[i] === undefined || segments[i].segment === undefined || segments[i].category === undefined) {
//invalid request //invalid request
return { pass: false, errorMessage: "One of your segments are invalid", errorCode: 400}; return { pass: false, errorMessage: "One of your segments are invalid", errorCode: 400 };
} }
if (!config.categoryList.includes(segments[i].category)) { if (!config.categoryList.includes(segments[i].category)) {
return { pass: false, errorMessage: "Category doesn't exist.", errorCode: 400}; return { pass: false, errorMessage: "Category doesn't exist.", errorCode: 400 };
} }
// Reject segment if it's in the locked categories list // Reject segment if it's in the locked categories list
@@ -392,24 +392,24 @@ async function checkEachSegmentValid(userID: string, videoID: VideoID,
|| (getCategoryActionType(segments[i].category) === CategoryActionType.Skippable && startTime === endTime) || (getCategoryActionType(segments[i].category) === CategoryActionType.Skippable && startTime === endTime)
|| (getCategoryActionType(segments[i].category) === CategoryActionType.POI && startTime !== endTime)) { || (getCategoryActionType(segments[i].category) === CategoryActionType.POI && startTime !== endTime)) {
//invalid request //invalid request
return { pass: false, errorMessage: "One of your segments times are invalid (too short, startTime before endTime, etc.)", errorCode: 400}; return { pass: false, errorMessage: "One of your segments times are invalid (too short, startTime before endTime, etc.)", errorCode: 400 };
} }
// Check for POI segments before some seconds // Check for POI segments before some seconds
if (!isVIP && getCategoryActionType(segments[i].category) === CategoryActionType.POI && startTime < config.poiMinimumStartTime) { if (!isVIP && getCategoryActionType(segments[i].category) === CategoryActionType.POI && startTime < config.poiMinimumStartTime) {
return { pass: false, errorMessage: `POI cannot be that early`, errorCode: 400}; return { pass: false, errorMessage: `POI cannot be that early`, errorCode: 400 };
} }
if (!isVIP && segments[i].category === "sponsor" && Math.abs(startTime - endTime) < 1) { if (!isVIP && segments[i].category === "sponsor" && Math.abs(startTime - endTime) < 1) {
// Too short // Too short
return { pass: false, errorMessage: "Sponsors must be longer than 1 second long", errorCode: 400}; return { pass: false, errorMessage: "Sponsors must be longer than 1 second long", errorCode: 400 };
} }
//check if this info has already been submitted before //check if this info has already been submitted before
const duplicateCheck2Row = await db.prepare("get", `SELECT COUNT(*) as count FROM "sponsorTimes" WHERE "startTime" = ? const duplicateCheck2Row = await db.prepare("get", `SELECT COUNT(*) as count FROM "sponsorTimes" WHERE "startTime" = ?
and "endTime" = ? and "category" = ? and "actionType" = ? and "videoID" = ? and "service" = ?`, [startTime, endTime, segments[i].category, segments[i].actionType, videoID, service]); and "endTime" = ? and "category" = ? and "actionType" = ? and "videoID" = ? and "service" = ?`, [startTime, endTime, segments[i].category, segments[i].actionType, videoID, service]);
if (duplicateCheck2Row.count > 0) { if (duplicateCheck2Row.count > 0) {
return { pass: false, errorMessage: "Sponsors has already been submitted before.", errorCode: 409}; return { pass: false, errorMessage: "Sponsors has already been submitted before.", errorCode: 409 };
} }
} }
@@ -419,7 +419,7 @@ async function checkEachSegmentValid(userID: string, videoID: VideoID,
async function checkByAutoModerator(videoID: any, userID: any, segments: Array<any>, isVIP: boolean, service:string, apiVideoInfo: APIVideoInfo, decreaseVotes: number): Promise<CheckResult & { decreaseVotes: number; } > { async function checkByAutoModerator(videoID: any, userID: any, segments: Array<any>, isVIP: boolean, service:string, apiVideoInfo: APIVideoInfo, decreaseVotes: number): Promise<CheckResult & { decreaseVotes: number; } > {
// Auto moderator check // Auto moderator check
if (!isVIP && service == Service.YouTube) { if (!isVIP && service == Service.YouTube) {
const autoModerateResult = await autoModerateSubmission(apiVideoInfo, {userID, videoID, segments});//startTime, endTime, category: segments[i].category}); const autoModerateResult = await autoModerateSubmission(apiVideoInfo, { userID, videoID, segments });//startTime, endTime, category: segments[i].category});
if (autoModerateResult == "Rejected based on NeuralBlock predictions.") { if (autoModerateResult == "Rejected based on NeuralBlock predictions.") {
// If NB automod rejects, the submission will start with -2 votes. // If NB automod rejects, the submission will start with -2 votes.
// Note, if one submission is bad all submissions will be affected. // Note, if one submission is bad all submissions will be affected.
@@ -570,7 +570,7 @@ function preprocessInput(req: Request) {
const userAgent = req.query.userAgent ?? req.body.userAgent ?? parseUserAgent(req.get("user-agent")) ?? ""; const userAgent = req.query.userAgent ?? req.body.userAgent ?? parseUserAgent(req.get("user-agent")) ?? "";
return {videoID, userID, service, videoDuration, videoDurationParam, segments, userAgent}; return { videoID, userID, service, videoDuration, videoDurationParam, segments, userAgent };
} }
export async function postSkipSegments(req: Request, res: Response): Promise<Response> { export async function postSkipSegments(req: Request, res: Response): Promise<Response> {
@@ -579,7 +579,7 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
} }
// eslint-disable-next-line prefer-const // eslint-disable-next-line prefer-const
let {videoID, userID, service, videoDuration, videoDurationParam, segments, userAgent} = preprocessInput(req); let { videoID, userID, service, videoDuration, videoDurationParam, segments, userAgent } = preprocessInput(req);
const invalidCheckResult = checkInvalidFields(videoID, userID, segments); const invalidCheckResult = checkInvalidFields(videoID, userID, segments);
if (!invalidCheckResult.pass) { if (!invalidCheckResult.pass) {

View File

@@ -1,8 +1,8 @@
import {Request, Response} from "express"; import { Request, Response } from "express";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import { HashedUserID, UserID } from "../types/user.model"; import { HashedUserID, UserID } from "../types/user.model";
import { config } from "../config"; import { config } from "../config";
@@ -23,7 +23,7 @@ function checkExpiredWarning(warning: warningEntry): boolean {
export async function postWarning(req: Request, res: Response): Promise<Response> { export async function postWarning(req: Request, res: Response): Promise<Response> {
// exit early if no body passed in // exit early if no body passed in
if (!req.body.userID && !req.body.issuerUserID) return res.status(400).json({"message": "Missing parameters"}); if (!req.body.userID && !req.body.issuerUserID) return res.status(400).json({ "message": "Missing parameters" });
// Collect user input data // Collect user input data
const issuerUserID: HashedUserID = getHash(<UserID> req.body.issuerUserID); const issuerUserID: HashedUserID = getHash(<UserID> req.body.issuerUserID);
const userID: UserID = req.body.userID; const userID: UserID = req.body.userID;
@@ -34,7 +34,7 @@ export async function postWarning(req: Request, res: Response): Promise<Response
// Ensure user is a VIP // Ensure user is a VIP
if (!await isUserVIP(issuerUserID)) { if (!await isUserVIP(issuerUserID)) {
Logger.warn(`Permission violation: User ${issuerUserID} attempted to warn user ${userID}.`); Logger.warn(`Permission violation: User ${issuerUserID} attempted to warn user ${userID}.`);
return res.status(403).json({"message": "Not a VIP"}); return res.status(403).json({ "message": "Not a VIP" });
} }
let resultStatus = ""; let resultStatus = "";

View File

@@ -1,8 +1,8 @@
import {config} from "../config"; import { config } from "../config";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {db, privateDB} from "../databases/databases"; import { db, privateDB } from "../databases/databases";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {Request, Response} from "express"; import { Request, Response } from "express";
async function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise<Response> { async function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise<Response> {
return privateDB.prepare("run", return privateDB.prepare("run",

View File

@@ -1,6 +1,6 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {Request, Response} from "express"; import { Request, Response } from "express";
import { config } from "../config"; import { config } from "../config";
import { Category, Service, VideoID, VideoIDHash } from "../types/segments.model"; import { Category, Service, VideoID, VideoIDHash } from "../types/segments.model";
import { UserID } from "../types/user.model"; import { UserID } from "../types/user.model";

View File

@@ -1,5 +1,5 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import {Request, Response} from "express"; import { Request, Response } from "express";
export async function viewedVideoSponsorTime(req: Request, res: Response): Promise<Response> { export async function viewedVideoSponsorTime(req: Request, res: Response): Promise<Response> {
const UUID = req.query.UUID; const UUID = req.query.UUID;

View File

@@ -1,14 +1,14 @@
import {Request, Response} from "express"; import { Request, Response } from "express";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import {isUserVIP} from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import fetch from "node-fetch"; import fetch from "node-fetch";
import {getMaxResThumbnail, YouTubeAPI} from "../utils/youtubeApi"; import { getMaxResThumbnail, YouTubeAPI } from "../utils/youtubeApi";
import {db, privateDB} from "../databases/databases"; import { db, privateDB } from "../databases/databases";
import {dispatchEvent, getVoteAuthor, getVoteAuthorRaw} from "../utils/webhookUtils"; import { dispatchEvent, getVoteAuthor, getVoteAuthorRaw } from "../utils/webhookUtils";
import {getFormattedTime} from "../utils/getFormattedTime"; import { getFormattedTime } from "../utils/getFormattedTime";
import {getIP} from "../utils/getIP"; import { getIP } from "../utils/getIP";
import {getHash} from "../utils/getHash"; import { getHash } from "../utils/getHash";
import {config} from "../config"; import { config } from "../config";
import { UserID } from "../types/user.model"; import { UserID } from "../types/user.model";
import { Category, CategoryActionType, HashedIP, IPAddress, SegmentUUID, Service, VideoID, VideoIDHash, Visibility } from "../types/segments.model"; import { Category, CategoryActionType, HashedIP, IPAddress, SegmentUUID, Service, VideoID, VideoIDHash, Visibility } from "../types/segments.model";
import { getCategoryActionType } from "../utils/categoryInfo"; import { getCategoryActionType } from "../utils/categoryInfo";
@@ -459,6 +459,6 @@ export async function voteOnSponsorTime(req: Request, res: Response): Promise<Re
return res.status(finalResponse.finalStatus).send(finalResponse.finalMessage ?? undefined); return res.status(finalResponse.finalStatus).send(finalResponse.finalMessage ?? undefined);
} catch (err) { } catch (err) {
Logger.error(err as string); Logger.error(err as string);
return res.status(500).json({error: "Internal error creating segment vote"}); return res.status(500).json({ error: "Internal error creating segment vote" });
} }
} }

View File

@@ -1,5 +1,5 @@
import {config} from "../config"; import { config } from "../config";
import {Request} from "express"; import { Request } from "express";
import { IPAddress } from "../types/segments.model"; import { IPAddress } from "../types/segments.model";
export function getIP(req: Request): IPAddress { export function getIP(req: Request): IPAddress {

View File

@@ -1,4 +1,4 @@
import {getHash} from "./getHash"; import { getHash } from "./getHash";
import { HashedValue } from "../types/hash.model"; import { HashedValue } from "../types/hash.model";
import { ActionType, VideoID } from "../types/segments.model"; import { ActionType, VideoID } from "../types/segments.model";
import { UserID } from "../types/user.model"; import { UserID } from "../types/user.model";

View File

@@ -1,4 +1,4 @@
import {config} from "../config"; import { config } from "../config";
const minimumPrefix = config.minimumPrefix || "3"; const minimumPrefix = config.minimumPrefix || "3";
const maximumPrefix = config.maximumPrefix || "32"; // Half the hash. const maximumPrefix = config.maximumPrefix || "32"; // Half the hash.

View File

@@ -1,4 +1,4 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
/** /**
* Returns true if the user is considered trustworthy. This happens after a user has made 5 submissions and has less than 60% downvoted submissions * Returns true if the user is considered trustworthy. This happens after a user has made 5 submissions and has less than 60% downvoted submissions

View File

@@ -1,4 +1,4 @@
import {db} from "../databases/databases"; import { db } from "../databases/databases";
import { HashedUserID } from "../types/user.model"; import { HashedUserID } from "../types/user.model";
export async function isUserVIP(userID: HashedUserID): Promise<boolean> { export async function isUserVIP(userID: HashedUserID): Promise<boolean> {

View File

@@ -1,4 +1,4 @@
import {config} from "../config"; import { config } from "../config";
const enum LogLevel { const enum LogLevel {
ERROR = "ERROR", ERROR = "ERROR",

View File

@@ -5,7 +5,7 @@ import { Service, VideoID, VideoIDHash } from "../types/segments.model";
import { UserID } from "../types/user.model"; import { UserID } from "../types/user.model";
async function get<T>(fetchFromDB: () => Promise<T>, key: string): Promise<T> { async function get<T>(fetchFromDB: () => Promise<T>, key: string): Promise<T> {
const {err, reply} = await redis.getAsync(key); const { err, reply } = await redis.getAsync(key);
if (!err && reply) { if (!err && reply) {
try { try {

View File

@@ -1,6 +1,6 @@
import {config} from "../config"; import { config } from "../config";
import {Logger} from "./logger"; import { Logger } from "./logger";
import redis, {Callback} from "redis"; import redis, { Callback } from "redis";
interface RedisSB { interface RedisSB {
get(key: string, callback?: Callback<string | null>): void; get(key: string, callback?: Callback<string | null>): void;
@@ -13,10 +13,10 @@ interface RedisSB {
let exportObject: RedisSB = { let exportObject: RedisSB = {
get: (key, callback?) => callback(null, undefined), get: (key, callback?) => callback(null, undefined),
getAsync: () => getAsync: () =>
new Promise((resolve) => resolve({err: null, reply: undefined})), new Promise((resolve) => resolve({ err: null, reply: undefined })),
set: (key, value, callback) => callback(null, undefined), set: (key, value, callback) => callback(null, undefined),
setAsync: () => setAsync: () =>
new Promise((resolve) => resolve({err: null, reply: undefined})), new Promise((resolve) => resolve({ err: null, reply: undefined })),
delAsync: () => delAsync: () =>
new Promise((resolve) => resolve(null)), new Promise((resolve) => resolve(null)),
}; };
@@ -26,8 +26,8 @@ if (config.redis) {
const client = redis.createClient(config.redis); const client = redis.createClient(config.redis);
exportObject = client; exportObject = client;
exportObject.getAsync = (key) => new Promise((resolve) => client.get(key, (err, reply) => resolve({err, reply}))); exportObject.getAsync = (key) => new Promise((resolve) => client.get(key, (err, reply) => resolve({ err, reply })));
exportObject.setAsync = (key, value) => new Promise((resolve) => client.set(key, value, (err, reply) => resolve({err, reply}))); exportObject.setAsync = (key, value) => new Promise((resolve) => client.set(key, value, (err, reply) => resolve({ err, reply })));
exportObject.delAsync = (...keys) => new Promise((resolve) => client.del(keys, (err) => resolve(err))); exportObject.delAsync = (...keys) => new Promise((resolve) => client.del(keys, (err) => resolve(err)));
client.on("error", function(error) { client.on("error", function(error) {

View File

@@ -1,5 +1,5 @@
import {config} from "../config"; import { config } from "../config";
import {Logger} from "../utils/logger"; import { Logger } from "../utils/logger";
import fetch from "node-fetch"; import fetch from "node-fetch";
function getVoteAuthorRaw(submissionCount: number, isVIP: boolean, isOwnSubmission: boolean): string { function getVoteAuthorRaw(submissionCount: number, isVIP: boolean, isOwnSubmission: boolean): string {

View File

@@ -1,6 +1,6 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import {config} from "../config"; import { config } from "../config";
import {Logger} from "./logger"; import { Logger } from "./logger";
import { APIVideoData, APIVideoInfo } from "../types/youtubeApi.model"; import { APIVideoData, APIVideoInfo } from "../types/youtubeApi.model";
import DiskCache from "./diskCache"; import DiskCache from "./diskCache";
@@ -24,7 +24,7 @@ export class YouTubeAPI {
} }
} }
if (!config.newLeafURLs || config.newLeafURLs.length <= 0) return {err: "NewLeaf URL not found", data: null}; if (!config.newLeafURLs || config.newLeafURLs.length <= 0) return { err: "NewLeaf URL not found", data: null };
try { try {
const result = await fetch(`${config.newLeafURLs[Math.floor(Math.random() * config.newLeafURLs.length)]}/api/v1/videos/${videoID}`, { method: "GET" }); const result = await fetch(`${config.newLeafURLs[Math.floor(Math.random() * config.newLeafURLs.length)]}/api/v1/videos/${videoID}`, { method: "GET" });
@@ -45,7 +45,7 @@ export class YouTubeAPI {
return { err: result.statusText, data: null }; return { err: result.statusText, data: null };
} }
} catch (err) { } catch (err) {
return {err: err as string | boolean, data: null}; return { err: err as string | boolean, data: null };
} }
} }
} }

View File

@@ -1,6 +1,6 @@
import assert from "assert"; import assert from "assert";
import {db, privateDB} from "../../src/databases/databases"; import { db, privateDB } from "../../src/databases/databases";
describe("dbUpgrade", () => { describe("dbUpgrade", () => {
it("Should update the database version when starting the application", async () => { it("Should update the database version when starting the application", async () => {

View File

@@ -1,4 +1,4 @@
import {strictEqual, ok} from "assert"; import { strictEqual, ok } from "assert";
import { db } from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { archiveDownvoteSegment } from "../../src/cronjob/downvoteSegmentArchiveJob"; import { archiveDownvoteSegment } from "../../src/cronjob/downvoteSegmentArchiveJob";
import { DBSegment } from "../../src/types/segments.model"; import { DBSegment } from "../../src/types/segments.model";

View File

@@ -1,5 +1,5 @@
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {notStrictEqual, strictEqual} from "assert"; import { notStrictEqual, strictEqual } from "assert";
describe("getHash", () => { describe("getHash", () => {
it("Should not output the input string", () => { it("Should not output the input string", () => {

View File

@@ -1,12 +1,12 @@
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
import assert from "assert"; import assert from "assert";
const VIPUser = "isUserVIPVIP"; const VIPUser = "isUserVIPVIP";
const normalUser = "isUserVIPNormal"; const normalUser = "isUserVIPNormal";
const endpoint = "/api/isUserVIP"; const endpoint = "/api/isUserVIP";
const vipUserRequest = (userID: string) => client.get(endpoint, { params: { userID }}); const vipUserRequest = (userID: string) => client.get(endpoint, { params: { userID } });
describe("getIsUserVIP", () => { describe("getIsUserVIP", () => {
before(() => { before(() => {

View File

@@ -1,5 +1,5 @@
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
const endpoint = "/api/lockCategories"; const endpoint = "/api/lockCategories";

View File

@@ -1,5 +1,5 @@
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";

View File

@@ -1,8 +1,8 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import {Done} from "../utils/utils"; import { Done } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
const endpoint = `${getbaseURL()}/api/lockReason`; const endpoint = `${getbaseURL()}/api/lockReason`;
@@ -63,7 +63,7 @@ describe("getLockReason", () => {
const data = await res.json(); const data = await res.json();
const expected = [ const expected = [
{ category: "sponsor", locked: 1, reason: "sponsor-reason" }, { category: "sponsor", locked: 1, reason: "sponsor-reason" },
{ category: "intro", locked: 0, reason: ""} { category: "intro", locked: 0, reason: "" }
]; ];
assert.deepStrictEqual(data, expected); assert.deepStrictEqual(data, expected);
done(); done();

View File

@@ -1,6 +1,6 @@
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 {deepStrictEqual} from "assert"; import { deepStrictEqual } from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
const endpoint = "/api/getSavedTimeForUser"; const endpoint = "/api/getSavedTimeForUser";
@@ -14,7 +14,7 @@ describe("getSavedTimeForUser", () => {
}); });
it("Should be able to get a 200", (done) => { it("Should be able to get a 200", (done) => {
client.get(endpoint, { params: { userID: user1 }}) client.get(endpoint, { params: { userID: user1 } })
.then(res => { .then(res => {
// (end-start)*minute * views // (end-start)*minute * views
const savedMinutes = ((11-1)/60) * 50; const savedMinutes = ((11-1)/60) * 50;

View File

@@ -1,4 +1,4 @@
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
import assert from "assert"; import assert from "assert";
@@ -33,7 +33,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to show all segments under searchTest0", (done) => { it("Should be able to show all segments under searchTest0", (done) => {
client.get(endpoint, { params: { videoID: "searchTest0" }}) client.get(endpoint, { params: { videoID: "searchTest0" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -51,7 +51,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter by category", (done) => { it("Should be able to filter by category", (done) => {
client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" }}) client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -65,7 +65,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter by category", (done) => { it("Should be able to filter by category", (done) => {
client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" }}) client.get(endpoint, { params: { videoID: "searchTest0", category: "selfpromo" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -79,7 +79,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter by lock status", (done) => { it("Should be able to filter by lock status", (done) => {
client.get(endpoint, { params: { videoID: "searchTest0", locked: false }}) client.get(endpoint, { params: { videoID: "searchTest0", locked: false } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -96,7 +96,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter by hide status", (done) => { it("Should be able to filter by hide status", (done) => {
client.get(endpoint, { params: { videoID: "searchTest0", hidden: false }}) client.get(endpoint, { params: { videoID: "searchTest0", hidden: false } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -113,7 +113,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter by ignored status", (done) => { it("Should be able to filter by ignored status", (done) => {
client.get(endpoint, { params: { videoID: "searchTest0", ignored: false }}) client.get(endpoint, { params: { videoID: "searchTest0", ignored: false } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -129,7 +129,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter segments by min views", (done) => { it("Should be able to filter segments by min views", (done) => {
client.get(endpoint, { params: { videoID: "searchTest1", minViews: 6 }}) client.get(endpoint, { params: { videoID: "searchTest1", minViews: 6 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -143,7 +143,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter segments by max views", (done) => { it("Should be able to filter segments by max views", (done) => {
client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10 }}) client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -157,7 +157,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter segments by min and max views", (done) => { it("Should be able to filter segments by min and max views", (done) => {
client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10, minViews: 1 }}) client.get(endpoint, { params: { videoID: "searchTest1", maxViews: 10, minViews: 1 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -171,7 +171,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter segments by min votes", (done) => { it("Should be able to filter segments by min votes", (done) => {
client.get(endpoint, { params: { videoID: "searchTest2", minVotes: 0 }}) client.get(endpoint, { params: { videoID: "searchTest2", minVotes: 0 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -186,7 +186,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter segments by max votes", (done) => { it("Should be able to filter segments by max votes", (done) => {
client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10 }}) client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -201,7 +201,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to filter segments by both min and max votes", (done) => { it("Should be able to filter segments by both min and max votes", (done) => {
client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10, minVotes: 0 }}) client.get(endpoint, { params: { videoID: "searchTest2", maxVotes: 10, minVotes: 0 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -215,7 +215,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to get first page of results", (done) => { it("Should be able to get first page of results", (done) => {
client.get(endpoint, { params: { videoID: "searchTest4" }}) client.get(endpoint, { params: { videoID: "searchTest4" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -238,7 +238,7 @@ describe("getSearchSegments", () => {
}); });
it("Should be able to get second page of results", (done) => { it("Should be able to get second page of results", (done) => {
client.get(endpoint, { params: { videoID: "searchTest4", page: 1 }}) client.get(endpoint, { params: { videoID: "searchTest4", page: 1 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;

View File

@@ -1,4 +1,4 @@
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { partialDeepEquals } from "../utils/partialDeepEquals"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
@@ -169,7 +169,7 @@ describe("getSegmentInfo", () => {
}); });
it("Should be able to retreive single segment in array", (done) => { it("Should be able to retreive single segment in array", (done) => {
client.get(endpoint, { params: { UUIDs: `["${upvotedID}"]` }}) client.get(endpoint, { params: { UUIDs: `["${upvotedID}"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -185,7 +185,7 @@ describe("getSegmentInfo", () => {
}); });
it("Should be able to retreive multiple segments in array", (done) => { it("Should be able to retreive multiple segments in array", (done) => {
client.get(endpoint, { params: { UUIDs: `["${upvotedID}", "${downvotedID}"]` }}) client.get(endpoint, { params: { UUIDs: `["${upvotedID}", "${downvotedID}"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -204,7 +204,7 @@ describe("getSegmentInfo", () => {
}); });
it("Should be possible to send unexpected query parameters", (done) => { it("Should be possible to send unexpected query parameters", (done) => {
client.get(endpoint, { params: { UUID: upvotedID, fakeparam: "hello", category: "sponsor" }}) client.get(endpoint, { params: { UUID: upvotedID, fakeparam: "hello", category: "sponsor" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -273,7 +273,7 @@ describe("getSegmentInfo", () => {
it("Should cut off array at 10", function(done) { it("Should cut off array at 10", function(done) {
this.timeout(10000); this.timeout(10000);
const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`; const filledIDArray = `["${upvotedID}", "${downvotedID}", "${lockedupID}", "${shadowhiddenID}", "${lockeddownID}", "${hiddenID}", "${fillerID1}", "${fillerID2}", "${fillerID3}", "${fillerID4}", "${fillerID5}"]`;
client.get(endpoint, { params: { UUIDs: filledIDArray }}) client.get(endpoint, { params: { UUIDs: filledIDArray } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -298,7 +298,7 @@ describe("getSegmentInfo", () => {
}); });
it("Should return 400 if UUID not found", (done) => { it("Should return 400 if UUID not found", (done) => {
client.get(endpoint, { params: { UUID: ENOENTID }}) client.get(endpoint, { params: { UUID: ENOENTID } })
.then(res => { .then(res => {
if (res.status !== 400) done(`non 400 response code: ${res.status}`); if (res.status !== 400) done(`non 400 response code: ${res.status}`);
else done(); // pass else done(); // pass

View File

@@ -1,4 +1,4 @@
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { partialDeepEquals } from "../utils/partialDeepEquals"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
@@ -27,7 +27,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get a time by category 1", (done) => { it("Should be able to get a time by category 1", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -43,7 +43,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get a time by category and action type", (done) => { it("Should be able to get a time by category and action type", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionType: "mute" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionType: "mute" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -81,7 +81,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done) => { it("Should be able to get a time by category and getSkipSegmentMultiple action types (JSON array)", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionTypes: `["mute","skip"]` }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "sponsor", actionTypes: `["mute","skip"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -100,7 +100,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get a time by category for a different service 1", (done) => { it("Should be able to get a time by category for a different service 1", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID1", category: "sponsor", service: "PeerTube" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID1", category: "sponsor", service: "PeerTube" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -118,7 +118,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get a time by category 2", (done) => { it("Should be able to get a time by category 2", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "intro" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", category: "intro" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -135,7 +135,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get a time by categories array", (done) => { it("Should be able to get a time by categories array", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor"]` }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -153,7 +153,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get a time by categories array 2", (done) => { it("Should be able to get a time by categories array 2", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["intro"]` }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["intro"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -171,7 +171,7 @@ describe("getSkipSegments", () => {
}); });
it("Should return 404 if all submissions are hidden", (done) => { it("Should return 404 if all submissions are hidden", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID6" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID6" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -180,7 +180,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get getSkipSegmentMultiple times by category", (done) => { it("Should be able to get getSkipSegmentMultiple times by category", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentMultiple", categories: `["intro"]` }}) client.get(endpoint, { params: { videoID: "getSkipSegmentMultiple", categories: `["intro"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -201,7 +201,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done) => { it("Should be able to get getSkipSegmentMultiple times by getSkipSegmentMultiple categories", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor", "intro"]` }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `["sponsor", "intro"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -222,7 +222,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be possible to send unexpected query parameters", (done) => { it("Should be possible to send unexpected query parameters", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", fakeparam: "hello", category: "sponsor" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", fakeparam: "hello", category: "sponsor" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -239,7 +239,7 @@ describe("getSkipSegments", () => {
}); });
it("Low voted submissions should be hidden", (done) => { it("Low voted submissions should be hidden", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID3", category: "sponsor" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID3", category: "sponsor" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -256,7 +256,7 @@ describe("getSkipSegments", () => {
}); });
it("Should return 404 if no segment found", (done) => { it("Should return 404 if no segment found", (done) => {
client.get(endpoint, { params: { videoID: "notarealvideo" }}) client.get(endpoint, { params: { videoID: "notarealvideo" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -265,7 +265,7 @@ describe("getSkipSegments", () => {
}); });
it("Should return 400 if bad categories argument", (done) => { it("Should return 400 if bad categories argument", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `[not-quoted,not-quoted]` }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID0", categories: `[not-quoted,not-quoted]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -274,7 +274,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able send a comma in a query param", (done) => { it("Should be able send a comma in a query param", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentID2", category: "sponsor" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentID2", category: "sponsor" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -291,7 +291,7 @@ describe("getSkipSegments", () => {
}); });
it("Should always get getSkipSegmentLocked segment", (done) => { it("Should always get getSkipSegmentLocked segment", (done) => {
client.get(endpoint, { params: { videoID: "getSkipSegmentLocked", category: "intro" }}) client.get(endpoint, { params: { videoID: "getSkipSegmentLocked", category: "intro" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -308,7 +308,7 @@ describe("getSkipSegments", () => {
}); });
it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done) => { it("Should be able to get getSkipSegmentMultiple categories with repeating parameters", (done) => {
client.get(`${endpoint}?category=sponsor&category=intro`, { params: { videoID: "getSkipSegmentID0" }}) client.get(`${endpoint}?category=sponsor&category=intro`, { params: { videoID: "getSkipSegmentID0" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -348,7 +348,7 @@ describe("getSkipSegments", () => {
it("Should be able to get specific segments with requiredSegments", (done) => { it("Should be able to get specific segments with requiredSegments", (done) => {
const required2 = "requiredSegmentVid2"; const required2 = "requiredSegmentVid2";
const required3 = "requiredSegmentVid3"; const required3 = "requiredSegmentVid3";
client.get(endpoint, { params: { videoID: "requiredSegmentVid", requiredSegments: `["${required2}","${required3}"]` }}) client.get(endpoint, { params: { videoID: "requiredSegmentVid", requiredSegments: `["${required2}","${required3}"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;

View File

@@ -1,9 +1,9 @@
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { partialDeepEquals } from "../utils/partialDeepEquals"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {ImportMock,} from "ts-mock-imports"; import { ImportMock, } from "ts-mock-imports";
import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi";
import {YouTubeApiMock} from "../youtubeMock"; import { YouTubeApiMock } from "../youtubeMock";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
@@ -33,7 +33,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should be able to get a 200", (done) => { it("Should be able to get a 200", (done) => {
client.get(`${endpoint}/3272f`, { params: { categories: `["sponsor", "intro"]` }}) client.get(`${endpoint}/3272f`, { params: { categories: `["sponsor", "intro"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -42,7 +42,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should return 404 if no segments are found even if a video for the given hash is known", (done) => { it("Should return 404 if no segments are found even if a video for the given hash is known", (done) => {
client.get(`${endpoint}/3272f`, { params: { categories: `["shilling"]` }}) client.get(`${endpoint}/3272f`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
assert.equal(res.data.length, 0); assert.equal(res.data.length, 0);
@@ -52,7 +52,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should be able to get an empty array if no videos", (done) => { it("Should be able to get an empty array if no videos", (done) => {
client.get(`${endpoint}/11111`, { params: { categories: `["shilling"]` }}) client.get(`${endpoint}/11111`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
const body = res.data; const body = res.data;
@@ -63,7 +63,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should be able to get an empty array if only hidden videos", (done) => { it("Should be able to get an empty array if only hidden videos", (done) => {
client.get(`${endpoint}/f3a1`, { params: { categories:`["sponsor"]` }}) client.get(`${endpoint}/f3a1`, { params: { categories:`["sponsor"]` } })
.then(res => { .then(res => {
if (res.status !== 404) done(`non 404 status code, was ${res.status}`); if (res.status !== 404) done(`non 404 status code, was ${res.status}`);
else { else {
@@ -76,7 +76,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should return 400 prefix too short", (done) => { it("Should return 400 prefix too short", (done) => {
client.get(`${endpoint}/11`, { params: { categories: `["shilling"]` }}) client.get(`${endpoint}/11`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -87,7 +87,7 @@ describe("getSkipSegmentsByHash", () => {
it("Should return 400 prefix too long", (done) => { it("Should return 400 prefix too long", (done) => {
const prefix = "1".repeat(50); const prefix = "1".repeat(50);
assert.ok(prefix.length > 33, "failed to generate long enough string"); assert.ok(prefix.length > 33, "failed to generate long enough string");
client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` }}) client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -97,7 +97,7 @@ describe("getSkipSegmentsByHash", () => {
it("Should return 404 prefix in range", (done) => { it("Should return 404 prefix in range", (done) => {
const prefix = "1".repeat(5); const prefix = "1".repeat(5);
client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` }}) client.get(`${endpoint}/${prefix}`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 404); assert.strictEqual(res.status, 404);
done(); done();
@@ -106,7 +106,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should return 400 for no hash", (done) => { it("Should return 400 for no hash", (done) => {
client.get(`${endpoint}`, { params: { categories: `["shilling"]` }}) client.get(`${endpoint}`, { params: { categories: `["shilling"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -115,7 +115,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should return 400 for bad format categories", (done) => { it("Should return 400 for bad format categories", (done) => {
client.get(`${endpoint}/fdaf`, { params: { categories: "shilling" }}) client.get(`${endpoint}/fdaf`, { params: { categories: "shilling" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -124,7 +124,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should be able to get multiple videos", (done) => { it("Should be able to get multiple videos", (done) => {
client.get(`${endpoint}/fdaf`, { params: { categories: `["sponsor","intro"]` }}) client.get(`${endpoint}/fdaf`, { params: { categories: `["sponsor","intro"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -161,7 +161,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should be able to get 200 for no categories (default sponsor) with action type", (done) => { it("Should be able to get 200 for no categories (default sponsor) with action type", (done) => {
client.get(`${endpoint}/fdaf`, { params: { actionType: "skip" }}) client.get(`${endpoint}/fdaf`, { params: { actionType: "skip" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -235,7 +235,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done) => { it("Should be able to get 200 for no categories (default sponsor) for a non YouTube service", (done) => {
client.get(`${endpoint}/fdaf`, { params: { service: "PeerTube" }}) client.get(`${endpoint}/fdaf`, { params: { service: "PeerTube" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -253,7 +253,7 @@ describe("getSkipSegmentsByHash", () => {
}); });
it("Should only return one segment when fetching highlight segments", (done) => { it("Should only return one segment when fetching highlight segments", (done) => {
client.get(`${endpoint}/c962`, { params: { category: "poi_highlight" }}) client.get(`${endpoint}/c962`, { params: { category: "poi_highlight" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;

View File

@@ -1,5 +1,5 @@
import assert from "assert"; import assert from "assert";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
let dbVersion: number; let dbVersion: number;

View File

@@ -1,4 +1,4 @@
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 { ActionType, VideoID } from "../../src/types/segments.model";
import { UserID } from "../../src/types/user.model"; import { UserID } from "../../src/types/user.model";

View File

@@ -1,11 +1,11 @@
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
import { AxiosResponse } from "axios"; import { AxiosResponse } from "axios";
const endpoint = "/api/userID"; const endpoint = "/api/userID";
const getUserName = (username: string): Promise<AxiosResponse> => client.get(endpoint, { params: { username }}); const getUserName = (username: string): Promise<AxiosResponse> => client.get(endpoint, { params: { username } });
describe("getUserID", () => { describe("getUserID", () => {
before(async () => { before(async () => {
@@ -43,7 +43,7 @@ describe("getUserID", () => {
}); });
it("Should be able to get a 200 (username is public id)", (done) => { it("Should be able to get a 200 (username is public id)", (done) => {
client.get(endpoint, { params: { username: getHash("getuserid_user_06") }}) client.get(endpoint, { params: { username: getHash("getuserid_user_06") } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -52,7 +52,7 @@ describe("getUserID", () => {
}); });
it("Should be able to get a 400 (username longer than 64 chars)", (done) => { it("Should be able to get a 400 (username longer than 64 chars)", (done) => {
client.get(endpoint, { params: { username: `${getHash("getuserid_user_06")}0` }}) client.get(endpoint, { params: { username: `${getHash("getuserid_user_06")}0` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -61,7 +61,7 @@ describe("getUserID", () => {
}); });
it("Should be able to get single username", (done) => { it("Should be able to get single username", (done) => {
client.get(endpoint, { params: { username: "fuzzy user 01" }}) client.get(endpoint, { params: { username: "fuzzy user 01" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
@@ -254,7 +254,7 @@ describe("getUserID", () => {
}); });
it("should allow exact match", (done) => { it("should allow exact match", (done) => {
client.get(endpoint, { params: { username: "a", exact: true }}) client.get(endpoint, { params: { username: "a", exact: true } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
@@ -268,7 +268,7 @@ describe("getUserID", () => {
}); });
it("Should be able to get repeating username with exact username", (done) => { it("Should be able to get repeating username with exact username", (done) => {
client.get(endpoint, { params: { username: "repeating", exact: true }}) client.get(endpoint, { params: { username: "repeating", exact: true } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{
@@ -285,7 +285,7 @@ describe("getUserID", () => {
}); });
it("Should not get exact unless explicitly set to true", (done) => { it("Should not get exact unless explicitly set to true", (done) => {
client.get(endpoint, { params: { username: "user", exact: 1 }}) client.get(endpoint, { params: { username: "user", exact: 1 } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = [{ const expected = [{

View File

@@ -1,6 +1,6 @@
import { partialDeepEquals } from "../utils/partialDeepEquals"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
@@ -35,7 +35,7 @@ describe("getUserInfo", () => {
}); });
it("Should be able to get a 200", (done) => { it("Should be able to get a 200", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_user_01" }}) client.get(endpoint, { params: { userID: "getuserinfo_user_01" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();
@@ -44,7 +44,7 @@ describe("getUserInfo", () => {
}); });
it("Should be able to get a 400 (No userID parameter)", (done) => { it("Should be able to get a 400 (No userID parameter)", (done) => {
client.get(endpoint, { params: { userID: "" }}) client.get(endpoint, { params: { userID: "" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();
@@ -53,7 +53,7 @@ describe("getUserInfo", () => {
}); });
it("Should be able to get user info", (done) => { it("Should be able to get user info", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_user_01" }}) client.get(endpoint, { params: { userID: "getuserinfo_user_01" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -77,7 +77,7 @@ describe("getUserInfo", () => {
}); });
it("Should get warning data", (done) => { it("Should get warning data", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_warning_0", value: "warnings" }}) client.get(endpoint, { params: { userID: "getuserinfo_warning_0", value: "warnings" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -90,7 +90,7 @@ describe("getUserInfo", () => {
}); });
it("Should get warning data with public ID", (done) => { it("Should get warning data with public ID", (done) => {
client.get(endpoint, { params: { publicUserID: getHash("getuserinfo_warning_0"), values: `["warnings"]` }}) client.get(endpoint, { params: { publicUserID: getHash("getuserinfo_warning_0"), values: `["warnings"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -103,7 +103,7 @@ describe("getUserInfo", () => {
}); });
it("Should get multiple warnings", (done) => { it("Should get multiple warnings", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warnings" }}) client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warnings" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -116,7 +116,7 @@ describe("getUserInfo", () => {
}); });
it("Should not get warnings if none", (done) => { it("Should not get warnings if none", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_warning_2", value: "warnings" }}) client.get(endpoint, { params: { userID: "getuserinfo_warning_2", value: "warnings" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -129,7 +129,7 @@ describe("getUserInfo", () => {
}); });
it("Should done(userID for userName (No userName set)", (done) => { it("Should done(userID for userName (No userName set)", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_user_02", value: "userName" }}) client.get(endpoint, { params: { userID: "getuserinfo_user_02", value: "userName" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -142,7 +142,7 @@ describe("getUserInfo", () => {
}); });
it("Should return null segment if none", (done) => { it("Should return null segment if none", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" }}) client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
assert.strictEqual(res.data.lastSegmentID, null); assert.strictEqual(res.data.lastSegmentID, null);
@@ -152,7 +152,7 @@ describe("getUserInfo", () => {
}); });
it("Should return zeroes if userid does not exist", (done) => { it("Should return zeroes if userid does not exist", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" }}) client.get(endpoint, { params: { userID: "getuserinfo_null", value: "lastSegmentID" } })
.then(res => { .then(res => {
const data = res.data; const data = res.data;
for (const value in data) { for (const value in data) {
@@ -166,7 +166,7 @@ describe("getUserInfo", () => {
}); });
it("Should get warning reason from from single enabled warning", (done) => { it("Should get warning reason from from single enabled warning", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_warning_0", values: `["warningReason"]` }}) client.get(endpoint, { params: { userID: "getuserinfo_warning_0", values: `["warningReason"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -179,7 +179,7 @@ describe("getUserInfo", () => {
}); });
it("Should get most recent warning from two enabled warnings", (done) => { it("Should get most recent warning from two enabled warnings", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warningReason" }}) client.get(endpoint, { params: { userID: "getuserinfo_warning_1", value: "warningReason" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -192,7 +192,7 @@ describe("getUserInfo", () => {
}); });
it("Should not get disabled warning", (done) => { it("Should not get disabled warning", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_warning_2", values: `["warnings","warningReason"]` }}) client.get(endpoint, { params: { userID: "getuserinfo_warning_2", values: `["warnings","warningReason"]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -220,7 +220,7 @@ describe("getUserInfo", () => {
}); });
it("Should get 400 if bad values specified", (done) => { it("Should get 400 if bad values specified", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_warning_3", value: "invalid-value" }}) client.get(endpoint, { params: { userID: "getuserinfo_warning_3", value: "invalid-value" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); // pass done(); // pass
@@ -229,7 +229,7 @@ describe("getUserInfo", () => {
}); });
it("Should get ban data for banned user (only appears when specifically requested)", (done) => { it("Should get ban data for banned user (only appears when specifically requested)", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_ban_01", value: "banned" }}) client.get(endpoint, { params: { userID: "getuserinfo_ban_01", value: "banned" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -242,7 +242,7 @@ describe("getUserInfo", () => {
}); });
it("Should get ban data for unbanned user (only appears when specifically requested)", (done) => { it("Should get ban data for unbanned user (only appears when specifically requested)", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_notban_01", value: "banned" }}) client.get(endpoint, { params: { userID: "getuserinfo_notban_01", value: "banned" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -255,7 +255,7 @@ describe("getUserInfo", () => {
}); });
it("Should throw 400 on bad json in values", (done) => { it("Should throw 400 on bad json in values", (done) => {
client.get(endpoint, { params: { userID: "x", values: `[userID]` }}) client.get(endpoint, { params: { userID: "x", values: `[userID]` } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); // pass done(); // pass
@@ -264,7 +264,7 @@ describe("getUserInfo", () => {
}); });
it("Should return 200 on userID not found", (done) => { it("Should return 200 on userID not found", (done) => {
client.get(endpoint, { params: { userID: "notused-userid" }}) client.get(endpoint, { params: { userID: "notused-userid" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -285,7 +285,7 @@ describe("getUserInfo", () => {
}); });
it("Should only count long segments as 10 minutes", (done) => { it("Should only count long segments as 10 minutes", (done) => {
client.get(endpoint, { params: { userID: "getuserinfo_user_03" }}) client.get(endpoint, { params: { userID: "getuserinfo_user_03" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {

View File

@@ -33,7 +33,7 @@ describe("getUserStats", () => {
}); });
it("Should be able to get all user info", (done) => { it("Should be able to get all user info", (done) => {
client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchCategoryStats: true, fetchActionTypeStats: true }}) client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchCategoryStats: true, fetchActionTypeStats: true } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const expected = { const expected = {
@@ -65,7 +65,7 @@ describe("getUserStats", () => {
}); });
it("Should be able to get all zeroes for invalid userid", (done) => { it("Should be able to get all zeroes for invalid userid", (done) => {
client.get(endpoint, { params: { userID: "getuserstats_user_invalid" }}) client.get(endpoint, { params: { userID: "getuserstats_user_invalid" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -80,7 +80,7 @@ describe("getUserStats", () => {
}); });
it("Should be able to get all zeroes for only ignored segments", (done) => { it("Should be able to get all zeroes for only ignored segments", (done) => {
client.get(endpoint, { params: { userID: "getuserstats_user_02" }}) client.get(endpoint, { params: { userID: "getuserstats_user_02" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -95,7 +95,7 @@ describe("getUserStats", () => {
}); });
it("Should not get extra stats if not requested", (done) => { it("Should not get extra stats if not requested", (done) => {
client.get(endpoint, { params: { userID: "getuserstats_user_01" }}) client.get(endpoint, { params: { userID: "getuserstats_user_01" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;
@@ -109,7 +109,7 @@ describe("getUserStats", () => {
}); });
it("Should get parts of extra stats if not requested", (done) => { it("Should get parts of extra stats if not requested", (done) => {
client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchActionTypeStats: true }}) client.get(endpoint, { params: { userID: "getuserstats_user_01", fetchActionTypeStats: true } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;

View File

@@ -1,7 +1,7 @@
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import {LockCategory } from "../../src/types/segments.model"; import { LockCategory } from "../../src/types/segments.model";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
const stringDeepEquals = (a: string[] ,b: string[]): boolean => { const stringDeepEquals = (a: string[] ,b: string[]): boolean => {
@@ -455,7 +455,7 @@ describe("lockCategoriesRecords", () => {
"shilling" "shilling"
], ],
}; };
client.get(endpoint, { params: {videoID: "no-segments-video-id" }}) client.get(endpoint, { params: { videoID: "no-segments-video-id" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const data = res.data; const data = res.data;

View File

@@ -1,4 +1,4 @@
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { partialDeepEquals } from "../utils/partialDeepEquals"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
@@ -33,7 +33,7 @@ describe("getVideoSponsorTime (Old get method)", () => {
it("Should be possible to send unexpected query parameters", (done) => { it("Should be possible to send unexpected query parameters", (done) => {
client.get(endpoint, { params: { videoID: "oldGetSponsorTime0", fakeparam: "hello" }}) client.get(endpoint, { params: { videoID: "oldGetSponsorTime0", fakeparam: "hello" } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
done(); done();

View File

@@ -1,4 +1,4 @@
import { partialDeepEquals } from "../utils/partialDeepEquals";import {db} from "../../src/databases/databases"; import { partialDeepEquals } from "../utils/partialDeepEquals";import { db } from "../../src/databases/databases";
import assert from "assert"; import assert from "assert";
import { client } from "../utils/httpClient"; import { client } from "../utils/httpClient";
@@ -9,7 +9,7 @@ const endpoint = "/api/postVideoSponsorTimes";
describe("postVideoSponsorTime (Old submission method)", () => { describe("postVideoSponsorTime (Old submission method)", () => {
it("Should be able to submit a time (GET)", (done) => { it("Should be able to submit a time (GET)", (done) => {
client.get(endpoint, { params: { videoID: videoID1, startTime: 1, endTime: 10, userID }}) client.get(endpoint, { params: { videoID: videoID1, startTime: 1, endTime: 10, userID } })
.then(async res => { .then(async res => {
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID1]); const row = await db.prepare("get", `SELECT "startTime", "endTime", "category" FROM "sponsorTimes" WHERE "videoID" = ?`, [videoID1]);
@@ -45,7 +45,7 @@ describe("postVideoSponsorTime (Old submission method)", () => {
}); });
it("Should return 400 for missing params", (done) => { it("Should return 400 for missing params", (done) => {
client.post(endpoint, { params: { startTime: 1, endTime: 10, userID }}) client.post(endpoint, { params: { startTime: 1, endTime: 10, userID } })
.then(res => { .then(res => {
assert.strictEqual(res.status, 400); assert.strictEqual(res.status, 400);
done(); done();

View File

@@ -1,8 +1,8 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import { Done } from "../utils/utils"; import { Done } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
const VIPUser = "clearCacheVIP"; const VIPUser = "clearCacheVIP";

View File

@@ -1,9 +1,9 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import {Done, postJSON} from "../utils/utils"; import { Done, postJSON } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {IDatabase} from "../../src/databases/IDatabase"; import { IDatabase } from "../../src/databases/IDatabase";
import assert from "assert"; import assert from "assert";
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) {

View File

@@ -1,13 +1,13 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import {config} from "../../src/config"; import { config } from "../../src/config";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import { Done, postJSON } from "../utils/utils"; import { Done, postJSON } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import { partialDeepEquals } from "../utils/partialDeepEquals"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {db} from "../../src/databases/databases"; 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"; import assert from "assert";
const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI");

View File

@@ -2,8 +2,8 @@ import fetch from "node-fetch";
import { Done, postJSON } from "../utils/utils"; import { Done, postJSON } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import { partialDeepEquals } from "../utils/partialDeepEquals"; import { partialDeepEquals } from "../utils/partialDeepEquals";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
describe("postWarning", () => { describe("postWarning", () => {

View File

@@ -1,9 +1,9 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import {Done, postJSON} from "../utils/utils"; import { Done, postJSON } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {IDatabase} from "../../src/databases/IDatabase"; import { IDatabase } from "../../src/databases/IDatabase";
import assert from "assert"; import assert from "assert";
describe("segmentShift", function () { describe("segmentShift", function () {

View File

@@ -1,8 +1,8 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { Done } from "../utils/utils"; import { Done } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import assert from "assert"; import assert from "assert";
import { Category } from "../../src/types/segments.model"; import { Category } from "../../src/types/segments.model";

View File

@@ -15,8 +15,8 @@ describe("Test utils ", () => {
false false
), "Did not match empty expect"); ), "Did not match empty expect");
assert(partialDeepEquals( assert(partialDeepEquals(
[{a: [1,2,3]}, {a: [1,2]}], [{ a: [1,2,3] }, { a: [1,2] }],
[{a: [1,2,3]}, {a: [1,2]}] [{ a: [1,2,3] }, { a: [1,2] }]
), "Did not match same arrays"); ), "Did not match same arrays");
assert(partialDeepEquals( assert(partialDeepEquals(
{ {

View File

@@ -1,12 +1,12 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import {config} from "../../src/config"; import { config } from "../../src/config";
import {db} from "../../src/databases/databases"; import { db } from "../../src/databases/databases";
import { Done } from "../utils/utils"; import { Done } from "../utils/utils";
import { getbaseURL } from "../utils/getBaseURL"; import { getbaseURL } from "../utils/getBaseURL";
import {getHash} from "../../src/utils/getHash"; import { getHash } from "../../src/utils/getHash";
import {ImportMock} from "ts-mock-imports"; import { ImportMock } from "ts-mock-imports";
import * as YouTubeAPIModule from "../../src/utils/youtubeApi"; import * as YouTubeAPIModule from "../../src/utils/youtubeApi";
import {YouTubeApiMock} from "../youtubeMock"; import { YouTubeApiMock } from "../youtubeMock";
import assert from "assert"; import assert from "assert";
const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI"); const mockManager = ImportMock.mockStaticClass(YouTubeAPIModule, "YouTubeAPI");

View File

@@ -1,5 +1,5 @@
import express from "express"; import express from "express";
import {config} from "../src/config"; import { config } from "../src/config";
import { Server } from "http"; import { Server } from "http";
const app = express(); const app = express();

View File

@@ -1,12 +1,12 @@
import Mocha from "mocha"; import Mocha from "mocha";
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
import {config} from "../src/config"; import { config } from "../src/config";
import {createServer} from "../src/app"; import { createServer } from "../src/app";
import {createMockServer} from "./mocks"; import { createMockServer } from "./mocks";
import {Logger} from "../src/utils/logger"; import { Logger } from "../src/utils/logger";
import {initDb} from "../src/databases/databases"; import { initDb } from "../src/databases/databases";
import {ImportMock} from "ts-mock-imports"; import { ImportMock } from "ts-mock-imports";
import * as rateLimitMiddlewareModule from "../src/middleware/requestRateLimit"; import * as rateLimitMiddlewareModule from "../src/middleware/requestRateLimit";
import rateLimit from "express-rate-limit"; import rateLimit from "express-rate-limit";