14 Commits

Author SHA1 Message Date
Ajay
a860b89ef0 Add config for min 2022-05-27 23:23:45 -04:00
Ajay
4650316067 FIx max not being used 2022-05-27 22:46:35 -04:00
Ajay
08d458bdd6 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into k8s-test 2022-05-27 19:07:53 -04:00
Ajay
6abfba1b12 Add max to postgres config 2022-05-27 19:07:25 -04:00
Ajay
d038279d79 more logs 2022-05-27 12:41:09 -04:00
Ajay
35d3627760 more logs 2022-05-27 02:35:32 -04:00
Ajay
dcffb83e62 Logs for submiting 2022-05-27 01:24:34 -04:00
Ajay
a0465a44ae More logging 2022-05-26 22:59:59 -04:00
Ajay
db55d314ee Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into k8s-test 2022-05-26 22:49:27 -04:00
Ajay
b2af4fc7b0 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into k8s-test 2022-05-26 22:47:17 -04:00
Ajay
4f28d92eb8 Fix params check 2022-05-26 22:21:00 -04:00
Ajay
c822a37a6e Add more logging for debugging 2022-05-26 22:15:09 -04:00
Ajay
fd636a2770 Merge branch 'master' of https://github.com/ajayyy/SponsorBlockServer into k8s-test 2022-05-24 19:15:58 -04:00
Ajay
c2e0d5a98f logs 2022-05-20 04:27:39 -04:00
252 changed files with 8757 additions and 21122 deletions

View File

@@ -29,18 +29,4 @@ module.exports = {
"semi": "warn",
"no-console": "warn"
},
overrides: [
{
files: ["**/*.ts"],
parserOptions: {
project: ["./tsconfig.eslint.json"],
},
rules: {
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/no-floating-promises" : "error"
}
},
],
};

View File

@@ -1,3 +0,0 @@
- [ ] I agree to license my contribution under AGPL-3.0-only with my contribution automatically being licensed under LGPL-3.0 additionally after 6 months
***

21
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: SQLite CI
on:
push:
branches:
- master
pull_request:
jobs:
test:
name: Run Tests with SQLite
runs-on: ubuntu-latest
steps:
# Initialization
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- run: npm install
- name: Run Tests
timeout-minutes: 5
run: npm test

View File

@@ -19,13 +19,12 @@ on:
jobs:
build_container:
runs-on: ubuntu-latest
permissions:
packages: write
steps:
- uses: actions/checkout@v4
- name: Checkout
uses: actions/checkout@v3
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
uses: docker/metadata-action@v4
with:
images: |
ghcr.io/${{ inputs.username }}/${{ inputs.name }}
@@ -34,21 +33,14 @@ jobs:
flavor: |
latest=true
- name: Login to GHCR
uses: docker/login-action@v3
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GH_TOKEN }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm,arm64
- name: Set up buildx
uses: docker/setup-buildx-action@v3
- name: push
uses: docker/build-push-action@v6
uses: docker/build-push-action@v3
with:
context: ${{ inputs.folder }}
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}

View File

@@ -1,16 +0,0 @@
name: Docker image builds
on:
push:
branches:
- master
workflow_dispatch:
jobs:
error-server:
uses: ./.github/workflows/docker-build.yml
with:
name: "error-server"
username: "ajayyy"
folder: "./containers/error-server"
secrets:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

21
.github/workflows/eslint.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: Linting
on:
push:
branches:
- master
pull_request:
jobs:
lint:
name: Lint with ESLint
runs-on: ubuntu-latest
steps:
# Initialization
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- run: npm install
- name: Run Tests
timeout-minutes: 5
run: npm run lint

View File

@@ -6,7 +6,6 @@ on:
- master
paths:
- databases/**
workflow_dispatch:
jobs:
make-base-db:
@@ -14,28 +13,16 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
cache: npm
- run: npm ci
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- run: npm install
- name: Set config
run: |
echo '{"mode": "init-db-and-exit"}' > config.json
- name: Run Server
timeout-minutes: 10
run: npm start
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v2
with:
name: SponsorTimesDB.db
path: databases/sponsorTimes.db
- uses: mchangrh/s3cmd-sync@f4f36b9705bdd9af7ac91964136989ac17e3b513
with:
args: --acl-public
env:
S3_ENDPOINT: ${{ secrets.S3_ENDPOINT }}
S3_BUCKET: ${{ secrets.S3_BUCKET }}
S3_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
S3_ACCESS_KEY_SECRET: ${{ secrets.S3_ACCESS_KEY_SECRET }}
SOURCE_DIR: 'databases/sponsorTimes.db'
path: databases/sponsorTimes.db

29
.github/workflows/postgres-redis-ci.yml vendored Normal file
View File

@@ -0,0 +1,29 @@
name: PostgreSQL + Redis CI
on:
push:
branches:
- master
pull_request:
jobs:
test:
name: Run Tests with PostgreSQL and Redis
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build the docker-compose stack
env:
PG_USER: ci_db_user
PG_PASS: ci_db_pass
run: docker-compose -f docker/docker-compose-ci.yml up -d
- name: Check running containers
run: docker ps
- uses: actions/setup-node@v2
- run: npm install
- name: Run Tests
env:
TEST_POSTGRES: true
timeout-minutes: 5
run: npm test

View File

@@ -7,6 +7,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: take the issue
uses: bdougie/take-action@28b86cd8d25593f037406ecbf96082db2836e928
uses: bdougie/take-action@main
env:
GITHUB_TOKEN: ${{ github.token }}

View File

@@ -1,121 +0,0 @@
name: Tests
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
jobs:
lint-build:
name: Lint with ESLint and build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run tsc
- name: cache dist build
uses: actions/cache/save@v4
with:
key: dist-${{ github.sha }}
path: |
${{ github.workspace }}/dist
${{ github.workspace }}/node_modules
test-sqlite:
name: Run Tests with SQLite
runs-on: ubuntu-latest
needs: lint-build
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
cache: npm
- id: cache
uses: actions/cache/restore@v4
with:
key: dist-${{ github.sha }}
path: |
${{ github.workspace }}/dist
${{ github.workspace }}/node_modules
- if: steps.cache.outputs.cache-hit != 'true'
run: npm ci
env:
youTubeKeys_visitorData: ${{ secrets.YOUTUBEKEYS_VISITORDATA }}
youTubeKeys_poToken: ${{ secrets.YOUTUBEKEYS_POTOKEN }}
- name: Run SQLite Tests
timeout-minutes: 5
run: npx nyc --silent npm test
- name: cache nyc output
uses: actions/cache/save@v4
with:
key: nyc-sqlite-${{ github.sha }}
path: ${{ github.workspace }}/.nyc_output
test-postgres:
name: Run Tests with PostgreSQL and Redis
runs-on: ubuntu-latest
needs: lint-build
steps:
- uses: actions/checkout@v4
- name: Build the docker-compose stack
env:
PG_USER: ci_db_user
PG_PASS: ci_db_pass
run: docker compose -f docker/docker-compose-ci.yml up -d
- name: Check running containers
run: docker ps
- uses: actions/setup-node@v4
with:
node-version: 18
cache: npm
- id: cache
uses: actions/cache/restore@v4
with:
key: dist-${{ github.sha }}
path: |
${{ github.workspace }}/dist
${{ github.workspace }}/node_modules
- if: steps.cache.outputs.cache-hit != 'true'
run: npm ci
- name: Run Postgres Tests
env:
TEST_POSTGRES: true
youTubeKeys_visitorData: ${{ secrets.YOUTUBEKEYS_VISITORDATA }}
youTubeKeys_poToken: ${{ secrets.YOUTUBEKEYS_POTOKEN }}
timeout-minutes: 5
run: npx nyc --silent npm test
- name: cache nyc output
uses: actions/cache/save@v4
with:
key: nyc-postgres-${{ github.sha }}
path: ${{ github.workspace }}/.nyc_output
codecov:
needs: [test-sqlite, test-postgres]
name: Run Codecov
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
cache: npm
- run: npm ci
- name: restore postgres nyc output
uses: actions/cache/restore@v4
with:
key: nyc-postgres-${{ github.sha }}
path: ${{ github.workspace }}/.nyc_output
- name: restore sqlite nyc output
uses: actions/cache/restore@v4
with:
key: nyc-sqlite-${{ github.sha }}
path: ${{ github.workspace }}/.nyc_output
- run: npx nyc report --reporter=lcov
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v4

6
.gitignore vendored
View File

@@ -45,9 +45,3 @@ working
.DS_Store
/.idea/
/dist/
# nyc coverage output
.nyc_output/
coverage/
.vscode

View File

@@ -1,14 +0,0 @@
{
"extends": "@istanbuljs/nyc-config-typescript",
"check-coverage": false,
"ski-full": true,
"reporter": ["text", "html"],
"include": [
"src/**/*.ts"
],
"exclude": [
"src/routes/addUnlistedVideo.ts",
"src/cronjob/downvoteSegmentArchiveJob.ts",
"src/databases/*"
]
}

View File

@@ -1,29 +1,20 @@
# SponsorTimesDB
- [vipUsers](#vipusers)
- [sponsorTimes](#sponsortimes)
- [userNames](#usernames)
- [categoryVotes](#categoryvotes)
- [lockCategories](#lockcategories)
- [warnings](#warnings)
- [shadowBannedUsers](#shadowbannedusers)
- [videoInfo](#videoinfo)
- [unlistedVideos](#unlistedvideos)
- [config](#config)
- [archivedSponsorTimes](#archivedsponsortimes)
- [ratings](#ratings)
- [userFeatures](#userFeatures)
- [shadowBannedIPs](#shadowBannedIPs)
- [titles](#titles)
- [titleVotes](#titleVotes)
- [thumbnails](#thumbnails)
- [thumbnailTimestamps](#thumbnailTimestamps)
- [thumbnailVotes](#thumbnailVotes)
[vipUsers](#vipUsers)
[sponsorTimes](#sponsorTimes)
[userNames](#userNames)
[categoryVotes](#categoryVotes)
[lockCategories](#lockCategories)
[warnings](#warnings)
[shadowBannedUsers](#shadowBannedUsers)
[unlistedVideos](#unlistedVideos)
[config](#config)
[archivedSponsorTimes](#archivedSponsorTimes)
### vipUsers
| Name | Type | |
| -- | :--: | -- |
| userID | TEXT | not null, primary key |
| userID | TEXT | not null |
| index | field |
| -- | :--: |
@@ -39,7 +30,7 @@
| votes | INTEGER | not null |
| locked | INTEGER | not null, default '0' |
| incorrectVotes | INTEGER | not null, default 1 |
| UUID | TEXT | not null, unique, primary key |
| UUID | TEXT | not null, unique |
| userID | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| views | INTEGER | not null |
@@ -59,16 +50,14 @@
| sponsorTime_timeSubmitted | timeSubmitted |
| sponsorTime_userID | userID |
| sponsorTimes_UUID | UUID |
| sponsorTimes_hashedVideoID | service, hashedVideoID, startTime |
| sponsorTimes_videoID | service, videoID, startTime |
| sponsorTimes_videoID_category | videoID, category |
| sponsorTimes_description_gin | description, category |
| sponsorTimes_hashedVideoID | hashedVideoID, category |
| sponsorTimes_videoID | videoID, service, category, timeSubmitted |
### userNames
| Name | Type | |
| -- | :--: | -- |
| userID | TEXT | not null, primary key |
| userID | TEXT | not null |
| userName | TEXT | not null |
| locked | INTEGER | not nul, default '0' |
@@ -83,7 +72,6 @@
| UUID | TEXT | not null |
| category | TEXT | not null |
| votes | INTEGER | not null, default 0 |
| id | SERIAL | primary key
| index | field |
| -- | :--: |
@@ -100,7 +88,6 @@
| hashedVideoID | TEXT | not null, default '' |
| reason | TEXT | not null, default '' |
| service | TEXT | not null, default 'YouTube' |
| id | SERIAL | primary key
| index | field |
| -- | :--: |
@@ -115,22 +102,17 @@
| issuerUserID | TEXT | not null |
| enabled | INTEGER | not null |
| reason | TEXT | not null, default '' |
| type | INTEGER | default 0 |
| constraint | field |
| -- | :--: |
| PRIMARY KEY | userID, issueTime |
| index | field |
| -- | :--: |
| warnings_index | userID, issueTime, enabled |
| warnings_index | userID |
| warnings_issueTime | issueTime |
### shadowBannedUsers
| Name | Type | |
| -- | :--: | -- |
| userID | TEXT | not null, primary key |
| userID | TEXT | not null |
| index | field |
| -- | :--: |
@@ -144,11 +126,12 @@
| channelID | TEXT | not null |
| title | TEXT | not null |
| published | REAL | not null |
| genreUrl | TEXT | not null |
| index | field |
| -- | :--: |
| videoInfo_videoID | videoID |
| videoInfo_channelID | channelID |
| videoInfo_videoID | timeSubmitted |
| videoInfo_channelID | userID |
### unlistedVideos
@@ -160,13 +143,12 @@
| channelID | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| service | TEXT | not null, default 'YouTube' |
| id | SERIAL | primary key
### config
| Name | Type | |
| -- | :--: | -- |
| key | TEXT | not null, unique, primary key |
| key | TEXT | not null, unique |
| value | TEXT | not null |
### archivedSponsorTimes
@@ -179,7 +161,7 @@
| votes | INTEGER | not null |
| locked | INTEGER | not null, default '0' |
| incorrectVotes | INTEGER | not null, default 1 |
| UUID | TEXT | not null, unique, primary key |
| UUID | TEXT | not null, unique |
| userID | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| views | INTEGER | not null |
@@ -192,7 +174,6 @@
| shadowHidden | INTEGER | not null |
| hashedVideoID | TEXT | not null, default '', sha256 |
| userAgent | TEXT | not null, default '' |
| description | TEXT | not null, default '' |
### ratings
@@ -203,7 +184,6 @@
| type | INTEGER | not null |
| count | INTEGER | not null |
| hashedVideoID | TEXT | not null |
| id | SERIAL | primary key
| index | field |
| -- | :--: |
@@ -211,125 +191,15 @@
| ratings_hashedVideoID | hashedVideoID, service |
| ratings_videoID | videoID, service |
### userFeatures
| Name | Type | |
| -- | :--: | -- |
| userID | TEXT | not null |
| feature | INTEGER | not null |
| issuerUserID | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| constraint | field |
| -- | :--: |
| primary key | userID, feature |
| index | field |
| -- | :--: |
| userFeatures_userID | userID, feature |
### shadowBannedIPs
| Name | Type | |
| -- | :--: | -- |
| hashedIP | TEXT | not null, primary key |
### titles
| Name | Type | |
| -- | :--: | -- |
| videoID | TEXT | not null |
| title | TEXT | not null |
| original | INTEGER | default 0 |
| userID | TEXT | not null
| service | TEXT | not null |
| hashedVideoID | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| UUID | TEXT | not null, primary key
| index | field |
| -- | :--: |
| titles_timeSubmitted | timeSubmitted |
| titles_userID_timeSubmitted | videoID, service, userID, timeSubmitted |
| titles_videoID | videoID, service |
| titles_hashedVideoID_2 | service, hashedVideoID, timeSubmitted |
### titleVotes
| Name | Type | |
| -- | :--: | -- |
| UUID | TEXT | not null, primary key |
| votes | INTEGER | not null, default 0 |
| locked | INTEGER | not null, default 0 |
| shadowHidden | INTEGER | not null, default 0 |
| verification | INTEGER | default 0 |
| downvotes | INTEGER | default 0 |
| removed | INTEGER | default 0 |
| constraint | field |
| -- | :--: |
| foreign key | UUID references "titles"("UUID")
| index | field |
| -- | :--: |
| titleVotes_votes | UUID, votes
### thumbnails
| Name | Type | |
| -- | :--: | -- |
| original | INTEGER | default 0 |
| userID | TEXT | not null |
| service | TEXT | not null |
| hashedVideoID | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| UUID | TEXT | not null, primary key |
| index | field |
| -- | :--: |
| thumbnails_timeSubmitted | timeSubmitted |
| thumbnails_votes_timeSubmitted | videoID, service, userID, timeSubmitted |
| thumbnails_videoID | videoID, service |
| thumbnails_hashedVideoID_2 | service, hashedVideoID, timeSubmitted |
### thumbnailTimestamps
| index | field |
| -- | :--: |
| UUID | TEXT | not null, primary key
| timestamp | INTEGER | not null, default 0
| constraint | field |
| -- | :--: |
| foreign key | UUID references "thumbnails"("UUID")
### thumbnailVotes
| Name | Type | |
| -- | :--: | -- |
| UUID | TEXT | not null, primary key |
| votes | INTEGER | not null, default 0 |
| locked | INTEGER |not null, default 0 |
| shadowHidden | INTEGER | not null, default 0 |
| downvotes | INTEGER | default 0 |
| removed | INTEGER | default 0 |
| constraint | field |
| -- | :--: |
| foreign key | UUID references "thumbnails"("UUID")
| index | field |
| -- | :--: |
| thumbnailVotes_votes | UUID, votes
# Private
- [votes](#votes)
- [categoryVotes](#categoryVotes)
- [sponsorTimes](#sponsorTimes)
- [config](#config)
- [ratings](#ratings)
- [tempVipLog](#tempVipLog)
- [userNameLogs](#userNameLogs)
[votes](#votes)
[categoryVotes](#categoryVotes)
[sponsorTimes](#sponsorTimes)
[config](#config)
[ratings](#ratings)
[tempVipLog](#tempVipLog)
[userNameLogs](#userNameLogs)
### votes
@@ -339,8 +209,6 @@
| userID | TEXT | not null |
| hashedIP | TEXT | not null |
| type | INTEGER | not null |
| originalVoteType | INTEGER | not null | # Since type was reused to also specify the number of votes removed when less than 0, this is being used for the actual type
| id | SERIAL | primary key |
| index | field |
| -- | :--: |
@@ -355,11 +223,10 @@
| hashedIP | TEXT | not null |
| category | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| id | SERIAL | primary key |
| index | field |
| -- | :--: |
| categoryVotes_UUID | UUID, userID, hashedIP, category |
| categoryVotes_UUID | UUID, userID, hasedIP, category |
### sponsorTimes
@@ -369,17 +236,17 @@
| hashedIP | TEXT | not null |
| timeSubmitted | INTEGER | not null |
| service | TEXT | not null, default 'YouTube' |
| id | SERIAL | primary key |
| index | field |
| -- | :--: |
| privateDB_sponsorTimes_v4 | videoID, service, timeSubmitted |
| sponsorTimes_hashedIP | hashedIP |
| privateDB_sponsorTimes_videoID_v2 | videoID, service |
### config
| Name | Type | |
| -- | :--: | -- |
| key | TEXT | not null, primary key |
| key | TEXT | not null |
| value | TEXT | not null |
### ratings
@@ -392,7 +259,6 @@
| type | INTEGER | not null |
| timeSubmitted | INTEGER | not null |
| hashedIP | TEXT | not null |
| id | SERIAL | primary key |
| index | field |
| -- | :--: |
@@ -405,7 +271,6 @@
| targetUserID | TEXT | not null |
| enabled | BOOLEAN | not null |
| updatedAt | INTEGER | not null |
| id | SERIAL | primary key |
### userNameLogs
@@ -416,4 +281,3 @@
| oldUserName | TEXT | not null |
| updatedByAdmin | BOOLEAN | not null |
| updatedAt | INTEGER | not null |
| id | SERIAL | primary key |

View File

@@ -1,16 +1,16 @@
FROM node:18-alpine as builder
FROM node:16-alpine as builder
RUN apk add --no-cache --virtual .build-deps python3 make g++
COPY package.json package-lock.json tsconfig.json entrypoint.sh ./
COPY src src
RUN npm ci && npm run tsc
FROM node:18-alpine as app
FROM node:16-alpine as app
WORKDIR /usr/src/app
RUN apk add --no-cache git postgresql-client
RUN apk add git postgresql-client
COPY --from=builder ./node_modules ./node_modules
COPY --from=builder ./dist ./dist
COPY ./.git/ ./.git
COPY ./.git ./.git
COPY entrypoint.sh .
COPY databases/*.sql databases/
EXPOSE 8080
CMD ./entrypoint.sh
CMD ./entrypoint.sh

682
LICENSE
View File

@@ -1,661 +1,21 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
MIT License
Copyright (c) 2019 Ajay Ramachandran
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,27 +0,0 @@
License for code prior to commit d738e89f203e9cea21b7df4acb9f4b3505f0acdd
You must follow LICENSE instead if you want to use any newer version.
----
MIT License
Copyright (c) 2019 Ajay Ramachandran
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -35,7 +35,3 @@ If you want to make changes, run `npm run dev` to automatically reload the serve
# API Docs
Available [here](https://wiki.sponsor.ajay.app/index.php/API_Docs)
# License
This is licensed under AGPL-3.0-only.

24
ci.json
View File

@@ -4,12 +4,11 @@
"globalSalt": "testSalt",
"adminUserID": "4bdfdc9cddf2c7d07a8a87b57bf6d25389fb75d1399674ee0e0938a6a60f4c3b",
"newLeafURLs": ["placeholder"],
"discordReportChannelWebhookURL": "http://127.0.0.1:8081/webhook/ReportChannel",
"discordFirstTimeSubmissionsWebhookURL": "http://127.0.0.1:8081/webhook/FirstTimeSubmissions",
"discordCompletelyIncorrectReportWebhookURL": "http://127.0.0.1:8081/webhook/CompletelyIncorrectReport",
"discordNeuralBlockRejectWebhookURL": "http://127.0.0.1:8081/webhook/NeuralBlockReject",
"discordReportChannelWebhookURL": "http://127.0.0.1:8081/ReportChannelWebhook",
"discordFirstTimeSubmissionsWebhookURL": "http://127.0.0.1:8081/FirstTimeSubmissionsWebhook",
"discordCompletelyIncorrectReportWebhookURL": "http://127.0.0.1:8081/CompletelyIncorrectReportWebhook",
"discordNeuralBlockRejectWebhookURL": "http://127.0.0.1:8081/NeuralBlockRejectWebhook",
"neuralBlockURL": "http://127.0.0.1:8081/NeuralBlock",
"userCounterURL": "http://127.0.0.1:8081/UserCounter",
"behindProxy": true,
"postgres": {
"user": "ci_db_user",
@@ -18,12 +17,10 @@
"port": 5432
},
"redis": {
"enabled": true,
"socket": {
"host": "localhost",
"port": 6379
},
"expiryTime": 86400
}
},
"createDatabaseIfNotExist": true,
"schemaFolder": "./databases",
@@ -56,6 +53,8 @@
]
}
],
"maxNumberOfActiveWarnings": 3,
"hoursAfterWarningExpires": 24,
"rateLimit": {
"vote": {
"windowMs": 900000,
@@ -68,12 +67,5 @@
"max": 20,
"statusCode": 200
}
},
"patreon": {
"clientId": "testClientID",
"clientSecret": "testClientSecret",
"redirectUri": "http://127.0.0.1/fake/callback"
},
"minReputationToSubmitFiller": -1,
"minUserIDLength": 0
}
}

View File

@@ -1,9 +0,0 @@
comment: false
coverage:
status:
project:
default:
informational: true
patch:
default:
informational: true

View File

@@ -25,6 +25,8 @@
"webhooks": [],
"categoryList": ["sponsor", "intro", "outro", "interaction", "selfpromo", "preview", "music_offtopic", "poi_highlight"], // List of supported categories any other category will be rejected
"getTopUsersCacheTimeMinutes": 5, // cacheTime for getTopUsers result in minutes
"maxNumberOfActiveWarnings": 3, // Users with this number of warnings will be blocked until warnings expire
"hoursAfterWarningExpire": 24,
"rateLimit": {
"vote": {
"windowMs": 900000, // 15 minutes
@@ -64,6 +66,5 @@
{
"name": "vipUsers"
}]
},
"minUserIDLength": 30 // minimum length of UserID to be accepted
}
}

View File

@@ -1,13 +1,13 @@
FROM alpine as builder
WORKDIR /scripts
COPY ./backup.sh ./backup.sh
COPY ./forget.sh ./forget.sh
FROM alpine
RUN apk add --no-cache postgresql-client restic
COPY --from=builder --chmod=755 /scripts /usr/src/app/
RUN apk add postgresql-client
RUN apk add restic --repository http://dl-cdn.alpinelinux.org/alpine/latest-stable/community/
COPY ./backup.sh /usr/src/app/backup.sh
RUN chmod +x /usr/src/app/backup.sh
COPY ./backup.sh /usr/src/app/forget.sh
RUN chmod +x /usr/src/app/forget.sh
RUN echo '30 * * * * /usr/src/app/backup.sh' >> /etc/crontabs/root
RUN echo '10 0 * * */2 /usr/src/app/forget.sh' >> /etc/crontabs/root
RUN echo '10 0 * * 1 /usr/src/app/forget.sh' >> /etc/crontabs/root
CMD crond -l 2 -f
CMD crond -l 2 -f

View File

@@ -1 +1 @@
restic forget --prune --keep-hourly 24 --keep-daily 7 --keep-weekly 8
restic forget --prune --keep-last 48 --keep-daily 7 --keep-weekly 8

View File

@@ -1,4 +0,0 @@
FROM nginx as app
EXPOSE 80
COPY nginx.conf /etc/nginx/nginx.conf
COPY default.conf /etc/nginx/conf.d/default.conf

View File

@@ -1,9 +0,0 @@
server {
listen 80;
listen [::]:80;
server_name localhost;
location / {
return 503;
}
}

View File

@@ -1,19 +0,0 @@
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 4096;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log off;
error_log /dev/null crit;
include /etc/nginx/conf.d/*.conf;
}

View File

@@ -1,6 +1,6 @@
FROM ghcr.io/ajayyy/sb-server:latest
EXPOSE 873/tcp
RUN apk add rsync>3.4.1-r0
RUN apk add rsync>3.2.4-r0
RUN mkdir /usr/src/app/database-export
CMD rsync --no-detach --daemon & ./entrypoint.sh
CMD rsync --no-detach --daemon & ./entrypoint.sh

View File

@@ -26,33 +26,4 @@ CREATE TABLE IF NOT EXISTS "config" (
"value" TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS "titleVotes" (
"id" SERIAL PRIMARY KEY,
"videoID" TEXT NOT NULL,
"UUID" TEXT NOT NULL,
"userID" TEXT NOT NULL,
"hashedIP" TEXT NOT NULL,
"type" INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS "thumbnailVotes" (
"id" SERIAL PRIMARY KEY,
"videoID" TEXT NOT NULL,
"UUID" TEXT NOT NULL,
"userID" TEXT NOT NULL,
"hashedIP" TEXT NOT NULL,
"type" INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS "casualVotes" (
"UUID" SERIAL PRIMARY KEY,
"videoID" TEXT NOT NULL,
"service" TEXT NOT NULL,
"userID" TEXT NOT NULL,
"hashedIP" TEXT NOT NULL,
"category" TEXT NOT NULL,
"type" INTEGER NOT NULL,
"timeSubmitted" INTEGER NOT NULL
);
COMMIT;

View File

@@ -23,16 +23,4 @@ CREATE INDEX IF NOT EXISTS "categoryVotes_UUID"
CREATE INDEX IF NOT EXISTS "ratings_videoID"
ON public."ratings" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, service COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
-- casualVotes
CREATE INDEX IF NOT EXISTS "casualVotes_videoID"
ON public."casualVotes" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "casualVotes_userID"
ON public."casualVotes" USING btree
("userID" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;

View File

@@ -32,78 +32,11 @@ CREATE TABLE IF NOT EXISTS "categoryVotes" (
"votes" INTEGER NOT NULL default 0
);
CREATE TABLE IF NOT EXISTS "shadowBannedIPs" (
"hashedIP" TEXT NOT NULL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS "config" (
"key" TEXT NOT NULL UNIQUE,
"value" TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS "titles" (
"videoID" TEXT NOT NULL,
"title" TEXT NOT NULL,
"original" INTEGER default 0,
"userID" TEXT NOT NULL,
"service" TEXT NOT NULL,
"hashedVideoID" TEXT NOT NULL,
"timeSubmitted" INTEGER NOT NULL,
"UUID" TEXT NOT NULL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS "titleVotes" (
"UUID" TEXT NOT NULL PRIMARY KEY,
"votes" INTEGER NOT NULL default 0,
"locked" INTEGER NOT NULL default 0,
"shadowHidden" INTEGER NOT NULL default 0,
FOREIGN KEY("UUID") REFERENCES "titles"("UUID")
);
CREATE TABLE IF NOT EXISTS "thumbnails" (
"videoID" TEXT NOT NULL,
"original" INTEGER default 0,
"userID" TEXT NOT NULL,
"service" TEXT NOT NULL,
"hashedVideoID" TEXT NOT NULL,
"timeSubmitted" INTEGER NOT NULL,
"UUID" TEXT NOT NULL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS "thumbnailTimestamps" (
"UUID" TEXT NOT NULL PRIMARY KEY,
"timestamp" INTEGER NOT NULL default 0,
FOREIGN KEY("UUID") REFERENCES "thumbnails"("UUID")
);
CREATE TABLE IF NOT EXISTS "thumbnailVotes" (
"UUID" TEXT NOT NULL PRIMARY KEY,
"votes" INTEGER NOT NULL default 0,
"locked" INTEGER NOT NULL default 0,
"shadowHidden" INTEGER NOT NULL default 0,
FOREIGN KEY("UUID") REFERENCES "thumbnails"("UUID")
);
CREATE TABLE IF NOT EXISTS "casualVotes" (
"UUID" TEXT PRIMARY KEY,
"videoID" TEXT NOT NULL,
"service" TEXT NOT NULL,
"hashedVideoID" TEXT NOT NULL,
"category" TEXT NOT NULL,
"upvotes" INTEGER NOT NULL default 0,
"downvotes" INTEGER NOT NULL default 0,
"timeSubmitted" INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS "casualVoteTitles" (
"videoID" TEXT NOT NULL,
"service" TEXT NOT NULL,
"id" INTEGER NOT NULL,
"hashedVideoID" TEXT NOT NULL,
"title" TEXT NOT NULL,
PRIMARY KEY("videoID", "service", "id")
);
CREATE EXTENSION IF NOT EXISTS pgcrypto; --!sqlite-ignore
CREATE EXTENSION IF NOT EXISTS pg_trgm; --!sqlite-ignore

View File

@@ -25,11 +25,6 @@ CREATE INDEX IF NOT EXISTS "sponsorTimes_videoID"
(service COLLATE pg_catalog."default" ASC NULLS LAST, "videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "startTime" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "sponsorTimes_videoID_category"
ON public."sponsorTimes" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "category" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "sponsorTimes_description_gin"
ON public."sponsorTimes" USING gin
("description" COLLATE pg_catalog."default" gin_trgm_ops, category COLLATE pg_catalog."default" gin_trgm_ops)
@@ -108,91 +103,4 @@ CREATE INDEX IF NOT EXISTS "ratings_hashedVideoID"
CREATE INDEX IF NOT EXISTS "ratings_videoID"
ON public."ratings" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, service COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
--- userFeatures
CREATE INDEX IF NOT EXISTS "userFeatures_userID"
ON public."userFeatures" USING btree
("userID" COLLATE pg_catalog."default" ASC NULLS LAST, "feature" ASC NULLS LAST)
TABLESPACE pg_default;
-- titles
CREATE INDEX IF NOT EXISTS "titles_timeSubmitted"
ON public."titles" USING btree
("timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "titles_userID_timeSubmitted"
ON public."titles" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" DESC NULLS LAST, "timeSubmitted" DESC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "titles_videoID"
ON public."titles" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "titles_hashedVideoID_2"
ON public."titles" USING btree
(service COLLATE pg_catalog."default" ASC NULLS LAST, "hashedVideoID" text_pattern_ops ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
-- titleVotes
CREATE INDEX IF NOT EXISTS "titleVotes_votes"
ON public."titleVotes" USING btree
("UUID" COLLATE pg_catalog."default" ASC NULLS LAST, "votes" DESC NULLS LAST)
TABLESPACE pg_default;
-- thumbnails
CREATE INDEX IF NOT EXISTS "thumbnails_timeSubmitted"
ON public."thumbnails" USING btree
("timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "thumbnails_votes_timeSubmitted"
ON public."thumbnails" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "userID" COLLATE pg_catalog."default" DESC NULLS LAST, "timeSubmitted" DESC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "thumbnails_videoID"
ON public."thumbnails" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "thumbnails_hashedVideoID_2"
ON public."thumbnails" USING btree
(service COLLATE pg_catalog."default" ASC NULLS LAST, "hashedVideoID" text_pattern_ops ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
-- thumbnailVotes
CREATE INDEX IF NOT EXISTS "thumbnailVotes_votes"
ON public."thumbnailVotes" USING btree
("UUID" COLLATE pg_catalog."default" ASC NULLS LAST, "votes" DESC NULLS LAST)
TABLESPACE pg_default;
-- casualVotes
CREATE INDEX IF NOT EXISTS "casualVotes_timeSubmitted"
ON public."casualVotes" USING btree
("timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "casualVotes_userID_timeSubmitted"
ON public."casualVotes" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST, "timeSubmitted" DESC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "casualVotes_videoID"
ON public."casualVotes" USING btree
("videoID" COLLATE pg_catalog."default" ASC NULLS LAST, "service" COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX IF NOT EXISTS "casualVotes_hashedVideoID_2"
ON public."casualVotes" USING btree
(service COLLATE pg_catalog."default" ASC NULLS LAST, "hashedVideoID" text_pattern_ops ASC NULLS LAST, "timeSubmitted" ASC NULLS LAST)
TABLESPACE pg_default;

View File

@@ -1,9 +0,0 @@
BEGIN TRANSACTION;
-- Add primary keys
ALTER TABLE "votes" ADD "originalType" INTEGER NOT NULL default -1;
UPDATE "config" SET value = 10 WHERE key = 'version';
COMMIT;

View File

@@ -1,18 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "licenseKeys" (
"licenseKey" TEXT NOT NULL PRIMARY KEY,
"time" INTEGER NOT NULL,
"type" TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS "oauthLicenseKeys" (
"licenseKey" TEXT NOT NULL PRIMARY KEY,
"accessToken" TEXT NOT NULL,
"refreshToken" TEXT NOT NULL,
"expiresIn" INTEGER NOT NULL
);
UPDATE "config" SET value = 11 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "casualVotes" DROP COLUMN "type";
UPDATE "config" SET value = 12 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "casualVotes" ADD "titleID" INTEGER default 0;
UPDATE "config" SET value = 13 WHERE key = 'version';
COMMIT;

View File

@@ -1,13 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "userFeatures" (
"userID" TEXT NOT NULL,
"feature" INTEGER NOT NULL,
"issuerUserID" TEXT NOT NULL,
"timeSubmitted" INTEGER NOT NULL,
PRIMARY KEY ("userID", "feature")
);
UPDATE "config" SET value = 33 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "videoInfo" DROP COLUMN "genreUrl";
UPDATE "config" SET value = 34 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "titleVotes" ADD "verification" INTEGER default 0;
UPDATE "config" SET value = 35 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "warnings" ADD "type" INTEGER default 0;
UPDATE "config" SET value = 36 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "titles" ADD UNIQUE ("videoID", "title"); --!sqlite-ignore
UPDATE "config" SET value = 37 WHERE key = 'version';
COMMIT;

View File

@@ -1,11 +0,0 @@
BEGIN TRANSACTION;
UPDATE "titleVotes" SET "shadowHidden" = 1
WHERE "UUID" IN (SELECT "UUID" FROM "titles" INNER JOIN "shadowBannedUsers" "bans" ON "titles"."userID" = "bans"."userID");
UPDATE "thumbnailVotes" SET "shadowHidden" = 1
WHERE "UUID" IN (SELECT "UUID" FROM "thumbnails" INNER JOIN "shadowBannedUsers" "bans" ON "thumbnails"."userID" = "bans"."userID");
UPDATE "config" SET value = 38 WHERE key = 'version';
COMMIT;

View File

@@ -1,11 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "titleVotes" ADD "downvotes" INTEGER default 0;
ALTER TABLE "titleVotes" ADD "removed" INTEGER default 0;
ALTER TABLE "thumbnailVotes" ADD "downvotes" INTEGER default 0;
ALTER TABLE "thumbnailVotes" ADD "removed" INTEGER default 0;
UPDATE "config" SET value = 39 WHERE key = 'version';
COMMIT;

View File

@@ -1,8 +0,0 @@
BEGIN TRANSACTION;
DROP INDEX IF EXISTS "titles_hashedVideoID";
DROP INDEX IF EXISTS "thumbnails_hashedVideoID";
UPDATE "config" SET value = 40 WHERE key = 'version';
COMMIT;

View File

@@ -1,8 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "titles" ADD "casualMode" INTEGER default 0;
ALTER TABLE "thumbnails" ADD "casualMode" INTEGER default 0;
UPDATE "config" SET value = 41 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "casualVotes" DROP COLUMN "downvotes";
UPDATE "config" SET value = 42 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "casualVotes" ADD "titleID" INTEGER default 0;
UPDATE "config" SET value = 43 WHERE key = 'version';
COMMIT;

View File

@@ -1,8 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "titles" ADD "userAgent" TEXT NOT NULL default '';
ALTER TABLE "thumbnails" ADD "userAgent" TEXT NOT NULL default '';
UPDATE "config" SET value = 44 WHERE key = 'version';
COMMIT;

View File

@@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE "warnings" ADD "disableTime" INTEGER NULL;
UPDATE "config" SET value = 45 WHERE key = 'version';
COMMIT;

View File

@@ -1,6 +1,6 @@
BEGIN TRANSACTION;
/* Add 'locked' field */
/* Add new voting field */
CREATE TABLE "sqlb_temp_table_6" (
"videoID" TEXT NOT NULL,
"startTime" REAL NOT NULL,

View File

@@ -1,6 +1,6 @@
BEGIN TRANSACTION;
/* Add 'videoDuration' field */
/* Add Service field */
CREATE TABLE "sqlb_temp_table_8" (
"videoID" TEXT NOT NULL,
"startTime" REAL NOT NULL,

View File

@@ -1,6 +1,6 @@
BEGIN TRANSACTION;
/* Change 'videoDuration' field from INTEGER to REAL */
/* Add Service field */
CREATE TABLE "sqlb_temp_table_9" (
"videoID" TEXT NOT NULL,
"startTime" REAL NOT NULL,

View File

@@ -1,7 +1,6 @@
version: '3'
services:
postgres:
container_name: database-co
image: postgres:alpine
environment:
- POSTGRES_USER=${PG_USER}
@@ -9,7 +8,6 @@ services:
ports:
- 5432:5432
redis:
container_name: redis-ci
image: redis:alpine
ports:
- 6379:6379

View File

@@ -2,7 +2,7 @@ version: '3'
services:
database:
container_name: database
image: postgres:14
image: postgres:13
env_file:
- database.env
volumes:
@@ -12,15 +12,12 @@ services:
restart: always
redis:
container_name: redis
image: redis:7.0
image: redis:6.0
command: /usr/local/etc/redis/redis.conf
volumes:
- ./redis/redis.conf:/usr/local/etc/redis/redis.conf
ports:
- 32773:6379
sysctls:
- net.core.somaxconn=324000
- net.ipv4.tcp_max_syn_backlog=3240000
restart: always
newleaf:
image: abeltramo/newleaf:latest

View File

@@ -1,5 +1,4 @@
maxmemory-policy allkeys-lru
maxmemory 6000mb
maxmemory 6500mb
appendonly no
save ""

View File

@@ -4,9 +4,9 @@ echo 'Entrypoint script'
cd /usr/src/app
# blank config, use defaults
test -e config.json || cat <<EOF > config.json
cat <<EOF > config.json
{
}
EOF
node dist/src/index.js
node dist/src/index.js

11
nginx/cors.conf Normal file
View File

@@ -0,0 +1,11 @@
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type';
# cache CORS for 24 hours
add_header 'Access-Control-Max-Age' 86400;
# return empty response for preflight
add_header 'Content-Type' 'text/plain; charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}

7
nginx/error.conf Normal file
View File

@@ -0,0 +1,7 @@
error_page 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 421 422 423 424 425 426 428 429 431 451 500 501 502 503 504 505 506 507 508 510 511 /error.html;
location = /error.html {
ssi on;
internal;
root /etc/nginx/error;
}

1
nginx/error/error.html Normal file
View File

@@ -0,0 +1 @@
<!--# echo var="status"--> <!--# echo var="status_text"--> https://status.sponsor.ajay.app

15
nginx/error_map.conf Normal file
View File

@@ -0,0 +1,15 @@
map $status $status_text {
400 'Bad Request';
401 'Unauthorized';
403 'Forbidden';
404 'Not Found';
405 'Method Not Allowed';
408 'Request Timeout';
409 'Conflict';
429 'Too Many Requests';
500 'Internal Server Error';
502 'Bad Gateway';
503 'Service Unavailable';
504 'Gateway Timeout';
505 'HTTP Version Not Supported';
}

317
nginx/nginx.conf Normal file
View File

@@ -0,0 +1,317 @@
worker_processes 2;
worker_rlimit_nofile 500000;
worker_shutdown_timeout 10;
events {
worker_connections 100000; # Default: 1024
#use epoll;
#multi_accept on;
}
http {
log_format no_ip '$remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
log_format user_agent '[$time_local] '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
#limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
limit_req_log_level warn;
include /etc/nginx/mime.types;
include /etc/nginx/proxy.conf;
# error_map has to be at http level
include /etc/nginx/error_map.conf;
# Custom MIME definition
types {
text/csv csv;
}
# keepalive settings
#keepalive_requests 10;
keepalive_timeout 10s;
http2_idle_timeout 20s; # replaced by keepalive_timeout in 1.19.7
access_log off;
#error_log /etc/nginx/logs/error.log warn;
error_log /dev/null crit;
upstream backend_GET {
least_conn;
#keepalive 5;
#server localhost:4441;
#server localhost:4442;
#server localhost:4443;
#server localhost:4444;
#server localhost:4445;
#server localhost:4446;
#server localhost:4447;
#server localhost:4448;
#server 10.0.0.4:4441 max_fails=25 fail_timeout=20s;
#server 10.0.0.3:4441 max_fails=25 fail_timeout=20s;
#server 10.0.0.3:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.5:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.5:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.6:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.6:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.9:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.9:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.12:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.12:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.10:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.10:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.13:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.13:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.14:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.14:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.11:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.11:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.16:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.16:4442 max_fails=25 fail_timeout=20s;
server 10.0.0.17:4441 max_fails=25 fail_timeout=20s;
server 10.0.0.17:4442 max_fails=25 fail_timeout=20s;
#server 134.209.69.251:80 backup;
#server 116.203.32.253:80 backup;
#server 116.203.32.253:80;
}
upstream backend_POST {
#server localhost:4441;
#server localhost:4442;
server 10.0.0.3:4441 max_fails=25 fail_timeout=15s;
server 10.0.0.4:4441 max_fails=25 fail_timeout=15s;
#server 10.0.0.3:4442;
}
upstream backend_db {
server 10.0.0.4:4441 max_fails=1 fail_timeout=3s;
#server 10.0.0.3:4441;
#server 10.0.0.4;
}
upstream backend_db_dl {
server 10.0.0.4;
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=CACHEZONE:10m inactive=60m max_size=400m;
proxy_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache $upstream_cache_status;
server {
server_name sponsor.ajay.app api.sponsor.ajay.app;
include /etc/nginx/error.conf;
set_real_ip_from 10.0.0.0/24;
real_ip_header proxy_protocol;
location /news {
return 301 https://blog.ajay.app/sponsorblock;
}
location /viewer {
return 301 https://sb.ltn.fi;
}
location /test/ {
# return 404 "";
proxy_pass http://10.0.0.4:4445/;
#proxy_pass https://sbtest.etcinit.com/;
}
#access_log /etc/nginx/logs/requests.log no_ip buffer=64k;
location /api/skipSegments {
include /etc/nginx/cors.conf;
#return 200 "[]";
proxy_pass http://backend_$request_method;
#proxy_cache CACHEZONE;
#proxy_cache_valid 10s;
#limit_req zone=mylimit;
#access_log /etc/nginx/logs/download.log no_ip;
gzip on;
if ($request_method = POST) {
access_log /etc/nginx/logs/submissions.log user_agent buffer=64k;
}
#proxy_read_timeout 6s;
#proxy_next_upstream error timeout http_500 http_502;
}
location /api/getTopUsers {
include /etc/nginx/cors.conf;
proxy_pass http://backend_GET;
proxy_cache CACHEZONE;
proxy_cache_valid 20m;
}
location /api/getTotalStats {
include /etc/nginx/cors.conf;
proxy_pass http://backend_POST;
proxy_cache CACHEZONE;
proxy_cache_valid 20m;
#return 204;
}
location /api/getTopCategoryUsers {
include /etc/nginx/cors.conf;
proxy_pass http://backend_POST;
proxy_cache CACHEZONE;
proxy_cache_valid 20m;
}
location /api/getVideoSponsorTimes {
include /etc/nginx/cors.conf;
proxy_pass http://backend_GET;
}
location /api/isUserVIP {
include /etc/nginx/cors.conf;
proxy_pass http://backend_GET;
}
location /download/ {
#access_log /etc/nginx/logs/download.log no_ip buffer=64k;
gzip on;
proxy_max_temp_file_size 0;
#proxy_cache CACHEZONE;
#proxy_cache_valid 20m;
#proxy_http_version 1.0;
#gzip_types text/csv;
#gzip_comp_level 1;
#proxy_buffering off;
proxy_pass http://backend_db;
#alias /home/sbadmin/sponsor/docker/database-export/;
#return 307 https://rsync.sponsor.ajay.app$request_uri;
}
location /database {
proxy_pass http://backend_db;
#return 200 "Disabled for load reasons";
}
location = /database.db {
return 404 "Sqlite database has been replaced with csv exports at https://sponsor.ajay.app/database. Sqlite exports might come back soon, but exported at longer intervals.";
#alias /home/sbadmin/sponsor/databases/sponsorTimes.db;
#alias /home/sbadmin/test-db/database.db;
}
#location = /database/sponsorTimes.csv {
# alias /home/sbadmin/sponsorTimes.csv;
#}
#location /api/voteOnSponsorTime {
# return 200 "Success";
#}
#location /api/viewedVideoSponsorTime {
# return 200 "Success";
#}
location /api {
include /etc/nginx/cors.conf;
proxy_pass http://backend_POST;
}
location / {
root /home/sbadmin/SponsorBlockSite/public-prod;
error_page 404 /404.html;
}
listen [::]:443 default_server ssl http2 ipv6only=on backlog=323999;
listen 443 default_server ssl http2 reuseport backlog=3000999; # managed by Certbot
listen 4443 default_server ssl http2 proxy_protocol reuseport backlog=3000999;
#listen 443 http3 reuseport;
#ssl_protocols TLSv1.2 TLSv1.3;
listen 8081 proxy_protocol;
port_in_redirect off;
ssl_certificate /home/sbadmin/certs/cert.pem;
ssl_certificate_key /home/sbadmin/certs/key.pem;
#ssl_certificate /etc/letsencrypt/live/sponsor.ajay.app-0001/fullchain.pem; # managed by Certbot
#ssl_certificate_key /etc/letsencrypt/live/sponsor.ajay.app-0001/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
server_name cdnsponsor.ajay.app;
error_page 404 /404.html;
#location /database/ {
# alias /home/sbadmin/sponsor/docker/database-export/;
#}
#location /download/ {
# alias /home/sbadmin/sponsor/docker/database-export/;
#}
location / {
root /home/sbadmin/SponsorBlockSite/public-prod;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /home/sbadmin/certs/cert.pem;
ssl_certificate_key /home/sbadmin/certs/key.pem;
#ssl_certificate /etc/letsencrypt/live/sponsor.ajay.app-0001/fullchain.pem; # managed by Certbot
#ssl_certificate_key /etc/letsencrypt/live/sponsor.ajay.app-0001/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
access_log off;
return 301 https://$host$request_uri;
listen [::]:80 ipv6only=on;
listen 8080 proxy_protocol;
listen 80;
server_name sponsor.ajay.app api.sponsor.ajay.app, cdnsponsor.ajay.app, wiki.sponsor.ajay.app;
return 404; # managed by Certbot
}
server {
server_name wiki.sponsor.ajay.app; # managed by Certbot
location /.well-known/ {
root /home/sbadmin/SponsorBlockSite/public-prod;
}
location ~* ^/index.php/(?<pagename>.*)$ {
return 301 /w/$pagename;
}
location / {
proxy_pass http://10.0.0.3:8080;
}
port_in_redirect off;
listen [::]:443 ssl http2;
listen 443 ssl http2; # managed by Certbot
listen 8081 proxy_protocol;
#listen 443 http3 reuseport;
#ssl_protocols TLSv1.2 TLSv1.3;
#listen 80;
ssl_certificate /home/sbadmin/certs/cert.pem;
ssl_certificate_key /home/sbadmin/certs/key.pem;
#ssl_certificate /etc/letsencrypt/live/sponsor.ajay.app-0001/fullchain.pem; # managed by Certbot
#ssl_certificate_key /etc/letsencrypt/live/sponsor.ajay.app-0001/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
}

12
nginx/proxy.conf Normal file
View File

@@ -0,0 +1,12 @@
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 5s;
#proxy_send_timeout 10;
proxy_read_timeout 30s;
proxy_buffers 32 4k;
proxy_http_version 1.1;

8249
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,59 +5,49 @@
"main": "src/index.ts",
"scripts": {
"test": "npm run tsc && ts-node test/test.ts",
"cover": "nyc npm test",
"cover:report": "nyc report",
"dev": "nodemon",
"dev:bash": "nodemon -x 'npm test ; npm start'",
"postgres:docker": "docker run --init -it --rm -p 5432:5432 -e POSTGRES_USER=ci_db_user -e POSTGRES_PASSWORD=ci_db_pass postgres:14-alpine",
"redis:docker": "docker run --init -it --rm -p 6379:6379 redis:7-alpine --save '' --appendonly no",
"postgres:docker": "docker run --rm -p 5432:5432 -e POSTGRES_USER=ci_db_user -e POSTGRES_PASSWORD=ci_db_pass postgres:alpine",
"redis:docker": "docker run --rm -p 6379:6379 redis:alpine",
"start": "ts-node src/index.ts",
"tsc": "tsc -p tsconfig.json",
"lint": "eslint src test",
"lint:fix": "eslint src test --fix"
},
"author": "Ajay Ramachandran",
"license": "AGPL-3.0-only",
"license": "MIT",
"dependencies": {
"axios": "^1.12.1",
"better-sqlite3": "^11.2.1",
"cron": "^2.1.0",
"express": "^4.21.2",
"axios": "^0.24.0",
"better-sqlite3": "^7.4.5",
"cron": "^1.8.2",
"express": "^4.17.1",
"express-promise-router": "^4.1.1",
"express-rate-limit": "^6.7.0",
"form-data": "^4.0.4",
"express-rate-limit": "^6.3.0",
"lodash": "^4.17.21",
"lru-cache": "^10.2.0",
"lz4-napi": "^2.2.0",
"pg": "^8.8.0",
"pg": "^8.7.1",
"rate-limit-redis": "^3.0.1",
"redis": "^4.6.13",
"seedrandom": "^3.0.5"
"redis": "^4.0.6",
"sync-mysql": "^3.0.1"
},
"devDependencies": {
"@istanbuljs/nyc-config-typescript": "^1.0.2",
"@types/better-sqlite3": "^7.6.2",
"@types/cron": "^2.0.0",
"@types/express": "^4.17.14",
"@types/lodash": "^4.14.189",
"@types/mocha": "^10.0.0",
"@types/node": "^18.11.9",
"@types/pg": "^8.6.5",
"@types/seedrandom": "^3.0.5",
"@types/sinon": "^10.0.13",
"@typescript-eslint/eslint-plugin": "^5.44.0",
"@typescript-eslint/parser": "^5.44.0",
"axios-mock-adapter": "^1.21.2",
"eslint": "^8.28.0",
"mocha": "^10.8.2",
"nodemon": "^3.1.9",
"nyc": "^15.1.0",
"sinon": "^14.0.2",
"@types/better-sqlite3": "^7.4.1",
"@types/cron": "^1.7.3",
"@types/express": "^4.17.13",
"@types/lodash": "^4.14.178",
"@types/mocha": "^9.0.0",
"@types/node": "^16.11.11",
"@types/pg": "^8.6.1",
"@typescript-eslint/eslint-plugin": "^5.5.0",
"@typescript-eslint/parser": "^5.5.0",
"eslint": "^8.3.0",
"mocha": "^9.1.3",
"nodemon": "^2.0.15",
"sinon": "^12.0.1",
"ts-mock-imports": "^1.3.8",
"ts-node": "^10.9.1",
"typescript": "^4.9.3"
"ts-node": "^10.4.0",
"typescript": "^4.5.2"
},
"engines": {
"node": ">=18"
"node": ">=10"
}
}

View File

@@ -1,6 +1,7 @@
import express, { Request, RequestHandler, Response, Router } from "express";
import { config } from "./config";
import { oldSubmitSponsorTimes } from "./routes/oldSubmitSponsorTimes";
import { oldGetVideoSponsorTimes } from "./routes/oldGetVideoSponsorTimes";
import { postSegmentShift } from "./routes/postSegmentShift";
import { postWarning } from "./routes/postWarning";
import { getIsUserVIP } from "./routes/getIsUserVIP";
@@ -20,13 +21,13 @@ import { viewedVideoSponsorTime } from "./routes/viewedVideoSponsorTime";
import { voteOnSponsorTime, getUserID as voteGetUserID } from "./routes/voteOnSponsorTime";
import { getSkipSegmentsByHash } from "./routes/getSkipSegmentsByHash";
import { postSkipSegments } from "./routes/postSkipSegments";
import { getSkipSegments, oldGetVideoSponsorTimes } from "./routes/getSkipSegments";
import { endpoint as getSkipSegments } from "./routes/getSkipSegments";
import { userCounter } from "./middleware/userCounter";
import { loggerMiddleware } from "./middleware/logger";
import { corsMiddleware } from "./middleware/cors";
import { apiCspMiddleware } from "./middleware/apiCsp";
import { rateLimitMiddleware } from "./middleware/requestRateLimit";
import dumpDatabase from "./routes/dumpDatabase";
import dumpDatabase, { appExportPath, downloadFile } from "./routes/dumpDatabase";
import { endpoint as getSegmentInfo } from "./routes/getSegmentInfo";
import { postClearCache } from "./routes/postClearCache";
import { addUnlistedVideo } from "./routes/addUnlistedVideo";
@@ -42,26 +43,11 @@ import ExpressPromiseRouter from "express-promise-router";
import { Server } from "http";
import { youtubeApiProxy } from "./routes/youtubeApiProxy";
import { getChapterNames } from "./routes/getChapterNames";
import { postRating } from "./routes/ratings/postRating";
import { getRating } from "./routes/ratings/getRating";
import { postClearCache as ratingPostClearCache } from "./routes/ratings/postClearCache";
import { getTopCategoryUsers } from "./routes/getTopCategoryUsers";
import { addUserAsTempVIP } from "./routes/addUserAsTempVIP";
import { endpoint as getVideoLabels } from "./routes/getVideoLabel";
import { getVideoLabelsByHash } from "./routes/getVideoLabelByHash";
import { addFeature } from "./routes/addFeature";
import { generateTokenRequest } from "./routes/generateToken";
import { verifyTokenRequest } from "./routes/verifyToken";
import { getBranding, getBrandingByHashEndpoint } from "./routes/getBranding";
import { postBranding } from "./routes/postBranding";
import { cacheMiddlware } from "./middleware/etag";
import { hostHeader } from "./middleware/hostHeader";
import { getBrandingStats } from "./routes/getBrandingStats";
import { getTopBrandingUsers } from "./routes/getTopBrandingUsers";
import { getFeatureFlag } from "./routes/getFeatureFlag";
import { getReady } from "./routes/getReady";
import { getMetrics } from "./routes/getMetrics";
import { getSegmentID } from "./routes/getSegmentID";
import { postCasual } from "./routes/postCasual";
import { getConfigEndpoint } from "./routes/getConfig";
import { setConfig } from "./routes/setConfig";
export function createServer(callback: () => void): Server {
// Create a service (the app object is just a callback).
@@ -69,14 +55,11 @@ export function createServer(callback: () => void): Server {
const router = ExpressPromiseRouter();
app.use(router);
app.set("etag", false); // disable built in etag
//setup CORS correctly
router.use(corsMiddleware);
router.use(loggerMiddleware);
router.use("/api/", apiCspMiddleware);
router.use(hostHeader);
router.use(cacheMiddlware);
router.use(express.json());
if (config.userCounterURL) router.use(userCounter);
@@ -87,21 +70,20 @@ export function createServer(callback: () => void): Server {
// Set production mode
app.set("env", config.mode || "production");
const server = app.listen(config.port, callback);
setupRoutes(router);
setupRoutes(router, server);
return server;
return app.listen(config.port, callback);
}
/* eslint-disable @typescript-eslint/no-misused-promises */
function setupRoutes(router: Router, server: Server) {
function setupRoutes(router: Router) {
// Rate limit endpoint lists
const voteEndpoints: RequestHandler[] = [voteOnSponsorTime];
const viewEndpoints: RequestHandler[] = [viewedVideoSponsorTime];
if (config.rateLimit && config.redisRateLimit) {
const postRateEndpoints: RequestHandler[] = [postRating];
if (config.rateLimit) {
if (config.rateLimit.vote) voteEndpoints.unshift(rateLimitMiddleware(config.rateLimit.vote, voteGetUserID));
if (config.rateLimit.view) viewEndpoints.unshift(rateLimitMiddleware(config.rateLimit.view));
if (config.rateLimit.rate) postRateEndpoints.unshift(rateLimitMiddleware(config.rateLimit.rate));
}
//add the get function
@@ -126,8 +108,6 @@ function setupRoutes(router: Router, server: Server) {
router.get("/api/viewedVideoSponsorTime", ...viewEndpoints);
router.post("/api/viewedVideoSponsorTime", ...viewEndpoints);
router.get("/api/segmentID", getSegmentID);
//To set your username for the stats view
router.post("/api/setUsername", setUsername);
@@ -153,14 +133,11 @@ function setupRoutes(router: Router, server: Server) {
router.get("/api/getTopUsers", getTopUsers);
router.get("/api/getTopCategoryUsers", getTopCategoryUsers);
router.get("/api/getTopBrandingUsers", getTopBrandingUsers);
//send out totals
//send the total submissions, total views and total minutes saved
router.get("/api/getTotalStats", getTotalStats);
router.get("/api/brandingStats", getBrandingStats);
router.get("/api/getUserInfo", getUserInfo);
router.get("/api/userInfo", getUserInfo);
@@ -210,11 +187,8 @@ function setupRoutes(router: Router, server: Server) {
router.get("/api/chapterNames", getChapterNames);
// get status
router.get("/api/status/:value", (req, res) => getStatus(req, res, server));
router.get("/api/status", (req, res) => getStatus(req, res, server));
router.get("/metrics", (req, res) => getMetrics(req, res, server));
router.get("/api/ready", (req, res) => getReady(req, res, server));
router.get("/api/status/:value", getStatus);
router.get("/api/status", getStatus);
router.get("/api/youtubeApiProxy", youtubeApiProxy);
// get user category stats
@@ -222,36 +196,20 @@ function setupRoutes(router: Router, server: Server) {
router.get("/api/lockReason", getLockReason);
router.post("/api/feature", addFeature);
// ratings
router.get("/api/ratings/rate/:prefix", getRating);
router.get("/api/ratings/rate", getRating);
router.post("/api/ratings/rate", postRateEndpoints);
router.post("/api/ratings/clearCache", ratingPostClearCache);
router.get("/api/featureFlag/:name", getFeatureFlag);
router.get("/api/generateToken/:type", generateTokenRequest);
router.get("/api/verifyToken", verifyTokenRequest);
// labels
router.get("/api/videoLabels", getVideoLabels);
router.get("/api/videoLabels/:prefix", getVideoLabelsByHash);
router.get("/api/branding", getBranding);
router.get("/api/branding/:prefix", getBrandingByHashEndpoint);
router.post("/api/branding", postBranding);
router.get("/api/config", getConfigEndpoint);
router.post("/api/config", setConfig);
router.post("/api/casual", postCasual);
/* istanbul ignore next */
if (config.postgres?.enabled) {
router.get("/database", (req, res) => dumpDatabase(req, res, true));
router.get("/database.json", (req, res) => dumpDatabase(req, res, false));
router.get("/database/*", (req, res) => res.status(404).send("CSV downloads disabled. Please use sb-mirror rsync"));
router.use("/download", (req, res) => res.status(404).send("CSV downloads disabled. Please use sb-mirror rsync"));
router.get("/database/*", downloadFile);
router.use("/download", express.static(appExportPath));
} else {
router.get("/database.db", function (req: Request, res: Response) {
res.sendFile("./databases/sponsorTimes.db", { root: "./" });
});
}
}
/* eslint-enable @typescript-eslint/no-misused-promises */

View File

@@ -1,6 +1,7 @@
import fs from "fs";
import { SBSConfig } from "./types/config.model";
import packageJson from "../package.json";
import { isBoolean, isNumber } from "lodash";
const isTestMode = process.env.npm_lifecycle_script === packageJson.scripts.test;
const configFile = process.env.TEST_POSTGRES ? "ci.json"
@@ -19,8 +20,7 @@ addDefaults(config, {
privateDBSchema: "./databases/_private.db.sql",
readOnly: false,
webhooks: [],
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "hook", "music_offtopic", "filler", "poi_highlight", "chapter"],
casualCategoryList: ["funny", "creative", "clever", "descriptive", "other"],
categoryList: ["sponsor", "selfpromo", "exclusive_access", "interaction", "intro", "outro", "preview", "music_offtopic", "filler", "poi_highlight"],
categorySupport: {
sponsor: ["skip", "mute", "full"],
selfpromo: ["skip", "mute", "full"],
@@ -29,27 +29,19 @@ addDefaults(config, {
intro: ["skip", "mute"],
outro: ["skip", "mute"],
preview: ["skip", "mute"],
hook: ["skip", "mute"],
filler: ["skip", "mute"],
music_offtopic: ["skip"],
poi_highlight: ["poi"],
chapter: ["chapter"]
},
deArrowTypes: ["title", "thumbnail"],
maxTitleLength: 110,
maxNumberOfActiveWarnings: 1,
hoursAfterWarningExpires: 16300000,
adminUserID: "",
discordCompletelyIncorrectReportWebhookURL: null,
discordFirstTimeSubmissionsWebhookURL: null,
discordNeuralBlockRejectWebhookURL: null,
discordFailedReportChannelWebhookURL: null,
discordReportChannelWebhookURL: null,
discordMaliciousReportWebhookURL: null,
discordDeArrowLockedWebhookURL: null,
discordDeArrowWarnedWebhookURL: null,
discordNewUserWebhookURL: null,
discordRejectedNewUserWebhookURL: null,
minReputationToSubmitChapter: 0,
minReputationToSubmitFiller: 0,
getTopUsersCacheTimeMinutes: 240,
globalSalt: null,
mode: "",
@@ -67,11 +59,15 @@ addDefaults(config, {
max: 10,
statusCode: 200,
message: "OK",
},
rate: {
windowMs: 900000,
max: 20,
statusCode: 200,
message: "Success",
}
},
requestValidatorRules: [],
userCounterURL: null,
userCounterRatio: 10,
newLeafURLs: null,
maxRewardTimePerSegmentInSeconds: 600,
poiMinimumStartTime: 2,
@@ -81,29 +77,9 @@ addDefaults(config, {
host: "",
password: "",
port: 5432,
max: 10,
idleTimeoutMillis: 10000,
maxTries: 3,
maxActiveRequests: 0,
timeout: 60000,
highLoadThreshold: 10,
redisTimeoutThreshold: 1000
max: 150,
min: 10
},
postgresReadOnly: {
enabled: false,
weight: 1,
user: "",
host: "",
password: "",
port: 5432,
readTimeout: 250,
max: 10,
idleTimeoutMillis: 10000,
maxTries: 3,
fallbackOnFail: true,
stopRetryThreshold: 800
},
postgresPrivateMax: 10,
dumpDatabase: {
enabled: false,
minTimeBetweenMs: 180000,
@@ -136,28 +112,6 @@ addDefaults(config, {
},
{
name: "ratings"
},
{
name: "titles"
},
{
name: "titleVotes"
},
{
name: "thumbnails"
},
{
name: "thumbnailTimestamps"
},
{
name: "thumbnailVotes"
},
{
name: "casualVotes",
order: "timeSubmitted"
},
{
name: "casualVoteTitles"
}]
},
diskCacheURL: null,
@@ -168,52 +122,7 @@ addDefaults(config, {
host: "",
port: 0
},
disableOfflineQueue: true,
expiryTime: 24 * 60 * 60,
getTimeout: 40,
maxConnections: 15000,
maxWriteConnections: 1000,
commandsQueueMaxLength: 3000,
stopWritingAfterResponseTime: 50,
responseTimePause: 1000,
maxReadResponseTime: 500,
disableHashCache: false,
clientCacheSize: 2000,
useCompression: false,
dragonflyMode: false
},
redisRead: {
enabled: false,
socket: {
host: "",
port: 0
},
disableOfflineQueue: true,
weight: 1
},
redisRateLimit: true,
patreon: {
clientId: "",
clientSecret: "",
minPrice: 0,
redirectUri: "https://sponsor.ajay.app/api/generateToken/patreon"
},
gumroad: {
productPermalinks: ["sponsorblock"]
},
tokenSeed: "",
minUserIDLength: 30,
deArrowPaywall: false,
useCacheForSegmentGroups: false,
maxConnections: 100,
maxResponseTime: 1000,
maxResponseTimeWhileLoadingCache: 2000,
etagExpiry: 5000,
youTubeKeys: {
visitorData: null,
poToken: null,
floatieUrl: null,
floatieAuth: null
disableOfflineQueue: true
}
});
loadFromEnv(config);
@@ -262,17 +171,15 @@ function loadFromEnv(config: SBSConfig, prefix = "") {
loadFromEnv(data, fullKey);
} else if (process.env[fullKey]) {
const value = process.env[fullKey];
if (value !== "" && !isNaN(value as unknown as number)) {
config[key] = parseFloat(value);
if (isNumber(value)) {
config[key] = parseInt(value, 10);
} else if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
config[key] = value === "true";
} else if (key === "newLeafURLs") {
config[key] = [value];
} else if (key === "requestValidatorRules") {
config[key] = JSON.parse(value) ?? [];
} else {
config[key] = value;
}
}
}
}
}

View File

@@ -3,6 +3,7 @@ import { CronJob } from "cron";
import { config as serverConfig } from "../config";
import { Logger } from "../utils/logger";
import { db } from "../databases/databases";
import { DBSegment } from "../types/segments.model";
const jobConfig = serverConfig?.crons?.downvoteSegmentArchive;
@@ -13,18 +14,18 @@ export const archiveDownvoteSegment = async (dayLimit: number, voteLimit: number
Logger.info(`DownvoteSegmentArchiveJob starts at ${timeNow}`);
try {
// insert into archive sponsorTime
await db.prepare(
"run",
`INSERT INTO "archivedSponsorTimes"
SELECT *
FROM "sponsorTimes"
WHERE "votes" < ? AND (? - "timeSubmitted") > ?`,
[
voteLimit,
timeNow,
threshold
]
);
await db.prepare(
"run",
`INSERT INTO "archivedSponsorTimes"
SELECT *
FROM "sponsorTimes"
WHERE "votes" < ? AND (? - "timeSubmitted") > ?`,
[
voteLimit,
timeNow,
threshold
]
) as DBSegment[];
} catch (err) {
Logger.error("Execption when insert segment in archivedSponsorTimes");
@@ -34,15 +35,15 @@ export const archiveDownvoteSegment = async (dayLimit: number, voteLimit: number
// remove from sponsorTime
try {
await db.prepare(
"run",
'DELETE FROM "sponsorTimes" WHERE "votes" < ? AND (? - "timeSubmitted") > ?',
[
voteLimit,
timeNow,
threshold
]
);
await db.prepare(
"run",
'DELETE FROM "sponsorTimes" WHERE "votes" < ? AND (? - "timeSubmitted") > ?',
[
voteLimit,
timeNow,
threshold
]
) as DBSegment[];
} catch (err) {
Logger.error("Execption when deleting segment in sponsorTimes");
@@ -56,7 +57,7 @@ export const archiveDownvoteSegment = async (dayLimit: number, voteLimit: number
const DownvoteSegmentArchiveJob = new CronJob(
jobConfig?.schedule || "0 0 * * * 0",
() => void archiveDownvoteSegment(jobConfig?.timeThresholdInDays, jobConfig?.voteThreshold)
() => archiveDownvoteSegment(jobConfig?.timeThresholdInDays, jobConfig?.voteThreshold)
);
if (serverConfig?.crons?.enabled && jobConfig && !jobConfig.schedule) {

View File

@@ -1,19 +1,7 @@
export interface QueryOption {
useReplica?: boolean;
forceReplica?: boolean;
}
export interface IDatabase {
init(): Promise<void>;
prepare(type: "run", query: string, params?: any[], options?: QueryOption): Promise<void>;
prepare(type: "get", query: string, params?: any[], options?: QueryOption): Promise<any>;
prepare(type: "all", query: string, params?: any[], options?: QueryOption): Promise<any[]>;
prepare(type: QueryType, query: string, params?: any[], options?: QueryOption): Promise<any>;
highLoad(): boolean;
shouldUseRedisTimeout(): boolean;
prepare(type: QueryType, query: string, params?: any[]): Promise<any | any[] | void>;
}
export type QueryType = "get" | "all" | "run";

35
src/databases/Mysql.ts Normal file
View File

@@ -0,0 +1,35 @@
import { Logger } from "../utils/logger";
import { IDatabase, QueryType } from "./IDatabase";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import MysqlInterface from "sync-mysql";
export class Mysql implements IDatabase {
private connection: any;
constructor(private config: unknown) {
}
// eslint-disable-next-line require-await
async init(): Promise<void> {
this.connection = new MysqlInterface(this.config);
}
prepare(type: QueryType, query: string, params?: any[]): Promise<any[]> {
Logger.debug(`prepare (mysql): type: ${type}, query: ${query}, params: ${params}`);
const queryResult = this.connection.query(query, params);
switch (type) {
case "get": {
return queryResult[0];
}
case "all": {
return queryResult;
}
case "run": {
break;
}
}
}
}

View File

@@ -1,10 +1,8 @@
import { Logger } from "../utils/logger";
import { IDatabase, QueryOption, QueryType } from "./IDatabase";
import { Client, Pool, QueryResult, types } from "pg";
import { IDatabase, QueryType } from "./IDatabase";
import { Client, Pool, PoolClient, types } from "pg";
import fs from "fs";
import { CustomPostgresReadOnlyConfig, CustomWritePostgresConfig } from "../types/config.model";
import { timeoutPomise, PromiseWithState, savePromiseState, nextFulfilment } from "../utils/promise";
// return numeric (pg_type oid=1700) as float
types.setTypeParser(1700, function(val) {
@@ -16,77 +14,13 @@ types.setTypeParser(20, function(val) {
return parseInt(val, 10);
});
interface PostgresStats {
activeRequests: number;
avgReadTime: number;
avgWriteTime: number;
avgFailedTime: number;
pool: {
total: number;
idle: number;
waiting: number;
}
}
export interface DatabaseConfig {
dbSchemaFileName: string,
dbSchemaFolder: string,
fileNamePrefix: string,
readOnly: boolean,
createDbIfNotExists: boolean,
postgres: CustomWritePostgresConfig,
postgresReadOnly: CustomPostgresReadOnlyConfig
}
export class Postgres implements IDatabase {
private pool: Pool;
private lastPoolFail = 0;
private poolRead: Pool;
private lastPoolReadFail = 0;
activePostgresRequests = 0;
readResponseTime: number[] = [];
writeResponseTime: number[] = [];
failedResponseTime: number[] = [];
maxStoredTimes = 200;
constructor(private config: DatabaseConfig) {}
constructor(private config: Record<string, any>) {}
async init(): Promise<void> {
this.pool = new Pool({
...this.config.postgres
});
this.pool.on("error", (err, client) => {
Logger.error(err.stack);
this.lastPoolFail = Date.now();
try {
client.release(true);
} catch (err) {
Logger.error(`pool (postgres): ${err}`);
}
});
if (this.config.postgresReadOnly && this.config.postgresReadOnly.enabled) {
try {
this.poolRead = new Pool({
...this.config.postgresReadOnly
});
this.poolRead.on("error", (err, client) => {
Logger.error(err.stack);
this.lastPoolReadFail = Date.now();
try {
client.release(true);
} catch (err) {
Logger.error(`poolRead (postgres): ${err}`);
}
});
} catch (e) {
Logger.error(`poolRead (postgres): ${e}`);
}
}
this.pool = new Pool(this.config.postgres);
if (!this.config.readOnly) {
if (this.config.createDbIfNotExists) {
@@ -109,7 +43,7 @@ export class Postgres implements IDatabase {
}
}
async prepare(type: QueryType, query: string, params?: any[], options: QueryOption = {}): Promise<any> {
async prepare(type: QueryType, query: string, params?: any[]): Promise<any[]> {
// Convert query to use numbered parameters
let count = 1;
for (let char = 0; char < query.length; char++) {
@@ -121,88 +55,33 @@ export class Postgres implements IDatabase {
Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`);
if (this.config.postgres.maxActiveRequests && this.isReadQuery(type)
&& this.activePostgresRequests > this.config.postgres.maxActiveRequests) {
throw new Error("Too many active postgres requests");
}
let client: PoolClient;
try {
client = await this.pool.connect();
const queryResult = await client.query({ text: query, values: params });
const start = Date.now();
const pendingQueries: PromiseWithState<QueryResult<any>>[] = [];
let tries = 0;
let lastPool: Pool = null;
const maxTries = () => (lastPool === this.pool
? this.config.postgres.maxTries : this.config.postgresReadOnly.maxTries);
do {
tries++;
try {
this.activePostgresRequests++;
lastPool = this.getPool(type, options);
pendingQueries.push(savePromiseState(lastPool.query({ text: query, values: params })));
const currentPromises = [...pendingQueries];
if (options.useReplica && maxTries() - tries > 1) currentPromises.push(savePromiseState(timeoutPomise(this.config.postgresReadOnly.readTimeout)));
else if (this.config.postgres.timeout) currentPromises.push(savePromiseState(timeoutPomise(this.config.postgres.timeout)));
const queryResult = await nextFulfilment(currentPromises);
this.updateResponseTime(type, start);
this.activePostgresRequests--;
switch (type) {
case "get": {
const value = queryResult.rows[0];
Logger.debug(`result (postgres): ${JSON.stringify(value)}`);
return value;
}
case "all": {
const values = queryResult.rows;
Logger.debug(`result (postgres): ${JSON.stringify(values)}`);
return values;
}
case "run": {
return;
}
switch (type) {
case "get": {
const value = queryResult.rows[0];
Logger.debug(`result (postgres): ${JSON.stringify(value)}`);
return value;
}
} catch (err) {
if (lastPool === this.pool) {
// Only applies if it is get or all request
options.forceReplica = true;
} else if (lastPool === this.poolRead) {
this.lastPoolReadFail = Date.now();
if (maxTries() - tries <= 1) {
options.useReplica = false;
}
case "all": {
const values = queryResult.rows;
Logger.debug(`result (postgres): ${JSON.stringify(values)}`);
return values;
}
case "run": {
break;
}
this.updateResponseTime(type, start, this.failedResponseTime);
this.activePostgresRequests--;
Logger.error(`prepare (postgres) try ${tries}: ${err}`);
}
} while (this.isReadQuery(type) && tries < maxTries()
&& this.activePostgresRequests < this.config.postgresReadOnly.stopRetryThreshold);
throw new Error(`prepare (postgres): ${type} ${query} failed after ${tries} tries`);
}
private getPool(type: string, options: QueryOption): Pool {
const readAvailable = this.poolRead && options.useReplica && this.isReadQuery(type);
const ignoreReadDueToFailure = this.config.postgresReadOnly.fallbackOnFail
&& this.lastPoolReadFail > Date.now() - 1000 * 30;
const readDueToFailure = this.config.postgresReadOnly.fallbackOnFail
&& this.lastPoolFail > Date.now() - 1000 * 30;
if (readAvailable && !ignoreReadDueToFailure && (options.forceReplica || readDueToFailure ||
Math.random() > 1 / (this.config.postgresReadOnly.weight + 1))) {
return this.poolRead;
} else {
return this.pool;
} catch (err) {
Logger.error(`prepare (postgres): ${err}`);
} finally {
client?.release();
}
}
private isReadQuery(type: string): boolean {
return type === "get" || type === "all";
}
private async createDB() {
const client = new Client({
...this.config.postgres,
@@ -219,7 +98,7 @@ export class Postgres implements IDatabase {
);
}
client.end().catch(err => Logger.error(`closing db (postgres): ${err}`));
client.end();
}
private async upgradeDB(fileNamePrefix: string, schemaFolder: string) {
@@ -255,36 +134,4 @@ export class Postgres implements IDatabase {
return result;
}
private updateResponseTime(type: string, start: number, customArray?: number[]): void {
const responseTime = Date.now() - start;
const array = customArray ?? (this.isReadQuery(type) ?
this.readResponseTime : this.writeResponseTime);
array.push(responseTime);
if (array.length > this.maxStoredTimes) array.shift();
}
getStats(): PostgresStats {
return {
activeRequests: this.activePostgresRequests,
avgReadTime: this.readResponseTime.length > 0 ? this.readResponseTime.reduce((a, b) => a + b, 0) / this.readResponseTime.length : 0,
avgWriteTime: this.writeResponseTime.length > 0 ? this.writeResponseTime.reduce((a, b) => a + b, 0) / this.writeResponseTime.length : 0,
avgFailedTime: this.failedResponseTime.length > 0 ? this.failedResponseTime.reduce((a, b) => a + b, 0) / this.failedResponseTime.length : 0,
pool: {
total: this.pool.totalCount,
idle: this.pool.idleCount,
waiting: this.pool.waitingCount
}
};
}
highLoad() {
return this.activePostgresRequests > this.config.postgres.highLoadThreshold;
}
shouldUseRedisTimeout() {
return this.activePostgresRequests < this.config.postgres.redisTimeoutThreshold;
}
}

View File

@@ -13,7 +13,7 @@ export class Sqlite implements IDatabase {
}
// eslint-disable-next-line require-await
async prepare(type: QueryType, query: string, params: any[] = []): Promise<any> {
async prepare(type: QueryType, query: string, params: any[] = []): Promise<any[]> {
// Logger.debug(`prepare (sqlite): type: ${type}, query: ${query}, params: ${params}`);
const preparedQuery = this.db.prepare(Sqlite.processQuery(query));
@@ -72,15 +72,6 @@ export class Sqlite implements IDatabase {
}
private static processQuery(query: string): string {
if (query.includes("DISTINCT ON")) {
const column = query.match(/DISTINCT ON \((.*)\) (.*)/)[1];
query = query.replace(/DISTINCT ON \((.*)\)/g, "");
const parts = query.split("ORDER BY");
query = `${parts[0]} GROUP BY ${column} ORDER BY ${parts[1]}`;
}
return query.replace(/ ~\* /g, " REGEXP ");
}
@@ -102,17 +93,7 @@ export class Sqlite implements IDatabase {
}
private static processUpgradeQuery(query: string): string {
return query
.replace(/SERIAL PRIMARY KEY/gi, "INTEGER PRIMARY KEY AUTOINCREMENT")
.replace(/^.*--!sqlite-ignore/gm, "");
}
highLoad() {
return false;
}
shouldUseRedisTimeout() {
return false;
return query.replace(/^.*--!sqlite-ignore/gm, "");
}
}

View File

@@ -1,11 +1,15 @@
import { config } from "../config";
import { Sqlite } from "./Sqlite";
import { Mysql } from "./Mysql";
import { Postgres } from "./Postgres";
import { IDatabase } from "./IDatabase";
let db: IDatabase;
let privateDB: IDatabase;
if (config.postgres?.enabled) {
if (config.mysql) {
db = new Mysql(config.mysql);
privateDB = new Mysql(config.privateMysql);
} else if (config.postgres?.enabled) {
db = new Postgres({
dbSchemaFileName: config.dbSchema,
dbSchemaFolder: config.schemaFolder,
@@ -13,13 +17,14 @@ if (config.postgres?.enabled) {
readOnly: config.readOnly,
createDbIfNotExists: config.createDatabaseIfNotExist,
postgres: {
...config.postgres,
user: config.postgres?.user,
host: config.postgres?.host,
database: "sponsorTimes",
},
postgresReadOnly: config.postgresReadOnly ? {
...config.postgresReadOnly,
database: "sponsorTimes"
} : null
password: config.postgres?.password,
port: config.postgres?.port,
max: config.postgres?.max,
min: config.postgres?.min,
}
});
privateDB = new Postgres({
@@ -29,14 +34,14 @@ if (config.postgres?.enabled) {
readOnly: config.readOnly,
createDbIfNotExists: config.createDatabaseIfNotExist,
postgres: {
...config.postgres,
max: config.postgresPrivateMax ?? config.postgres.max,
database: "privateDB"
},
postgresReadOnly: config.postgresReadOnly ? {
...config.postgresReadOnly,
database: "privateDB"
} : null
user: config.postgres?.user,
host: config.postgres?.host,
database: "privateDB",
password: config.postgres?.password,
port: config.postgres?.port,
max: config.postgres?.max,
min: config.postgres?.min,
}
});
} else {
db = new Sqlite({

View File

@@ -4,27 +4,15 @@ import { createServer } from "./app";
import { Logger } from "./utils/logger";
import { startAllCrons } from "./cronjob";
import { getCommit } from "./utils/getCommit";
import { connectionPromise } from "./utils/redis";
async function init() {
process.on("unhandledRejection", (error: any) => {
// eslint-disable-next-line no-console
console.dir(error?.stack);
});
process.on("uncaughtExceptions", (error: any) => {
// eslint-disable-next-line no-console
console.dir(error?.stack);
});
try {
await initDb();
await connectionPromise;
} catch (e) {
Logger.error(`Init Db: ${e}`);
process.exit(1);
}
});
await initDb();
// edge case clause for creating compatible .db files, do not enable
if (config.mode === "init-db-and-exit") process.exit(0);
// do not enable init-db-only mode for usage.
@@ -39,4 +27,4 @@ async function init() {
}).setTimeout(15000);
}
init().catch((err) => Logger.error(`Index.js: ${err}`));
init();

View File

@@ -3,6 +3,6 @@ import { NextFunction, Request, Response } from "express";
export function corsMiddleware(req: Request, res: Response, next: NextFunction): void {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type, If-None-Match, x-client-name");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
}

View File

@@ -1,53 +0,0 @@
import { NextFunction, Request, Response } from "express";
import { VideoID, VideoIDHash, Service } from "../types/segments.model";
import { QueryCacher } from "../utils/queryCacher";
import { brandingHashKey, brandingKey, skipSegmentsHashKey, skipSegmentsKey, skipSegmentsLargerHashKey, videoLabelsHashKey, videoLabelsKey, videoLabelsLargerHashKey } from "../utils/redisKeys";
type hashType = "skipSegments" | "skipSegmentsHash" | "skipSegmentsLargerHash" | "videoLabel" | "videoLabelHash" | "videoLabelsLargerHash" | "branding" | "brandingHash";
type ETag = `"${hashType};${VideoIDHash};${Service};${number}"`;
type hashKey = string | VideoID | VideoIDHash;
export function cacheMiddlware(req: Request, res: Response, next: NextFunction): void {
const reqEtag = req.get("If-None-Match") as string;
// if weak etag, do not handle
if (!reqEtag || reqEtag.startsWith("W/")) return next();
// split into components
const [hashType, hashKey, service, lastModified] = reqEtag.replace(/^"|"$/g, "").split(";");
// fetch last-modified
getLastModified(hashType as hashType, hashKey as VideoIDHash, service as Service)
.then(redisLastModified => {
if (redisLastModified <= new Date(Number(lastModified) + 1000)) {
// match cache, generate etag
const etag = `"${hashType};${hashKey};${service};${redisLastModified.getTime()}"` as ETag;
res.status(304).set("etag", etag).send();
}
else next();
})
.catch(next);
}
function getLastModified(hashType: hashType, hashKey: hashKey, service: Service): Promise<Date | null> {
let redisKey: string | null;
if (hashType === "skipSegments") redisKey = skipSegmentsKey(hashKey as VideoID, service);
else if (hashType === "skipSegmentsHash") redisKey = skipSegmentsHashKey(hashKey as VideoIDHash, service);
else if (hashType === "skipSegmentsLargerHash") redisKey = skipSegmentsLargerHashKey(hashKey as VideoIDHash, service);
else if (hashType === "videoLabel") redisKey = videoLabelsKey(hashKey as VideoID, service);
else if (hashType === "videoLabelHash") redisKey = videoLabelsHashKey(hashKey as VideoIDHash, service);
else if (hashType === "videoLabelsLargerHash") redisKey = videoLabelsLargerHashKey(hashKey as VideoIDHash, service);
else if (hashType === "branding") redisKey = brandingKey(hashKey as VideoID, service);
else if (hashType === "brandingHash") redisKey = brandingHashKey(hashKey as VideoIDHash, service);
else return Promise.reject();
return QueryCacher.getKeyLastModified(redisKey);
}
export async function getEtag(hashType: hashType, hashKey: hashKey, service: Service): Promise<ETag> {
const lastModified = await getLastModified(hashType, hashKey, service);
return `"${hashType};${hashKey};${service};${lastModified.getTime()}"` as ETag;
}
/* example usage
import { getEtag } from "../middleware/etag";
await getEtag(hashType, hashPrefix, service)
.then(etag => res.set("ETag", etag))
.catch(() => null);
*/

View File

@@ -1,7 +0,0 @@
import { NextFunction, Request, Response } from "express";
import os from "os";
export function hostHeader(req: Request, res: Response, next: NextFunction): void {
res.header("SBSERVER-HOST", os.hostname());
next();
}

View File

@@ -1,9 +1,9 @@
import { getIP } from "../utils/getIP";
import { getHash } from "../utils/getHash";
import { getHashCache } from "../utils/getHashCache";
import rateLimit from "express-rate-limit";
import rateLimit, { RateLimitRequestHandler } from "express-rate-limit";
import { RateLimitConfig } from "../types/config.model";
import { Request, RequestHandler } from "express";
import { Request } from "express";
import { isUserVIP } from "../utils/isUserVIP";
import { UserID } from "../types/user.model";
import RedisStore, { RedisReply } from "rate-limit-redis";
@@ -11,32 +11,26 @@ import redis from "../utils/redis";
import { config } from "../config";
import { Logger } from "../utils/logger";
export function rateLimitMiddleware(limitConfig: RateLimitConfig, getUserID?: (req: Request) => UserID): RequestHandler {
try {
return rateLimit({
windowMs: limitConfig.windowMs,
max: limitConfig.max,
message: limitConfig.message,
statusCode: limitConfig.statusCode,
legacyHeaders: false,
standardHeaders: false,
keyGenerator: (req) => {
return getHash(getIP(req), 1);
},
// eslint-disable-next-line @typescript-eslint/no-misused-promises
handler: async (req, res, next) => {
if (getUserID === undefined || !await isUserVIP(await getHashCache(getUserID(req)))) {
return res.status(limitConfig.statusCode).send(limitConfig.message);
} else {
return next();
}
},
store: config.redis?.enabled ? new RedisStore({
sendCommand: (...args: string[]) => redis.sendCommand(args).catch((err) => Logger.error(err)) as Promise<RedisReply>,
}) : null,
});
} catch (e) {
Logger.error(`Rate limit error: ${e}`);
return (req, res, next) => next();
}
export function rateLimitMiddleware(limitConfig: RateLimitConfig, getUserID?: (req: Request) => UserID): RateLimitRequestHandler {
return rateLimit({
windowMs: limitConfig.windowMs,
max: limitConfig.max,
message: limitConfig.message,
statusCode: limitConfig.statusCode,
legacyHeaders: false,
standardHeaders: false,
keyGenerator: (req) => {
return getHash(getIP(req), 1);
},
handler: async (req, res, next) => {
if (getUserID === undefined || !await isUserVIP(await getHashCache(getUserID(req)))) {
return res.status(limitConfig.statusCode).send(limitConfig.message);
} else {
return next();
}
},
store: config.redis?.enabled ? new RedisStore({
sendCommand: (...args: string[]) => redis.sendCommand(args).catch((err) => Logger.error(err)) as Promise<RedisReply>,
}) : null,
});
}

View File

@@ -2,20 +2,13 @@ import axios from "axios";
import { Logger } from "../utils/logger";
import { config } from "../config";
import { getIP } from "../utils/getIP";
import { getHash } from "../utils/getHash";
import { NextFunction, Request, Response } from "express";
import { Agent } from "http";
const httpAgent = new Agent({ keepAlive: true });
export function userCounter(req: Request, res: Response, next: NextFunction): void {
if (req.method !== "OPTIONS") {
if (Math.random() < 1 / config.userCounterRatio) {
axios({
method: "post",
url: `${config.userCounterURL}/api/v1/addIP?hashedIP=${getIP(req)}`,
httpAgent
}).catch(() => /* instanbul skip next */ Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
}
axios.post(`${config.userCounterURL}/api/v1/addIP?hashedIP=${getHash(getIP(req), 1)}`)
.catch(() => Logger.debug(`Failing to connect to user counter at: ${config.userCounterURL}`));
}
next();

View File

@@ -1,81 +0,0 @@
import { getHashCache } from "../utils/getHashCache";
import { db } from "../databases/databases";
import { config } from "../config";
import { Request, Response } from "express";
import { isUserVIP } from "../utils/isUserVIP";
import { Feature, HashedUserID, UserID } from "../types/user.model";
import { Logger } from "../utils/logger";
import { QueryCacher } from "../utils/queryCacher";
import { getVerificationValue, verifyOldSubmissions } from "./postBranding";
interface AddFeatureRequest extends Request {
body: {
userID: HashedUserID;
adminUserID: string;
feature: string;
enabled: string;
}
}
const allowedFeatures = {
vip: [
Feature.ChapterSubmitter,
Feature.FillerSubmitter,
Feature.DeArrowTitleSubmitter,
],
admin: [
Feature.ChapterSubmitter,
Feature.FillerSubmitter,
Feature.DeArrowTitleSubmitter,
]
};
export async function addFeature(req: AddFeatureRequest, res: Response): Promise<Response> {
const { body: { userID, adminUserID } } = req;
const feature = parseInt(req.body.feature) as Feature;
const enabled = req.body?.enabled !== "false";
if (!userID || !adminUserID) {
// invalid request
return res.sendStatus(400);
}
// hash the userID
const adminUserIDInput = await getHashCache(adminUserID as UserID);
const isAdmin = adminUserIDInput === config.adminUserID;
const isVIP = (await isUserVIP(adminUserIDInput)) || isAdmin;
if (!isVIP) {
// not authorized
return res.sendStatus(403);
}
try {
const currentAllowedFeatures = isAdmin ? allowedFeatures.admin : allowedFeatures.vip;
if (currentAllowedFeatures.includes(feature)) {
if (enabled) {
const featureAdded = await db.prepare("get", 'SELECT "feature" from "userFeatures" WHERE "userID" = ? AND "feature" = ?', [userID, feature]);
if (!featureAdded) {
await db.prepare("run", 'INSERT INTO "userFeatures" ("userID", "feature", "issuerUserID", "timeSubmitted") VALUES(?, ?, ?, ?)'
, [userID, feature, adminUserID, Date.now()]);
}
if (feature === Feature.DeArrowTitleSubmitter) {
await verifyOldSubmissions(userID, await getVerificationValue(userID, false));
}
} else {
await db.prepare("run", 'DELETE FROM "userFeatures" WHERE "userID" = ? AND "feature" = ?', [userID, feature]);
}
QueryCacher.clearFeatureCache(userID, feature);
} else {
return res.status(400).send("Invalid feature");
}
return res.sendStatus(200);
} catch (e) {
Logger.error(e as string);
return res.sendStatus(500);
}
}

View File

@@ -1,5 +1,7 @@
import { VideoID } from "../types/segments.model";
import { getVideoDetails } from "../utils/getVideoDetails";
import { YouTubeAPI } from "../utils/youtubeApi";
import { APIVideoInfo } from "../types/youtubeApi.model";
import { config } from "../config";
import { getHashCache } from "../utils/getHashCache";
import { privateDB } from "../databases/databases";
import { Request, Response } from "express";
@@ -18,11 +20,15 @@ interface AddUserAsTempVIPRequest extends Request {
}
}
function getYouTubeVideoInfo(videoID: VideoID, ignoreCache = false): Promise<APIVideoInfo> {
return (config.newLeafURLs) ? YouTubeAPI.listVideos(videoID, ignoreCache) : null;
}
const getChannelInfo = async (videoID: VideoID): Promise<{id: string | null, name: string | null }> => {
const videoInfo = await getVideoDetails(videoID);
const videoInfo = await getYouTubeVideoInfo(videoID);
return {
id: videoInfo?.authorId,
name: videoInfo?.authorName
id: videoInfo?.data?.authorId,
name: videoInfo?.data?.author
};
};

View File

@@ -4,7 +4,6 @@ import { config } from "../config";
import { Request, Response } from "express";
import { isUserVIP } from "../utils/isUserVIP";
import { HashedUserID } from "../types/user.model";
import { Logger } from "../utils/logger";
interface AddUserAsVIPRequest extends Request {
query: {
@@ -35,21 +34,15 @@ export async function addUserAsVIP(req: AddUserAsVIPRequest, res: Response): Pro
// check to see if this user is already a vip
const userIsVIP = await isUserVIP(userID);
try {
if (enabled && !userIsVIP) {
// add them to the vip list
await db.prepare("run", 'INSERT INTO "vipUsers" VALUES(?)', [userID]);
}
if (!enabled && userIsVIP) {
//remove them from the shadow ban list
await db.prepare("run", 'DELETE FROM "vipUsers" WHERE "userID" = ?', [userID]);
}
return res.sendStatus(200);
} catch (e) {
Logger.error(e as string);
return res.sendStatus(500);
if (enabled && !userIsVIP) {
// add them to the vip list
await db.prepare("run", 'INSERT INTO "vipUsers" VALUES(?)', [userID]);
}
if (!enabled && userIsVIP) {
//remove them from the shadow ban list
await db.prepare("run", 'DELETE FROM "vipUsers" WHERE "userID" = ?', [userID]);
}
return res.sendStatus(200);
}

View File

@@ -6,7 +6,6 @@ import { ActionType, Category, Service, VideoID } from "../types/segments.model"
import { UserID } from "../types/user.model";
import { getService } from "../utils/getService";
import { config } from "../config";
import { Logger } from "../utils/logger";
interface DeleteLockCategoriesRequest extends Request {
body: {
@@ -36,7 +35,6 @@ export async function deleteLockCategoriesEndpoint(req: DeleteLockCategoriesRequ
|| !categories
|| !Array.isArray(categories)
|| categories.length === 0
|| actionTypes && !Array.isArray(actionTypes)
|| actionTypes.length === 0
) {
return res.status(400).json({
@@ -50,16 +48,11 @@ export async function deleteLockCategoriesEndpoint(req: DeleteLockCategoriesRequ
if (!userIsVIP) {
return res.status(403).json({
message: "Must be a VIP to lock videos.",
message: "Must be a VIP to mark videos.",
});
}
try {
await deleteLockCategories(videoID, categories, actionTypes, getService(service));
} catch (e) {
Logger.error(e as string);
return res.status(500);
}
await deleteLockCategories(videoID, categories, actionTypes, getService(service));
return res.status(200).json({ message: `Removed lock categories entries for video ${videoID}` });
}

View File

@@ -5,7 +5,7 @@ import { config } from "../config";
import util from "util";
import fs from "fs";
import path from "path";
import { exec, ExecOptions } from "child_process";
import { ChildProcess, exec, ExecOptions, spawn } from "child_process";
const unlink = util.promisify(fs.unlink);
const ONE_MINUTE = 1000 * 60;
@@ -44,7 +44,7 @@ const credentials: ExecOptions = {
PGPASSWORD: String(config.postgres.password),
PGDATABASE: "sponsorTimes",
}
};
}
interface TableDumpList {
fileName: string;
@@ -75,7 +75,6 @@ function removeOutdatedDumps(exportPath: string): Promise<void> {
}, {});
// read files in export directory
// eslint-disable-next-line @typescript-eslint/no-misused-promises
fs.readdir(exportPath, async (err: any, files: string[]) => {
if (err) Logger.error(err);
if (err) return resolve();
@@ -96,12 +95,10 @@ function removeOutdatedDumps(exportPath: string): Promise<void> {
for (const tableName in tableFiles) {
const files = tableFiles[tableName].sort((a, b) => b.timestamp - a.timestamp);
for (let i = 2; i < files.length; i++) {
if (!latestDumpFiles.some((file) => file.fileName === files[i].file.match(/[^/]+$/)[0])) {
// remove old file
await unlink(files[i].file).catch((error: any) => {
Logger.error(`[dumpDatabase] Garbage collection failed ${error}`);
});
}
// remove old file
await unlink(files[i].file).catch((error: any) => {
Logger.error(`[dumpDatabase] Garbage collection failed ${error}`);
});
}
}
resolve();
@@ -126,7 +123,7 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
if (showPage) {
res.send(`${styleHeader}
<h1>SponsorBlock database dumps</h1>${licenseHeader}
<s><h3>How this works</h3>
<h3>How this works</h3>
Send a request to <code>https://sponsor.ajay.app/database.json</code>, or visit this page to get a list of urls and the update status database dump to run.
Then, you can download the csv files below, or use the links returned from the JSON request.
@@ -137,11 +134,6 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
If you want a live dump, please do not continually fetch this url.
Please instead use the <a href="https://github.com/mchangrh/sb-mirror">sb-mirror</a> project.
This can automatically fetch new data and will not require a redownload each time, saving bandwidth.
</s>
<h3>Please use sb-mirror</h3>
For bandwidth reasons, CSV downloads have been disabled. Please use the <a href="https://github.com/mchangrh/sb-mirror">sb-mirror</a> project.
<h3>Links</h3>
<table>
@@ -166,23 +158,18 @@ export default async function dumpDatabase(req: Request, res: Response, showPage
<hr/>
${updateQueued ? `Update queued.` : ``} Last updated: ${lastUpdate ? new Date(lastUpdate).toUTCString() : `Unknown`}`);
} else {
try {
res.send({
dbVersion: await getDbVersion(),
lastUpdated: lastUpdate,
updateQueued,
links: latestDumpFiles.map((item:any) => {
return {
table: item.tableName,
url: `/database/${item.tableName}.csv`,
size: item.fileSize,
};
}),
});
} catch (e) {
Logger.error(e as string);
res.sendStatus(500);
}
res.send({
dbVersion: await getDbVersion(),
lastUpdated: lastUpdate,
updateQueued,
links: latestDumpFiles.map((item:any) => {
return {
table: item.tableName,
url: `/database/${item.tableName}.csv`,
size: item.fileSize,
};
}),
});
}
await queueDump();
@@ -236,16 +223,16 @@ async function queueDump(): Promise<void> {
const fileName = `${table.name}_${startTime}.csv`;
const file = `${appExportPath}/${fileName}`;
await new Promise<string>((resolve, reject) => {
await new Promise<string>((resolve) => {
exec(`psql -c "\\copy (SELECT * FROM \\"${table.name}\\"${table.order ? ` ORDER BY \\"${table.order}\\"` : ``})`
+ ` TO '${file}' WITH (FORMAT CSV, HEADER true);"`, credentials, (error, stdout, stderr) => {
if (error) {
reject(`[dumpDatabase] Failed to dump ${table.name} to ${file} due to ${stderr}`);
Logger.error(`[dumpDatabase] Failed to dump ${table.name} to ${file} due to ${stderr}`);
}
resolve(error ? stderr : stdout);
});
});
})
dumpFiles.push({
fileName,
@@ -255,10 +242,10 @@ async function queueDump(): Promise<void> {
latestDumpFiles = [...dumpFiles];
lastUpdate = startTime;
updateQueued = false;
} catch(e) {
Logger.error(e as string);
} finally {
updateQueued = false;
updateRunning = false;
}
}

View File

@@ -1,68 +0,0 @@
import { Request, Response } from "express";
import { config } from "../config";
import { createAndSaveToken, TokenType } from "../utils/tokenUtils";
import { getHashCache } from "../utils/getHashCache";
interface GenerateTokenRequest extends Request {
query: {
code: string;
adminUserID?: string;
total?: string;
key?: string;
},
params: {
type: TokenType;
}
}
export async function generateTokenRequest(req: GenerateTokenRequest, res: Response): Promise<Response> {
const { query: { code, adminUserID, total, key }, params: { type } } = req;
const adminUserIDHash = adminUserID ? (await getHashCache(adminUserID)) : null;
if (!type || (!code && type === TokenType.patreon)) {
return res.status(400).send("Invalid request");
}
if (type === TokenType.free && (!key || Math.abs(Date.now() - parseInt(key)) > 1000 * 60 * 60 * 24)) {
return res.status(400).send("Invalid request");
}
if (type === TokenType.patreon
|| ([TokenType.local, TokenType.gift].includes(type) && adminUserIDHash === config.adminUserID)
|| type === TokenType.free) {
const licenseKeys = await createAndSaveToken(type, code, adminUserIDHash === config.adminUserID ? parseInt(total) : 1);
/* istanbul ignore else */
if (licenseKeys) {
if (type === TokenType.patreon) {
return res.status(200).send(`
<h1>
Your license key:
</h1>
<p>
<b>
${licenseKeys[0]}
</b>
</p>
<p>
Copy this into the textbox in the other tab
</p>
`);
} else if (type === TokenType.free) {
return res.status(200).send({
licenseKey: licenseKeys[0]
});
} else {
return res.status(200).send(licenseKeys.join("<br/>"));
}
} else {
return res.status(401).send(`
<h1>
Failed to generate an license key
</h1>
`);
}
} else {
return res.sendStatus(403);
}
}

View File

@@ -1,377 +0,0 @@
import { Request, Response } from "express";
import { isEmpty } from "lodash";
import { config } from "../config";
import { db, privateDB } from "../databases/databases";
import { Postgres } from "../databases/Postgres";
import { BrandingDBSubmission, BrandingDBSubmissionData, BrandingHashDBResult, BrandingResult, BrandingSegmentDBResult, BrandingSegmentHashDBResult, CasualVoteDBResult, CasualVoteHashDBResult, ThumbnailDBResult, ThumbnailResult, TitleDBResult, TitleResult } from "../types/branding.model";
import { HashedIP, IPAddress, Service, VideoID, VideoIDHash, Visibility } from "../types/segments.model";
import { shuffleArray } from "../utils/array";
import { getHashCache } from "../utils/getHashCache";
import { getIP } from "../utils/getIP";
import { getService } from "../utils/getService";
import { hashPrefixTester } from "../utils/hashPrefixTester";
import { Logger } from "../utils/logger";
import { promiseOrTimeout } from "../utils/promise";
import { QueryCacher } from "../utils/queryCacher";
import { brandingHashKey, brandingIPKey, brandingKey } from "../utils/redisKeys";
import * as SeedRandom from "seedrandom";
import { getEtag } from "../middleware/etag";
enum BrandingSubmissionType {
Title = "title",
Thumbnail = "thumbnail"
}
export async function getVideoBranding(res: Response, videoID: VideoID, service: Service, ip: IPAddress, returnUserID: boolean, fetchAll: boolean): Promise<BrandingResult> {
const getTitles = () => db.prepare(
"all",
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."downvotes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID", "titleVotes"."verification", "titles"."userID"
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
WHERE "titles"."videoID" = ? AND "titles"."service" = ? AND "titleVotes"."votes" > -1 AND "titleVotes"."votes" - "titleVotes"."downvotes" > -2 AND "titleVotes"."removed" = 0`,
[videoID, service],
{ useReplica: true }
) as Promise<TitleDBResult[]>;
const getThumbnails = () => db.prepare(
"all",
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "thumbnailVotes"."downvotes", "thumbnailVotes"."locked", "thumbnailVotes"."shadowHidden", "thumbnails"."UUID", "thumbnails"."videoID", "thumbnails"."hashedVideoID", "thumbnails"."userID"
FROM "thumbnails" LEFT JOIN "thumbnailVotes" ON "thumbnails"."UUID" = "thumbnailVotes"."UUID" LEFT JOIN "thumbnailTimestamps" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
WHERE "thumbnails"."videoID" = ? AND "thumbnails"."service" = ? AND "thumbnailVotes"."votes" - "thumbnailVotes"."downvotes" > -2 AND "thumbnailVotes"."removed" = 0
ORDER BY "thumbnails"."timeSubmitted" ASC`,
[videoID, service],
{ useReplica: true }
) as Promise<ThumbnailDBResult[]>;
const getSegments = () => db.prepare(
"all",
`SELECT "startTime", "endTime", "category", "videoDuration" FROM "sponsorTimes"
WHERE "votes" > -2 AND "shadowHidden" = 0 AND "hidden" = 0 AND "actionType" = 'skip' AND "videoID" = ? AND "service" = ?
ORDER BY "timeSubmitted" ASC`,
[videoID, service],
{ useReplica: true }
) as Promise<BrandingSegmentDBResult[]>;
const getCasualVotes = () => db.prepare(
"all",
`SELECT "casualVotes"."category", "casualVotes"."upvotes", "casualVoteTitles"."title"
FROM "casualVotes" LEFT JOIN "casualVoteTitles" ON "casualVotes"."videoID" = "casualVoteTitles"."videoID" AND "casualVotes"."service" = "casualVoteTitles"."service" AND "casualVotes"."titleID" = "casualVoteTitles"."id"
WHERE "casualVotes"."videoID" = ? AND "casualVotes"."service" = ?
ORDER BY "casualVotes"."timeSubmitted" ASC`,
[videoID, service],
{ useReplica: true }
) as Promise<CasualVoteDBResult[]>;
const getBranding = async () => {
const titles = getTitles();
const thumbnails = getThumbnails();
const segments = getSegments();
const casualVotes = getCasualVotes();
for (const title of await titles) {
title.title = title.title.replaceAll("<", "");
}
return {
titles: await titles,
thumbnails: await thumbnails,
segments: await segments,
casualVotes: await casualVotes
};
};
const brandingTrace = await QueryCacher.getTraced(getBranding, brandingKey(videoID, service));
const branding = brandingTrace.data;
// Add trace info to request for debugging purposes
res.setHeader("X-Start-Time", brandingTrace.startTime);
if (brandingTrace.dbStartTime) res.setHeader("X-DB-Start-Time", brandingTrace.dbStartTime);
res.setHeader("X-End-Time", brandingTrace.endTime);
const stats = (db as Postgres)?.getStats?.();
if (stats) {
res.setHeader("X-DB-Pool-Total", stats.pool.total);
res.setHeader("X-DB-Pool-Idle", stats.pool.idle);
res.setHeader("X-DB-Pool-Waiting", stats.pool.waiting);
}
const cache = {
currentIP: null as Promise<HashedIP> | null
};
return filterAndSortBranding(videoID, returnUserID, fetchAll, branding.titles,
branding.thumbnails, branding.segments, branding.casualVotes, ip, cache);
}
export async function getVideoBrandingByHash(videoHashPrefix: VideoIDHash, service: Service, ip: IPAddress, returnUserID: boolean, fetchAll: boolean): Promise<Record<VideoID, BrandingResult>> {
const getTitles = () => db.prepare(
"all",
`SELECT "titles"."title", "titles"."original", "titleVotes"."votes", "titleVotes"."downvotes", "titleVotes"."locked", "titleVotes"."shadowHidden", "titles"."UUID", "titles"."videoID", "titles"."hashedVideoID", "titleVotes"."verification"
FROM "titles" JOIN "titleVotes" ON "titles"."UUID" = "titleVotes"."UUID"
WHERE "titles"."hashedVideoID" LIKE ? AND "titles"."service" = ? AND "titleVotes"."votes" > -1 AND "titleVotes"."votes" - "titleVotes"."downvotes" > -2 AND "titleVotes"."removed" = 0`,
[`${videoHashPrefix}%`, service],
{ useReplica: true }
) as Promise<TitleDBResult[]>;
const getThumbnails = () => db.prepare(
"all",
`SELECT "thumbnailTimestamps"."timestamp", "thumbnails"."original", "thumbnailVotes"."votes", "thumbnailVotes"."downvotes", "thumbnailVotes"."locked", "thumbnailVotes"."shadowHidden", "thumbnails"."UUID", "thumbnails"."videoID", "thumbnails"."hashedVideoID"
FROM "thumbnails" LEFT JOIN "thumbnailVotes" ON "thumbnails"."UUID" = "thumbnailVotes"."UUID" LEFT JOIN "thumbnailTimestamps" ON "thumbnails"."UUID" = "thumbnailTimestamps"."UUID"
WHERE "thumbnails"."hashedVideoID" LIKE ? AND "thumbnails"."service" = ? AND "thumbnailVotes"."votes" - "thumbnailVotes"."downvotes" > -2 AND "thumbnailVotes"."removed" = 0
ORDER BY "thumbnails"."timeSubmitted" ASC`,
[`${videoHashPrefix}%`, service],
{ useReplica: true }
) as Promise<ThumbnailDBResult[]>;
const getSegments = () => db.prepare(
"all",
`SELECT "videoID", "startTime", "endTime", "category", "videoDuration" FROM "sponsorTimes"
WHERE "votes" > -2 AND "shadowHidden" = 0 AND "hidden" = 0 AND "actionType" = 'skip' AND "hashedVideoID" LIKE ? AND "service" = ?
ORDER BY "timeSubmitted" ASC`,
[`${videoHashPrefix}%`, service],
{ useReplica: true }
) as Promise<BrandingSegmentHashDBResult[]>;
const getCasualVotes = () => db.prepare(
"all",
`SELECT "casualVotes"."videoID", "casualVotes"."category", "casualVotes"."upvotes", "casualVoteTitles"."title"
FROM "casualVotes" LEFT JOIN "casualVoteTitles" ON "casualVotes"."videoID" = "casualVoteTitles"."videoID" AND "casualVotes"."service" = "casualVoteTitles"."service" AND "casualVotes"."titleID" = "casualVoteTitles"."id"
WHERE "casualVotes"."hashedVideoID" LIKE ? AND "casualVotes"."service" = ?
ORDER BY "casualVotes"."timeSubmitted" ASC`,
[`${videoHashPrefix}%`, service],
{ useReplica: true }
) as Promise<CasualVoteHashDBResult[]>;
const branding = await QueryCacher.get(async () => {
// Make sure they are both called in parallel
const branding = {
titles: getTitles(),
thumbnails: getThumbnails(),
segments: getSegments(),
casualVotes: getCasualVotes()
};
const dbResult: Record<VideoID, BrandingHashDBResult> = {};
const initResult = (submission: BrandingDBSubmissionData) => {
dbResult[submission.videoID] = dbResult[submission.videoID] || {
titles: [],
thumbnails: [],
segments: [],
casualVotes: []
};
};
(await branding.titles).forEach((title) => {
title.title = title.title.replaceAll("<", "");
initResult(title);
dbResult[title.videoID].titles.push(title);
});
(await branding.thumbnails).forEach((thumbnail) => {
initResult(thumbnail);
dbResult[thumbnail.videoID].thumbnails.push(thumbnail);
});
(await branding.segments).forEach((segment) => {
initResult(segment);
dbResult[segment.videoID].segments.push(segment);
});
(await branding.casualVotes).forEach((casualVote) => {
initResult(casualVote);
dbResult[casualVote.videoID].casualVotes.push(casualVote);
});
return dbResult;
}, brandingHashKey(videoHashPrefix, service));
const cache = {
currentIP: null as Promise<HashedIP> | null
};
const processedResult: Record<VideoID, BrandingResult> = {};
await Promise.all(Object.keys(branding).map(async (key) => {
const castedKey = key as VideoID;
processedResult[castedKey] = await filterAndSortBranding(castedKey, returnUserID, fetchAll, branding[castedKey].titles,
branding[castedKey].thumbnails, branding[castedKey].segments, branding[castedKey].casualVotes, ip, cache);
}));
return processedResult;
}
async function filterAndSortBranding(videoID: VideoID, returnUserID: boolean, fetchAll: boolean, dbTitles: TitleDBResult[],
dbThumbnails: ThumbnailDBResult[], dbSegments: BrandingSegmentDBResult[], dbCasualVotes: CasualVoteDBResult[],
ip: IPAddress, cache: { currentIP: Promise<HashedIP> | null }): Promise<BrandingResult> {
const shouldKeepTitles = shouldKeepSubmission(dbTitles, BrandingSubmissionType.Title, ip, cache);
const shouldKeepThumbnails = shouldKeepSubmission(dbThumbnails, BrandingSubmissionType.Thumbnail, ip, cache);
const titles = shuffleArray(dbTitles.filter(await shouldKeepTitles))
.map((r) => ({
title: r.title,
original: r.original === 1,
votes: r.votes + r.verification - r.downvotes,
locked: r.locked === 1,
UUID: r.UUID,
userID: returnUserID ? r.userID : undefined
}))
.filter((a) => fetchAll || a.votes >= 0 || a.locked)
.sort((a, b) => b.votes - a.votes)
.sort((a, b) => +b.locked - +a.locked) as TitleResult[];
const thumbnails = dbThumbnails.filter(await shouldKeepThumbnails)
.sort((a, b) => +a.original - +b.original)
.sort((a, b) => b.votes - a.votes)
.sort((a, b) => b.locked - a.locked)
.map((r) => ({
timestamp: r.timestamp,
original: r.original === 1,
votes: r.votes - r.downvotes,
locked: r.locked === 1,
UUID: r.UUID,
userID: returnUserID ? r.userID : undefined
}))
.filter((a) => (fetchAll && !a.original) || a.votes >= 1 || (a.votes >= 0 && !a.original) || a.locked) as ThumbnailResult[];
const casualDownvotes = dbCasualVotes.filter((r) => r.category === "downvote")[0];
const casualVotes = dbCasualVotes.filter((r) => r.category !== "downvote").map((r) => ({
id: r.category,
count: r.upvotes - (casualDownvotes?.upvotes ?? 0),
title: r.title
})).filter((a) => a.count > 0);
const videoDuration = dbSegments.filter(s => s.videoDuration !== 0)[0]?.videoDuration ?? null;
return {
titles,
thumbnails,
casualVotes,
randomTime: findRandomTime(videoID, dbSegments, videoDuration),
videoDuration: videoDuration,
};
}
async function shouldKeepSubmission(submissions: BrandingDBSubmission[], type: BrandingSubmissionType, ip: IPAddress,
cache: { currentIP: Promise<HashedIP> | null }): Promise<(_: unknown, index: number) => boolean> {
const shouldKeep = await Promise.all(submissions.map(async (s) => {
if (s.shadowHidden === Visibility.VISIBLE) return true;
const table = type === BrandingSubmissionType.Title ? "titleVotes" : "thumbnailVotes";
const fetchData = () => privateDB.prepare("get", `SELECT "hashedIP" FROM "${table}" WHERE "UUID" = ?`,
[s.UUID], { useReplica: true }) as Promise<{ hashedIP: HashedIP }>;
try {
const submitterIP = await promiseOrTimeout(QueryCacher.get(fetchData, brandingIPKey(s.UUID)), 150);
if (cache.currentIP === null) cache.currentIP = getHashCache((ip + config.globalSalt) as IPAddress);
const hashedIP = await cache.currentIP;
return submitterIP?.hashedIP === hashedIP;
} catch (e) {
// give up on shadow hide for now
Logger.error(`getBranding: Error while trying to find IP: ${e}`);
return false;
}
}));
return (_, index) => shouldKeep[index];
}
export function findRandomTime(videoID: VideoID, segments: BrandingSegmentDBResult[], videoDuration: number): number {
let randomTime = SeedRandom.alea(videoID)();
// Don't allow random times past 90% of the video if no endcard
if (!segments.some((s) => s.category === "outro") && randomTime > 0.9) {
randomTime -= 0.9;
}
if (segments.length === 0) return randomTime;
videoDuration ||= Math.max(...segments.map((s) => s.endTime)); // use highest end time as a fallback here
// There are segments, treat this as a relative time in the chopped up video
const sorted = segments.sort((a, b) => a.startTime - b.startTime);
const emptySegments: [number, number][] = [];
let totalTime = 0;
let nextEndTime = 0;
for (const segment of sorted) {
if (segment.startTime > nextEndTime) {
emptySegments.push([nextEndTime, segment.startTime]);
totalTime += segment.startTime - nextEndTime;
}
nextEndTime = Math.max(segment.endTime, nextEndTime);
}
if (nextEndTime < videoDuration) {
emptySegments.push([nextEndTime, videoDuration]);
totalTime += videoDuration - nextEndTime;
}
let cursor = 0;
for (const segment of emptySegments) {
const duration = segment[1] - segment[0];
if (cursor + duration >= randomTime * totalTime) {
// Found it
return (segment[0] + (randomTime * totalTime - cursor)) / videoDuration;
}
cursor += duration;
}
// Fallback to just the random time
return randomTime;
}
export async function getBranding(req: Request, res: Response) {
const videoID: VideoID = req.query.videoID as VideoID;
const service: Service = getService(req.query.service as string);
const returnUserID = req.query.returnUserID === "true";
const fetchAll = req.query.fetchAll === "true";
if (!videoID) {
return res.status(400).send("Missing parameter: videoID");
}
const ip = getIP(req);
try {
const result = await getVideoBranding(res, videoID, service, ip, returnUserID, fetchAll);
await getEtag("branding", (videoID as string), service)
.then(etag => res.set("ETag", etag))
.catch(() => null);
const status = result.titles.length > 0 || result.thumbnails.length > 0 || result.casualVotes.length > 0 ? 200 : 404;
return res.status(status).json(result);
} catch (e) {
Logger.error(e as string);
return res.status(500).send("Internal server error");
}
}
export async function getBrandingByHashEndpoint(req: Request, res: Response) {
let hashPrefix = req.params.prefix as VideoIDHash;
if (!hashPrefix || !hashPrefixTester(hashPrefix) || hashPrefix.length !== 4) {
return res.status(400).send("Hash prefix does not match format requirements."); // Exit early on faulty prefix
}
hashPrefix = hashPrefix.toLowerCase() as VideoIDHash;
const service: Service = getService(req.query.service as string);
const ip = getIP(req);
const returnUserID = req.query.returnUserID === "true";
const fetchAll = req.query.fetchAll === "true";
try {
const result = await getVideoBrandingByHash(hashPrefix, service, ip, returnUserID, fetchAll);
await getEtag("brandingHash", (hashPrefix as string), service)
.then(etag => res.set("ETag", etag))
.catch(() => null);
const status = !isEmpty(result) ? 200 : 404;
return res.status(status).json(result);
} catch (e) {
Logger.error(e as string);
return res.status(500).send([]);
}
}

View File

@@ -1,82 +0,0 @@
/* istanbul ignore file */
import { db } from "../databases/databases";
import { Request, Response } from "express";
import axios from "axios";
import { Logger } from "../utils/logger";
import { getCWSUsers, getChromeUsers } from "../utils/getCWSUsers";
// A cache of the number of chrome web store users
let chromeUsersCache = 30000;
let firefoxUsersCache = 0;
interface DBStatsData {
userCount: number,
titles: number,
thumbnails: number,
}
let lastFetch: DBStatsData = {
userCount: 0,
titles: 0,
thumbnails: 0
};
updateExtensionUsers();
export async function getBrandingStats(req: Request, res: Response): Promise<void> {
try {
const row = await getStats();
lastFetch = row;
/* istanbul ignore if */
if (!row) res.sendStatus(500);
const extensionUsers = chromeUsersCache + firefoxUsersCache;
//send this result
res.send({
userCount: row.userCount ?? 0,
activeUsers: extensionUsers,
titles: row.titles,
thumbnails: row.thumbnails,
});
} catch (e) {
Logger.error(e as string);
res.sendStatus(500);
}
}
async function getStats(): Promise<DBStatsData> {
if (db.highLoad()) {
return Promise.resolve(lastFetch);
} else {
const userCount = (await db.prepare("get", `SELECT COUNT(DISTINCT "userID") as "userCount" FROM titles`, []))?.userCount;
const titles = (await db.prepare("get", `SELECT COUNT(*) as "titles" FROM titles`, []))?.titles;
const thumbnails = (await db.prepare("get", `SELECT COUNT(*) as "thumbnails" FROM thumbnails`, []))?.thumbnails;
return {
userCount: userCount ?? 0,
titles: titles ?? 0,
thumbnails: thumbnails ?? 0
};
}
}
function updateExtensionUsers() {
const mozillaAddonsUrl = "https://addons.mozilla.org/api/v3/addons/addon/dearrow/";
const chromeExtensionUrl = "https://chromewebstore.google.com/detail/dearrow-better-titles-and/enamippconapkdmgfgjchkhakpfinmaj";
const chromeExtId = "enamippconapkdmgfgjchkhakpfinmaj";
axios.get(mozillaAddonsUrl)
.then(res => firefoxUsersCache = res.data.average_daily_users )
.catch( /* istanbul ignore next */ () => {
Logger.debug(`Failing to connect to ${mozillaAddonsUrl}`);
return 0;
});
getCWSUsers(chromeExtId)
.then(res => chromeUsersCache = res)
.catch(/* istanbul ignore next */ () =>
getChromeUsers(chromeExtensionUrl)
.then(res => chromeUsersCache = res)
);
}

View File

@@ -22,16 +22,15 @@ export async function getChapterNames(req: Request, res: Response): Promise<Resp
const descriptions = await db.prepare("all", `
SELECT "description"
FROM "sponsorTimes"
WHERE ("locked" = 1 OR "votes" >= 0) AND "videoID" IN (
WHERE ("votes" > 0 OR ("views" > 100 AND "votes" >= 0)) AND "videoID" IN (
SELECT "videoID"
FROM "videoInfo"
WHERE "channelID" = ?
) AND "description" != ''
AND similarity("description", ?) >= 0.1
GROUP BY "description"
ORDER BY SUM("votes"), similarity("description", ?) DESC
LIMIT 5;`
, [channelID, description, description]) as { description: string }[];
, [channelID, description]) as { description: string }[];
if (descriptions?.length > 0) {
return res.status(200).json(descriptions.map(d => ({

View File

@@ -1,35 +0,0 @@
import { getHashCache } from "../utils/getHashCache";
import { Request, Response } from "express";
import { isUserVIP } from "../utils/isUserVIP";
import { UserID } from "../types/user.model";
import { Logger } from "../utils/logger";
import { getServerConfig } from "../utils/serverConfig";
export async function getConfigEndpoint(req: Request, res: Response): Promise<Response> {
const userID = req.query.userID as string;
const key = req.query.key as string;
if (!userID || !key) {
// invalid request
return res.sendStatus(400);
}
// hash the userID
const hashedUserID = await getHashCache(userID as UserID);
const isVIP = (await isUserVIP(hashedUserID));
if (!isVIP) {
// not authorized
return res.sendStatus(403);
}
try {
return res.status(200).json({
value: await getServerConfig(key)
});
} catch (e) {
Logger.error(e as string);
return res.sendStatus(500);
}
}

View File

@@ -1,23 +1,13 @@
import { db } from "../databases/databases";
import { Request, Response } from "express";
import { Logger } from "../utils/logger";
export async function getDaysSavedFormatted(req: Request, res: Response): Promise<Response> {
try {
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', []);
if (row !== undefined) {
//send this result
return res.send({
daysSaved: row.daysSaved?.toFixed(2) ?? "0",
});
} else {
return res.send({
daysSaved: 0
});
}
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
if (row !== undefined) {
//send this result
return res.send({
daysSaved: row.daysSaved.toFixed(2),
});
}
}

View File

@@ -1,15 +0,0 @@
import { config } from "../config";
import { Request, Response } from "express";
export function getFeatureFlag(req: Request, res: Response): Response {
const { params: { name } } = req;
switch (name) {
case "deArrowPaywall":
return res.status(200).json({
enabled: config.deArrowPaywall,
});
}
return res.status(404).json();
}

View File

@@ -21,7 +21,7 @@ export async function getIsUserVIP(req: Request, res: Response): Promise<Respons
hashedUserID: hashedUserID,
vip: vipState,
});
} catch (err) /* istanbul ignore next */ {
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -3,12 +3,17 @@ import { Logger } from "../utils/logger";
import { Request, Response } from "express";
import { ActionType, Category, VideoID } from "../types/segments.model";
import { getService } from "../utils/getService";
import { parseActionTypes } from "../utils/parseParams";
export async function getLockCategories(req: Request, res: Response): Promise<Response> {
const videoID = req.query.videoID as VideoID;
const service = getService(req.query.service as string);
const actionTypes: ActionType[] = parseActionTypes(req, [ActionType.Skip, ActionType.Mute]);
const actionTypes: ActionType[] = req.query.actionTypes
? JSON.parse(req.query.actionTypes as string)
: req.query.actionType
? Array.isArray(req.query.actionType)
? req.query.actionType
: [req.query.actionType]
: [ActionType.Skip, ActionType.Mute];
if (!videoID || !Array.isArray(actionTypes)) {
//invalid request
return res.sendStatus(400);
@@ -28,7 +33,7 @@ export async function getLockCategories(req: Request, res: Response): Promise<Re
categories,
actionTypes
});
} catch (err) /* istanbul ignore next */{
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -3,7 +3,6 @@ import { Logger } from "../utils/logger";
import { Request, Response } from "express";
import { hashPrefixTester } from "../utils/hashPrefixTester";
import { ActionType, Category, VideoID, VideoIDHash } from "../types/segments.model";
import { parseActionTypes } from "../utils/parseParams";
interface LockResultByHash {
videoID: VideoID,
@@ -45,12 +44,13 @@ const mergeLocks = (source: DBLock[], actionTypes: ActionType[]): LockResultByHa
export async function getLockCategoriesByHash(req: Request, res: Response): Promise<Response> {
let hashPrefix = req.params.prefix as VideoIDHash;
const actionTypes: ActionType[] = parseActionTypes(req, [ActionType.Skip, ActionType.Mute]);
if (!Array.isArray(actionTypes)) {
//invalid request
return res.sendStatus(400);
}
const actionTypes: ActionType[] = req.query.actionTypes
? JSON.parse(req.query.actionTypes as string)
: req.query.actionType
? Array.isArray(req.query.actionType)
? req.query.actionType
: [req.query.actionType]
: [ActionType.Skip, ActionType.Mute];
if (!hashPrefixTester(req.params.prefix)) {
return res.status(400).send("Hash prefix does not match format requirements."); // Exit early on faulty prefix
}
@@ -62,7 +62,7 @@ export async function getLockCategoriesByHash(req: Request, res: Response): Prom
if (lockedRows.length === 0 || !lockedRows[0]) return res.sendStatus(404);
// merge all locks
return res.send(mergeLocks(lockedRows, actionTypes));
} catch (err) /* istanbul ignore next */ {
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -2,8 +2,9 @@ import { db } from "../databases/databases";
import { Logger } from "../utils/logger";
import { Request, Response } from "express";
import { Category, VideoID, ActionType } from "../types/segments.model";
import { filterInvalidCategoryActionType, parseActionTypes, parseCategories } from "../utils/parseParams";
import { config } from "../config";
const categorySupportList = config.categorySupport;
interface lockArray {
category: Category;
locked: number,
@@ -12,19 +13,61 @@ interface lockArray {
userName: string,
}
const filterActionType = (actionTypes: ActionType[]) => {
const filterCategories = new Set();
for (const [key, value] of Object.entries(categorySupportList)) {
for (const type of actionTypes) {
if (value.includes(type)) {
filterCategories.add(key as Category);
}
}
}
return [...filterCategories];
};
export async function getLockReason(req: Request, res: Response): Promise<Response> {
const videoID = req.query.videoID as VideoID;
const actionTypes = parseActionTypes(req, [ActionType.Skip, ActionType.Mute]);
const categories = parseCategories(req, []);
// invalid requests
const errors = [];
if (!videoID) errors.push("No videoID provided");
if (!Array.isArray(actionTypes)) errors.push("actionTypes parameter does not match format requirements");
if (!Array.isArray(categories)) errors.push("Categories parameter does not match format requirements.");
if (errors.length) return res.status(400).send(errors.join(", "));
if (!videoID) {
// invalid request
return res.status(400).send("No videoID provided");
}
let categories: Category[] = [];
const actionTypes: ActionType[] = req.query.actionTypes
? JSON.parse(req.query.actionTypes as string)
: req.query.actionType
? Array.isArray(req.query.actionType)
? req.query.actionType
: [req.query.actionType]
: [ActionType.Skip, ActionType.Mute];
const possibleCategories = filterActionType(actionTypes);
if (!Array.isArray(actionTypes)) {
//invalid request
return res.status(400).send("actionTypes parameter does not match format requirements");
}
try {
categories = req.query.categories
? JSON.parse(req.query.categories as string)
: req.query.category
? Array.isArray(req.query.category)
? req.query.category
: [req.query.category]
: []; // default to empty, will be set to all
if (!Array.isArray(categories)) {
return res.status(400).send("Categories parameter does not match format requirements.");
}
} catch(error) {
return res.status(400).send("Bad parameter: categories (invalid JSON)");
}
// only take valid categories
const searchCategories = filterInvalidCategoryActionType(categories, actionTypes);
const searchCategories = (categories.length === 0 )
? possibleCategories
: categories.filter(x =>
possibleCategories.includes(x));
if (!videoID || !Array.isArray(actionTypes)) {
//invalid request
return res.sendStatus(400);
}
try {
// Get existing lock categories markers
@@ -72,7 +115,7 @@ export async function getLockReason(req: Request, res: Response): Promise<Respon
}
return res.send(results);
} catch (err) /* istanbul ignore next */ {
} catch (err) {
Logger.error(err as string);
return res.sendStatus(500);
}

View File

@@ -1,106 +0,0 @@
import { db, privateDB } from "../databases/databases";
import { Request, Response } from "express";
import os from "os";
import redis, { getRedisStats } from "../utils/redis";
import { Postgres } from "../databases/Postgres";
import { Server } from "http";
export async function getMetrics(req: Request, res: Response, server: Server): Promise<Response> {
const redisStats = getRedisStats();
return res.type("text").send([
`# HELP sb_uptime Uptime of this instance`,
`# TYPE sb_uptime counter`,
`sb_uptime ${process.uptime()}`,
`# HELP sb_db_version The version of the database`,
`# TYPE sb_db_version counter`,
`sb_db_version ${await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"]).then(e => e.value).catch(() => -1)}`,
`# HELP sb_start_time The time this instance was started`,
`# TYPE sb_start_time gauge`,
`sb_start_time ${Date.now()}`,
`# HELP sb_loadavg_5 The 5 minute load average of the system`,
`# TYPE sb_loadavg_5 gauge`,
`sb_loadavg_5 ${os.loadavg()[0]}`,
`# HELP sb_loadavg_15 The 15 minute load average of the system`,
`# TYPE sb_loadavg_15 gauge`,
`sb_loadavg_15 ${os.loadavg()[1]}`,
`# HELP sb_connections The number of connections to this instance`,
`# TYPE sb_connections gauge`,
`sb_connections ${await new Promise((resolve) => server.getConnections((_, count) => resolve(count)) as any)}`,
`# HELP sb_status_requests The number of status requests made to this instance`,
`# TYPE sb_status_requests gauge`,
`sb_status_requests ${await redis.increment("statusRequest").then(e => e[0]).catch(() => -1)}`,
`# HELP sb_postgres_active_requests The number of active requests to the postgres database`,
`# TYPE sb_postgres_active_requests gauge`,
`sb_postgres_active_requests ${(db as Postgres)?.getStats?.()?.activeRequests ?? -1}`,
`# HELP sb_postgres_avg_read_time The average read time of the postgres database`,
`# TYPE sb_postgres_avg_read_time gauge`,
`sb_postgres_avg_read_time ${(db as Postgres)?.getStats?.()?.avgReadTime ?? -1}`,
`# HELP sb_postgres_avg_write_time The average write time of the postgres database`,
`# TYPE sb_postgres_avg_write_time gauge`,
`sb_postgres_avg_write_time ${(db as Postgres)?.getStats?.()?.avgWriteTime ?? -1}`,
`# HELP sb_postgres_avg_failed_time The average failed time of the postgres database`,
`# TYPE sb_postgres_avg_failed_time gauge`,
`sb_postgres_avg_failed_time ${(db as Postgres)?.getStats?.()?.avgFailedTime ?? -1}`,
`# HELP sb_postgres_pool_total The total number of connections in the postgres pool`,
`# TYPE sb_postgres_pool_total gauge`,
`sb_postgres_pool_total ${(db as Postgres)?.getStats?.()?.pool?.total ?? -1}`,
`# HELP sb_postgres_pool_idle The number of idle connections in the postgres pool`,
`# TYPE sb_postgres_pool_idle gauge`,
`sb_postgres_pool_idle ${(db as Postgres)?.getStats?.()?.pool?.idle ?? -1}`,
`# HELP sb_postgres_pool_waiting The number of connections waiting in the postgres pool`,
`# TYPE sb_postgres_pool_waiting gauge`,
`sb_postgres_pool_waiting ${(db as Postgres)?.getStats?.()?.pool?.waiting ?? -1}`,
`# HELP sb_postgres_private_active_requests The number of active requests to the private postgres database`,
`# TYPE sb_postgres_private_active_requests gauge`,
`sb_postgres_private_active_requests ${(privateDB as Postgres)?.getStats?.()?.activeRequests ?? -1}`,
`# HELP sb_postgres_private_avg_read_time The average read time of the private postgres database`,
`# TYPE sb_postgres_private_avg_read_time gauge`,
`sb_postgres_private_avg_read_time ${(privateDB as Postgres)?.getStats?.()?.avgReadTime ?? -1}`,
`# HELP sb_postgres_private_avg_write_time The average write time of the private postgres database`,
`# TYPE sb_postgres_private_avg_write_time gauge`,
`sb_postgres_private_avg_write_time ${(privateDB as Postgres)?.getStats?.()?.avgWriteTime ?? -1}`,
`# HELP sb_postgres_private_avg_failed_time The average failed time of the private postgres database`,
`# TYPE sb_postgres_private_avg_failed_time gauge`,
`sb_postgres_private_avg_failed_time ${(privateDB as Postgres)?.getStats?.()?.avgFailedTime ?? -1}`,
`# HELP sb_postgres_private_pool_total The total number of connections in the private postgres pool`,
`# TYPE sb_postgres_private_pool_total gauge`,
`sb_postgres_private_pool_total ${(privateDB as Postgres)?.getStats?.()?.pool?.total ?? -1}`,
`# HELP sb_postgres_private_pool_idle The number of idle connections in the private postgres pool`,
`# TYPE sb_postgres_private_pool_idle gauge`,
`sb_postgres_private_pool_idle ${(privateDB as Postgres)?.getStats?.()?.pool?.idle ?? -1}`,
`# HELP sb_postgres_private_pool_waiting The number of connections waiting in the private postgres pool`,
`# TYPE sb_postgres_private_pool_waiting gauge`,
`sb_postgres_private_pool_waiting ${(privateDB as Postgres)?.getStats?.()?.pool?.waiting ?? -1}`,
`# HELP sb_redis_active_requests The number of active requests to redis`,
`# TYPE sb_redis_active_requests gauge`,
`sb_redis_active_requests ${redisStats.activeRequests}`,
`# HELP sb_redis_write_requests The number of write requests to redis`,
`# TYPE sb_redis_write_requests gauge`,
`sb_redis_write_requests ${redisStats.writeRequests}`,
`# HELP sb_redis_avg_read_time The average read time of redis`,
`# TYPE sb_redis_avg_read_time gauge`,
`sb_redis_avg_read_time ${redisStats?.avgReadTime}`,
`# HELP sb_redis_avg_write_time The average write time of redis`,
`# TYPE sb_redis_avg_write_time gauge`,
`sb_redis_avg_write_time ${redisStats.avgWriteTime}`,
`# HELP sb_redis_memory_cache_hits The cache hit ratio in redis`,
`# TYPE sb_redis_memory_cache_hits gauge`,
`sb_redis_memory_cache_hits ${redisStats.memoryCacheHits}`,
`# HELP sb_redis_memory_cache_total_hits The cache hit ratio in redis including uncached items`,
`# TYPE sb_redis_memory_cache_total_hits gauge`,
`sb_redis_memory_cache_total_hits ${redisStats.memoryCacheTotalHits}`,
`# HELP sb_redis_memory_cache_length The length of the memory cache in redis`,
`# TYPE sb_redis_memory_cache_length gauge`,
`sb_redis_memory_cache_length ${redisStats.memoryCacheLength}`,
`# HELP sb_redis_memory_cache_size The size of the memory cache in redis`,
`# TYPE sb_redis_memory_cache_size gauge`,
`sb_redis_memory_cache_size ${redisStats.memoryCacheSize}`,
`# HELP sb_redis_last_invalidation The time of the last successful invalidation in redis`,
`# TYPE sb_redis_last_invalidation gauge`,
`sb_redis_last_invalidation ${redisStats.lastInvalidation}`,
`# HELP sb_redis_last_invalidation_message The time of the last invalidation message in redis`,
`# TYPE sb_redis_last_invalidation_message gauge`,
`sb_redis_last_invalidation_message ${redisStats.lastInvalidationMessage}`,
].join("\n"));
}

View File

@@ -1,26 +0,0 @@
import { Request, Response } from "express";
import { Server } from "http";
import { config } from "../config";
import { getRedisStats } from "../utils/redis";
import { Postgres } from "../databases/Postgres";
import { db } from "../databases/databases";
export async function getReady(req: Request, res: Response, server: Server): Promise<Response> {
const connections = await new Promise((resolve) => server.getConnections((_, count) => resolve(count))) as number;
const redisStats = getRedisStats();
const postgresStats = (db as Postgres).getStats?.();
if (!connections
|| (connections < config.maxConnections
&& (!config.redis || redisStats.activeRequests < config.redis.maxConnections * 0.8)
&& (!config.redis || redisStats.activeRequests < 1 || redisStats.avgReadTime < config.maxResponseTime
|| (redisStats.memoryCacheSize < config.redis.clientCacheSize * 0.8 && redisStats.avgReadTime < config.maxResponseTimeWhileLoadingCache))
&& (!config.postgres || postgresStats.activeRequests < config.postgres.maxActiveRequests * 0.8)
&& (!config.postgres || postgresStats.avgReadTime < config.maxResponseTime
|| (redisStats.memoryCacheSize < config.redis.clientCacheSize * 0.8 && postgresStats.avgReadTime < config.maxResponseTimeWhileLoadingCache)))) {
return res.sendStatus(200);
} else {
return res.sendStatus(500);
}
}

View File

@@ -18,7 +18,7 @@ export async function getSavedTimeForUser(req: Request, res: Response): Promise<
userID = await getHashCache(userID);
try {
const row = await db.prepare("get", 'SELECT SUM(((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views") as "minutesSaved" FROM "sponsorTimes" WHERE "userID" = ? AND "votes" > -1 AND "shadowHidden" != 1 ', [maxRewardTimePerSegmentInSeconds, maxRewardTimePerSegmentInSeconds, userID], { useReplica: true });
const row = await db.prepare("get", 'SELECT SUM(((CASE WHEN "endTime" - "startTime" > ? THEN ? ELSE "endTime" - "startTime" END) / 60) * "views") as "minutesSaved" FROM "sponsorTimes" WHERE "userID" = ? AND "votes" > -1 AND "shadowHidden" != 1 ', [maxRewardTimePerSegmentInSeconds, maxRewardTimePerSegmentInSeconds, userID]);
if (row.minutesSaved != null) {
return res.send({
@@ -27,7 +27,7 @@ export async function getSavedTimeForUser(req: Request, res: Response): Promise<
} else {
return res.sendStatus(404);
}
} catch (err) /* istanbul ignore next */ {
} catch (err) {
Logger.error(`getSavedTimeForUser ${err}`);
return res.sendStatus(500);
}

View File

@@ -2,8 +2,6 @@ import { Request, Response } from "express";
import { db } from "../databases/databases";
import { ActionType, Category, DBSegment, Service, VideoID, SortableFields } from "../types/segments.model";
import { getService } from "../utils/getService";
import { parseActionTypes, parseCategories } from "../utils/parseParams";
const maxSegmentsPerPage = 100;
const defaultSegmentsPerPage = 10;
@@ -16,7 +14,7 @@ type searchSegmentResponse = {
function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): Promise<DBSegment[]> {
return db.prepare(
"all",
`SELECT "UUID", "timeSubmitted", "startTime", "endTime", "category", "actionType", "votes", "views", "locked", "hidden", "shadowHidden", "userID", "description" FROM "sponsorTimes"
`SELECT "UUID", "timeSubmitted", "startTime", "endTime", "category", "actionType", "votes", "views", "locked", "hidden", "shadowHidden", "userID" FROM "sponsorTimes"
WHERE "videoID" = ? AND "service" = ? ORDER BY "timeSubmitted"`,
[videoID, service]
) as Promise<DBSegment[]>;
@@ -75,13 +73,25 @@ async function handleGetSegments(req: Request, res: Response): Promise<searchSeg
return false;
}
// Default to sponsor
const categories: Category[] = parseCategories(req, []);
const categories: Category[] = req.query.categories
? JSON.parse(req.query.categories as string)
: req.query.category
? Array.isArray(req.query.category)
? req.query.category
: [req.query.category]
: [];
if (!Array.isArray(categories)) {
res.status(400).send("Categories parameter does not match format requirements.");
return false;
}
const actionTypes: ActionType[] = parseActionTypes(req, [ActionType.Skip]);
const actionTypes: ActionType[] = req.query.actionTypes
? JSON.parse(req.query.actionTypes as string)
: req.query.actionType
? Array.isArray(req.query.actionType)
? req.query.actionType
: [req.query.actionType]
: [ActionType.Skip];
if (!Array.isArray(actionTypes)) {
res.status(400).send("actionTypes parameter does not match format requirements.");
return false;
@@ -118,7 +128,12 @@ async function handleGetSegments(req: Request, res: Response): Promise<searchSeg
const segments = await getSegmentsFromDBByVideoID(videoID, service);
if (!segments?.length) {
if (segments === null || segments === undefined) {
res.sendStatus(500);
return false;
}
if (segments.length === 0) {
res.sendStatus(404);
return false;
}
@@ -140,7 +155,6 @@ function filterSegments(segments: DBSegment[], filters: Record<string, any>, pag
);
if (sortBy !== SortableFields.timeSubmitted) {
/* istanbul ignore next */
filteredSegments.sort((a,b) => {
const key = sortDir === "desc" ? 1 : -1;
if (a[sortBy] < b[sortBy]) {
@@ -173,7 +187,6 @@ async function endpoint(req: Request, res: Response): Promise<Response> {
return res.send(segmentResponse);
}
} catch (err) {
/* istanbul ignore next */
if (err instanceof SyntaxError) {
return res.status(400).send("Invalid array in parameters");
} else return res.sendStatus(500);

View File

@@ -1,22 +0,0 @@
import { db } from "../databases/databases";
import { Request, Response } from "express";
import { getService } from "../utils/getService";
export async function getSegmentID(req: Request, res: Response): Promise<Response> {
const partialUUID = req.query?.UUID;
const videoID = req.query?.videoID;
const service = getService(req.query?.service as string);
if (!partialUUID || !videoID) {
//invalid request
return res.sendStatus(400);
}
const data = await db.prepare("get", `SELECT "UUID" from "sponsorTimes" WHERE "UUID" LIKE ? AND "videoID" = ? AND "service" = ?`, [`${partialUUID}%`, videoID, service]);
if (data) {
return res.status(200).send(data.UUID);
} else {
return res.sendStatus(404);
}
}

View File

@@ -7,7 +7,7 @@ const isValidSegmentUUID = (str: string): boolean => /^([a-f0-9]{64}|[a-f0-9]{8}
async function getSegmentFromDBByUUID(UUID: SegmentUUID): Promise<DBSegment> {
try {
return await db.prepare("get", `SELECT * FROM "sponsorTimes" WHERE "UUID" = ?`, [UUID]);
} catch (err) /* istanbul ignore next */ {
} catch (err) {
return null;
}
}
@@ -34,11 +34,11 @@ async function handleGetSegmentInfo(req: Request, res: Response): Promise<DBSegm
// deduplicate with set
UUIDs = [ ...new Set(UUIDs)];
// if more than 10 entries, slice
if (!Array.isArray(UUIDs) || !UUIDs?.length) {
if (UUIDs.length > 10) UUIDs = UUIDs.slice(0, 10);
if (!Array.isArray(UUIDs) || !UUIDs) {
res.status(400).send("UUIDs parameter does not match format requirements.");
return;
}
if (UUIDs.length > 10) UUIDs = UUIDs.slice(0, 10);
const DBSegments = await getSegmentsByUUID(UUIDs);
// all uuids failed lookup
if (!DBSegments?.length) {
@@ -62,7 +62,7 @@ async function endpoint(req: Request, res: Response): Promise<Response> {
//send result
return res.send(DBSegments);
}
} catch (err) /* istanbul ignore next */ {
} catch (err) {
if (err instanceof SyntaxError) { // catch JSON.parse error
return res.status(400).send("UUIDs parameter does not match format requirements.");
} else return res.sendStatus(500);

View File

@@ -2,7 +2,7 @@ import { Request, Response } from "express";
import { partition } from "lodash";
import { config } from "../config";
import { db, privateDB } from "../databases/databases";
import { skipSegmentsHashKey, skipSegmentsKey, skipSegmentGroupsKey, shadowHiddenIPKey, skipSegmentsLargerHashKey } from "../utils/redisKeys";
import { skipSegmentsHashKey, skipSegmentsKey, skipSegmentGroupsKey, shadowHiddenIPKey } from "../utils/redisKeys";
import { SBRecord } from "../types/lib.model";
import { ActionType, Category, DBSegment, HashedIP, IPAddress, OverlappingSegmentGroup, Segment, SegmentCache, SegmentUUID, Service, VideoData, VideoID, VideoIDHash, Visibility, VotableObject } from "../types/segments.model";
import { getHashCache } from "../utils/getHashCache";
@@ -11,85 +11,68 @@ import { Logger } from "../utils/logger";
import { QueryCacher } from "../utils/queryCacher";
import { getReputation } from "../utils/reputation";
import { getService } from "../utils/getService";
import { promiseOrTimeout } from "../utils/promise";
import { parseSkipSegments } from "../utils/parseSkipSegments";
import { getEtag } from "../middleware/etag";
import { shuffleArray } from "../utils/array";
import { Postgres } from "../databases/Postgres";
import { getRedisStats } from "../utils/redis";
async function prepareCategorySegments(req: Request, videoID: VideoID, service: Service, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }, useCache: boolean): Promise<Segment[]> {
async function prepareCategorySegments(req: Request, videoID: VideoID, service: Service, segments: DBSegment[], cache: SegmentCache = { shadowHiddenSegmentIPs: {} }, useCache: boolean, logData: any): Promise<Segment[]> {
const shouldFilter: boolean[] = await Promise.all(segments.map(async (segment) => {
if (segment.required) {
return true; //required - always send
}
if (segment.hidden
|| segment.votes < -1
|| segment.shadowHidden === Visibility.MORE_HIDDEN) {
if (segment.votes < -1 && !segment.required) {
return false; //too untrustworthy, just ignore it
}
//check if shadowHidden
//this means it is hidden to everyone but the original ip that submitted it
if (segment.shadowHidden === Visibility.VISIBLE) {
if (segment.shadowHidden != Visibility.HIDDEN) {
return true;
}
if (logData.extraLogging) {
Logger.error(`Starting ip fetch: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
if (cache.shadowHiddenSegmentIPs[videoID] === undefined) cache.shadowHiddenSegmentIPs[videoID] = {};
if (cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] === undefined) {
if (cache.userHashedIP === undefined && cache.userHashedIPPromise === undefined) {
cache.userHashedIPPromise = getHashCache((getIP(req) + config.globalSalt) as IPAddress);
}
const service = getService(req?.query?.service as string);
const fetchData = () => privateDB.prepare("all", 'SELECT "hashedIP" FROM "sponsorTimes" WHERE "videoID" = ? AND "timeSubmitted" = ? AND "service" = ?',
[videoID, segment.timeSubmitted, service], { useReplica: true }) as Promise<{ hashedIP: HashedIP }[]>;
try {
if (db.highLoad() || privateDB.highLoad()) {
Logger.error("High load, not handling shadowhide");
if (db instanceof Postgres && privateDB instanceof Postgres) {
Logger.error(`Postgres stats: ${JSON.stringify(db.getStats())}`);
Logger.error(`Postgres private stats: ${JSON.stringify(privateDB.getStats())}`);
}
Logger.error(`Redis stats: ${JSON.stringify(getRedisStats())}`);
return false;
}
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = promiseOrTimeout(QueryCacher.get(fetchData, shadowHiddenIPKey(videoID, segment.timeSubmitted, service)), 150);
} catch (e) {
// give up on shadowhide for now
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = null;
}
[videoID, segment.timeSubmitted, service]) as Promise<{ hashedIP: HashedIP }[]>;
cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted] = await QueryCacher.get(fetchData, shadowHiddenIPKey(videoID, segment.timeSubmitted, service));
}
let ipList = [];
try {
ipList = await cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted];
} catch (e) {
Logger.error(`skipSegments: Error while trying to find IP: ${e}`);
if (db instanceof Postgres && privateDB instanceof Postgres) {
Logger.error(`Postgres stats: ${JSON.stringify(db.getStats())}`);
Logger.error(`Postgres private stats: ${JSON.stringify(privateDB.getStats())}`);
}
return false;
}
const ipList = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted];
if (ipList?.length > 0 && cache.userHashedIP === undefined) {
cache.userHashedIP = await cache.userHashedIPPromise;
//hash the IP only if it's strictly necessary
if (logData.extraLogging) {
Logger.error(`Starting hash: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
cache.userHashedIP = await getHashCache((getIP(req) + config.globalSalt) as IPAddress);
if (logData.extraLogging) {
Logger.error(`Ending hash: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
}
//if this isn't their ip, don't send it to them
const shouldShadowHide = ipList?.some(
const shouldShadowHide = cache.shadowHiddenSegmentIPs[videoID][segment.timeSubmitted]?.some(
(shadowHiddenSegment) => shadowHiddenSegment.hashedIP === cache.userHashedIP) ?? false;
if (shouldShadowHide) useCache = false;
return shouldShadowHide;
}));
if (logData.extraLogging) {
Logger.error(`Preparing segments: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
const filteredSegments = segments.filter((_, index) => shouldFilter[index]);
return (await chooseSegments(videoID, service, filteredSegments, useCache)).map((chosenSegment) => ({
if (logData.extraLogging) {
Logger.error(`Filter complete: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
return (await chooseSegments(videoID, service, filteredSegments, useCache, logData)).map((chosenSegment) => ({
category: chosenSegment.category,
actionType: chosenSegment.actionType,
segment: [chosenSegment.startTime, chosenSegment.endTime],
@@ -113,6 +96,9 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
}
try {
categories = categories.filter((category) => !/[^a-z|_|-]/.test(category));
if (categories.length === 0) return null;
const segments: DBSegment[] = (await getSegmentsFromDBByVideoID(videoID, service))
.map((segment: DBSegment) => {
if (filterRequiredSegments(segment.UUID, requiredSegments)) segment.required = true;
@@ -120,18 +106,8 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
}, {});
const canUseCache = requiredSegments.length === 0;
let processedSegments: Segment[] = (await prepareCategorySegments(req, videoID, service, segments, cache, canUseCache))
.filter((segment: Segment) => categories.includes(segment?.category) && (actionTypes.includes(segment?.actionType)))
.map((segment: Segment) => ({
category: segment.category,
actionType: segment.actionType,
segment: segment.segment,
UUID: segment.UUID,
videoDuration: segment.videoDuration,
locked: segment.locked,
votes: segment.votes,
description: segment.description
}));
let processedSegments: Segment[] = (await prepareCategorySegments(req, videoID, service, segments, cache, canUseCache, {}))
.filter((segment: Segment) => categories.includes(segment?.category) && (actionTypes.includes(segment?.actionType)));
if (forcePoiAsSkip) {
processedSegments = processedSegments.map((segment) => ({
@@ -141,7 +117,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
}
return processedSegments;
} catch (err) /* istanbul ignore next */ {
} catch (err) {
if (err) {
Logger.error(err as string);
return null;
@@ -150,7 +126,7 @@ async function getSegmentsByVideoID(req: Request, videoID: VideoID, categories:
}
async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash, categories: Category[],
actionTypes: ActionType[], trimUUIDs: number, requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> {
actionTypes: ActionType[], requiredSegments: SegmentUUID[], service: Service): Promise<SBRecord<VideoID, VideoData>> {
const cache: SegmentCache = { shadowHiddenSegmentIPs: {} };
const segments: SBRecord<VideoID, VideoData> = {};
@@ -160,12 +136,28 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
actionTypes.push(ActionType.Poi);
}
try {
type SegmentPerVideoID = SBRecord<VideoID, { segments: DBSegment[] }>;
const logData = {
extraLogging: req.query.extraLogging,
startTime: Date.now(),
lastTime: Date.now()
};
const segmentPerVideoID: SegmentPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
.reduce((acc: SegmentPerVideoID, segment: DBSegment) => {
try {
type SegmentWithHashPerVideoID = SBRecord<VideoID, { hash: VideoIDHash, segments: DBSegment[] }>;
categories = categories.filter((category) => !(/[^a-z|_|-]/.test(category)));
if (categories.length === 0) return null;
if (logData.extraLogging) {
Logger.warn(`IP: ${getIP(req)}, request con ip: ${req.socket?.remoteAddress}`);
Logger.error(`About to fetch: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
const segmentPerVideoID: SegmentWithHashPerVideoID = (await getSegmentsFromDBByHash(hashedVideoIDPrefix, service))
.reduce((acc: SegmentWithHashPerVideoID, segment: DBSegment) => {
acc[segment.videoID] = acc[segment.videoID] || {
hash: segment.hashedVideoID,
segments: []
};
if (filterRequiredSegments(segment.UUID, requiredSegments)) segment.required = true;
@@ -176,44 +168,21 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
return acc;
}, {});
await Promise.all(Object.entries(segmentPerVideoID).map(async ([videoID, videoData]) => {
if (logData.extraLogging) {
Logger.error(`Fetch complete: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
for (const [videoID, videoData] of Object.entries(segmentPerVideoID)) {
const data: VideoData = {
hash: videoData.hash,
segments: [],
};
const canUseCache = requiredSegments.length === 0;
const filteredSegments = (await prepareCategorySegments(req, videoID as VideoID, service, videoData.segments, cache, canUseCache))
data.segments = (await prepareCategorySegments(req, videoID as VideoID, service, videoData.segments, cache, canUseCache, logData))
.filter((segment: Segment) => categories.includes(segment?.category) && actionTypes.includes(segment?.actionType));
// Make sure no hash duplicates exist
if (trimUUIDs) {
const seen = new Set<string>();
for (const segment of filteredSegments) {
const shortUUID = segment.UUID.substring(0, trimUUIDs);
if (seen.has(shortUUID)) {
// Duplicate found, disable trimming
trimUUIDs = undefined;
break;
}
seen.add(shortUUID);
}
seen.clear();
}
data.segments = filteredSegments
.map((segment) => ({
category: segment.category,
actionType: segment.actionType,
segment: segment.segment,
UUID: trimUUIDs ? segment.UUID.substring(0, trimUUIDs) as SegmentUUID : segment.UUID,
videoDuration: segment.videoDuration,
locked: segment.locked,
votes: segment.votes,
description: segment.description
}));
if (forcePoiAsSkip) {
data.segments = data.segments.map((segment) => ({
...segment,
@@ -224,11 +193,16 @@ async function getSegmentsByHash(req: Request, hashedVideoIDPrefix: VideoIDHash,
if (data.segments.length > 0) {
segments[videoID] = data;
}
}));
if (logData.extraLogging) {
Logger.error(`Done one video: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
}
return segments;
} catch (err) /* istanbul ignore next */ {
Logger.error(`get segments by hash error: ${err}`);
} catch (err) {
Logger.error(err as string);
return null;
}
}
@@ -237,16 +211,13 @@ async function getSegmentsFromDBByHash(hashedVideoIDPrefix: VideoIDHash, service
const fetchFromDB = () => db
.prepare(
"all",
`SELECT "videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "hidden", "reputation", "shadowHidden", "hashedVideoID", "timeSubmitted", "description" FROM "sponsorTimes"
WHERE "hashedVideoID" LIKE ? AND "service" = ? ORDER BY "startTime"`,
[`${hashedVideoIDPrefix}%`, service],
{ useReplica: true }
`SELECT "videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "reputation", "shadowHidden", "hashedVideoID", "timeSubmitted", "description" FROM "sponsorTimes"
WHERE "hashedVideoID" LIKE ? AND "service" = ? AND "hidden" = 0 ORDER BY "startTime"`,
[`${hashedVideoIDPrefix}%`, service]
) as Promise<DBSegment[]>;
if (hashedVideoIDPrefix.length === 4) {
return await QueryCacher.get(fetchFromDB, skipSegmentsHashKey(hashedVideoIDPrefix, service));
} else if (hashedVideoIDPrefix.length === 5) {
return await QueryCacher.get(fetchFromDB, skipSegmentsLargerHashKey(hashedVideoIDPrefix, service));
}
return await fetchFromDB();
@@ -256,20 +227,19 @@ async function getSegmentsFromDBByVideoID(videoID: VideoID, service: Service): P
const fetchFromDB = () => db
.prepare(
"all",
`SELECT "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "hidden", "reputation", "shadowHidden", "timeSubmitted", "description" FROM "sponsorTimes"
WHERE "videoID" = ? AND "service" = ? ORDER BY "startTime"`,
[videoID, service],
{ useReplica: true }
`SELECT "startTime", "endTime", "votes", "locked", "UUID", "userID", "category", "actionType", "videoDuration", "reputation", "shadowHidden", "timeSubmitted", "description" FROM "sponsorTimes"
WHERE "videoID" = ? AND "service" = ? AND "hidden" = 0 ORDER BY "startTime"`,
[videoID, service]
) as Promise<DBSegment[]>;
return await QueryCacher.get(fetchFromDB, skipSegmentsKey(videoID, service));
}
// Gets the best choice from the choices array based on their `votes` property.
// Gets a weighted random choice from the choices array based on their `votes` property.
// amountOfChoices specifies the maximum amount of choices to return, 1 or more.
// Choices are unique
// If a predicate is given, it will only filter choices following it, and will leave the rest in the list
function getBestChoice<T extends VotableObject>(choices: T[], amountOfChoices: number, filterLocked = false, predicate?: (choice: T) => void): T[] {
function getWeightedRandomChoice<T extends VotableObject>(choices: T[], amountOfChoices: number, filterLocked = false, predicate?: (choice: T) => void): T[] {
//trivial case: no need to go through the whole process
if (amountOfChoices >= choices.length) {
return choices;
@@ -292,50 +262,69 @@ function getBestChoice<T extends VotableObject>(choices: T[], amountOfChoices: n
}
//assign a weight to each choice
const choicesWithWeights: TWithWeight[] = shuffleArray(filteredChoices.map(choice => {
const boost = choice.reputation;
let totalWeight = 0;
const choicesWithWeights: TWithWeight[] = filteredChoices.map(choice => {
const boost = Math.min(choice.reputation, 4);
//The 3 makes -2 the minimum votes before being ignored completely
//this can be changed if this system increases in popularity.
const repFactor = choice.votes > 0 ? Math.max(1, choice.reputation + 1) : 1;
const weight = Math.exp(choice.votes * repFactor + 3 + boost);
totalWeight += Math.max(weight, 0);
const weight = choice.votes + boost;
return { ...choice, weight };
})).sort((a, b) => b.weight - a.weight);
});
// Nothing to filter for
if (amountOfChoices >= choicesWithWeights.length) {
return [...forceIncludedChoices, ...filteredChoices];
}
// Pick the top options
//iterate and find amountOfChoices choices
const chosen = [...forceIncludedChoices];
for (let i = 0; i < amountOfChoices; i++) {
while (amountOfChoices-- > 0) {
//weighted random draw of one element of choices
const randomNumber = Math.random() * totalWeight;
let stackWeight = choicesWithWeights[0].weight;
let i = 0;
while (stackWeight < randomNumber) {
stackWeight += choicesWithWeights[++i].weight;
}
//add it to the chosen ones and remove it from the choices before the next iteration
chosen.push(choicesWithWeights[i]);
totalWeight -= choicesWithWeights[i].weight;
choicesWithWeights.splice(i, 1);
}
return chosen;
}
async function chooseSegments(videoID: VideoID, service: Service, segments: DBSegment[], useCache: boolean): Promise<DBSegment[]> {
async function chooseSegments(videoID: VideoID, service: Service, segments: DBSegment[], useCache: boolean, logData: any): Promise<DBSegment[]> {
const fetchData = async () => await buildSegmentGroups(segments);
const groups = useCache && config.useCacheForSegmentGroups
const groups = useCache
? await QueryCacher.get(fetchData, skipSegmentGroupsKey(videoID, service))
: await fetchData();
if (logData.extraLogging) {
Logger.error(`Built groups: ${Date.now() - logData.lastTime}, ${Date.now() - logData.startTime}`);
logData.lastTime = Date.now();
}
// Filter for only 1 item for POI categories and Full video
let chosenGroups = getBestChoice(groups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Full);
chosenGroups = getBestChoice(chosenGroups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Poi);
return chosenGroups.map(// choose 1 good segment per group and return them
group => getBestChoice(group.segments, 1)[0]
let chosenGroups = getWeightedRandomChoice(groups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Full);
chosenGroups = getWeightedRandomChoice(chosenGroups, 1, true, (choice) => choice.segments[0].actionType === ActionType.Poi);
return chosenGroups.map(//randomly choose 1 good segment per group and return them
group => getWeightedRandomChoice(group.segments, 1)[0]
);
}
//This function will find segments that are contained inside of eachother, called similar segments
//Only one similar time will be returned, based on its score
//Only one similar time will be returned, randomly generated based on the sqrt of votes.
//This allows new less voted items to still sometimes appear to give them a chance at getting votes.
//Segments with less than -1 votes are already ignored before this function is called
async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSegmentGroup[]> {
const reputationPromises = segments.map(segment =>
segment.userID && !db.highLoad() ? getReputation(segment.userID).catch((e) => Logger.error(e)) : null);
//Create groups of segments that are similar to eachother
//Segments must be sorted by their startTime so that we can build groups chronologically:
//1. As long as the segments' startTime fall inside the currentGroup, we keep adding them to that group
@@ -344,8 +333,7 @@ async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSeg
let overlappingSegmentsGroups: OverlappingSegmentGroup[] = [];
let currentGroup: OverlappingSegmentGroup;
let cursor = -1; //-1 to make sure that, even if the 1st segment starts at 0, a new group is created
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
for (const segment of segments) {
if (segment.startTime >= cursor) {
currentGroup = { segments: [], votes: 0, reputation: 0, locked: false, required: false };
overlappingSegmentsGroups.push(currentGroup);
@@ -357,7 +345,7 @@ async function buildSegmentGroups(segments: DBSegment[]): Promise<OverlappingSeg
currentGroup.votes += segment.votes;
}
if (segment.userID) segment.reputation = Math.min(segment.reputation, (await reputationPromises[i]) || Infinity);
if (segment.userID) segment.reputation = Math.min(segment.reputation, await getReputation(segment.userID));
if (segment.reputation > 0) {
currentGroup.reputation += segment.reputation;
}
@@ -421,59 +409,75 @@ function splitPercentOverlap(groups: OverlappingSegmentGroup[]): OverlappingSegm
});
}
async function getSkipSegments(req: Request, res: Response): Promise<Response> {
/**
*
* Returns what would be sent to the client.
* Will respond with errors if required. Returns false if it errors.
*
* @param req
* @param res
*
* @returns
*/
async function handleGetSegments(req: Request, res: Response): Promise<Segment[] | false> {
const videoID = req.query.videoID as VideoID;
if (!videoID) {
return res.status(400).send("videoID not specified");
res.status(400).send("videoID not specified");
return false;
}
// Default to sponsor
// If using params instead of JSON, only one category can be pulled
const categories: Category[] = req.query.categories
? JSON.parse(req.query.categories as string)
: req.query.category
? Array.isArray(req.query.category)
? req.query.category
: [req.query.category]
: ["sponsor"];
if (!Array.isArray(categories)) {
res.status(400).send("Categories parameter does not match format requirements.");
return false;
}
const parseResult = parseSkipSegments(req);
if (parseResult.errors.length > 0) {
return res.status(400).send(parseResult.errors);
const actionTypes: ActionType[] = req.query.actionTypes
? JSON.parse(req.query.actionTypes as string)
: req.query.actionType
? Array.isArray(req.query.actionType)
? req.query.actionType
: [req.query.actionType]
: [ActionType.Skip];
if (!Array.isArray(actionTypes)) {
res.status(400).send("actionTypes parameter does not match format requirements.");
return false;
}
const { categories, actionTypes, requiredSegments, service } = parseResult;
const requiredSegments: SegmentUUID[] = req.query.requiredSegments
? JSON.parse(req.query.requiredSegments as string)
: req.query.requiredSegment
? Array.isArray(req.query.requiredSegment)
? req.query.requiredSegment
: [req.query.requiredSegment]
: [];
if (!Array.isArray(requiredSegments)) {
res.status(400).send("requiredSegments parameter does not match format requirements.");
return false;
}
const service = getService(req.query.service, req.body.service);
const segments = await getSegmentsByVideoID(req, videoID, categories, actionTypes, requiredSegments, service);
if (segments === null || segments === undefined) {
return res.sendStatus(500);
} else if (segments.length === 0) {
return res.sendStatus(404);
res.sendStatus(500);
return false;
}
await getEtag("skipSegments", (videoID as string), service)
.then(etag => res.set("ETag", etag))
.catch(() => ({}));
return res.send(segments);
}
async function oldGetVideoSponsorTimes(req: Request, res: Response): Promise<Response> {
const videoID = req.query.videoID as VideoID;
if (!videoID) {
return res.status(400).send("videoID not specified");
if (segments.length === 0) {
res.sendStatus(404);
return false;
}
const segments = await getSegmentsByVideoID(req, videoID, ["sponsor"] as Category[], [ActionType.Skip], [], Service.YouTube);
if (segments === null || segments === undefined) {
return res.sendStatus(500);
} else if (segments.length === 0) {
return res.sendStatus(404);
}
// Convert to old outputs
const sponsorTimes = [];
const UUIDs = [];
for (const segment of segments) {
sponsorTimes.push(segment.segment);
UUIDs.push(segment.UUID);
}
return res.send({
sponsorTimes,
UUIDs,
});
return segments;
}
const filterRequiredSegments = (UUID: SegmentUUID, requiredSegments: SegmentUUID[]): boolean => {
@@ -483,9 +487,25 @@ const filterRequiredSegments = (UUID: SegmentUUID, requiredSegments: SegmentUUID
return false;
};
async function endpoint(req: Request, res: Response): Promise<Response> {
try {
const segments = await handleGetSegments(req, res);
// If false, res.send has already been called
if (segments) {
//send result
return res.send(segments);
}
} catch (err) {
if (err instanceof SyntaxError) {
return res.status(400).send("Categories parameter does not match format requirements.");
} else return res.sendStatus(500);
}
}
export {
getSegmentsByVideoID,
getSegmentsByHash,
getSkipSegments,
oldGetVideoSponsorTimes
endpoint,
handleGetSegments
};

View File

@@ -1,10 +1,8 @@
import { hashPrefixTester } from "../utils/hashPrefixTester";
import { getSegmentsByHash } from "./getSkipSegments";
import { Request, Response } from "express";
import { VideoIDHash } from "../types/segments.model";
import { Logger } from "../utils/logger";
import { parseSkipSegments } from "../utils/parseSkipSegments";
import { getEtag } from "../middleware/etag";
import { ActionType, Category, SegmentUUID, VideoIDHash, Service } from "../types/segments.model";
import { getService } from "../utils/getService";
export async function getSkipSegmentsByHash(req: Request, res: Response): Promise<Response> {
let hashPrefix = req.params.prefix as VideoIDHash;
@@ -13,28 +11,68 @@ export async function getSkipSegmentsByHash(req: Request, res: Response): Promis
}
hashPrefix = hashPrefix.toLowerCase() as VideoIDHash;
const parseResult = parseSkipSegments(req);
if (parseResult.errors.length > 0) {
return res.status(400).send(parseResult.errors);
let categories: Category[] = [];
try {
categories = req.query.categories
? JSON.parse(req.query.categories as string)
: req.query.category
? Array.isArray(req.query.category)
? req.query.category
: [req.query.category]
: ["sponsor"];
if (!Array.isArray(categories)) {
return res.status(400).send("Categories parameter does not match format requirements.");
}
} catch(error) {
return res.status(400).send("Bad parameter: categories (invalid JSON)");
}
const { categories, actionTypes, trimUUIDs, requiredSegments, service } = parseResult;
let actionTypes: ActionType[] = [];
try {
actionTypes = req.query.actionTypes
? JSON.parse(req.query.actionTypes as string)
: req.query.actionType
? Array.isArray(req.query.actionType)
? req.query.actionType
: [req.query.actionType]
: [ActionType.Skip];
if (!Array.isArray(actionTypes)) {
return res.status(400).send("actionTypes parameter does not match format requirements.");
}
} catch(error) {
return res.status(400).send("Bad parameter: actionTypes (invalid JSON)");
}
let requiredSegments: SegmentUUID[] = [];
try {
requiredSegments = req.query.requiredSegments
? JSON.parse(req.query.requiredSegments as string)
: req.query.requiredSegment
? Array.isArray(req.query.requiredSegment)
? req.query.requiredSegment
: [req.query.requiredSegment]
: [];
if (!Array.isArray(requiredSegments)) {
return res.status(400).send("requiredSegments parameter does not match format requirements.");
}
} catch(error) {
return res.status(400).send("Bad parameter: requiredSegments (invalid JSON)");
}
const service: Service = getService(req.query.service, req.body.service);
// filter out none string elements, only flat array with strings is valid
categories = categories.filter((item: any) => typeof item === "string");
// Get all video id's that match hash prefix
const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, trimUUIDs, requiredSegments, service);
const segments = await getSegmentsByHash(req, hashPrefix, categories, actionTypes, requiredSegments, service);
try {
const hashKey = hashPrefix.length === 4 ? "skipSegmentsHash" : "skipSegmentsLargerHash";
await getEtag(hashKey, hashPrefix, service)
.then(etag => res.set("ETag", etag))
.catch(/* istanbul ignore next */ () => null);
const output = Object.entries(segments).map(([videoID, data]) => ({
videoID,
segments: data.segments,
}));
return res.status(output.length === 0 ? 404 : 200).json(output);
} catch (e) /* istanbul ignore next */ {
Logger.error(`skip segments by hash error: ${e}`);
if (!segments) return res.status(404).json([]);
return res.status(500).send("Internal server error");
}
const output = Object.entries(segments).map(([videoID, data]) => ({
videoID,
hash: data.hash,
segments: data.segments,
}));
return res.status(output.length === 0 ? 404 : 200).json(output);
}

Some files were not shown because too many files have changed in this diff Show More